Review Board 1.7.16


Fix transcode_via_sln and increase utility of PLC

Review Request #622 - Created April 22, 2010 and submitted

Mark Michelson
/trunk
Reviewers
asterisk-dev
Asterisk
The problem here is a bit complex, so try to bear with me...

It was noticed by a Digium customer that generic PLC (as configured in
codecs.conf) did not appear to actually be having any sort of benefit when
packet loss was introduced on an RTP stream. I reproduced this issue myself
by streaming a file across an RTP stream and dropping approx. 5% of the
RTP packets. I saw no real difference between when PLC was enabled or disabled
when using wireshark to analyze the RTP streams.

After analyzing what was going on, it became clear that one of the problems
faced was that when running my tests, the translation paths were being set
up in such a way that PLC could not possibly work as expected. To illustrate,
if packets are lost on channel A's read stream, then we expect that PLC will
be applied to channel B's write stream. The problem is that generic PLC can
only be done when there is a translation path that moves from some codec to
SLINEAR. When I would run my tests, I found that every single time, read
and write translation paths would be set up on channel A instead of channel
B. There appeared to be no real way to predict which channel the translation
paths would be set up on.

This is where Kevin swooped in to let me know about the transcode_via_sln
option in asterisk.conf. It is supposed to work by placing a read translation
path on both channels from the channel's rawreadformat to SLINEAR. It also
will place a write translation path on both channels from SLINEAR to the
channel's rawwriteformat. Using this option allows one to predictably set up
translation paths on all channels. There are two problems with this, though.
First and foremost, the transcode_via_sln option did not appear to be working
properly when I was placing a SIP call between two endpoints which did not
share any common formats. Second, even if this option were to work, for PLC
to be applied, there had to be a write translation path that would go from
some format to SLINEAR. It would not work properly if the starting format
of translation was SLINEAR.

The one-line change presented in this review request in chan_sip.c fixed the
first issue for me. The problem was that in sip_request_call, the
jointcapability of the outbound channel was being set to the format passed to
sip_request_call. This is nativeformats of the inbound channel. Because of this,
when ast_channel_make_compatible was called by app_dial, both channels already
had compatibly read and write formats. Thus, no translation path was set up at
the time. My change is to set the jointcapability of the sip_pvt created during
sip_request_call to the intersection of the inbound channel's nativeformats and
the configured peer capability that we determined during the earlier call to
create_addr. Doing this got the translation paths set up as expected when using
transcode_via_sln.

The changes presented in channel.c fixed the second issue for me. First and
foremost, when Asterisk is started, we'll read codecs.conf to see the value of
the genericplc option. If this option is set, and ast_write is called for a
frame with no data, then we will attempt to fill in the missing samples for
the frame. The implementation uses a channel datastore for maintaining the
PLC state and for creating a buffer to store PLC samples in. Even when we
receive a frame with data, we'll call plc_rx so that the PLC state will have
knowledge of the previous voice frame, which it can use as a basis for when
it comes time to actually do a PLC fill-in.

So, reviewers, now I ask for your help. First off, there's the one line change
in chan_sip that I have put in. Is it right? By my logic it seems correct, but
I'm sure someone can tell me why it is not going to work. This is probably the
change I'm least concerned about, though. What concerns me much more is the
set of changes in channel.c. First off, am I even doing it right? When I run
tests, I can clearly see that when PLC is activated, I see a significant increase
in RTP traffic where I would expect it to be. However, in my humble opinion, the
audio sounds kind of crappy whenever the PLC fill-in is done. It sounds worse to
me than when no PLC is used at all. I need someone to review the logic I have used
to be sure that I'm not misusing anything. As far as I can see my pointer arithmetic
is correct, and my use of AST_FRIENDLY_OFFSET should be correct as well, but I'm
sure someone can point out somewhere where I've done something incorrectly.

As I was writing this review request up, I decided to give the code a test run under
valgrind, and I find that for some reason, calls to plc_rx are causing some invalid
reads. Apparently I'm reading past the end of a buffer somehow. I'll have to dig around
a bit to see why that is the case. If it's obvious to someone reviewing, speak up!

Finally, I have one other proposal that is not reflected in my code review. Since
without transcode_via_sln set, one cannot predict or control where a translation
path will be up, it seems to me that the current practice of using PLC only when
transcoding to SLINEAR is not useful. I recommend that once it has been determined
that the method used in this code review is correct and works as expected, then
the code in translate.c that invokes PLC should be removed.
I ran a test where I would place a call from my Polycom phone through one Asterisk box
to a second one. The second box would play back the demo-congrats file. I modified the
RTP code in the second box to drop approximately 5 percent of the outgoing packets. The
audio between the two Asterisk boxes was GSM. The audio between the Polycom phone and
Asterisk was ulaw.

I used wireshark on the first Asterisk box to analyze the RTP streams. I noticed an increase
from an average of 2650 packets on the path from the first Asterisk box to the Polycom to
an average of 2786 packets when PLC was enabled.

Changes between revision 2 and 3

1 2 3 4 5
1 2 3 4 5

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

    
   
18

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

    
   
94

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

    
   
163

   
164
/*** MODULEINFO
164
/*** MODULEINFO
165
        <depend>chan_local</depend>
165
        <depend>chan_local</depend>
166
 ***/
166
 ***/
167

    
   
167

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

    
   
169

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

    
   
176

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

    
   
184

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

    
   
187

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

    
   
205

   
206
*/
206
*/
207

    
   
207

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

    
   
209

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

    
   
211

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

    
   
216

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

    
   
273

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

    
   
548

   
549
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
549
static int min_expiry = DEFAULT_MIN_EXPIRY;        /*!< Minimum accepted registration time */
550
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
550
static int max_expiry = DEFAULT_MAX_EXPIRY;        /*!< Maximum accepted registration time */
551
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
551
static int default_expiry = DEFAULT_DEFAULT_EXPIRY;
552
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
552
static int mwi_expiry = DEFAULT_MWI_EXPIRY;
553

    
   
553

   
554
/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
554
/*! \brief Global jitterbuffer configuration - by default, jb is disabled */
555
static struct ast_jb_conf default_jbconf =
555
static struct ast_jb_conf default_jbconf =
556
{
556
{
557
	.flags = 0,
557
	.flags = 0,
558
	.max_size = -1,
558
	.max_size = -1,
559
	.resync_threshold = -1,
559
	.resync_threshold = -1,
560
	.impl = "",
560
	.impl = "",
561
	.target_extra = -1,
561
	.target_extra = -1,
562
};
562
};
563
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
563
static struct ast_jb_conf global_jbconf;                /*!< Global jitterbuffer configuration */
564

    
   
564

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

    
   
567

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

    
   
583

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

    
   
603

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

    
   
633

   
634
/*! \brief List of well-known SIP options. If we get this in a require,
634
/*! \brief List of well-known SIP options. If we get this in a require,
635
   we should check the list and answer accordingly. */
635
   we should check the list and answer accordingly. */
636
static const struct cfsip_options {
636
static const struct cfsip_options {
637
	int id;             /*!< Bitmap ID */
637
	int id;             /*!< Bitmap ID */
638
	int supported;      /*!< Supported by Asterisk ? */
638
	int supported;      /*!< Supported by Asterisk ? */
639
	char * const text;  /*!< Text id, as in standard */
639
	char * const text;  /*!< Text id, as in standard */
640
} sip_options[] = {	/* XXX used in 3 places */
640
} sip_options[] = {	/* XXX used in 3 places */
641
	/* RFC3262: PRACK 100% reliability */
641
	/* RFC3262: PRACK 100% reliability */
642
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },
642
	{ SIP_OPT_100REL,	NOT_SUPPORTED,	"100rel" },
643
	/* RFC3959: SIP Early session support */
643
	/* RFC3959: SIP Early session support */
644
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },
644
	{ SIP_OPT_EARLY_SESSION, NOT_SUPPORTED,	"early-session" },
645
	/* SIMPLE events:  RFC4662 */
645
	/* SIMPLE events:  RFC4662 */
646
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },
646
	{ SIP_OPT_EVENTLIST,	NOT_SUPPORTED,	"eventlist" },
647
	/* RFC 4916- Connected line ID updates */
647
	/* RFC 4916- Connected line ID updates */
648
	{ SIP_OPT_FROMCHANGE,	NOT_SUPPORTED,	"from-change" },
648
	{ SIP_OPT_FROMCHANGE,	NOT_SUPPORTED,	"from-change" },
649
	/* GRUU: Globally Routable User Agent URI's */
649
	/* GRUU: Globally Routable User Agent URI's */
650
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },
650
	{ SIP_OPT_GRUU,		NOT_SUPPORTED,	"gruu" },
651
	/* RFC4244 History info */
651
	/* RFC4244 History info */
652
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },
652
	{ SIP_OPT_HISTINFO,	NOT_SUPPORTED,	"histinfo" },
653
	/* RFC3911: SIP Join header support */
653
	/* RFC3911: SIP Join header support */
654
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },
654
	{ SIP_OPT_JOIN,		NOT_SUPPORTED,	"join" },
655
	/* Disable the REFER subscription, RFC 4488 */
655
	/* Disable the REFER subscription, RFC 4488 */
656
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },
656
	{ SIP_OPT_NOREFERSUB,	NOT_SUPPORTED,	"norefersub" },
657
	/* SIP outbound - the final NAT battle - draft-sip-outbound */
657
	/* SIP outbound - the final NAT battle - draft-sip-outbound */
658
	{ SIP_OPT_OUTBOUND,	NOT_SUPPORTED,	"outbound" },
658
	{ SIP_OPT_OUTBOUND,	NOT_SUPPORTED,	"outbound" },
659
	/* RFC3327: Path support */
659
	/* RFC3327: Path support */
660
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },
660
	{ SIP_OPT_PATH,		NOT_SUPPORTED,	"path" },
661
	/* RFC3840: Callee preferences */
661
	/* RFC3840: Callee preferences */
662
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },
662
	{ SIP_OPT_PREF,		NOT_SUPPORTED,	"pref" },
663
	/* RFC3312: Precondition support */
663
	/* RFC3312: Precondition support */
664
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },
664
	{ SIP_OPT_PRECONDITION,	NOT_SUPPORTED,	"precondition" },
665
	/* RFC3323: Privacy with proxies*/
665
	/* RFC3323: Privacy with proxies*/
666
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },
666
	{ SIP_OPT_PRIVACY,	NOT_SUPPORTED,	"privacy" },
667
	/* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
667
	/* RFC-ietf-sip-uri-list-conferencing-02.txt conference invite lists */
668
	{ SIP_OPT_RECLISTINV,	NOT_SUPPORTED,	"recipient-list-invite" },
668
	{ SIP_OPT_RECLISTINV,	NOT_SUPPORTED,	"recipient-list-invite" },
669
	/* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
669
	/* RFC-ietf-sip-uri-list-subscribe-02.txt - subscription lists */
670
	{ SIP_OPT_RECLISTSUB,	NOT_SUPPORTED,	"recipient-list-subscribe" },
670
	{ SIP_OPT_RECLISTSUB,	NOT_SUPPORTED,	"recipient-list-subscribe" },
671
	/* RFC3891: Replaces: header for transfer */
671
	/* RFC3891: Replaces: header for transfer */
672
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },
672
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },
673
	/* One version of Polycom firmware has the wrong label */
673
	/* One version of Polycom firmware has the wrong label */
674
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },
674
	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },
675
	/* RFC4412 Resource priorities */
675
	/* RFC4412 Resource priorities */
676
	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },
676
	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },
677
	/* RFC3329: Security agreement mechanism */
677
	/* RFC3329: Security agreement mechanism */
678
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },
678
	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },
679
	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
679
	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
680
	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },
680
	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },
681
	/* RFC4028: SIP Session-Timers */
681
	/* RFC4028: SIP Session-Timers */
682
	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },
682
	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },
683
	/* RFC4538: Target-dialog */
683
	/* RFC4538: Target-dialog */
684
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },
684
	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },
685
};
685
};
686

    
   
686

   
687
/*! \brief Diversion header reasons
687
/*! \brief Diversion header reasons
688
 *
688
 *
689
 * The core defines a bunch of constants used to define
689
 * The core defines a bunch of constants used to define
690
 * redirecting reasons. This provides a translation table
690
 * redirecting reasons. This provides a translation table
691
 * between those and the strings which may be present in
691
 * between those and the strings which may be present in
692
 * a SIP Diversion header
692
 * a SIP Diversion header
693
 */
693
 */
694
static const struct sip_reasons {
694
static const struct sip_reasons {
695
	enum AST_REDIRECTING_REASON code;
695
	enum AST_REDIRECTING_REASON code;
696
	char * const text;
696
	char * const text;
697
} sip_reason_table[] = {
697
} sip_reason_table[] = {
698
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
698
	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
699
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
699
	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
700
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
700
	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
701
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
701
	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
702
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
702
	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
703
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
703
	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
704
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
704
	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
705
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
705
	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
706
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
706
	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
707
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
707
	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
708
	{ AST_REDIRECTING_REASON_AWAY, "away" },
708
	{ AST_REDIRECTING_REASON_AWAY, "away" },
709
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
709
	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
710
};
710
};
711

    
   
711

   
712

    
   
712

   
713
/*! \name DefaultSettings
713
/*! \name DefaultSettings
714
	Default setttings are used as a channel setting and as a default when
714
	Default setttings are used as a channel setting and as a default when
715
	configuring devices
715
	configuring devices
716
*/
716
*/
717
/*@{*/
717
/*@{*/
718
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
718
static char default_language[MAX_LANGUAGE];      /*!< Default language setting for new channels */
719
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
719
static char default_callerid[AST_MAX_EXTENSION]; /*!< Default caller ID for sip messages */
720
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
720
static char default_mwi_from[80];                /*!< Default caller ID for MWI updates */
721
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
721
static char default_fromdomain[AST_MAX_EXTENSION]; /*!< Default domain on outound messages */
722
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
722
static char default_notifymime[AST_MAX_EXTENSION]; /*!< Default MIME media type for MWI notify messages */
723
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
723
static char default_vmexten[AST_MAX_EXTENSION];    /*!< Default From Username on MWI updates */
724
static int default_qualify;                        /*!< Default Qualify= setting */
724
static int default_qualify;                        /*!< Default Qualify= setting */
725
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
725
static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
726
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
726
static char default_mohsuggest[MAX_MUSICCLASS];    /*!< Global setting for moh class to suggest when putting
727
                                                    *   a bridged channel on hold */
727
                                                    *   a bridged channel on hold */
728
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
728
static char default_parkinglot[AST_MAX_CONTEXT];   /*!< Parkinglot */
729
static char default_engine[256];                   /*!< Default RTP engine */
729
static char default_engine[256];                   /*!< Default RTP engine */
730
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
730
static int default_maxcallbitrate;                 /*!< Maximum bitrate for call */
731
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
731
static struct ast_codec_pref default_prefs;        /*!< Default codec prefs */
732
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
732
static unsigned int default_transports;            /*!< Default Transports (enum sip_transport) that are acceptable */
733
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
733
static unsigned int default_primary_transport;     /*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
734
/*@}*/
734
/*@}*/
735

    
   
735

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

    
   
738

   
739
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
739
/*!< use this macro when ast_uri_decode is dependent on pedantic checking to be on. */
740
#define SIP_PEDANTIC_DECODE(str)	\
740
#define SIP_PEDANTIC_DECODE(str)	\
741
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
741
	if (sip_cfg.pedanticsipchecking && !ast_strlen_zero(str)) {	\
742
		ast_uri_decode(str);	\
742
		ast_uri_decode(str);	\
743
	}	\
743
	}	\
744

    
   
744

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

    
   
747

   
748
static int global_relaxdtmf;        /*!< Relax DTMF */
748
static int global_relaxdtmf;        /*!< Relax DTMF */
749
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
749
static int global_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
750
static int global_rtptimeout;       /*!< Time out call if no RTP */
750
static int global_rtptimeout;       /*!< Time out call if no RTP */
751
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
751
static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
752
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
752
static int global_rtpkeepalive;     /*!< Send RTP keepalives */
753
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
753
static int global_reg_timeout;      /*!< Global time between attempts for outbound registrations */
754
static int global_regattempts_max;  /*!< Registration attempts before giving up */
754
static int global_regattempts_max;  /*!< Registration attempts before giving up */
755
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
755
static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
756
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
756
static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
757
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
757
                                     *   call-limit to INT_MAX. When we remove the call-limit from the code, we can make it
758
                                     *   with just a boolean flag in the device structure */
758
                                     *   with just a boolean flag in the device structure */
759
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
759
static unsigned int global_tos_sip;      /*!< IP type of service for SIP packets */
760
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
760
static unsigned int global_tos_audio;    /*!< IP type of service for audio RTP packets */
761
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
761
static unsigned int global_tos_video;    /*!< IP type of service for video RTP packets */
762
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
762
static unsigned int global_tos_text;     /*!< IP type of service for text RTP packets */
763
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
763
static unsigned int global_cos_sip;      /*!< 802.1p class of service for SIP packets */
764
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
764
static unsigned int global_cos_audio;    /*!< 802.1p class of service for audio RTP packets */
765
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
765
static unsigned int global_cos_video;    /*!< 802.1p class of service for video RTP packets */
766
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
766
static unsigned int global_cos_text;     /*!< 802.1p class of service for text RTP packets */
767
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
767
static unsigned int recordhistory;       /*!< Record SIP history. Off by default */
768
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
768
static unsigned int dumphistory;         /*!< Dump history to verbose before destroying SIP dialog */
769
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
769
static char global_useragent[AST_MAX_EXTENSION];    /*!< Useragent for the SIP channel */
770
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
770
static char global_sdpsession[AST_MAX_EXTENSION];   /*!< SDP session name for the SIP channel */
771
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
771
static char global_sdpowner[AST_MAX_EXTENSION];     /*!< SDP owner name for the SIP channel */
772
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
772
static int global_authfailureevents;     /*!< Whether we send authentication failure manager events or not. Default no. */
773
static int global_t1;           /*!< T1 time */
773
static int global_t1;           /*!< T1 time */
774
static int global_t1min;        /*!< T1 roundtrip time minimum */
774
static int global_t1min;        /*!< T1 roundtrip time minimum */
775
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
775
static int global_timer_b;      /*!< Timer B - RFC 3261 Section 17.1.1.2 */
776
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
776
static unsigned int global_autoframing; /*!< Turn autoframing on or off. */
777
static int global_qualifyfreq;          /*!< Qualify frequency */
777
static int global_qualifyfreq;          /*!< Qualify frequency */
778
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
778
static int global_qualify_gap;          /*!< Time between our group of peer pokes */
779
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
779
static int global_qualify_peers;        /*!< Number of peers to poke at a given time */
780

    
   
780

   
781
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
781
static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
782
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
782
static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
783
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
783
static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
784
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
784
static int global_max_se;                     /*!< Highest threshold for session refresh interval */
785

    
   
785

   
786
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
786
static int global_dynamic_exclude_static = 0; /*!< Exclude static peers from contact registrations */
787
/*@}*/
787
/*@}*/
788

    
   
788

   
789
/*!
789
/*!
790
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
790
 * We use libxml2 in order to parse XML that may appear in the body of a SIP message. Currently,
791
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
791
 * the only usage is for parsing PIDF bodies of incoming PUBLISH requests in the call-completion
792
 * event package. This variable is set at module load time and may be checked at runtime to determine
792
 * event package. This variable is set at module load time and may be checked at runtime to determine
793
 * if XML parsing support was found.
793
 * if XML parsing support was found.
794
 */
794
 */
795
static int can_parse_xml;
795
static int can_parse_xml;
796

    
   
796

   
797
/*! \name Object counters @{
797
/*! \name Object counters @{
798
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
798
 *  \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
799
 *  should be used to modify these values. */
799
 *  should be used to modify these values. */
800
static int speerobjs = 0;     /*!< Static peers */
800
static int speerobjs = 0;     /*!< Static peers */
801
static int rpeerobjs = 0;     /*!< Realtime peers */
801
static int rpeerobjs = 0;     /*!< Realtime peers */
802
static int apeerobjs = 0;     /*!< Autocreated peer objects */
802
static int apeerobjs = 0;     /*!< Autocreated peer objects */
803
static int regobjs = 0;       /*!< Registry objects */
803
static int regobjs = 0;       /*!< Registry objects */
804
/* }@ */
804
/* }@ */
805

    
   
805

   
806
static struct ast_flags global_flags[2] = {{0}};  /*!< global SIP_ flags */
806
static struct ast_flags global_flags[2] = {{0}};  /*!< global SIP_ flags */
807
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
807
static int global_t38_maxdatagram;                /*!< global T.38 FaxMaxDatagram override */
808

    
   
808

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

    
   
810

   
811
AST_MUTEX_DEFINE_STATIC(netlock);
811
AST_MUTEX_DEFINE_STATIC(netlock);
812

    
   
812

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

    
   
816

   
817
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
817
AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
818

    
   
818

   
819
/*! \brief This is the thread for the monitor which checks for input on the channels
819
/*! \brief This is the thread for the monitor which checks for input on the channels
820
   which are not currently in use.  */
820
   which are not currently in use.  */
821
static pthread_t monitor_thread = AST_PTHREADT_NULL;
821
static pthread_t monitor_thread = AST_PTHREADT_NULL;
822

    
   
822

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

    
   
825

   
826
struct sched_context *sched;     /*!< The scheduling context */
826
struct sched_context *sched;     /*!< The scheduling context */
827
static struct io_context *io;           /*!< The IO context */
827
static struct io_context *io;           /*!< The IO context */
828
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
828
static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
829
struct sip_pkt;
829
struct sip_pkt;
830
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
830
static AST_LIST_HEAD_STATIC(domain_list, domain);    /*!< The SIP domain list */
831

    
   
831

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

    
   
833

   
834
static enum sip_debug_e sipdebug;
834
static enum sip_debug_e sipdebug;
835

    
   
835

   
836
/*! \brief extra debugging for 'text' related events.
836
/*! \brief extra debugging for 'text' related events.
837
 *  At the moment this is set together with sip_debug_console.
837
 *  At the moment this is set together with sip_debug_console.
838
 *  \note It should either go away or be implemented properly.
838
 *  \note It should either go away or be implemented properly.
839
 */
839
 */
840
static int sipdebug_text;
840
static int sipdebug_text;
841

    
   
841

   
842
static const struct _map_x_s referstatusstrings[] = {
842
static const struct _map_x_s referstatusstrings[] = {
843
	{ REFER_IDLE,      "<none>" },
843
	{ REFER_IDLE,      "<none>" },
844
	{ REFER_SENT,      "Request sent" },
844
	{ REFER_SENT,      "Request sent" },
845
	{ REFER_RECEIVED,  "Request received" },
845
	{ REFER_RECEIVED,  "Request received" },
846
	{ REFER_CONFIRMED, "Confirmed" },
846
	{ REFER_CONFIRMED, "Confirmed" },
847
	{ REFER_ACCEPTED,  "Accepted" },
847
	{ REFER_ACCEPTED,  "Accepted" },
848
	{ REFER_RINGING,   "Target ringing" },
848
	{ REFER_RINGING,   "Target ringing" },
849
	{ REFER_200OK,     "Done" },
849
	{ REFER_200OK,     "Done" },
850
	{ REFER_FAILED,    "Failed" },
850
	{ REFER_FAILED,    "Failed" },
851
	{ REFER_NOAUTH,    "Failed - auth failure" },
851
	{ REFER_NOAUTH,    "Failed - auth failure" },
852
	{ -1,               NULL} /* terminator */
852
	{ -1,               NULL} /* terminator */
853
};
853
};
854

    
   
854

   
855
/* --- Hash tables of various objects --------*/
855
/* --- Hash tables of various objects --------*/
856
#ifdef LOW_MEMORY
856
#ifdef LOW_MEMORY
857
static const int HASH_PEER_SIZE = 17;
857
static const int HASH_PEER_SIZE = 17;
858
static const int HASH_DIALOG_SIZE = 17;
858
static const int HASH_DIALOG_SIZE = 17;
859
#else
859
#else
860
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
860
static const int HASH_PEER_SIZE = 563;	/*!< Size of peer hash table, prime number preferred! */
861
static const int HASH_DIALOG_SIZE = 563;
861
static const int HASH_DIALOG_SIZE = 563;
862
#endif
862
#endif
863

    
   
863

   
864
static const struct {
864
static const struct {
865
	enum ast_cc_service_type service;
865
	enum ast_cc_service_type service;
866
	const char *service_string;
866
	const char *service_string;
867
} sip_cc_service_map [] = {
867
} sip_cc_service_map [] = {
868
	[AST_CC_NONE] = { AST_CC_NONE, "" },
868
	[AST_CC_NONE] = { AST_CC_NONE, "" },
869
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
869
	[AST_CC_CCBS] = { AST_CC_CCBS, "BS" },
870
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
870
	[AST_CC_CCNR] = { AST_CC_CCNR, "NR" },
871
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
871
	[AST_CC_CCNL] = { AST_CC_CCNL, "NL" },
872
};
872
};
873

    
   
873

   
874
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
874
static enum ast_cc_service_type service_string_to_service_type(const char * const service_string)
875
{
875
{
876
	enum ast_cc_service_type service;
876
	enum ast_cc_service_type service;
877
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
877
	for (service = AST_CC_CCBS; service <= AST_CC_CCNL; ++service) {
878
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
878
		if (!strcasecmp(service_string, sip_cc_service_map[service].service_string)) {
879
			return service;
879
			return service;
880
		}
880
		}
881
	}
881
	}
882
	return AST_CC_NONE;
882
	return AST_CC_NONE;
883
}
883
}
884

    
   
884

   
885
static const struct {
885
static const struct {
886
	enum sip_cc_notify_state state;
886
	enum sip_cc_notify_state state;
887
	const char *state_string;
887
	const char *state_string;
888
} sip_cc_notify_state_map [] = {
888
} sip_cc_notify_state_map [] = {
889
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
889
	[CC_QUEUED] = {CC_QUEUED, "cc-state: queued"},
890
	[CC_READY] = {CC_READY, "cc-state: ready"},
890
	[CC_READY] = {CC_READY, "cc-state: ready"},
891
};
891
};
892

    
   
892

   
893
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
893
AST_LIST_HEAD_STATIC(epa_static_data_list, epa_backend);
894

    
   
894

   
895
static int sip_epa_register(const struct epa_static_data *static_data)
895
static int sip_epa_register(const struct epa_static_data *static_data)
896
{
896
{
897
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
897
	struct epa_backend *backend = ast_calloc(1, sizeof(*backend));
898

    
   
898

   
899
	if (!backend) {
899
	if (!backend) {
900
		return -1;
900
		return -1;
901
	}
901
	}
902

    
   
902

   
903
	backend->static_data = static_data;
903
	backend->static_data = static_data;
904

    
   
904

   
905
	AST_LIST_LOCK(&epa_static_data_list);
905
	AST_LIST_LOCK(&epa_static_data_list);
906
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
906
	AST_LIST_INSERT_TAIL(&epa_static_data_list, backend, next);
907
	AST_LIST_UNLOCK(&epa_static_data_list);
907
	AST_LIST_UNLOCK(&epa_static_data_list);
908
	return 0;
908
	return 0;
909
}
909
}
910

    
   
910

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

    
   
912

   
913
static void cc_epa_destructor(void *data)
913
static void cc_epa_destructor(void *data)
914
{
914
{
915
	struct sip_epa_entry *epa_entry = data;
915
	struct sip_epa_entry *epa_entry = data;
916
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
916
	struct cc_epa_entry *cc_entry = epa_entry->instance_data;
917
	ast_free(cc_entry);
917
	ast_free(cc_entry);
918
}
918
}
919

    
   
919

   
920
static const struct epa_static_data cc_epa_static_data  = {
920
static const struct epa_static_data cc_epa_static_data  = {
921
	.event = CALL_COMPLETION,
921
	.event = CALL_COMPLETION,
922
	.name = "call-completion",
922
	.name = "call-completion",
923
	.handle_error = cc_handle_publish_error,
923
	.handle_error = cc_handle_publish_error,
924
	.destructor = cc_epa_destructor,
924
	.destructor = cc_epa_destructor,
925
};
925
};
926

    
   
926

   
927
static const struct epa_static_data *find_static_data(const char * const event_package)
927
static const struct epa_static_data *find_static_data(const char * const event_package)
928
{
928
{
929
	const struct epa_backend *backend = NULL;
929
	const struct epa_backend *backend = NULL;
930

    
   
930

   
931
	AST_LIST_LOCK(&epa_static_data_list);
931
	AST_LIST_LOCK(&epa_static_data_list);
932
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
932
	AST_LIST_TRAVERSE(&epa_static_data_list, backend, next) {
933
		if (!strcmp(backend->static_data->name, event_package)) {
933
		if (!strcmp(backend->static_data->name, event_package)) {
934
			break;
934
			break;
935
		}
935
		}
936
	}
936
	}
937
	AST_LIST_UNLOCK(&epa_static_data_list);
937
	AST_LIST_UNLOCK(&epa_static_data_list);
938
	return backend ? backend->static_data : NULL;
938
	return backend ? backend->static_data : NULL;
939
}
939
}
940

    
   
940

   
941
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
941
static struct sip_epa_entry *create_epa_entry (const char * const event_package, const char * const destination)
942
{
942
{
943
	struct sip_epa_entry *epa_entry;
943
	struct sip_epa_entry *epa_entry;
944
	const struct epa_static_data *static_data;
944
	const struct epa_static_data *static_data;
945

    
   
945

   
946
	if (!(static_data = find_static_data(event_package))) {
946
	if (!(static_data = find_static_data(event_package))) {
947
		return NULL;
947
		return NULL;
948
	}
948
	}
949

    
   
949

   
950
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
950
	if (!(epa_entry = ao2_t_alloc(sizeof(*epa_entry), static_data->destructor, "Allocate new EPA entry"))) {
951
		return NULL;
951
		return NULL;
952
	}
952
	}
953

    
   
953

   
954
	epa_entry->static_data = static_data;
954
	epa_entry->static_data = static_data;
955
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
955
	ast_copy_string(epa_entry->destination, destination, sizeof(epa_entry->destination));
956
	return epa_entry;
956
	return epa_entry;
957
}
957
}
958

    
   
958

   
959
/*!
959
/*!
960
 * Used to create new entity IDs by ESCs.
960
 * Used to create new entity IDs by ESCs.
961
 */
961
 */
962
static int esc_etag_counter;
962
static int esc_etag_counter;
963
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
963
static const int DEFAULT_PUBLISH_EXPIRES = 3600;
964

    
   
964

   
965
#ifdef HAVE_LIBXML2
965
#ifdef HAVE_LIBXML2
966
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);
966
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);
967

    
   
967

   
968
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
968
static const struct sip_esc_publish_callbacks cc_esc_publish_callbacks = {
969
	.initial_handler = cc_esc_publish_handler,
969
	.initial_handler = cc_esc_publish_handler,
970
	.modify_handler = cc_esc_publish_handler,
970
	.modify_handler = cc_esc_publish_handler,
971
};
971
};
972
#endif
972
#endif
973

    
   
973

   
974
/*!
974
/*!
975
 * \brief The Event State Compositors
975
 * \brief The Event State Compositors
976
 *
976
 *
977
 * An Event State Compositor is an entity which
977
 * An Event State Compositor is an entity which
978
 * accepts PUBLISH requests and acts appropriately
978
 * accepts PUBLISH requests and acts appropriately
979
 * based on these requests.
979
 * based on these requests.
980
 *
980
 *
981
 * The actual event_state_compositor structure is simply
981
 * The actual event_state_compositor structure is simply
982
 * an ao2_container of sip_esc_entrys. When an incoming
982
 * an ao2_container of sip_esc_entrys. When an incoming
983
 * PUBLISH is received, we can match the appropriate sip_esc_entry
983
 * PUBLISH is received, we can match the appropriate sip_esc_entry
984
 * using the entity ID of the incoming PUBLISH.
984
 * using the entity ID of the incoming PUBLISH.
985
 */
985
 */
986
static struct event_state_compositor {
986
static struct event_state_compositor {
987
	enum subscriptiontype event;
987
	enum subscriptiontype event;
988
	const char * name;
988
	const char * name;
989
	const struct sip_esc_publish_callbacks *callbacks;
989
	const struct sip_esc_publish_callbacks *callbacks;
990
	struct ao2_container *compositor;
990
	struct ao2_container *compositor;
991
} event_state_compositors [] = {
991
} event_state_compositors [] = {
992
#ifdef HAVE_LIBXML2
992
#ifdef HAVE_LIBXML2
993
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
993
	{CALL_COMPLETION, "call-completion", &cc_esc_publish_callbacks},
994
#endif
994
#endif
995
};
995
};
996

    
   
996

   
997
static const int ESC_MAX_BUCKETS = 37;
997
static const int ESC_MAX_BUCKETS = 37;
998

    
   
998

   
999
static void esc_entry_destructor(void *obj)
999
static void esc_entry_destructor(void *obj)
1000
{
1000
{
1001
	struct sip_esc_entry *esc_entry = obj;
1001
	struct sip_esc_entry *esc_entry = obj;
1002
	if (esc_entry->sched_id > -1) {
1002
	if (esc_entry->sched_id > -1) {
1003
		AST_SCHED_DEL(sched, esc_entry->sched_id);
1003
		AST_SCHED_DEL(sched, esc_entry->sched_id);
1004
	}
1004
	}
1005
}
1005
}
1006

    
   
1006

   
1007
static int esc_hash_fn(const void *obj, const int flags)
1007
static int esc_hash_fn(const void *obj, const int flags)
1008
{
1008
{
1009
	const struct sip_esc_entry *entry = obj;
1009
	const struct sip_esc_entry *entry = obj;
1010
	return ast_str_hash(entry->entity_tag);
1010
	return ast_str_hash(entry->entity_tag);
1011
}
1011
}
1012

    
   
1012

   
1013
static int esc_cmp_fn(void *obj, void *arg, int flags)
1013
static int esc_cmp_fn(void *obj, void *arg, int flags)
1014
{
1014
{
1015
	struct sip_esc_entry *entry1 = obj;
1015
	struct sip_esc_entry *entry1 = obj;
1016
	struct sip_esc_entry *entry2 = arg;
1016
	struct sip_esc_entry *entry2 = arg;
1017

    
   
1017

   
1018
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1018
	return (!strcmp(entry1->entity_tag, entry2->entity_tag)) ? (CMP_MATCH | CMP_STOP) : 0;
1019
}
1019
}
1020

    
   
1020

   
1021
static struct event_state_compositor *get_esc(const char * const event_package) {
1021
static struct event_state_compositor *get_esc(const char * const event_package) {
1022
	int i;
1022
	int i;
1023
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1023
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1024
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1024
		if (!strcasecmp(event_package, event_state_compositors[i].name)) {
1025
			return &event_state_compositors[i];
1025
			return &event_state_compositors[i];
1026
		}
1026
		}
1027
	}
1027
	}
1028
	return NULL;
1028
	return NULL;
1029
}
1029
}
1030

    
   
1030

   
1031
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1031
static struct sip_esc_entry *get_esc_entry(const char * entity_tag, struct event_state_compositor *esc) {
1032
	struct sip_esc_entry *entry;
1032
	struct sip_esc_entry *entry;
1033
	struct sip_esc_entry finder;
1033
	struct sip_esc_entry finder;
1034

    
   
1034

   
1035
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1035
	ast_copy_string(finder.entity_tag, entity_tag, sizeof(finder.entity_tag));
1036

    
   
1036

   
1037
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1037
	entry = ao2_find(esc->compositor, &finder, OBJ_POINTER);
1038

    
   
1038

   
1039
	return entry;
1039
	return entry;
1040
}
1040
}
1041

    
   
1041

   
1042
static int publish_expire(const void *data)
1042
static int publish_expire(const void *data)
1043
{
1043
{
1044
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1044
	struct sip_esc_entry *esc_entry = (struct sip_esc_entry *) data;
1045
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1045
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1046

    
   
1046

   
1047
	ast_assert(esc != NULL);
1047
	ast_assert(esc != NULL);
1048

    
   
1048

   
1049
	ao2_unlink(esc->compositor, esc_entry);
1049
	ao2_unlink(esc->compositor, esc_entry);
1050
	ao2_ref(esc_entry, -1);
1050
	ao2_ref(esc_entry, -1);
1051
	return 0;
1051
	return 0;
1052
}
1052
}
1053

    
   
1053

   
1054
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1054
static void create_new_sip_etag(struct sip_esc_entry *esc_entry, int is_linked)
1055
{
1055
{
1056
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1056
	int new_etag = ast_atomic_fetchadd_int(&esc_etag_counter, +1);
1057
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1057
	struct event_state_compositor *esc = get_esc(esc_entry->event);
1058

    
   
1058

   
1059
	ast_assert(esc != NULL);
1059
	ast_assert(esc != NULL);
1060
	if (is_linked) {
1060
	if (is_linked) {
1061
		ao2_unlink(esc->compositor, esc_entry);
1061
		ao2_unlink(esc->compositor, esc_entry);
1062
	}
1062
	}
1063
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1063
	snprintf(esc_entry->entity_tag, sizeof(esc_entry->entity_tag), "%d", new_etag);
1064
	ao2_link(esc->compositor, esc_entry);
1064
	ao2_link(esc->compositor, esc_entry);
1065
}
1065
}
1066

    
   
1066

   
1067
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1067
static struct sip_esc_entry *create_esc_entry(struct event_state_compositor *esc, struct sip_request *req, const int expires)
1068
{
1068
{
1069
	struct sip_esc_entry *esc_entry;
1069
	struct sip_esc_entry *esc_entry;
1070
	int expires_ms;
1070
	int expires_ms;
1071

    
   
1071

   
1072
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1072
	if (!(esc_entry = ao2_alloc(sizeof(*esc_entry), esc_entry_destructor))) {
1073
		return NULL;
1073
		return NULL;
1074
	}
1074
	}
1075

    
   
1075

   
1076
	esc_entry->event = esc->name;
1076
	esc_entry->event = esc->name;
1077

    
   
1077

   
1078
	expires_ms = expires * 1000;
1078
	expires_ms = expires * 1000;
1079
	/* Bump refcount for scheduler */
1079
	/* Bump refcount for scheduler */
1080
	ao2_ref(esc_entry, +1);
1080
	ao2_ref(esc_entry, +1);
1081
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1081
	esc_entry->sched_id = ast_sched_add(sched, expires_ms, publish_expire, esc_entry);
1082

    
   
1082

   
1083
	/* Note: This links the esc_entry into the ESC properly */
1083
	/* Note: This links the esc_entry into the ESC properly */
1084
	create_new_sip_etag(esc_entry, 0);
1084
	create_new_sip_etag(esc_entry, 0);
1085

    
   
1085

   
1086
	return esc_entry;
1086
	return esc_entry;
1087
}
1087
}
1088

    
   
1088

   
1089
static int initialize_escs(void)
1089
static int initialize_escs(void)
1090
{
1090
{
1091
	int i, res = 0;
1091
	int i, res = 0;
1092
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1092
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1093
		if (!((event_state_compositors[i].compositor) =
1093
		if (!((event_state_compositors[i].compositor) =
1094
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1094
					ao2_container_alloc(ESC_MAX_BUCKETS, esc_hash_fn, esc_cmp_fn))) {
1095
			res = -1;
1095
			res = -1;
1096
		}
1096
		}
1097
	}
1097
	}
1098
	return res;
1098
	return res;
1099
}
1099
}
1100

    
   
1100

   
1101
static void destroy_escs(void)
1101
static void destroy_escs(void)
1102
{
1102
{
1103
	int i;
1103
	int i;
1104
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1104
	for (i = 0; i < ARRAY_LEN(event_state_compositors); i++) {
1105
		ao2_ref(event_state_compositors[i].compositor, -1);
1105
		ao2_ref(event_state_compositors[i].compositor, -1);
1106
	}
1106
	}
1107
}
1107
}
1108

    
   
1108

   
1109
/*! \brief
1109
/*! \brief
1110
 * Here we implement the container for dialogs (sip_pvt), defining
1110
 * Here we implement the container for dialogs (sip_pvt), defining
1111
 * generic wrapper functions to ease the transition from the current
1111
 * generic wrapper functions to ease the transition from the current
1112
 * implementation (a single linked list) to a different container.
1112
 * implementation (a single linked list) to a different container.
1113
 * In addition to a reference to the container, we need functions to lock/unlock
1113
 * 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
1114
 * the container and individual items, and functions to add/remove
1115
 * references to the individual items.
1115
 * references to the individual items.
1116
 */
1116
 */
1117
static struct ao2_container *dialogs;
1117
static struct ao2_container *dialogs;
1118
#define sip_pvt_lock(x) ao2_lock(x)
1118
#define sip_pvt_lock(x) ao2_lock(x)
1119
#define sip_pvt_trylock(x) ao2_trylock(x)
1119
#define sip_pvt_trylock(x) ao2_trylock(x)
1120
#define sip_pvt_unlock(x) ao2_unlock(x)
1120
#define sip_pvt_unlock(x) ao2_unlock(x)
1121

    
   
1121

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

    
   
1124

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

    
   
1128

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

    
   
1134

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

    
   
1141

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

    
   
1144

   
1145
/*! \brief Authentication list for realm authentication
1145
/*! \brief Authentication list for realm authentication
1146
 * \todo Move the sip_auth list to AST_LIST */
1146
 * \todo Move the sip_auth list to AST_LIST */
1147
static struct sip_auth *authl = NULL;
1147
static struct sip_auth *authl = NULL;
1148

    
   
1148

   
1149
/* --- Sockets and networking --------------*/
1149
/* --- Sockets and networking --------------*/
1150

    
   
1150

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

    
   
1166

   
1167
struct sockaddr_in bindaddr;	/*!< UDP: The address we bind to */
1167
struct sockaddr_in bindaddr;	/*!< UDP: The address we bind to */
1168

    
   
1168

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

    
   
1176

   
1177
/*! \brief our external IP address/port for SIP sessions.
1177
/*! \brief our external IP address/port for SIP sessions.
1178
 * externip.sin_addr is only set when we know we might be behind
1178
 * externip.sin_addr is only set when we know we might be behind
1179
 * a NAT, and this is done using a variety of (mutually exclusive)
1179
 * a NAT, and this is done using a variety of (mutually exclusive)
1180
 * ways from the config file:
1180
 * ways from the config file:
1181
 *
1181
 *
1182
 * + with "externip = host[:port]" we specify the address/port explicitly.
1182
 * + with "externip = host[:port]" we specify the address/port explicitly.
1183
 *   The address is looked up only once when (re)loading the config file;
1183
 *   The address is looked up only once when (re)loading the config file;
1184
 *
1184
 *
1185
 * + with "externhost = host[:port]" we do a similar thing, but the
1185
 * + with "externhost = host[:port]" we do a similar thing, but the
1186
 *   hostname is stored in externhost, and the hostname->IP mapping
1186
 *   hostname is stored in externhost, and the hostname->IP mapping
1187
 *   is refreshed every 'externrefresh' seconds;
1187
 *   is refreshed every 'externrefresh' seconds;
1188
 *
1188
 *
1189
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1189
 * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
1190
 *   to the specified server, and store the result in externip.
1190
 *   to the specified server, and store the result in externip.
1191
 *
1191
 *
1192
 * Other variables (externhost, externexpire, externrefresh) are used
1192
 * Other variables (externhost, externexpire, externrefresh) are used
1193
 * to support the above functions.
1193
 * to support the above functions.
1194
 */
1194
 */
1195
static struct sockaddr_in externip;       /*!< External IP address if we are behind NAT */
1195
static struct sockaddr_in externip;       /*!< External IP address if we are behind NAT */
1196
static struct sockaddr_in media_address;  /*!< External RTP IP address if we are behind NAT */
1196
static struct sockaddr_in media_address;  /*!< External RTP IP address if we are behind NAT */
1197

    
   
1197

   
1198
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1198
static char externhost[MAXHOSTNAMELEN];   /*!< External host name */
1199
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1199
static time_t externexpire;             /*!< Expiration counter for re-resolving external host name in dynamic DNS */
1200
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1200
static int externrefresh = 10;          /*!< Refresh timer for DNS-based external address (dyndns) */
1201
static struct sockaddr_in stunaddr;     /*!< stun server address */
1201
static struct sockaddr_in stunaddr;     /*!< stun server address */
1202
static uint16_t externtcpport;          /*!< external tcp port */ 
1202
static uint16_t externtcpport;          /*!< external tcp port */ 
1203
static uint16_t externtlsport;          /*!< external tls port */
1203
static uint16_t externtlsport;          /*!< external tls port */
1204

    
   
1204

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

    
   
1212

   
1213
static int ourport_tcp;             /*!< The port used for TCP connections */
1213
static int ourport_tcp;             /*!< The port used for TCP connections */
1214
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1214
static int ourport_tls;             /*!< The port used for TCP/TLS connections */
1215
static struct sockaddr_in debugaddr;
1215
static struct sockaddr_in debugaddr;
1216

    
   
1216

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

    
   
1218

   
1219
/*! some list management macros. */
1219
/*! some list management macros. */
1220

    
   
1220

   
1221
#define UNLINK(element, head, prev) do {	\
1221
#define UNLINK(element, head, prev) do {	\
1222
	if (prev)				\
1222
	if (prev)				\
1223
		(prev)->next = (element)->next;	\
1223
		(prev)->next = (element)->next;	\
1224
	else					\
1224
	else					\
1225
		(head) = (element)->next;	\
1225
		(head) = (element)->next;	\
1226
	} while (0)
1226
	} while (0)
1227

    
   
1227

   
1228
/*---------------------------- Forward declarations of functions in chan_sip.c */
1228
/*---------------------------- Forward declarations of functions in chan_sip.c */
1229
/* Note: This is added to help splitting up chan_sip.c into several files
1229
/* Note: This is added to help splitting up chan_sip.c into several files
1230
	in coming releases. */
1230
	in coming releases. */
1231

    
   
1231

   
1232
/*--- PBX interface functions */
1232
/*--- PBX interface functions */
1233
static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1233
static struct ast_channel *sip_request_call(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
1234
static int sip_devicestate(void *data);
1234
static int sip_devicestate(void *data);
1235
static int sip_sendtext(struct ast_channel *ast, const char *text);
1235
static int sip_sendtext(struct ast_channel *ast, const char *text);
1236
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1236
static int sip_call(struct ast_channel *ast, char *dest, int timeout);
1237
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1237
static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
1238
static int sip_hangup(struct ast_channel *ast);
1238
static int sip_hangup(struct ast_channel *ast);
1239
static int sip_answer(struct ast_channel *ast);
1239
static int sip_answer(struct ast_channel *ast);
1240
static struct ast_frame *sip_read(struct ast_channel *ast);
1240
static struct ast_frame *sip_read(struct ast_channel *ast);
1241
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1241
static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
1242
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1242
static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
1243
static int sip_transfer(struct ast_channel *ast, const char *dest);
1243
static int sip_transfer(struct ast_channel *ast, const char *dest);
1244
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1244
static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1245
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1245
static int sip_senddigit_begin(struct ast_channel *ast, char digit);
1246
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1246
static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
1247
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1247
static int sip_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1248
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1248
static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1249
static const char *sip_get_callid(struct ast_channel *chan);
1249
static const char *sip_get_callid(struct ast_channel *chan);
1250

    
   
1250

   
1251
static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1251
static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
1252
static int sip_standard_port(enum sip_transport type, int port);
1252
static int sip_standard_port(enum sip_transport type, int port);
1253
static int sip_prepare_socket(struct sip_pvt *p);
1253
static int sip_prepare_socket(struct sip_pvt *p);
1254

    
   
1254

   
1255
/*--- Transmitting responses and requests */
1255
/*--- Transmitting responses and requests */
1256
static int sipsock_read(int *id, int fd, short events, void *ignore);
1256
static int sipsock_read(int *id, int fd, short events, void *ignore);
1257
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1257
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
1258
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1258
static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
1259
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1259
static void add_cc_call_info_to_response(struct sip_pvt *p, struct sip_request *resp);
1260
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1260
static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1261
static int retrans_pkt(const void *data);
1261
static int retrans_pkt(const void *data);
1262
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1262
static int transmit_response_using_temp(ast_string_field callid, struct sockaddr_in *sin, int useglobal_nat, const int intended_method, const struct sip_request *req, const char *msg);
1263
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1263
static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1264
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1264
static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1265
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1265
static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
1266
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);
1266
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);
1267
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1267
static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
1268
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);
1268
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);
1269
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1269
static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
1270
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1270
static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
1271
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1271
static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
1272
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1272
static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
1273
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1273
static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
1274
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1274
static int transmit_publish(struct sip_epa_entry *epa_entry, enum sip_publish_type publish_type, const char * const explicit_uri);
1275
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1275
static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init, const char * const explicit_uri);
1276
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1276
static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
1277
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1277
static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
1278
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1278
static int transmit_info_with_vidupdate(struct sip_pvt *p);
1279
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1279
static int transmit_message_with_text(struct sip_pvt *p, const char *text);
1280
static int transmit_refer(struct sip_pvt *p, const char *dest);
1280
static int transmit_refer(struct sip_pvt *p, const char *dest);
1281
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1281
static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, const char *vmexten);
1282
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1282
static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
1283
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1283
static int transmit_cc_notify(struct ast_cc_agent *agent, struct sip_pvt *subscription, enum sip_cc_notify_state state);
1284
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1284
static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
1285
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1285
static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1286
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1286
static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
1287
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1287
static void copy_request(struct sip_request *dst, const struct sip_request *src);
1288
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1288
static void receive_message(struct sip_pvt *p, struct sip_request *req);
1289
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1289
static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req, char **name, char **number, int set_call_forward);
1290
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1290
static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
1291

    
   
1291

   
1292
/* Misc dialog routines */
1292
/* Misc dialog routines */
1293
static int __sip_autodestruct(const void *data);
1293
static int __sip_autodestruct(const void *data);
1294
static void *registry_unref(struct sip_registry *reg, char *tag);
1294
static void *registry_unref(struct sip_registry *reg, char *tag);
1295
static int update_call_counter(struct sip_pvt *fup, int event);
1295
static int update_call_counter(struct sip_pvt *fup, int event);
1296
static int auto_congest(const void *arg);
1296
static int auto_congest(const void *arg);
1297
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1297
static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
1298
static void free_old_route(struct sip_route *route);
1298
static void free_old_route(struct sip_route *route);
1299
static void list_route(struct sip_route *route);
1299
static void list_route(struct sip_route *route);
1300
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1300
static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
1301
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1301
static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
1302
					      struct sip_request *req, const char *uri);
1302
					      struct sip_request *req, const char *uri);
1303
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1303
static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
1304
static void check_pendings(struct sip_pvt *p);
1304
static void check_pendings(struct sip_pvt *p);
1305
static void *sip_park_thread(void *stuff);
1305
static void *sip_park_thread(void *stuff);
1306
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1306
static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
1307
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1307
static int sip_sipredirect(struct sip_pvt *p, const char *dest);
1308
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1308
static int is_method_allowed(unsigned int *allowed_methods, enum sipmethod method);
1309

    
   
1309

   
1310
/*--- Codec handling / SDP */
1310
/*--- Codec handling / SDP */
1311
static void try_suggested_sip_codec(struct sip_pvt *p);
1311
static void try_suggested_sip_codec(struct sip_pvt *p);
1312
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1312
static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
1313
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1313
static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
1314
static int find_sdp(struct sip_request *req);
1314
static int find_sdp(struct sip_request *req);
1315
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1315
static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
1316
static int process_sdp_o(const char *o, struct sip_pvt *p);
1316
static int process_sdp_o(const char *o, struct sip_pvt *p);
1317
static int process_sdp_c(const char *c, struct ast_hostent *hp);
1317
static int process_sdp_c(const char *c, struct ast_hostent *hp);
1318
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1318
static int process_sdp_a_sendonly(const char *a, int *sendonly);
1319
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1319
static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newaudiortp, int *last_rtpmap_codec);
1320
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1320
static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp_codecs *newvideortp, int *last_rtpmap_codec);
1321
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);
1321
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);
1322
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1322
static int process_sdp_a_image(const char *a, struct sip_pvt *p);
1323
static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1323
static void add_codec_to_sdp(const struct sip_pvt *p, format_t codec,
1324
			     struct ast_str **m_buf, struct ast_str **a_buf,
1324
			     struct ast_str **m_buf, struct ast_str **a_buf,
1325
			     int debug, int *min_packet_size);
1325
			     int debug, int *min_packet_size);
1326
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1326
static void add_noncodec_to_sdp(const struct sip_pvt *p, int format,
1327
				struct ast_str **m_buf, struct ast_str **a_buf,
1327
				struct ast_str **m_buf, struct ast_str **a_buf,
1328
				int debug);
1328
				int debug);
1329
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1329
static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
1330
static void do_setnat(struct sip_pvt *p);
1330
static void do_setnat(struct sip_pvt *p);
1331
static void stop_media_flows(struct sip_pvt *p);
1331
static void stop_media_flows(struct sip_pvt *p);
1332

    
   
1332

   
1333
/*--- Authentication stuff */
1333
/*--- Authentication stuff */
1334
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1334
static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
1335
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1335
static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
1336
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1336
static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
1337
					 const char *secret, const char *md5secret, int sipmethod,
1337
					 const char *secret, const char *md5secret, int sipmethod,
1338
					 const char *uri, enum xmittype reliable, int ignore);
1338
					 const char *uri, enum xmittype reliable, int ignore);
1339
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1339
static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
1340
					      int sipmethod, const char *uri, enum xmittype reliable,
1340
					      int sipmethod, const char *uri, enum xmittype reliable,
1341
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
1341
					      struct sockaddr_in *sin, struct sip_peer **authpeer);
1342
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1342
static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, const char *uri, enum xmittype reliable, struct sockaddr_in *sin);
1343

    
   
1343

   
1344
/*--- Domain handling */
1344
/*--- Domain handling */
1345
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1345
static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
1346
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1346
static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
1347
static void clear_sip_domains(void);
1347
static void clear_sip_domains(void);
1348

    
   
1348

   
1349
/*--- SIP realm authentication */
1349
/*--- SIP realm authentication */
1350
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1350
static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
1351
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1351
static int clear_realm_authentication(struct sip_auth *authlist);	/* Clear realm authentication list (at reload) */
1352
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1352
static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
1353

    
   
1353

   
1354
/*--- Misc functions */
1354
/*--- Misc functions */
1355
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1355
static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
1356
static int sip_do_reload(enum channelreloadreason reason);
1356
static int sip_do_reload(enum channelreloadreason reason);
1357
static int reload_config(enum channelreloadreason reason);
1357
static int reload_config(enum channelreloadreason reason);
1358
static int expire_register(const void *data);
1358
static int expire_register(const void *data);
1359
static void *do_monitor(void *data);
1359
static void *do_monitor(void *data);
1360
static int restart_monitor(void);
1360
static int restart_monitor(void);
1361
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1361
static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
1362
static struct ast_variable *copy_vars(struct ast_variable *src);
1362
static struct ast_variable *copy_vars(struct ast_variable *src);
1363
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1363
/* static int sip_addrcmp(char *name, struct sockaddr_in *sin);	Support for peer matching */
1364
static int sip_refer_allocate(struct sip_pvt *p);
1364
static int sip_refer_allocate(struct sip_pvt *p);
1365
static int sip_notify_allocate(struct sip_pvt *p);
1365
static int sip_notify_allocate(struct sip_pvt *p);
1366
static void ast_quiet_chan(struct ast_channel *chan);
1366
static void ast_quiet_chan(struct ast_channel *chan);
1367
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1367
static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
1368
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1368
static int do_magic_pickup(struct ast_channel *channel, const char *extension, const char *context);
1369

    
   
1369

   
1370
/*--- Device monitoring and Device/extension state/event handling */
1370
/*--- Device monitoring and Device/extension state/event handling */
1371
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1371
static int cb_extensionstate(char *context, char* exten, int state, void *data);
1372
static int sip_devicestate(void *data);
1372
static int sip_devicestate(void *data);
1373
static int sip_poke_noanswer(const void *data);
1373
static int sip_poke_noanswer(const void *data);
1374
static int sip_poke_peer(struct sip_peer *peer, int force);
1374
static int sip_poke_peer(struct sip_peer *peer, int force);
1375
static void sip_poke_all_peers(void);
1375
static void sip_poke_all_peers(void);
1376
static void sip_peer_hold(struct sip_pvt *p, int hold);
1376
static void sip_peer_hold(struct sip_pvt *p, int hold);
1377
static void mwi_event_cb(const struct ast_event *, void *);
1377
static void mwi_event_cb(const struct ast_event *, void *);
1378

    
   
1378

   
1379
/*--- Applications, functions, CLI and manager command helpers */
1379
/*--- Applications, functions, CLI and manager command helpers */
1380
static const char *sip_nat_mode(const struct sip_pvt *p);
1380
static const char *sip_nat_mode(const struct sip_pvt *p);
1381
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1381
static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1382
static char *transfermode2str(enum transfermodes mode) attribute_const;
1382
static char *transfermode2str(enum transfermodes mode) attribute_const;
1383
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1383
static int peer_status(struct sip_peer *peer, char *status, int statuslen);
1384
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1384
static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1385
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1385
static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1386
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1386
static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1387
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1387
static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1388
static void  print_group(int fd, ast_group_t group, int crlf);
1388
static void  print_group(int fd, ast_group_t group, int crlf);
1389
static const char *dtmfmode2str(int mode) attribute_const;
1389
static const char *dtmfmode2str(int mode) attribute_const;
1390
static int str2dtmfmode(const char *str) attribute_unused;
1390
static int str2dtmfmode(const char *str) attribute_unused;
1391
static const char *insecure2str(int mode) attribute_const;
1391
static const char *insecure2str(int mode) attribute_const;
1392
static void cleanup_stale_contexts(char *new, char *old);
1392
static void cleanup_stale_contexts(char *new, char *old);
1393
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1393
static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
1394
static const char *domain_mode_to_text(const enum domain_mode mode);
1394
static const char *domain_mode_to_text(const enum domain_mode mode);
1395
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1395
static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1396
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1396
static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1397
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1397
static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1398
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1398
static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
1399
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1399
static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1400
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1400
static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1401
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1401
static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1402
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1402
static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1403
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1403
static char *sip_show_mwi(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1404
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1404
static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
1405
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1405
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1406
static char *complete_sip_peer(const char *word, int state, int flags2);
1406
static char *complete_sip_peer(const char *word, int state, int flags2);
1407
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1407
static char *complete_sip_registered_peer(const char *word, int state, int flags2);
1408
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1408
static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
1409
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1409
static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
1410
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1410
static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
1411
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1411
static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
1412
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1412
static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1413
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1413
static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1414
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1414
static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1415
static char *sip_do_debug_ip(int fd, const char *arg);
1415
static char *sip_do_debug_ip(int fd, const char *arg);
1416
static char *sip_do_debug_peer(int fd, const char *arg);
1416
static char *sip_do_debug_peer(int fd, const char *arg);
1417
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1417
static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1418
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1418
static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1419
static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1420
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1420
static int sip_dtmfmode(struct ast_channel *chan, const char *data);
1421
static int sip_addheader(struct ast_channel *chan, const char *data);
1421
static int sip_addheader(struct ast_channel *chan, const char *data);
1422
static int sip_do_reload(enum channelreloadreason reason);
1422
static int sip_do_reload(enum channelreloadreason reason);
1423
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1423
static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1424

    
   
1424

   
1425
/*--- Debugging
1425
/*--- Debugging
1426
	Functions for enabling debug per IP or fully, or enabling history logging for
1426
	Functions for enabling debug per IP or fully, or enabling history logging for
1427
	a SIP dialog
1427
	a SIP dialog
1428
*/
1428
*/
1429
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1429
static void sip_dump_history(struct sip_pvt *dialog);	/* Dump history to debuglog at end of dialog, before destroying data */
1430
static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1430
static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
1431
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1431
static inline int sip_debug_test_pvt(struct sip_pvt *p);
1432
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1432
static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
1433
static void sip_dump_history(struct sip_pvt *dialog);
1433
static void sip_dump_history(struct sip_pvt *dialog);
1434

    
   
1434

   
1435
/*--- Device object handling */
1435
/*--- Device object handling */
1436
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1436
static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
1437
static int update_call_counter(struct sip_pvt *fup, int event);
1437
static int update_call_counter(struct sip_pvt *fup, int event);
1438
static void sip_destroy_peer(struct sip_peer *peer);
1438
static void sip_destroy_peer(struct sip_peer *peer);
1439
static void sip_destroy_peer_fn(void *peer);
1439
static void sip_destroy_peer_fn(void *peer);
1440
static void set_peer_defaults(struct sip_peer *peer);
1440
static void set_peer_defaults(struct sip_peer *peer);
1441
static struct sip_peer *temp_peer(const char *name);
1441
static struct sip_peer *temp_peer(const char *name);
1442
static void register_peer_exten(struct sip_peer *peer, int onoff);
1442
static void register_peer_exten(struct sip_peer *peer, int onoff);
1443
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1443
static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int forcenamematch, int devstate_only, int transport);
1444
static int sip_poke_peer_s(const void *data);
1444
static int sip_poke_peer_s(const void *data);
1445
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1445
static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
1446
static void reg_source_db(struct sip_peer *peer);
1446
static void reg_source_db(struct sip_peer *peer);
1447
static void destroy_association(struct sip_peer *peer);
1447
static void destroy_association(struct sip_peer *peer);
1448
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1448
static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
1449
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1449
static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
1450
static void set_socket_transport(struct sip_socket *socket, int transport);
1450
static void set_socket_transport(struct sip_socket *socket, int transport);
1451

    
   
1451

   
1452
/* Realtime device support */
1452
/* Realtime device support */
1453
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1453
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, const char *username, const char *fullcontact, const char *useragent, int expirey, unsigned short deprecated_username, int lastms);
1454
static void update_peer(struct sip_peer *p, int expire);
1454
static void update_peer(struct sip_peer *p, int expire);
1455
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1455
static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
1456
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1456
static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
1457
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1457
static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
1458
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1458
static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
1459

    
   
1459

   
1460
/*--- Internal UA client handling (outbound registrations) */
1460
/*--- Internal UA client handling (outbound registrations) */
1461
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1461
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
1462
static void sip_registry_destroy(struct sip_registry *reg);
1462
static void sip_registry_destroy(struct sip_registry *reg);
1463
static int sip_register(const char *value, int lineno);
1463
static int sip_register(const char *value, int lineno);
1464
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1464
static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
1465
static int sip_reregister(const void *data);
1465
static int sip_reregister(const void *data);
1466
static int __sip_do_register(struct sip_registry *r);
1466
static int __sip_do_register(struct sip_registry *r);
1467
static int sip_reg_timeout(const void *data);
1467
static int sip_reg_timeout(const void *data);
1468
static void sip_send_all_registers(void);
1468
static void sip_send_all_registers(void);
1469
static int sip_reinvite_retry(const void *data);
1469
static int sip_reinvite_retry(const void *data);
1470

    
   
1470

   
1471
/*--- Parsing SIP requests and responses */
1471
/*--- Parsing SIP requests and responses */
1472
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1472
static void append_date(struct sip_request *req);	/* Append date to SIP packet */
1473
static int determine_firstline_parts(struct sip_request *req);
1473
static int determine_firstline_parts(struct sip_request *req);
1474
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1474
static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
1475
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1475
static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
1476
static int find_sip_method(const char *msg);
1476
static int find_sip_method(const char *msg);
1477
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1477
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
1478
static unsigned int parse_allowed_methods(struct sip_request *req);
1478
static unsigned int parse_allowed_methods(struct sip_request *req);
1479
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1479
static unsigned int set_pvt_allowed_methods(struct sip_pvt *pvt, struct sip_request *req);
1480
static int parse_request(struct sip_request *req);
1480
static int parse_request(struct sip_request *req);
1481
static const char *get_header(const struct sip_request *req, const char *name);
1481
static const char *get_header(const struct sip_request *req, const char *name);
1482
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1482
static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
1483
static int method_match(enum sipmethod id, const char *name);
1483
static int method_match(enum sipmethod id, const char *name);
1484
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1484
static void parse_copy(struct sip_request *dst, const struct sip_request *src);
1485
static const char *find_alias(const char *name, const char *_default);
1485
static const char *find_alias(const char *name, const char *_default);
1486
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1486
static const char *__get_header(const struct sip_request *req, const char *name, int *start);
1487
static int lws2sws(char *msgbuf, int len);
1487
static int lws2sws(char *msgbuf, int len);
1488
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1488
static void extract_uri(struct sip_pvt *p, struct sip_request *req);
1489
static char *remove_uri_parameters(char *uri);
1489
static char *remove_uri_parameters(char *uri);
1490
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1490
static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
1491
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1491
static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
1492
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1492
static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
1493
static int set_address_from_contact(struct sip_pvt *pvt);
1493
static int set_address_from_contact(struct sip_pvt *pvt);
1494
static void check_via(struct sip_pvt *p, struct sip_request *req);
1494
static void check_via(struct sip_pvt *p, struct sip_request *req);
1495
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1495
static int get_rpid(struct sip_pvt *p, struct sip_request *oreq);
1496
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1496
static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq, char **name, char **number, int *reason);
1497
static int get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1497
static int get_destination(struct sip_pvt *p, struct sip_request *oreq, int *cc_recall_core_id);
1498
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1498
static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
1499
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1499
static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
1500
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1500
static void update_connectedline(struct sip_pvt *p, const void *data, size_t datalen);
1501
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1501
static void update_redirecting(struct sip_pvt *p, const void *data, size_t datalen);
1502
static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
1502
static void change_redirecting_information(struct sip_pvt *p, struct sip_request *req, struct ast_party_redirecting *redirecting, int set_call_forward);
1503
static int get_domain(const char *str, char *domain, int len);
1503
static int get_domain(const char *str, char *domain, int len);
1504
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1504
static void get_realm(struct sip_pvt *p, const struct sip_request *req);
1505

    
   
1505

   
1506
/*-- TCP connection handling ---*/
1506
/*-- TCP connection handling ---*/
1507
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1507
static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
1508
static void *sip_tcp_worker_fn(void *);
1508
static void *sip_tcp_worker_fn(void *);
1509

    
   
1509

   
1510
/*--- Constructing requests and responses */
1510
/*--- Constructing requests and responses */
1511
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1511
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
1512
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1512
static int init_req(struct sip_request *req, int sipmethod, const char *recip);
1513
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1513
static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
1514
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1514
static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, const char * const explicit_uri);
1515
static int init_resp(struct sip_request *resp, const char *msg);
1515
static int init_resp(struct sip_request *resp, const char *msg);
1516
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1516
static inline int resp_needs_contact(const char *msg, enum sipmethod method);
1517
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1517
static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
1518
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1518
static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
1519
static void build_via(struct sip_pvt *p);
1519
static void build_via(struct sip_pvt *p);
1520
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1520
static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
1521
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog, struct sockaddr_in *remote_address);
1521
static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog, struct sockaddr_in *remote_address);
1522
static char *generate_random_string(char *buf, size_t size);
1522
static char *generate_random_string(char *buf, size_t size);
1523
static void build_callid_pvt(struct sip_pvt *pvt);
1523
static void build_callid_pvt(struct sip_pvt *pvt);
1524
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1524
static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
1525
static void make_our_tag(char *tagbuf, size_t len);
1525
static void make_our_tag(char *tagbuf, size_t len);
1526
static int add_header(struct sip_request *req, const char *var, const char *value);
1526
static int add_header(struct sip_request *req, const char *var, const char *value);
1527
static int add_header_contentLength(struct sip_request *req, int len);
1527
static int add_header_contentLength(struct sip_request *req, int len);
1528
static int add_line(struct sip_request *req, const char *line);
1528
static int add_line(struct sip_request *req, const char *line);
1529
static int add_text(struct sip_request *req, const char *text);
1529
static int add_text(struct sip_request *req, const char *text);
1530
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1530
static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
1531
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1531
static int add_rpid(struct sip_request *req, struct sip_pvt *p);
1532
static int add_vidupdate(struct sip_request *req);
1532
static int add_vidupdate(struct sip_request *req);
1533
static void add_route(struct sip_request *req, struct sip_route *route);
1533
static void add_route(struct sip_request *req, struct sip_route *route);
1534
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1534
static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1535
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1535
static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
1536
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1536
static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
1537
static void set_destination(struct sip_pvt *p, char *uri);
1537
static void set_destination(struct sip_pvt *p, char *uri);
1538
static void append_date(struct sip_request *req);
1538
static void append_date(struct sip_request *req);
1539
static void build_contact(struct sip_pvt *p);
1539
static void build_contact(struct sip_pvt *p);
1540

    
   
1540

   
1541
/*------Request handling functions */
1541
/*------Request handling functions */
1542
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1542
static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
1543
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1543
static int handle_request_update(struct sip_pvt *p, struct sip_request *req);
1544
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, const char *e, int *nounlock);
1544
static int handle_request_invite(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *recount, const char *e, int *nounlock);
1545
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1545
static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
1546
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1546
static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
1547
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1547
static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, const char *e);
1548
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1548
static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
1549
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1549
static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
1550
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1550
static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1551
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1551
static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
1552
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1552
static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
1553
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1553
static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
1554
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1554
static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, const char *e);
1555
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1555
static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno, int *nounlock);
1556

    
   
1556

   
1557
/*------Response handling functions */
1557
/*------Response handling functions */
1558
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1558
static void handle_response_publish(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1559
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1559
static void handle_response_invite(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1560
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1560
static void handle_response_notify(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1561
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1561
static void handle_response_refer(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1562
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1562
static void handle_response_subscribe(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1563
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1563
static int handle_response_register(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1564
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1564
static void handle_response(struct sip_pvt *p, int resp, const char *rest, struct sip_request *req, int seqno);
1565

    
   
1565

   
1566
/*------ T38 Support --------- */
1566
/*------ T38 Support --------- */
1567
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1567
static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
1568
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1568
static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
1569
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1569
static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
1570
static void change_t38_state(struct sip_pvt *p, int state);
1570
static void change_t38_state(struct sip_pvt *p, int state);
1571

    
   
1571

   
1572
/*------ Session-Timers functions --------- */
1572
/*------ Session-Timers functions --------- */
1573
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1573
static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
1574
static int  proc_session_timer(const void *vp);
1574
static int  proc_session_timer(const void *vp);
1575
static void stop_session_timer(struct sip_pvt *p);
1575
static void stop_session_timer(struct sip_pvt *p);
1576
static void start_session_timer(struct sip_pvt *p);
1576
static void start_session_timer(struct sip_pvt *p);
1577
static void restart_session_timer(struct sip_pvt *p);
1577
static void restart_session_timer(struct sip_pvt *p);
1578
static const char *strefresher2str(enum st_refresher r);
1578
static const char *strefresher2str(enum st_refresher r);
1579
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1579
static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
1580
static int parse_minse(const char *p_hdrval, int *const p_interval);
1580
static int parse_minse(const char *p_hdrval, int *const p_interval);
1581
static int st_get_se(struct sip_pvt *, int max);
1581
static int st_get_se(struct sip_pvt *, int max);
1582
static enum st_refresher st_get_refresher(struct sip_pvt *);
1582
static enum st_refresher st_get_refresher(struct sip_pvt *);
1583
static enum st_mode st_get_mode(struct sip_pvt *);
1583
static enum st_mode st_get_mode(struct sip_pvt *);
1584
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1584
static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
1585

    
   
1585

   
1586
/*------- RTP Glue functions -------- */
1586
/*------- RTP Glue functions -------- */
1587
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, format_t codecs, int nat_active);
1587
static int sip_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *instance, struct ast_rtp_instance *vinstance, struct ast_rtp_instance *tinstance, format_t codecs, int nat_active);
1588

    
   
1588

   
1589
/*!--- SIP MWI Subscription support */
1589
/*!--- SIP MWI Subscription support */
1590
static int sip_subscribe_mwi(const char *value, int lineno);
1590
static int sip_subscribe_mwi(const char *value, int lineno);
1591
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1591
static void sip_subscribe_mwi_destroy(struct sip_subscription_mwi *mwi);
1592
static void sip_send_all_mwi_subscriptions(void);
1592
static void sip_send_all_mwi_subscriptions(void);
1593
static int sip_subscribe_mwi_do(const void *data);
1593
static int sip_subscribe_mwi_do(const void *data);
1594
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1594
static int __sip_subscribe_mwi_do(struct sip_subscription_mwi *mwi);
1595

    
   
1595

   
1596
/*! \brief Definition of this channel for PBX channel registration */
1596
/*! \brief Definition of this channel for PBX channel registration */
1597
const struct ast_channel_tech sip_tech = {
1597
const struct ast_channel_tech sip_tech = {
1598
	.type = "SIP",
1598
	.type = "SIP",
1599
	.description = "Session Initiation Protocol (SIP)",
1599
	.description = "Session Initiation Protocol (SIP)",
1600
	.capabilities = AST_FORMAT_AUDIO_MASK,	/* all audio formats */
1600
	.capabilities = AST_FORMAT_AUDIO_MASK,	/* all audio formats */
1601
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1601
	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
1602
	.requester = sip_request_call,			/* called with chan unlocked */
1602
	.requester = sip_request_call,			/* called with chan unlocked */
1603
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1603
	.devicestate = sip_devicestate,			/* called with chan unlocked (not chan-specific) */
1604
	.call = sip_call,			/* called with chan locked */
1604
	.call = sip_call,			/* called with chan locked */
1605
	.send_html = sip_sendhtml,
1605
	.send_html = sip_sendhtml,
1606
	.hangup = sip_hangup,			/* called with chan locked */
1606
	.hangup = sip_hangup,			/* called with chan locked */
1607
	.answer = sip_answer,			/* called with chan locked */
1607
	.answer = sip_answer,			/* called with chan locked */
1608
	.read = sip_read,			/* called with chan locked */
1608
	.read = sip_read,			/* called with chan locked */
1609
	.write = sip_write,			/* called with chan locked */
1609
	.write = sip_write,			/* called with chan locked */
1610
	.write_video = sip_write,		/* called with chan locked */
1610
	.write_video = sip_write,		/* called with chan locked */
1611
	.write_text = sip_write,
1611
	.write_text = sip_write,
1612
	.indicate = sip_indicate,		/* called with chan locked */
1612
	.indicate = sip_indicate,		/* called with chan locked */
1613
	.transfer = sip_transfer,		/* called with chan locked */
1613
	.transfer = sip_transfer,		/* called with chan locked */
1614
	.fixup = sip_fixup,			/* called with chan locked */
1614
	.fixup = sip_fixup,			/* called with chan locked */
1615
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1615
	.send_digit_begin = sip_senddigit_begin,	/* called with chan unlocked */
1616
	.send_digit_end = sip_senddigit_end,
1616
	.send_digit_end = sip_senddigit_end,
1617
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1617
	.bridge = ast_rtp_instance_bridge,			/* XXX chan unlocked ? */
1618
	.early_bridge = ast_rtp_instance_early_bridge,
1618
	.early_bridge = ast_rtp_instance_early_bridge,
1619
	.send_text = sip_sendtext,		/* called with chan locked */
1619
	.send_text = sip_sendtext,		/* called with chan locked */
1620
	.func_channel_read = sip_acf_channel_read,
1620
	.func_channel_read = sip_acf_channel_read,
1621
	.setoption = sip_setoption,
1621
	.setoption = sip_setoption,
1622
	.queryoption = sip_queryoption,
1622
	.queryoption = sip_queryoption,
1623
	.get_pvt_uniqueid = sip_get_callid,
1623
	.get_pvt_uniqueid = sip_get_callid,
1624
};
1624
};
1625

    
   
1625

   
1626
/*! \brief This version of the sip channel tech has no send_digit_begin
1626
/*! \brief This version of the sip channel tech has no send_digit_begin
1627
 * callback so that the core knows that the channel does not want
1627
 * callback so that the core knows that the channel does not want
1628
 * DTMF BEGIN frames.
1628
 * DTMF BEGIN frames.
1629
 * The struct is initialized just before registering the channel driver,
1629
 * The struct is initialized just before registering the channel driver,
1630
 * and is for use with channels using SIP INFO DTMF.
1630
 * and is for use with channels using SIP INFO DTMF.
1631
 */
1631
 */
1632
struct ast_channel_tech sip_tech_info;
1632
struct ast_channel_tech sip_tech_info;
1633

    
   
1633

   
1634
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1634
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan);
1635
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1635
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent);
1636
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1636
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent);
1637
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1637
static void sip_cc_agent_ack(struct ast_cc_agent *agent);
1638
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1638
static int sip_cc_agent_status_request(struct ast_cc_agent *agent);
1639
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1639
static int sip_cc_agent_start_monitoring(struct ast_cc_agent *agent);
1640
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1640
static int sip_cc_agent_recall(struct ast_cc_agent *agent);
1641
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1641
static void sip_cc_agent_destructor(struct ast_cc_agent *agent);
1642

    
   
1642

   
1643
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1643
static struct ast_cc_agent_callbacks sip_cc_agent_callbacks = {
1644
	.type = "SIP",
1644
	.type = "SIP",
1645
	.init = sip_cc_agent_init,
1645
	.init = sip_cc_agent_init,
1646
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1646
	.start_offer_timer = sip_cc_agent_start_offer_timer,
1647
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1647
	.stop_offer_timer = sip_cc_agent_stop_offer_timer,
1648
	.ack = sip_cc_agent_ack,
1648
	.ack = sip_cc_agent_ack,
1649
	.status_request = sip_cc_agent_status_request,
1649
	.status_request = sip_cc_agent_status_request,
1650
	.start_monitoring = sip_cc_agent_start_monitoring,
1650
	.start_monitoring = sip_cc_agent_start_monitoring,
1651
	.callee_available = sip_cc_agent_recall,
1651
	.callee_available = sip_cc_agent_recall,
1652
	.destructor = sip_cc_agent_destructor,
1652
	.destructor = sip_cc_agent_destructor,
1653
};
1653
};
1654

    
   
1654

   
1655
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1655
static int find_by_notify_uri_helper(void *obj, void *arg, int flags)
1656
{
1656
{
1657
	struct ast_cc_agent *agent = obj;
1657
	struct ast_cc_agent *agent = obj;
1658
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1658
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1659
	const char *uri = arg;
1659
	const char *uri = arg;
1660

    
   
1660

   
1661
	return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1661
	return !strcmp(agent_pvt->notify_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1662
}
1662
}
1663

    
   
1663

   
1664
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1664
static struct ast_cc_agent *find_sip_cc_agent_by_notify_uri(const char * const uri)
1665
{
1665
{
1666
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1666
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_notify_uri_helper, (char *)uri, "SIP");
1667
	return agent;
1667
	return agent;
1668
}
1668
}
1669

    
   
1669

   
1670
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1670
static int find_by_subscribe_uri_helper(void *obj, void *arg, int flags)
1671
{
1671
{
1672
	struct ast_cc_agent *agent = obj;
1672
	struct ast_cc_agent *agent = obj;
1673
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1673
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1674
	const char *uri = arg;
1674
	const char *uri = arg;
1675

    
   
1675

   
1676
	return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1676
	return !strcmp(agent_pvt->subscribe_uri, uri) ? CMP_MATCH | CMP_STOP : 0;
1677
}
1677
}
1678

    
   
1678

   
1679
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1679
static struct ast_cc_agent *find_sip_cc_agent_by_subscribe_uri(const char * const uri)
1680
{
1680
{
1681
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1681
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_subscribe_uri_helper, (char *)uri, "SIP");
1682
	return agent;
1682
	return agent;
1683
}
1683
}
1684

    
   
1684

   
1685
static int find_by_callid_helper(void *obj, void *arg, int flags)
1685
static int find_by_callid_helper(void *obj, void *arg, int flags)
1686
{
1686
{
1687
	struct ast_cc_agent *agent = obj;
1687
	struct ast_cc_agent *agent = obj;
1688
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1688
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1689
	struct sip_pvt *call_pvt = arg;
1689
	struct sip_pvt *call_pvt = arg;
1690

    
   
1690

   
1691
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1691
	return !strcmp(agent_pvt->original_callid, call_pvt->callid) ? CMP_MATCH | CMP_STOP : 0;
1692
}
1692
}
1693

    
   
1693

   
1694
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1694
static struct ast_cc_agent *find_sip_cc_agent_by_original_callid(struct sip_pvt *pvt)
1695
{
1695
{
1696
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1696
	struct ast_cc_agent *agent = ast_cc_agent_callback(0, find_by_callid_helper, pvt, "SIP");
1697
	return agent;
1697
	return agent;
1698
}
1698
}
1699

    
   
1699

   
1700
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1700
static int sip_cc_agent_init(struct ast_cc_agent *agent, struct ast_channel *chan)
1701
{
1701
{
1702
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1702
	struct sip_cc_agent_pvt *agent_pvt = ast_calloc(1, sizeof(*agent_pvt));
1703
	struct sip_pvt *call_pvt = chan->tech_pvt;
1703
	struct sip_pvt *call_pvt = chan->tech_pvt;
1704

    
   
1704

   
1705
	if (!agent_pvt) {
1705
	if (!agent_pvt) {
1706
		return -1;
1706
		return -1;
1707
	}
1707
	}
1708

    
   
1708

   
1709
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1709
	ast_assert(!strcmp(chan->tech->type, "SIP"));
1710

    
   
1710

   
1711
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1711
	ast_copy_string(agent_pvt->original_callid, call_pvt->callid, sizeof(agent_pvt->original_callid));
1712
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1712
	ast_copy_string(agent_pvt->original_exten, call_pvt->exten, sizeof(agent_pvt->original_exten));
1713
	agent_pvt->offer_timer_id = -1;
1713
	agent_pvt->offer_timer_id = -1;
1714
	agent->private_data = agent_pvt;
1714
	agent->private_data = agent_pvt;
1715
	sip_pvt_lock(call_pvt);
1715
	sip_pvt_lock(call_pvt);
1716
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1716
	ast_set_flag(&call_pvt->flags[0], SIP_OFFER_CC);
1717
	sip_pvt_unlock(call_pvt);
1717
	sip_pvt_unlock(call_pvt);
1718
	return 0;
1718
	return 0;
1719
}
1719
}
1720

    
   
1720

   
1721
static int sip_offer_timer_expire(const void *data)
1721
static int sip_offer_timer_expire(const void *data)
1722
{
1722
{
1723
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1723
	struct ast_cc_agent *agent = (struct ast_cc_agent *) data;
1724
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1724
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1725

    
   
1725

   
1726
	agent_pvt->offer_timer_id = -1;
1726
	agent_pvt->offer_timer_id = -1;
1727

    
   
1727

   
1728
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1728
	return ast_cc_failed(agent->core_id, "SIP agent %s's offer timer expired", agent->device_name);
1729
}
1729
}
1730

    
   
1730

   
1731
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1731
static int sip_cc_agent_start_offer_timer(struct ast_cc_agent *agent)
1732
{
1732
{
1733
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1733
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1734
	int when;
1734
	int when;
1735

    
   
1735

   
1736
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1736
	when = ast_get_cc_offer_timer(agent->cc_params) * 1000;
1737
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1737
	agent_pvt->offer_timer_id = ast_sched_add(sched, when, sip_offer_timer_expire, agent);
1738
	return 0;
1738
	return 0;
1739
}
1739
}
1740

    
   
1740

   
1741
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1741
static int sip_cc_agent_stop_offer_timer(struct ast_cc_agent *agent)
1742
{
1742
{
1743
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1743
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1744

    
   
1744

   
1745
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1745
	AST_SCHED_DEL(sched, agent_pvt->offer_timer_id);
1746
	return 0;
1746
	return 0;
1747
}
1747
}
1748

    
   
1748

   
1749
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1749
static void sip_cc_agent_ack(struct ast_cc_agent *agent)
1750
{
1750
{
1751
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1751
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1752

    
   
1752

   
1753
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1753
	sip_pvt_lock(agent_pvt->subscribe_pvt);
1754
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1754
	ast_set_flag(&agent_pvt->subscribe_pvt->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
1755
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1755
	transmit_response(agent_pvt->subscribe_pvt, "200 OK", &agent_pvt->subscribe_pvt->initreq);
1756
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1756
	transmit_cc_notify(agent, agent_pvt->subscribe_pvt, CC_QUEUED);
1757
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1757
	sip_pvt_unlock(agent_pvt->subscribe_pvt);
1758
	agent_pvt->is_available = TRUE;
1758
	agent_pvt->is_available = TRUE;
1759
}
1759
}
1760

    
   
1760

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

    
   
1767

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

    
   
1776

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

    
   
1796

   
1797
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1797
static void sip_cc_agent_destructor(struct ast_cc_agent *agent)
1798
{
1798
{
1799
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1799
	struct sip_cc_agent_pvt *agent_pvt = agent->private_data;
1800

    
   
1800

   
1801
	if (!agent_pvt) {
1801
	if (!agent_pvt) {
1802
		/* The agent constructor probably failed. */
1802
		/* The agent constructor probably failed. */
1803
		return;
1803
		return;
1804
	}
1804
	}
1805

    
   
1805

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

    
   
1820

   
1821
struct ao2_container *sip_monitor_instances;
1821
struct ao2_container *sip_monitor_instances;
1822

    
   
1822

   
1823
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1823
static int sip_monitor_instance_hash_fn(const void *obj, const int flags)
1824
{
1824
{
1825
	const struct sip_monitor_instance *monitor_instance = obj;
1825
	const struct sip_monitor_instance *monitor_instance = obj;
1826
	return monitor_instance->core_id;
1826
	return monitor_instance->core_id;
1827
}
1827
}
1828

    
   
1828

   
1829
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1829
static int sip_monitor_instance_cmp_fn(void *obj, void *arg, int flags)
1830
{
1830
{
1831
	struct sip_monitor_instance *monitor_instance1 = obj;
1831
	struct sip_monitor_instance *monitor_instance1 = obj;
1832
	struct sip_monitor_instance *monitor_instance2 = arg;
1832
	struct sip_monitor_instance *monitor_instance2 = arg;
1833

    
   
1833

   
1834
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1834
	return monitor_instance1->core_id == monitor_instance2->core_id ? CMP_MATCH | CMP_STOP : 0;
1835
}
1835
}
1836

    
   
1836

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

    
   
1854

   
1855
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)
1855
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)
1856
{
1856
{
1857
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1857
	struct sip_monitor_instance *monitor_instance = ao2_alloc(sizeof(*monitor_instance), sip_monitor_instance_destructor);
1858

    
   
1858

   
1859
	if (!monitor_instance) {
1859
	if (!monitor_instance) {
1860
		return NULL;
1860
		return NULL;
1861
	}
1861
	}
1862

    
   
1862

   
1863
	if (ast_string_field_init(monitor_instance, 256)) {
1863
	if (ast_string_field_init(monitor_instance, 256)) {
1864
		ao2_ref(monitor_instance, -1);
1864
		ao2_ref(monitor_instance, -1);
1865
		return NULL;
1865
		return NULL;
1866
	}
1866
	}
1867

    
   
1867

   
1868
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1868
	ast_string_field_set(monitor_instance, subscribe_uri, subscribe_uri);
1869
	ast_string_field_set(monitor_instance, peername, peername);
1869
	ast_string_field_set(monitor_instance, peername, peername);
1870
	ast_string_field_set(monitor_instance, device_name, device_name);
1870
	ast_string_field_set(monitor_instance, device_name, device_name);
1871
	monitor_instance->core_id = core_id;
1871
	monitor_instance->core_id = core_id;
1872
	ao2_link(sip_monitor_instances, monitor_instance);
1872
	ao2_link(sip_monitor_instances, monitor_instance);
1873
	return monitor_instance;
1873
	return monitor_instance;
1874
}
1874
}
1875

    
   
1875

   
1876
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1876
static int find_sip_monitor_instance_by_subscription_pvt(void *obj, void *arg, int flags)
1877
{
1877
{
1878
	struct sip_monitor_instance *monitor_instance = obj;
1878
	struct sip_monitor_instance *monitor_instance = obj;
1879
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1879
	return monitor_instance->subscription_pvt == arg ? CMP_MATCH | CMP_STOP : 0;
1880
}
1880
}
1881

    
   
1881

   
1882
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1882
static int find_sip_monitor_instance_by_suspension_entry(void *obj, void *arg, int flags)
1883
{
1883
{
1884
	struct sip_monitor_instance *monitor_instance = obj;
1884
	struct sip_monitor_instance *monitor_instance = obj;
1885
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1885
	return monitor_instance->suspension_entry == arg ? CMP_MATCH | CMP_STOP : 0;
1886
}
1886
}
1887

    
   
1887

   
1888
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1888
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id);
1889
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1889
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor);
1890
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1890
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor);
1891
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1891
static int sip_cc_monitor_cancel_available_timer(struct ast_cc_monitor *monitor, int *sched_id);
1892
static void sip_cc_monitor_destructor(void *private_data);
1892
static void sip_cc_monitor_destructor(void *private_data);
1893

    
   
1893

   
1894
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1894
static struct ast_cc_monitor_callbacks sip_cc_monitor_callbacks = {
1895
	.type = "SIP",
1895
	.type = "SIP",
1896
	.request_cc = sip_cc_monitor_request_cc,
1896
	.request_cc = sip_cc_monitor_request_cc,
1897
	.suspend = sip_cc_monitor_suspend,
1897
	.suspend = sip_cc_monitor_suspend,
1898
	.unsuspend = sip_cc_monitor_unsuspend,
1898
	.unsuspend = sip_cc_monitor_unsuspend,
1899
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1899
	.cancel_available_timer = sip_cc_monitor_cancel_available_timer,
1900
	.destructor = sip_cc_monitor_destructor,
1900
	.destructor = sip_cc_monitor_destructor,
1901
};
1901
};
1902

    
   
1902

   
1903
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1903
static int sip_cc_monitor_request_cc(struct ast_cc_monitor *monitor, int *available_timer_id)
1904
{
1904
{
1905
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1905
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1906
	enum ast_cc_service_type service = monitor->service_offered;
1906
	enum ast_cc_service_type service = monitor->service_offered;
1907
	int when;
1907
	int when;
1908

    
   
1908

   
1909
	if (!monitor_instance) {
1909
	if (!monitor_instance) {
1910
		return -1;
1910
		return -1;
1911
	}
1911
	}
1912

    
   
1912

   
1913
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1913
	if (!(monitor_instance->subscription_pvt = sip_alloc(NULL, NULL, 0, SIP_SUBSCRIBE, NULL))) {
1914
		return -1;
1914
		return -1;
1915
	}
1915
	}
1916

    
   
1916

   
1917
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1917
	when = service == AST_CC_CCBS ? ast_get_ccbs_available_timer(monitor->interface->config_params) :
1918
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1918
		ast_get_ccnr_available_timer(monitor->interface->config_params);
1919

    
   
1919

   
1920
	sip_pvt_lock(monitor_instance->subscription_pvt);
1920
	sip_pvt_lock(monitor_instance->subscription_pvt);
1921
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1921
	create_addr(monitor_instance->subscription_pvt, monitor_instance->peername, 0, 1, NULL);
1922
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa.sin_addr, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1922
	ast_sip_ouraddrfor(&monitor_instance->subscription_pvt->sa.sin_addr, &monitor_instance->subscription_pvt->ourip, monitor_instance->subscription_pvt);
1923
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1923
	monitor_instance->subscription_pvt->subscribed = CALL_COMPLETION;
1924
	monitor_instance->subscription_pvt->expiry = when;
1924
	monitor_instance->subscription_pvt->expiry = when;
1925

    
   
1925

   
1926
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1926
	transmit_invite(monitor_instance->subscription_pvt, SIP_SUBSCRIBE, FALSE, 2, monitor_instance->subscribe_uri);
1927
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1927
	sip_pvt_unlock(monitor_instance->subscription_pvt);
1928

    
   
1928

   
1929
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1929
	ao2_t_ref(monitor, +1, "Adding a ref to the monitor for the scheduler");
1930
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1930
	*available_timer_id = ast_sched_add(sched, when * 1000, ast_cc_available_timer_expire, monitor);
1931
	return 0;
1931
	return 0;
1932
}
1932
}
1933

    
   
1933

   
1934
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1934
static int construct_pidf_body(enum sip_cc_publish_state state, char *pidf_body, size_t size, const char *presentity)
1935
{
1935
{
1936
	struct ast_str *body = ast_str_alloca(size);
1936
	struct ast_str *body = ast_str_alloca(size);
1937
	char tuple_id[32];
1937
	char tuple_id[32];
1938

    
   
1938

   
1939
	generate_random_string(tuple_id, sizeof(tuple_id));
1939
	generate_random_string(tuple_id, sizeof(tuple_id));
1940

    
   
1940

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

    
   
1959

   
1960
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1960
static int sip_cc_monitor_suspend(struct ast_cc_monitor *monitor)
1961
{
1961
{
1962
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1962
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
1963
	enum sip_publish_type publish_type;
1963
	enum sip_publish_type publish_type;
1964
	struct cc_epa_entry *cc_entry;
1964
	struct cc_epa_entry *cc_entry;
1965

    
   
1965

   
1966
	if (!monitor_instance) {
1966
	if (!monitor_instance) {
1967
		return -1;
1967
		return -1;
1968
	}
1968
	}
1969

    
   
1969

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

    
   
1989

   
1990
	cc_entry->current_state = CC_CLOSED;
1990
	cc_entry->current_state = CC_CLOSED;
1991

    
   
1991

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

    
   
2010

   
2011
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2011
static int sip_cc_monitor_unsuspend(struct ast_cc_monitor *monitor)
2012
{
2012
{
2013
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2013
	struct sip_monitor_instance *monitor_instance = monitor->private_data;
2014
	struct cc_epa_entry *cc_entry;
2014
	struct cc_epa_entry *cc_entry;
2015

    
   
2015

   
2016
	if (!monitor_instance) {
2016
	if (!monitor_instance) {
2017
		return -1;
2017
		return -1;
2018
	}
2018
	}
2019

    
   
2019

   
2020
	ast_assert(monitor_instance->suspension_entry != NULL);
2020
	ast_assert(monitor_instance->suspension_entry != NULL);
2021

    
   
2021

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

    
   
2034

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

    
   
2043

   
2044
static void sip_cc_monitor_destructor(void *private_data)
2044
static void sip_cc_monitor_destructor(void *private_data)
2045
{
2045
{
2046
	struct sip_monitor_instance *monitor_instance = private_data;
2046
	struct sip_monitor_instance *monitor_instance = private_data;
2047
	ao2_unlink(sip_monitor_instances, monitor_instance);
2047
	ao2_unlink(sip_monitor_instances, monitor_instance);
2048
	ast_module_unref(ast_module_info->self);
2048
	ast_module_unref(ast_module_info->self);
2049
}
2049
}
2050

    
   
2050

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

    
   
2059

   
2060
	if (ast_strlen_zero(call_info)) {
2060
	if (ast_strlen_zero(call_info)) {
2061
		/* No Call-Info present. Definitely no CC offer */
2061
		/* No Call-Info present. Definitely no CC offer */
2062
		return -1;
2062
		return -1;
2063
	}
2063
	}
2064

    
   
2064

   
2065
	uri = strsep(&call_info, ";");
2065
	uri = strsep(&call_info, ";");
2066

    
   
2066

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

    
   
2076

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

    
   
2094

   
2095
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2095
	if ((*service = service_string_to_service_type(service_str)) == AST_CC_NONE) {
2096
		/* Invalid service offered */
2096
		/* Invalid service offered */
2097
		return -1;
2097
		return -1;
2098
	}
2098
	}
2099

    
   
2099

   
2100
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2100
	ast_copy_string(subscribe_uri, get_in_brackets(uri), size);
2101

    
   
2101

   
2102
	return 0;
2102
	return 0;
2103
}
2103
}
2104

    
   
2104

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

    
   
2127

   
2128
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2128
	if (monitor_policy == AST_CC_MONITOR_NEVER) {
2129
		/* Don't bother, just return */
2129
		/* Don't bother, just return */
2130
		return;
2130
		return;
2131
	}
2131
	}
2132

    
   
2132

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

    
   
2137

   
2138
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2138
	ast_channel_get_device_name(pvt->owner, interface_name, sizeof(interface_name));
2139

    
   
2139

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

    
   
2166

   
2167
generic:
2167
generic:
2168
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2168
	if (monitor_policy == AST_CC_MONITOR_GENERIC || monitor_policy == AST_CC_MONITOR_ALWAYS) {
2169
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2169
		ast_queue_cc_frame(pvt->owner, AST_CC_GENERIC_MONITOR_TYPE, interface_name, service, NULL);
2170
	}
2170
	}
2171
}
2171
}
2172

    
   
2172

   
2173
/*! \brief Working TLS connection configuration */
2173
/*! \brief Working TLS connection configuration */
2174
static struct ast_tls_config sip_tls_cfg;
2174
static struct ast_tls_config sip_tls_cfg;
2175

    
   
2175

   
2176
/*! \brief Default TLS connection configuration */
2176
/*! \brief Default TLS connection configuration */
2177
static struct ast_tls_config default_tls_cfg;
2177
static struct ast_tls_config default_tls_cfg;
2178

    
   
2178

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

    
   
2189

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

    
   
2200

   
2201
/*! \brief Append to SIP dialog history
2201
/*! \brief Append to SIP dialog history
2202
	\return Always returns 0 */
2202
	\return Always returns 0 */
2203
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2203
#define append_history(p, event, fmt , args... )	append_history_full(p, "%-15s " fmt, event, ## args)
2204

    
   
2204

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

    
   
2217

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

    
   
2228

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

    
   
2235

   
2236
	for (cur = table; cur->s; cur++)
2236
	for (cur = table; cur->s; cur++)
2237
		if (cur->x == x)
2237
		if (cur->x == x)
2238
			return cur->s;
2238
			return cur->s;
2239
	return errorstring;
2239
	return errorstring;
2240
}
2240
}
2241

    
   
2241

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

    
   
2248

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

    
   
2254

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

    
   
2259

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

    
   
2266

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

    
   
2269

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

    
   
2275

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

    
   
2278

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

    
   
2309

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

    
   
2316

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

    
   
2325

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

    
   
2329

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

    
   
2332

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

    
   
2346

   
2347
static void sip_threadinfo_destructor(void *obj)
2347
static void sip_threadinfo_destructor(void *obj)
2348
{
2348
{
2349
	struct sip_threadinfo *th = obj;
2349
	struct sip_threadinfo *th = obj;
2350
	struct tcptls_packet *packet;
2350
	struct tcptls_packet *packet;
2351
	if (th->alert_pipe[1] > -1) {
2351
	if (th->alert_pipe[1] > -1) {
2352
		close(th->alert_pipe[0]);
2352
		close(th->alert_pipe[0]);
2353
	}
2353
	}
2354
	if (th->alert_pipe[1] > -1) {
2354
	if (th->alert_pipe[1] > -1) {
2355
		close(th->alert_pipe[1]);
2355
		close(th->alert_pipe[1]);
2356
	}
2356
	}
2357
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2357
	th->alert_pipe[0] = th->alert_pipe[1] = -1;
2358

    
   
2358

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

    
   
2362

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

    
   
2367

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

    
   
2372

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

    
   
2376

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

    
   
2378

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

    
   
2391

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

    
   
2402

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

    
   
2406

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

    
   
2408

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

    
   
2415

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

    
   
2419

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

    
   
2433

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

    
   
2437

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

    
   
2446

   
2447
	return XMIT_ERROR;
2447
	return XMIT_ERROR;
2448
}
2448
}
2449

    
   
2449

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

    
   
2454

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

    
   
2457

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

    
   
2469

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

    
   
2489

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

    
   
2496

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

    
   
2499

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

    
   
2504

   
2505
	if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2505
	if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
2506
		goto cleanup;
2506
		goto cleanup;
2507
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2507
	if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
2508
		goto cleanup;
2508
		goto cleanup;
2509

    
   
2509

   
2510
	for (;;) {
2510
	for (;;) {
2511
		struct ast_str *str_save;
2511
		struct ast_str *str_save;
2512

    
   
2512

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

    
   
2518

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

    
   
2522

   
2523
			fds[0].revents = 0;
2523
			fds[0].revents = 0;
2524

    
   
2524

   
2525
			/* clear request structure */
2525
			/* clear request structure */
2526
			str_save = req.data;
2526
			str_save = req.data;
2527
			memset(&req, 0, sizeof(req));
2527
			memset(&req, 0, sizeof(req));
2528
			req.data = str_save;
2528
			req.data = str_save;
2529
			ast_str_reset(req.data);
2529
			ast_str_reset(req.data);
2530

    
   
2530

   
2531
			str_save = reqcpy.data;
2531
			str_save = reqcpy.data;
2532
			memset(&reqcpy, 0, sizeof(reqcpy));
2532
			memset(&reqcpy, 0, sizeof(reqcpy));
2533
			reqcpy.data = str_save;
2533
			reqcpy.data = str_save;
2534
			ast_str_reset(reqcpy.data);
2534
			ast_str_reset(reqcpy.data);
2535

    
   
2535

   
2536
			memset(buf, 0, sizeof(buf));
2536
			memset(buf, 0, sizeof(buf));
2537

    
   
2537

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

    
   
2546

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

    
   
2582

   
2583
			req.socket.tcptls_session = tcptls_session;
2583
			req.socket.tcptls_session = tcptls_session;
2584
			handle_request_do(&req, &tcptls_session->remote_address);
2584
			handle_request_do(&req, &tcptls_session->remote_address);
2585
		}
2585
		}
2586

    
   
2586

   
2587
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2587
		if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
2588
			enum sip_tcptls_alert alert;
2588
			enum sip_tcptls_alert alert;
2589
			struct tcptls_packet *packet;
2589
			struct tcptls_packet *packet;
2590

    
   
2590

   
2591
			fds[1].revents = 0;
2591
			fds[1].revents = 0;
2592

    
   
2592

   
2593
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2593
			if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
2594
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2594
				ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
2595
				continue;
2595
				continue;
2596
			}
2596
			}
2597

    
   
2597

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

    
   
2608

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

    
   
2619

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

    
   
2621

   
2622
cleanup:
2622
cleanup:
2623
	if (me) {
2623
	if (me) {
2624
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2624
		ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
2625
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2625
		ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
2626
	}
2626
	}
2627
	if (reqcpy.data) {
2627
	if (reqcpy.data) {
2628
		ast_free(reqcpy.data);
2628
		ast_free(reqcpy.data);
2629
	}
2629
	}
2630

    
   
2630

   
2631
	if (req.data) {
2631
	if (req.data) {
2632
		ast_free(req.data);
2632
		ast_free(req.data);
2633
		req.data = NULL;
2633
		req.data = NULL;
2634
	}
2634
	}
2635

    
   
2635

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

    
   
2640

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

    
   
2653

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

    
   
2659

   
2660

    
   
2660

   
2661
/*!
2661
/*!
2662
 * helper functions to unreference various types of objects.
2662
 * helper functions to unreference various types of objects.
2663
 * By handling them this way, we don't have to declare the
2663
 * By handling them this way, we don't have to declare the
2664
 * destructor on each call, which removes the chance of errors.
2664
 * destructor on each call, which removes the chance of errors.
2665
 */
2665
 */
2666
static void *unref_peer(struct sip_peer *peer, char *tag)
2666
static void *unref_peer(struct sip_peer *peer, char *tag)
2667
{
2667
{
2668
	ao2_t_ref(peer, -1, tag);
2668
	ao2_t_ref(peer, -1, tag);
2669
	return NULL;
2669
	return NULL;
2670
}
2670
}
2671

    
   
2671

   
2672
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2672
static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
2673
{
2673
{
2674
	ao2_t_ref(peer, 1, tag);
2674
	ao2_t_ref(peer, 1, tag);
2675
	return peer;
2675
	return peer;
2676
}
2676
}
2677

    
   
2677

   
2678
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2678
/*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
2679
 *
2679
 *
2680
 * This function sets pvt's outboundproxy pointer to the one referenced
2680
 * This function sets pvt's outboundproxy pointer to the one referenced
2681
 * by the proxy parameter. Because proxy may be a refcounted object, and
2681
 * by the proxy parameter. Because proxy may be a refcounted object, and
2682
 * because pvt's old outboundproxy may also be a refcounted object, we need
2682
 * because pvt's old outboundproxy may also be a refcounted object, we need
2683
 * to maintain the proper refcounts.
2683
 * to maintain the proper refcounts.
2684
 *
2684
 *
2685
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2685
 * \param pvt The sip_pvt for which we wish to set the outboundproxy
2686
 * \param proxy The sip_proxy which we will point pvt towards.
2686
 * \param proxy The sip_proxy which we will point pvt towards.
2687
 * \return Returns void
2687
 * \return Returns void
2688
 */
2688
 */
2689
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2689
static void ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
2690
{
2690
{
2691
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2691
	struct sip_proxy *old_obproxy = pvt->outboundproxy;
2692
	/* The sip_cfg.outboundproxy is statically allocated, and so
2692
	/* The sip_cfg.outboundproxy is statically allocated, and so
2693
	 * we don't ever need to adjust refcounts for it
2693
	 * we don't ever need to adjust refcounts for it
2694
	 */
2694
	 */
2695
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2695
	if (proxy && proxy != &sip_cfg.outboundproxy) {
2696
		ao2_ref(proxy, +1);
2696
		ao2_ref(proxy, +1);
2697
	}
2697
	}
2698
	pvt->outboundproxy = proxy;
2698
	pvt->outboundproxy = proxy;
2699
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2699
	if (old_obproxy && old_obproxy != &sip_cfg.outboundproxy) {
2700
		ao2_ref(old_obproxy, -1);
2700
		ao2_ref(old_obproxy, -1);
2701
	}
2701
	}
2702
}
2702
}
2703

    
   
2703

   
2704
/*!
2704
/*!
2705
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2705
 * \brief Unlink a dialog from the dialogs container, as well as any other places
2706
 * that it may be currently stored.
2706
 * that it may be currently stored.
2707
 *
2707
 *
2708
 * \note A reference to the dialog must be held before calling this function, and this
2708
 * \note A reference to the dialog must be held before calling this function, and this
2709
 * function does not release that reference.
2709
 * function does not release that reference.
2710
 */
2710
 */
2711
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2711
void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
2712
{
2712
{
2713
	struct sip_pkt *cp;
2713
	struct sip_pkt *cp;
2714

    
   
2714

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

    
   
2716

   
2717
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2717
	ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
2718

    
   
2718

   
2719
	/* Unlink us from the owner (channel) if we have one */
2719
	/* Unlink us from the owner (channel) if we have one */
2720
	if (dialog->owner) {
2720
	if (dialog->owner) {
2721
		if (lockowner)
2721
		if (lockowner)
2722
			ast_channel_lock(dialog->owner);
2722
			ast_channel_lock(dialog->owner);
2723
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2723
		ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
2724
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2724
		dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
2725
		if (lockowner)
2725
		if (lockowner)
2726
			ast_channel_unlock(dialog->owner);
2726
			ast_channel_unlock(dialog->owner);
2727
	}
2727
	}
2728
	if (dialog->registry) {
2728
	if (dialog->registry) {
2729
		if (dialog->registry->call == dialog)
2729
		if (dialog->registry->call == dialog)
2730
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2730
			dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
2731
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2731
		dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
2732
	}
2732
	}
2733
	if (dialog->stateid > -1) {
2733
	if (dialog->stateid > -1) {
2734
		ast_extension_state_del(dialog->stateid, NULL);
2734
		ast_extension_state_del(dialog->stateid, NULL);
2735
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2735
		dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
2736
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2736
		dialog->stateid = -1; /* shouldn't we 'zero' this out? */
2737
	}
2737
	}
2738
	/* Remove link from peer to subscription of MWI */
2738
	/* Remove link from peer to subscription of MWI */
2739
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2739
	if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
2740
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2740
		dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
2741
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2741
	if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
2742
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2742
		dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
2743

    
   
2743

   
2744
	/* remove all current packets in this dialog */
2744
	/* remove all current packets in this dialog */
2745
	while((cp = dialog->packets)) {
2745
	while((cp = dialog->packets)) {
2746
		dialog->packets = dialog->packets->next;
2746
		dialog->packets = dialog->packets->next;
2747
		AST_SCHED_DEL(sched, cp->retransid);
2747
		AST_SCHED_DEL(sched, cp->retransid);
2748
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2748
		dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
2749
		if (cp->data) {
2749
		if (cp->data) {
2750
			ast_free(cp->data);
2750
			ast_free(cp->data);
2751
		}
2751
		}
2752
		ast_free(cp);
2752
		ast_free(cp);
2753
	}
2753
	}
2754

    
   
2754

   
2755
	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"));
2755
	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"));
2756

    
   
2756

   
2757
	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"));
2757
	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"));
2758
	
2758
	
2759
	if (dialog->autokillid > -1)
2759
	if (dialog->autokillid > -1)
2760
		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"));
2760
		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"));
2761

    
   
2761

   
2762
	if (dialog->request_queue_sched_id > -1) {
2762
	if (dialog->request_queue_sched_id > -1) {
2763
		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"));
2763
		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"));
2764
	}
2764
	}
2765

    
   
2765

   
2766
	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"));
2766
	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"));
2767

    
   
2767

   
2768
	if (dialog->t38id > -1) {
2768
	if (dialog->t38id > -1) {
2769
		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"));
2769
		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"));
2770
	}
2770
	}
2771

    
   
2771

   
2772
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2772
	dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
2773
	return NULL;
2773
	return NULL;
2774
}
2774
}
2775

    
   
2775

   
2776
void *registry_unref(struct sip_registry *reg, char *tag)
2776
void *registry_unref(struct sip_registry *reg, char *tag)
2777
{
2777
{
2778
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2778
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
2779
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2779
	ASTOBJ_UNREF(reg, sip_registry_destroy);
2780
	return NULL;
2780
	return NULL;
2781
}
2781
}
2782

    
   
2782

   
2783
/*! \brief Add object reference to SIP registry */
2783
/*! \brief Add object reference to SIP registry */
2784
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2784
static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
2785
{
2785
{
2786
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2786
	ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
2787
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2787
	return ASTOBJ_REF(reg);	/* Add pointer to registry in packet */
2788
}
2788
}
2789

    
   
2789

   
2790
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2790
/*! \brief Interface structure with callbacks used to connect to UDPTL module*/
2791
static struct ast_udptl_protocol sip_udptl = {
2791
static struct ast_udptl_protocol sip_udptl = {
2792
	type: "SIP",
2792
	type: "SIP",
2793
	get_udptl_info: sip_get_udptl_peer,
2793
	get_udptl_info: sip_get_udptl_peer,
2794
	set_udptl_peer: sip_set_udptl_peer,
2794
	set_udptl_peer: sip_set_udptl_peer,
2795
};
2795
};
2796

    
   
2796

   
2797
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2797
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
2798
	__attribute__((format(printf, 2, 3)));
2798
	__attribute__((format(printf, 2, 3)));
2799

    
   
2799

   
2800

    
   
2800

   
2801
/*! \brief Convert transfer status to string */
2801
/*! \brief Convert transfer status to string */
2802
static const char *referstatus2str(enum referstatus rstatus)
2802
static const char *referstatus2str(enum referstatus rstatus)
2803
{
2803
{
2804
	return map_x_s(referstatusstrings, rstatus, "");
2804
	return map_x_s(referstatusstrings, rstatus, "");
2805
}
2805
}
2806

    
   
2806

   
2807
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2807
static inline void pvt_set_needdestroy(struct sip_pvt *pvt, const char *reason)
2808
{
2808
{
2809
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2809
	append_history(pvt, "NeedDestroy", "Setting needdestroy because %s", reason);
2810
	pvt->needdestroy = 1;
2810
	pvt->needdestroy = 1;
2811
}
2811
}
2812

    
   
2812

   
2813
/*! \brief Initialize the initital request packet in the pvt structure.
2813
/*! \brief Initialize the initital request packet in the pvt structure.
2814
 	This packet is used for creating replies and future requests in
2814
 	This packet is used for creating replies and future requests in
2815
	a dialog */
2815
	a dialog */
2816
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2816
static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
2817
{
2817
{
2818
	if (p->initreq.headers)
2818
	if (p->initreq.headers)
2819
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2819
		ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
2820
	else
2820
	else
2821
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2821
		ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
2822
	/* Use this as the basis */
2822
	/* Use this as the basis */
2823
	copy_request(&p->initreq, req);
2823
	copy_request(&p->initreq, req);
2824
	parse_request(&p->initreq);
2824
	parse_request(&p->initreq);
2825
	if (req->debug)
2825
	if (req->debug)
2826
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2826
		ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
2827
}
2827
}
2828

    
   
2828

   
2829
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2829
/*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
2830
static void sip_alreadygone(struct sip_pvt *dialog)
2830
static void sip_alreadygone(struct sip_pvt *dialog)
2831
{
2831
{
2832
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2832
	ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
2833
	dialog->alreadygone = 1;
2833
	dialog->alreadygone = 1;
2834
}
2834
}
2835

    
   
2835

   
2836
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2836
/*! Resolve DNS srv name or host name in a sip_proxy structure */
2837
static int proxy_update(struct sip_proxy *proxy)
2837
static int proxy_update(struct sip_proxy *proxy)
2838
{
2838
{
2839
	/* if it's actually an IP address and not a name,
2839
	/* if it's actually an IP address and not a name,
2840
           there's no need for a managed lookup */
2840
           there's no need for a managed lookup */
2841
	if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2841
	if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
2842
		/* Ok, not an IP address, then let's check if it's a domain or host */
2842
		/* Ok, not an IP address, then let's check if it's a domain or host */
2843
		/* XXX Todo - if we have proxy port, don't do SRV */
2843
		/* XXX Todo - if we have proxy port, don't do SRV */
2844
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2844
		if (ast_get_ip_or_srv(&proxy->ip, proxy->name, sip_cfg.srvlookup ? "_sip._udp" : NULL) < 0) {
2845
			ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2845
			ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
2846
			return FALSE;
2846
			return FALSE;
2847
		}
2847
		}
2848
	}
2848
	}
2849
	proxy->last_dnsupdate = time(NULL);
2849
	proxy->last_dnsupdate = time(NULL);
2850
	return TRUE;
2850
	return TRUE;
2851
}
2851
}
2852

    
   
2852

   
2853
/*! \brief converts ascii port to int representation. If no
2853
/*! \brief converts ascii port to int representation. If no
2854
 *  pt buffer is provided or the pt has errors when being converted
2854
 *  pt buffer is provided or the pt has errors when being converted
2855
 *  to an int value, the port provided as the standard is used.
2855
 *  to an int value, the port provided as the standard is used.
2856
 */
2856
 */
2857
unsigned int port_str2int(const char *pt, unsigned int standard)
2857
unsigned int port_str2int(const char *pt, unsigned int standard)
2858
{
2858
{
2859
	int port = standard;
2859
	int port = standard;
2860
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2860
	if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
2861
		port = standard;
2861
		port = standard;
2862
	}
2862
	}
2863

    
   
2863

   
2864
	return port;
2864
	return port;
2865
}
2865
}
2866

    
   
2866

   
2867
/*! \brief Allocate and initialize sip proxy */
2867
/*! \brief Allocate and initialize sip proxy */
2868
static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2868
static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
2869
{
2869
{
2870
	struct sip_proxy *proxy;
2870
	struct sip_proxy *proxy;
2871

    
   
2871

   
2872
	if (ast_strlen_zero(name)) {
2872
	if (ast_strlen_zero(name)) {
2873
		return NULL;
2873
		return NULL;
2874
	}
2874
	}
2875

    
   
2875

   
2876
	proxy = ao2_alloc(sizeof(*proxy), NULL);
2876
	proxy = ao2_alloc(sizeof(*proxy), NULL);
2877
	if (!proxy)
2877
	if (!proxy)
2878
		return NULL;
2878
		return NULL;
2879
	proxy->force = force;
2879
	proxy->force = force;
2880
	ast_copy_string(proxy->name, name, sizeof(proxy->name));
2880
	ast_copy_string(proxy->name, name, sizeof(proxy->name));
2881
	proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
2881
	proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
2882
	proxy_update(proxy);
2882
	proxy_update(proxy);
2883
	return proxy;
2883
	return proxy;
2884
}
2884
}
2885

    
   
2885

   
2886
/*! \brief Get default outbound proxy or global proxy */
2886
/*! \brief Get default outbound proxy or global proxy */
2887
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2887
static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
2888
{
2888
{
2889
	if (peer && peer->outboundproxy) {
2889
	if (peer && peer->outboundproxy) {
2890
		if (sipdebug)
2890
		if (sipdebug)
2891
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2891
			ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
2892
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2892
		append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
2893
		return peer->outboundproxy;
2893
		return peer->outboundproxy;
2894
	}
2894
	}
2895
	if (sip_cfg.outboundproxy.name[0]) {
2895
	if (sip_cfg.outboundproxy.name[0]) {
2896
		if (sipdebug)
2896
		if (sipdebug)
2897
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2897
			ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
2898
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2898
		append_history(dialog, "OBproxy", "Using global obproxy %s", sip_cfg.outboundproxy.name);
2899
		return &sip_cfg.outboundproxy;
2899
		return &sip_cfg.outboundproxy;
2900
	}
2900
	}
2901
	if (sipdebug)
2901
	if (sipdebug)
2902
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2902
		ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
2903
	return NULL;
2903
	return NULL;
2904
}
2904
}
2905

    
   
2905

   
2906
/*! \brief returns true if 'name' (with optional trailing whitespace)
2906
/*! \brief returns true if 'name' (with optional trailing whitespace)
2907
 * matches the sip method 'id'.
2907
 * matches the sip method 'id'.
2908
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2908
 * Strictly speaking, SIP methods are case SENSITIVE, but we do
2909
 * a case-insensitive comparison to be more tolerant.
2909
 * a case-insensitive comparison to be more tolerant.
2910
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2910
 * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
2911
 */
2911
 */
2912
static int method_match(enum sipmethod id, const char *name)
2912
static int method_match(enum sipmethod id, const char *name)
2913
{
2913
{
2914
	int len = strlen(sip_methods[id].text);
2914
	int len = strlen(sip_methods[id].text);
2915
	int l_name = name ? strlen(name) : 0;
2915
	int l_name = name ? strlen(name) : 0;
2916
	/* true if the string is long enough, and ends with whitespace, and matches */
2916
	/* true if the string is long enough, and ends with whitespace, and matches */
2917
	return (l_name >= len && name[len] < 33 &&
2917
	return (l_name >= len && name[len] < 33 &&
2918
		!strncasecmp(sip_methods[id].text, name, len));
2918
		!strncasecmp(sip_methods[id].text, name, len));
2919
}
2919
}
2920

    
   
2920

   
2921
/*! \brief  find_sip_method: Find SIP method from header */
2921
/*! \brief  find_sip_method: Find SIP method from header */
2922
static int find_sip_method(const char *msg)
2922
static int find_sip_method(const char *msg)
2923
{
2923
{
2924
	int i, res = 0;
2924
	int i, res = 0;
2925
	
2925
	
2926
	if (ast_strlen_zero(msg))
2926
	if (ast_strlen_zero(msg))
2927
		return 0;
2927
		return 0;
2928
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2928
	for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
2929
		if (method_match(i, msg))
2929
		if (method_match(i, msg))
2930
			res = sip_methods[i].id;
2930
			res = sip_methods[i].id;
2931
	}
2931
	}
2932
	return res;
2932
	return res;
2933
}
2933
}
2934

    
   
2934

   
2935
/*! \brief Parse supported header in incoming packet */
2935
/*! \brief Parse supported header in incoming packet */
2936
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2936
static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
2937
{
2937
{
2938
	char *next, *sep;
2938
	char *next, *sep;
2939
	char *temp;
2939
	char *temp;
2940
	unsigned int profile = 0;
2940
	unsigned int profile = 0;
2941
	int i, found;
2941
	int i, found;
2942

    
   
2942

   
2943
	if (ast_strlen_zero(supported) )
2943
	if (ast_strlen_zero(supported) )
2944
		return 0;
2944
		return 0;
2945
	temp = ast_strdupa(supported);
2945
	temp = ast_strdupa(supported);
2946

    
   
2946

   
2947
	if (sipdebug)
2947
	if (sipdebug)
2948
		ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2948
		ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
2949

    
   
2949

   
2950
	for (next = temp; next; next = sep) {
2950
	for (next = temp; next; next = sep) {
2951
		found = FALSE;
2951
		found = FALSE;
2952
		if ( (sep = strchr(next, ',')) != NULL)
2952
		if ( (sep = strchr(next, ',')) != NULL)
2953
			*sep++ = '\0';
2953
			*sep++ = '\0';
2954
		next = ast_skip_blanks(next);
2954
		next = ast_skip_blanks(next);
2955
		if (sipdebug)
2955
		if (sipdebug)
2956
			ast_debug(3, "Found SIP option: -%s-\n", next);
2956
			ast_debug(3, "Found SIP option: -%s-\n", next);
2957
		for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2957
		for (i = 0; i < ARRAY_LEN(sip_options); i++) {
2958
			if (!strcasecmp(next, sip_options[i].text)) {
2958
			if (!strcasecmp(next, sip_options[i].text)) {
2959
				profile |= sip_options[i].id;
2959
				profile |= sip_options[i].id;
2960
				found = TRUE;
2960
				found = TRUE;
2961
				if (sipdebug)
2961
				if (sipdebug)
2962
					ast_debug(3, "Matched SIP option: %s\n", next);
2962
					ast_debug(3, "Matched SIP option: %s\n", next);
2963
				break;
2963
				break;
2964
			}
2964
			}
2965
		}
2965
		}
2966

    
   
2966

   
2967
		/* This function is used to parse both Suported: and Require: headers.
2967
		/* This function is used to parse both Suported: and Require: headers.
2968
		Let the caller of this function know that an unknown option tag was
2968
		Let the caller of this function know that an unknown option tag was
2969
		encountered, so that if the UAC requires it then the request can be
2969
		encountered, so that if the UAC requires it then the request can be
2970
		rejected with a 420 response. */
2970
		rejected with a 420 response. */
2971
		if (!found)
2971
		if (!found)
2972
			profile |= SIP_OPT_UNKNOWN;
2972
			profile |= SIP_OPT_UNKNOWN;
2973

    
   
2973

   
2974
		if (!found && sipdebug) {
2974
		if (!found && sipdebug) {
2975
			if (!strncasecmp(next, "x-", 2))
2975
			if (!strncasecmp(next, "x-", 2))
2976
				ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2976
				ast_debug(3, "Found private SIP option, not supported: %s\n", next);
2977
			else
2977
			else
2978
				ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2978
				ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
2979
		}
2979
		}
2980
	}
2980
	}
2981

    
   
2981

   
2982
	if (pvt)
2982
	if (pvt)
2983
		pvt->sipoptions = profile;
2983
		pvt->sipoptions = profile;
2984
	return profile;
2984
	return profile;
2985
}
2985
}
2986

    
   
2986

   
2987
/*! \brief See if we pass debug IP filter */
2987
/*! \brief See if we pass debug IP filter */
2988
static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2988
static inline int sip_debug_test_addr(const struct sockaddr_in *addr)
2989
{
2989
{
2990
	if (!sipdebug)
2990
	if (!sipdebug)
2991
		return 0;
2991
		return 0;
2992
	if (debugaddr.sin_addr.s_addr) {
2992
	if (debugaddr.sin_addr.s_addr) {
2993
		if (((ntohs(debugaddr.sin_port) != 0)
2993
		if (((ntohs(debugaddr.sin_port) != 0)
2994
			&& (debugaddr.sin_port != addr->sin_port))
2994
			&& (debugaddr.sin_port != addr->sin_port))
2995
			|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2995
			|| (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
2996
			return 0;
2996
			return 0;
2997
	}
2997
	}
2998
	return 1;
2998
	return 1;
2999
}
2999
}
3000

    
   
3000

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

    
   
3006

   
3007
	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;
3007
	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;
3008
}
3008
}
3009

    
   
3009

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

    
   
3015

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

    
   
3023

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

    
   
3028

   
3029
	if (ast_strlen_zero(transport)) {
3029
	if (ast_strlen_zero(transport)) {
3030
		return res;
3030
		return res;
3031
	}
3031
	}
3032

    
   
3032

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

    
   
3042

   
3043
	return res;
3043
	return res;
3044
}
3044
}
3045

    
   
3045

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

    
   
3066

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

    
   
3078

   
3079
	return "UNKNOWN";
3079
	return "UNKNOWN";
3080
}
3080
}
3081

    
   
3081

   
3082
/*! \brief Return transport of dialog.
3082
/*! \brief Return transport of dialog.
3083
	\note this is based on a false assumption. We don't always use the
3083
	\note this is based on a false assumption. We don't always use the
3084
	outbound proxy for all requests in a dialog. It depends on the
3084
	outbound proxy for all requests in a dialog. It depends on the
3085
	"force" parameter. The FIRST request is always sent to the ob proxy.
3085
	"force" parameter. The FIRST request is always sent to the ob proxy.
3086
	\todo Fix this function to work correctly
3086
	\todo Fix this function to work correctly
3087
*/
3087
*/
3088
static inline const char *get_transport_pvt(struct sip_pvt *p)
3088
static inline const char *get_transport_pvt(struct sip_pvt *p)
3089
{
3089
{
3090
	if (p->outboundproxy && p->outboundproxy->transport) {
3090
	if (p->outboundproxy && p->outboundproxy->transport) {
3091
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3091
		set_socket_transport(&p->socket, p->outboundproxy->transport);
3092
	}
3092
	}
3093

    
   
3093

   
3094
	return get_transport(p->socket.type);
3094
	return get_transport(p->socket.type);
3095
}
3095
}
3096

    
   
3096

   
3097
/*! \brief Transmit SIP message
3097
/*! \brief Transmit SIP message
3098
	Sends a SIP request or response on a given socket (in the pvt)
3098
	Sends a SIP request or response on a given socket (in the pvt)
3099
	Called by retrans_pkt, send_request, send_response and
3099
	Called by retrans_pkt, send_request, send_response and
3100
	__sip_reliable_xmit
3100
	__sip_reliable_xmit
3101
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3101
	\return length of transmitted message, XMIT_ERROR on known network failures -1 on other failures.
3102
*/
3102
*/
3103
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3103
static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
3104
{
3104
{
3105
	int res = 0;
3105
	int res = 0;
3106
	const struct sockaddr_in *dst = sip_real_dst(p);
3106
	const struct sockaddr_in *dst = sip_real_dst(p);
3107

    
   
3107

   
3108
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
3108
	ast_debug(2, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
3109

    
   
3109

   
3110
	if (sip_prepare_socket(p) < 0)
3110
	if (sip_prepare_socket(p) < 0)
3111
		return XMIT_ERROR;
3111
		return XMIT_ERROR;
3112

    
   
3112

   
3113
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3113
	if (p->socket.type == SIP_TRANSPORT_UDP) {
3114
		res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
3114
		res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
3115
	} else if (p->socket.tcptls_session) {
3115
	} else if (p->socket.tcptls_session) {
3116
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3116
		res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
3117
	} else {
3117
	} else {
3118
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3118
		ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
3119
		return XMIT_ERROR;
3119
		return XMIT_ERROR;
3120
	}
3120
	}
3121

    
   
3121

   
3122
	if (res == -1) {
3122
	if (res == -1) {
3123
		switch (errno) {
3123
		switch (errno) {
3124
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3124
		case EBADF: 		/* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
3125
		case EHOSTUNREACH: 	/* Host can't be reached */
3125
		case EHOSTUNREACH: 	/* Host can't be reached */
3126
		case ENETDOWN: 		/* Interface down */
3126
		case ENETDOWN: 		/* Interface down */
3127
		case ENETUNREACH:	/* Network failure */
3127
		case ENETUNREACH:	/* Network failure */
3128
		case ECONNREFUSED:      /* ICMP port unreachable */
3128
		case ECONNREFUSED:      /* ICMP port unreachable */
3129
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3129
			res = XMIT_ERROR;	/* Don't bother with trying to transmit again */
3130
		}
3130
		}
3131
	}
3131
	}
3132
	if (res != len)
3132
	if (res != len)
3133
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
3133
		ast_log(LOG_WARNING, "sip_xmit of %p (len %d) to %s:%d returned %d: %s\n", data, len, ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), res, strerror(errno));
3134

    
   
3134

   
3135
	return res;
3135
	return res;
3136
}
3136
}
3137

    
   
3137

   
3138
/*! \brief Build a Via header for a request */
3138
/*! \brief Build a Via header for a request */
3139
static void build_via(struct sip_pvt *p)
3139
static void build_via(struct sip_pvt *p)
3140
{
3140
{
3141
	/* Work around buggy UNIDEN UIP200 firmware */
3141
	/* Work around buggy UNIDEN UIP200 firmware */
3142
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3142
	const char *rport = (ast_test_flag(&p->flags[0], SIP_NAT_FORCE_RPORT) || ast_test_flag(&p->flags[0], SIP_NAT_RPORT_PRESENT)) ? ";rport" : "";
3143

    
   
3143

   
3144
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3144
	/* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
3145
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
3145
	snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
3146
		 get_transport_pvt(p),
3146
		 get_transport_pvt(p),
3147
		 ast_inet_ntoa(p->ourip.sin_addr),
3147
		 ast_inet_ntoa(p->ourip.sin_addr),
3148
		 ntohs(p->ourip.sin_port), (int) p->branch, rport);
3148
		 ntohs(p->ourip.sin_port), (int) p->branch, rport);
3149
}
3149
}
3150

    
   
3150

   
3151
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3151
/*! \brief NAT fix - decide which IP address to use for Asterisk server?
3152
 *
3152
 *
3153
 * Using the localaddr structure built up with localnet statements in sip.conf
3153
 * Using the localaddr structure built up with localnet statements in sip.conf
3154
 * apply it to their address to see if we need to substitute our
3154
 * apply it to their address to see if we need to substitute our
3155
 * externip or can get away with our internal bindaddr
3155
 * externip or can get away with our internal bindaddr
3156
 * 'us' is always overwritten.
3156
 * 'us' is always overwritten.
3157
 */
3157
 */
3158
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
3158
static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
3159
{
3159
{
3160
	struct sockaddr_in theirs;
3160
	struct sockaddr_in theirs;
3161
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3161
	/* Set want_remap to non-zero if we want to remap 'us' to an externally
3162
	 * reachable IP address and port. This is done if:
3162
	 * reachable IP address and port. This is done if:
3163
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3163
	 * 1. we have a localaddr list (containing 'internal' addresses marked
3164
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3164
	 *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
3165
	 *    and AST_SENSE_ALLOW on 'external' ones);
3165
	 *    and AST_SENSE_ALLOW on 'external' ones);
3166
	 * 2. either stunaddr or externip is set, so we know what to use as the
3166
	 * 2. either stunaddr or externip is set, so we know what to use as the
3167
	 *    externally visible address;
3167
	 *    externally visible address;
3168
	 * 3. the remote address, 'them', is external;
3168
	 * 3. the remote address, 'them', is external;
3169
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3169
	 * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
3170
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3170
	 *    when passed to ast_apply_ha() so it does need to be remapped.
3171
	 *    This fourth condition is checked later.
3171
	 *    This fourth condition is checked later.
3172
	 */
3172
	 */
3173
	int want_remap;
3173
	int want_remap;
3174

    
   
3174

   
3175
	*us = internip;		/* starting guess for the internal address */
3175
	*us = internip;		/* starting guess for the internal address */
3176
	/* now ask the system what would it use to talk to 'them' */
3176
	/* now ask the system what would it use to talk to 'them' */
3177
	ast_ouraddrfor(them, &us->sin_addr);
3177
	ast_ouraddrfor(them, &us->sin_addr);
3178
	theirs.sin_addr = *them;
3178
	theirs.sin_addr = *them;
3179

    
   
3179

   
3180
	want_remap = localaddr &&
3180
	want_remap = localaddr &&
3181
		(externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
3181
		(externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
3182
		ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3182
		ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
3183

    
   
3183

   
3184
	if (want_remap &&
3184
	if (want_remap &&
3185
	    (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
3185
	    (!sip_cfg.matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
3186
		/* if we used externhost or stun, see if it is time to refresh the info */
3186
		/* if we used externhost or stun, see if it is time to refresh the info */
3187
		if (externexpire && time(NULL) >= externexpire) {
3187
		if (externexpire && time(NULL) >= externexpire) {
3188
			if (stunaddr.sin_addr.s_addr) {
3188
			if (stunaddr.sin_addr.s_addr) {
3189
				ast_stun_request(sipsock, &stunaddr, NULL, &externip);
3189
				ast_stun_request(sipsock, &stunaddr, NULL, &externip);
3190
			} else {
3190
			} else {
3191
				if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
3191
				if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
3192
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3192
					ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
3193
			}
3193
			}
3194
			externexpire = time(NULL) + externrefresh;
3194
			externexpire = time(NULL) + externrefresh;
3195
		}
3195
		}
3196
		if (externip.sin_addr.s_addr) {
3196
		if (externip.sin_addr.s_addr) {
3197
			*us = externip;
3197
			*us = externip;
3198
			switch (p->socket.type) {
3198
			switch (p->socket.type) {
3199
			case SIP_TRANSPORT_TCP:
3199
			case SIP_TRANSPORT_TCP:
3200
				us->sin_port = htons(externtcpport);
3200
				us->sin_port = htons(externtcpport);
3201
				break;
3201
				break;
3202
			case SIP_TRANSPORT_TLS:
3202
			case SIP_TRANSPORT_TLS:
3203
				us->sin_port = htons(externtlsport);
3203
				us->sin_port = htons(externtlsport);
3204
				break;
3204
				break;
3205
			case SIP_TRANSPORT_UDP:
3205
			case SIP_TRANSPORT_UDP:
3206
				break; /* fall through */
3206
				break; /* fall through */
3207
			default:
3207
			default:
3208
				us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */
3208
				us->sin_port = htons(STANDARD_SIP_PORT); /* we should never get here */
3209
			}
3209
			}
3210
		}
3210
		}
3211
		else
3211
		else
3212
			ast_log(LOG_WARNING, "stun failed\n");
3212
			ast_log(LOG_WARNING, "stun failed\n");
3213
		ast_debug(1, "Target address %s is not local, substituting externip\n",
3213
		ast_debug(1, "Target address %s is not local, substituting externip\n",
3214
			ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
3214
			ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
3215
	} else if (p) {
3215
	} else if (p) {
3216
		/* no remapping, but we bind to a specific address, so use it. */
3216
		/* no remapping, but we bind to a specific address, so use it. */
3217
		switch (p->socket.type) {
3217
		switch (p->socket.type) {
3218
		case SIP_TRANSPORT_TCP:
3218
		case SIP_TRANSPORT_TCP:
3219
			if (sip_tcp_desc.local_address.sin_addr.s_addr) {
3219
			if (sip_tcp_desc.local_address.sin_addr.s_addr) {
3220
				*us = sip_tcp_desc.local_address;
3220
				*us = sip_tcp_desc.local_address;
3221
			} else {
3221
			} else {
3222
				us->sin_port = sip_tcp_desc.local_address.sin_port;
3222
				us->sin_port = sip_tcp_desc.local_address.sin_port;
3223
			}
3223
			}
3224
			break;
3224
			break;
3225
		case SIP_TRANSPORT_TLS:
3225
		case SIP_TRANSPORT_TLS:
3226
			if (sip_tls_desc.local_address.sin_addr.s_addr) {
3226
			if (sip_tls_desc.local_address.sin_addr.s_addr) {
3227
				*us = sip_tls_desc.local_address;
3227
				*us = sip_tls_desc.local_address;
3228
			} else {
3228
			} else {
3229
				us->sin_port = sip_tls_desc.local_address.sin_port;
3229
				us->sin_port = sip_tls_desc.local_address.sin_port;
3230
			}
3230
			}
3231
				break;
3231
				break;
3232
		case SIP_TRANSPORT_UDP:
3232
		case SIP_TRANSPORT_UDP:
3233
			/* fall through on purpose */
3233
			/* fall through on purpose */
3234
		default:
3234
		default:
3235
			if (bindaddr.sin_addr.s_addr) {
3235
			if (bindaddr.sin_addr.s_addr) {
3236
				*us = bindaddr;
3236
				*us = bindaddr;
3237
			}
3237
			}
3238
		}
3238
		}
3239
	} else if (bindaddr.sin_addr.s_addr) {
3239
	} else if (bindaddr.sin_addr.s_addr) {
3240
		*us = bindaddr;
3240
		*us = bindaddr;
3241
	}
3241
	}
3242
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
3242
	ast_debug(3, "Setting SIP_TRANSPORT_%s with address %s:%d\n", get_transport(p->socket.type), ast_inet_ntoa(us->sin_addr), ntohs(us->sin_port));
3243
}
3243
}
3244

    
   
3244

   
3245
/*! \brief Append to SIP dialog history with arg list  */
3245
/*! \brief Append to SIP dialog history with arg list  */
3246
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3246
static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
3247
{
3247
{
3248
	char buf[80], *c = buf; /* max history length */
3248
	char buf[80], *c = buf; /* max history length */
3249
	struct sip_history *hist;
3249
	struct sip_history *hist;
3250
	int l;
3250
	int l;
3251

    
   
3251

   
3252
	vsnprintf(buf, sizeof(buf), fmt, ap);
3252
	vsnprintf(buf, sizeof(buf), fmt, ap);
3253
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3253
	strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
3254
	l = strlen(buf) + 1;
3254
	l = strlen(buf) + 1;
3255
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
3255
	if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
3256
		return;
3256
		return;
3257
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3257
	if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
3258
		ast_free(hist);
3258
		ast_free(hist);
3259
		return;
3259
		return;
3260
	}
3260
	}
3261
	memcpy(hist->event, buf, l);
3261
	memcpy(hist->event, buf, l);
3262
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3262
	if (p->history_entries == MAX_HISTORY_ENTRIES) {
3263
		struct sip_history *oldest;
3263
		struct sip_history *oldest;
3264
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3264
		oldest = AST_LIST_REMOVE_HEAD(p->history, list);
3265
		p->history_entries--;
3265
		p->history_entries--;
3266
		ast_free(oldest);
3266
		ast_free(oldest);
3267
	}
3267
	}
3268
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3268
	AST_LIST_INSERT_TAIL(p->history, hist, list);
3269
	p->history_entries++;
3269
	p->history_entries++;
3270
}
3270
}
3271

    
   
3271

   
3272
/*! \brief Append to SIP dialog history with arg list  */
3272
/*! \brief Append to SIP dialog history with arg list  */
3273
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3273
static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
3274
{
3274
{
3275
	va_list ap;
3275
	va_list ap;
3276

    
   
3276

   
3277
	if (!p)
3277
	if (!p)
3278
		return;
3278
		return;
3279

    
   
3279

   
3280
	if (!p->do_history && !recordhistory && !dumphistory)
3280
	if (!p->do_history && !recordhistory && !dumphistory)
3281
		return;
3281
		return;
3282

    
   
3282

   
3283
	va_start(ap, fmt);
3283
	va_start(ap, fmt);
3284
	append_history_va(p, fmt, ap);
3284
	append_history_va(p, fmt, ap);
3285
	va_end(ap);
3285
	va_end(ap);
3286

    
   
3286

   
3287
	return;
3287
	return;
3288
}
3288
}
3289

    
   
3289

   
3290
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3290
/*! \brief Retransmit SIP message if no answer (Called from scheduler) */
3291
static int retrans_pkt(const void *data)
3291
static int retrans_pkt(const void *data)
3292
{
3292
{
3293
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3293
	struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
3294
	int reschedule = DEFAULT_RETRANS;
3294
	int reschedule = DEFAULT_RETRANS;
3295
	int xmitres = 0;
3295
	int xmitres = 0;
3296
	
3296
	
3297
	/* Lock channel PVT */
3297
	/* Lock channel PVT */
3298
	sip_pvt_lock(pkt->owner);
3298
	sip_pvt_lock(pkt->owner);
3299

    
   
3299

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

    
   
3307

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

    
   
3314

   
3315
 			/* For non-invites, a maximum of 4 secs */
3315
 			/* For non-invites, a maximum of 4 secs */
3316
 			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3316
 			siptimer_a = pkt->timer_t1 * pkt->timer_a;	/* Double each time */
3317
 			if (pkt->method != SIP_INVITE && siptimer_a > 4000)
3317
 			if (pkt->method != SIP_INVITE && siptimer_a > 4000)
3318
 				siptimer_a = 4000;
3318
 				siptimer_a = 4000;
3319
 		
3319
 		
3320
 			/* Reschedule re-transmit */
3320
 			/* Reschedule re-transmit */
3321
			reschedule = siptimer_a;
3321
			reschedule = siptimer_a;
3322
 			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
3322
 			ast_debug(4, "** SIP timers: Rescheduling retransmission %d to %d ms (t1 %d ms (Retrans id #%d)) \n", pkt->retrans +1, siptimer_a, pkt->timer_t1, pkt->retransid);
3323
 		}
3323
 		}
3324

    
   
3324

   
3325
		if (sip_debug_test_pvt(pkt->owner)) {
3325
		if (sip_debug_test_pvt(pkt->owner)) {
3326
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
3326
			const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
3327
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
3327
			ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
3328
				pkt->retrans, sip_nat_mode(pkt->owner),
3328
				pkt->retrans, sip_nat_mode(pkt->owner),
3329
				ast_inet_ntoa(dst->sin_addr),
3329
				ast_inet_ntoa(dst->sin_addr),
3330
				ntohs(dst->sin_port), pkt->data->str);
3330
				ntohs(dst->sin_port), pkt->data->str);
3331
		}
3331
		}
3332

    
   
3332

   
3333
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3333
		append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
3334
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3334
		xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
3335
		sip_pvt_unlock(pkt->owner);
3335
		sip_pvt_unlock(pkt->owner);
3336
		if (xmitres == XMIT_ERROR)
3336
		if (xmitres == XMIT_ERROR)
3337
			ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
3337
			ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
3338
		else
3338
		else
3339
			return  reschedule;
3339
			return  reschedule;
3340
	}
3340
	}
3341
	/* Too many retries */
3341
	/* Too many retries */
3342
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3342
	if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
3343
		if (pkt->is_fatal || sipdebug)	/* Tell us if it's critical or if we're debugging */
3343
		if (pkt->is_fatal || sipdebug)	/* Tell us if it's critical or if we're debugging */
3344
			ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
3344
			ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
3345
				pkt->owner->callid, pkt->seqno,
3345
				pkt->owner->callid, pkt->seqno,
3346
				pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
3346
				pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
3347
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3347
	} else if (pkt->method == SIP_OPTIONS && sipdebug) {
3348
			ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3348
			ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
3349

    
   
3349

   
3350
	}
3350
	}
3351
	if (xmitres == XMIT_ERROR) {
3351
	if (xmitres == XMIT_ERROR) {
3352
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3352
		ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
3353
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3353
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3354
	} else
3354
	} else
3355
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3355
		append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3356
 		
3356
 		
3357
	pkt->retransid = -1;
3357
	pkt->retransid = -1;
3358

    
   
3358

   
3359
	if (pkt->is_fatal) {
3359
	if (pkt->is_fatal) {
3360
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3360
		while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
3361
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3361
			sip_pvt_unlock(pkt->owner);	/* SIP_PVT, not channel */
3362
			usleep(1);
3362
			usleep(1);
3363
			sip_pvt_lock(pkt->owner);
3363
			sip_pvt_lock(pkt->owner);
3364
		}
3364
		}
3365

    
   
3365

   
3366
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
3366
		if (pkt->owner->owner && !pkt->owner->owner->hangupcause)
3367
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3367
			pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
3368
		
3368
		
3369
		if (pkt->owner->owner) {
3369
		if (pkt->owner->owner) {
3370
			sip_alreadygone(pkt->owner);
3370
			sip_alreadygone(pkt->owner);
3371
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3371
			ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
3372
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3372
			ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
3373
			ast_channel_unlock(pkt->owner->owner);
3373
			ast_channel_unlock(pkt->owner->owner);
3374
		} else {
3374
		} else {
3375
			/* If no channel owner, destroy now */
3375
			/* If no channel owner, destroy now */
3376

    
   
3376

   
3377
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3377
			/* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
3378
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3378
			if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
3379
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3379
				pvt_set_needdestroy(pkt->owner, "no response to critical packet");
3380
				sip_alreadygone(pkt->owner);
3380
				sip_alreadygone(pkt->owner);
3381
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3381
				append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
3382
			}
3382
			}
3383
		}
3383
		}
3384
	}
3384
	}
3385

    
   
3385

   
3386
	if (pkt->method == SIP_BYE) {
3386
	if (pkt->method == SIP_BYE) {
3387
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3387
		/* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
3388
		if (pkt->owner->owner)
3388
		if (pkt->owner->owner)
3389
			ast_channel_unlock(pkt->owner->owner);
3389
			ast_channel_unlock(pkt->owner->owner);
3390
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3390
		append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
3391
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3391
		pvt_set_needdestroy(pkt->owner, "no response to BYE");
3392
	}
3392
	}
3393

    
   
3393

   
3394
	/* Remove the packet */
3394
	/* Remove the packet */
3395
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3395
	for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
3396
		if (cur == pkt) {
3396
		if (cur == pkt) {
3397
			UNLINK(cur, pkt->owner->packets, prev);
3397
			UNLINK(cur, pkt->owner->packets, prev);
3398
			sip_pvt_unlock(pkt->owner);
3398
			sip_pvt_unlock(pkt->owner);
3399
			if (pkt->owner)
3399
			if (pkt->owner)
3400
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3400
				pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3401
			if (pkt->data)
3401
			if (pkt->data)
3402
				ast_free(pkt->data);
3402
				ast_free(pkt->data);
3403
			pkt->data = NULL;
3403
			pkt->data = NULL;
3404
			ast_free(pkt);
3404
			ast_free(pkt);
3405
			return 0;
3405
			return 0;
3406
		}
3406
		}
3407
	}
3407
	}
3408
	/* error case */
3408
	/* error case */
3409
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3409
	ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
3410
	sip_pvt_unlock(pkt->owner);
3410
	sip_pvt_unlock(pkt->owner);
3411
	return 0;
3411
	return 0;
3412
}
3412
}
3413

    
   
3413

   
3414
/*! \brief Transmit packet with retransmits
3414
/*! \brief Transmit packet with retransmits
3415
	\return 0 on success, -1 on failure to allocate packet
3415
	\return 0 on success, -1 on failure to allocate packet
3416
*/
3416
*/
3417
static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
3417
static enum sip_result __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod)
3418
{
3418
{
3419
	struct sip_pkt *pkt = NULL;
3419
	struct sip_pkt *pkt = NULL;
3420
	int siptimer_a = DEFAULT_RETRANS;
3420
	int siptimer_a = DEFAULT_RETRANS;
3421
	int xmitres = 0;
3421
	int xmitres = 0;
3422
	int respid;
3422
	int respid;
3423

    
   
3423

   
3424
	if (sipmethod == SIP_INVITE) {
3424
	if (sipmethod == SIP_INVITE) {
3425
		/* Note this is a pending invite */
3425
		/* Note this is a pending invite */
3426
		p->pendinginvite = seqno;
3426
		p->pendinginvite = seqno;
3427
	}
3427
	}
3428

    
   
3428

   
3429
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3429
	/* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
3430
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3430
	/* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
3431
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3431
	/*! \todo According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
3432
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3432
	if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
3433
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3433
		xmitres = __sip_xmit(p, data, len);	/* Send packet */
3434
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3434
		if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3435
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3435
			append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
3436
			return AST_FAILURE;
3436
			return AST_FAILURE;
3437
		} else {
3437
		} else {
3438
			return AST_SUCCESS;
3438
			return AST_SUCCESS;
3439
		}
3439
		}
3440
	}
3440
	}
3441

    
   
3441

   
3442
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3442
	if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
3443
		return AST_FAILURE;
3443
		return AST_FAILURE;
3444
	/* copy data, add a terminator and save length */
3444
	/* copy data, add a terminator and save length */
3445
	if (!(pkt->data = ast_str_create(len))) {
3445
	if (!(pkt->data = ast_str_create(len))) {
3446
		ast_free(pkt);
3446
		ast_free(pkt);
3447
		return AST_FAILURE;
3447
		return AST_FAILURE;
3448
	}
3448
	}
3449
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3449
	ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
3450
	pkt->packetlen = len;
3450
	pkt->packetlen = len;
3451
	/* copy other parameters from the caller */
3451
	/* copy other parameters from the caller */
3452
	pkt->method = sipmethod;
3452
	pkt->method = sipmethod;
3453
	pkt->seqno = seqno;
3453
	pkt->seqno = seqno;
3454
	pkt->is_resp = resp;
3454
	pkt->is_resp = resp;
3455
	pkt->is_fatal = fatal;
3455
	pkt->is_fatal = fatal;
3456
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3456
	pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
3457
	pkt->next = p->packets;
3457
	pkt->next = p->packets;
3458
	p->packets = pkt;	/* Add it to the queue */
3458
	p->packets = pkt;	/* Add it to the queue */
3459
	if (resp) {
3459
	if (resp) {
3460
		/* Parse out the response code */
3460
		/* Parse out the response code */
3461
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3461
		if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
3462
			pkt->response_code = respid;
3462
			pkt->response_code = respid;
3463
		}
3463
		}
3464
	}
3464
	}
3465
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3465
	pkt->timer_t1 = p->timer_t1;	/* Set SIP timer T1 */
3466
	pkt->retransid = -1;
3466
	pkt->retransid = -1;
3467
	if (pkt->timer_t1)
3467
	if (pkt->timer_t1)
3468
		siptimer_a = pkt->timer_t1 * 2;
3468
		siptimer_a = pkt->timer_t1 * 2;
3469

    
   
3469

   
3470
	/* Schedule retransmission */
3470
	/* Schedule retransmission */
3471
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3471
	AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
3472
	if (sipdebug)
3472
	if (sipdebug)
3473
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3473
		ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
3474

    
   
3474

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

    
   
3476

   
3477
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3477
	if (xmitres == XMIT_ERROR) {	/* Serious network trouble, no need to try again */
3478
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3478
		append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
3479
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3479
		ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
3480
		AST_SCHED_DEL(sched, pkt->retransid);
3480
		AST_SCHED_DEL(sched, pkt->retransid);
3481
		p->packets = pkt->next;
3481
		p->packets = pkt->next;
3482
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3482
		pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
3483
		ast_free(pkt->data);
3483
		ast_free(pkt->data);
3484
		ast_free(pkt);
3484
		ast_free(pkt);
3485
		return AST_FAILURE;
3485
		return AST_FAILURE;
3486
	} else {
3486
	} else {
3487
		return AST_SUCCESS;
3487
		return AST_SUCCESS;
3488
	}
3488
	}
3489
}
3489
}
3490

    
   
3490

   
3491
/*! \brief Kill a SIP dialog (called only by the scheduler)
3491
/*! \brief Kill a SIP dialog (called only by the scheduler)
3492
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3492
 * The scheduler has a reference to this dialog when p->autokillid != -1,
3493
 * and we are called using that reference. So if the event is not
3493
 * and we are called using that reference. So if the event is not
3494
 * rescheduled, we need to call dialog_unref().
3494
 * rescheduled, we need to call dialog_unref().
3495
 */
3495
 */
3496
static int __sip_autodestruct(const void *data)
3496
static int __sip_autodestruct(const void *data)
3497
{
3497
{
3498
	struct sip_pvt *p = (struct sip_pvt *)data;
3498
	struct sip_pvt *p = (struct sip_pvt *)data;
3499

    
   
3499

   
3500
	/* If this is a subscription, tell the phone that we got a timeout */
3500
	/* If this is a subscription, tell the phone that we got a timeout */
3501
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3501
	if (p->subscribed && p->subscribed != MWI_NOTIFICATION && p->subscribed != CALL_COMPLETION) {
3502
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3502
		transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);	/* Send last notification */
3503
		p->subscribed = NONE;
3503
		p->subscribed = NONE;
3504
		append_history(p, "Subscribestatus", "timeout");
3504
		append_history(p, "Subscribestatus", "timeout");
3505
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3505
		ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
3506
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3506
		return 10000;	/* Reschedule this destruction so that we know that it's gone */
3507
	}
3507
	}
3508

    
   
3508

   
3509
	/* If there are packets still waiting for delivery, delay the destruction */
3509
	/* If there are packets still waiting for delivery, delay the destruction */
3510
	if (p->packets) {
3510
	if (p->packets) {
3511
		if (!p->needdestroy) {
3511
		if (!p->needdestroy) {
3512
			char method_str[31];
3512
			char method_str[31];
3513
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3513
			ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
3514
			append_history(p, "ReliableXmit", "timeout");
3514
			append_history(p, "ReliableXmit", "timeout");
3515
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3515
			if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
3516
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3516
				if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
3517
					pvt_set_needdestroy(p, "autodestruct");
3517
					pvt_set_needdestroy(p, "autodestruct");
3518
				}
3518
				}
3519
			}
3519
			}
3520
			return 10000;
3520
			return 10000;
3521
		} else {
3521
		} else {
3522
			/* They've had their chance to respond. Time to bail */
3522
			/* They've had their chance to respond. Time to bail */
3523
			__sip_pretend_ack(p);
3523
			__sip_pretend_ack(p);
3524
		}
3524
		}
3525
	}
3525
	}
3526

    
   
3526

   
3527
	if (p->subscribed == MWI_NOTIFICATION) {
3527
	if (p->subscribed == MWI_NOTIFICATION) {
3528
		if (p->relatedpeer) {
3528
		if (p->relatedpeer) {
3529
			p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3529
			p->relatedpeer = unref_peer(p->relatedpeer, "__sip_autodestruct: unref peer p->relatedpeer");	/* Remove link to peer. If it's realtime, make sure it's gone from memory) */
3530
		}
3530
		}
3531
	}
3531
	}
3532

    
   
3532

   
3533
	/* Reset schedule ID */
3533
	/* Reset schedule ID */
3534
	p->autokillid = -1;
3534
	p->autokillid = -1;
3535

    
   
3535

   
3536
	if (p->owner) {
3536
	if (p->owner) {
3537
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3537
		ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
3538
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3538
		ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
3539
	} else if (p->refer && !p->alreadygone) {
3539
	} else if (p->refer && !p->alreadygone) {
3540
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3540
		ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
3541
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3541
		transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
3542
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3542
		append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
3543
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3543
		sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
3544
	} else {
3544
	} else {
3545
		append_history(p, "AutoDestroy", "%s", p->callid);
3545
		append_history(p, "AutoDestroy", "%s", p->callid);
3546
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3546
		ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
3547
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3547
		dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
3548
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3548
		/* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
3549
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3549
		/* sip_destroy(p); */		/* Go ahead and destroy dialog. All attempts to recover is done */
3550
		/* sip_destroy also absorbs the reference */
3550
		/* sip_destroy also absorbs the reference */
3551
	}
3551
	}
3552
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3552
	dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
3553
	return 0;
3553
	return 0;
3554
}
3554
}
3555

    
   
3555

   
3556
/*! \brief Schedule destruction of SIP dialog */
3556
/*! \brief Schedule destruction of SIP dialog */
3557
void sip_scheddestroy(struct sip_pvt *p, int ms)
3557
void sip_scheddestroy(struct sip_pvt *p, int ms)
3558
{
3558
{
3559
	if (ms < 0) {
3559
	if (ms < 0) {
3560
		if (p->timer_t1 == 0) {
3560
		if (p->timer_t1 == 0) {
3561
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3561
			p->timer_t1 = global_t1;	/* Set timer T1 if not set (RFC 3261) */
3562
		}
3562
		}
3563
		if (p->timer_b == 0) {
3563
		if (p->timer_b == 0) {
3564
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3564
			p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
3565
		}
3565
		}
3566
		ms = p->timer_t1 * 64;
3566
		ms = p->timer_t1 * 64;
3567
	}
3567
	}
3568
	if (sip_debug_test_pvt(p))
3568
	if (sip_debug_test_pvt(p))
3569
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3569
		ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
3570
	if (sip_cancel_destroy(p))
3570
	if (sip_cancel_destroy(p))
3571
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3571
		ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
3572

    
   
3572

   
3573
	if (p->do_history)
3573
	if (p->do_history)
3574
		append_history(p, "SchedDestroy", "%d ms", ms);
3574
		append_history(p, "SchedDestroy", "%d ms", ms);
3575
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3575
	p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
3576

    
   
3576

   
3577
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3577
	if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
3578
		stop_session_timer(p);
3578
		stop_session_timer(p);
3579
}
3579
}
3580

    
   
3580

   
3581
/*! \brief Cancel destruction of SIP dialog.
3581
/*! \brief Cancel destruction of SIP dialog.
3582
 * Be careful as this also absorbs the reference - if you call it
3582
 * Be careful as this also absorbs the reference - if you call it
3583
 * from within the scheduler, this might be the last reference.
3583
 * from within the scheduler, this might be the last reference.
3584
 */
3584
 */
3585
int sip_cancel_destroy(struct sip_pvt *p)
3585
int sip_cancel_destroy(struct sip_pvt *p)
3586
{
3586
{
3587
	int res = 0;
3587
	int res = 0;
3588
	if (p->autokillid > -1) {
3588
	if (p->autokillid > -1) {
3589
		int res3;
3589
		int res3;
3590

    
   
3590

   
3591
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3591
		if (!(res3 = ast_sched_del(sched, p->autokillid))) {
3592
			append_history(p, "CancelDestroy", "");
3592
			append_history(p, "CancelDestroy", "");
3593
			p->autokillid = -1;
3593
			p->autokillid = -1;
3594
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3594
			dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
3595
		}
3595
		}
3596
	}
3596
	}
3597
	return res;
3597
	return res;
3598
}
3598
}
3599

    
   
3599

   
3600
/*! \brief Acknowledges receipt of a packet and stops retransmission
3600
/*! \brief Acknowledges receipt of a packet and stops retransmission
3601
 * called with p locked*/
3601
 * called with p locked*/
3602
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3602
int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3603
{
3603
{
3604
	struct sip_pkt *cur, *prev = NULL;
3604
	struct sip_pkt *cur, *prev = NULL;
3605
	const char *msg = "Not Found";	/* used only for debugging */
3605
	const char *msg = "Not Found";	/* used only for debugging */
3606
	int res = FALSE;
3606
	int res = FALSE;
3607

    
   
3607

   
3608
	/* If we have an outbound proxy for this dialog, then delete it now since
3608
	/* If we have an outbound proxy for this dialog, then delete it now since
3609
	  the rest of the requests in this dialog needs to follow the routing.
3609
	  the rest of the requests in this dialog needs to follow the routing.
3610
	  If obforcing is set, we will keep the outbound proxy during the whole
3610
	  If obforcing is set, we will keep the outbound proxy during the whole
3611
	  dialog, regardless of what the SIP rfc says
3611
	  dialog, regardless of what the SIP rfc says
3612
	*/
3612
	*/
3613
	if (p->outboundproxy && !p->outboundproxy->force){
3613
	if (p->outboundproxy && !p->outboundproxy->force){
3614
		ref_proxy(p, NULL);
3614
		ref_proxy(p, NULL);
3615
	}
3615
	}
3616

    
   
3616

   
3617
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3617
	for (cur = p->packets; cur; prev = cur, cur = cur->next) {
3618
		if (cur->seqno != seqno || cur->is_resp != resp)
3618
		if (cur->seqno != seqno || cur->is_resp != resp)
3619
			continue;
3619
			continue;
3620
		if (cur->is_resp || cur->method == sipmethod) {
3620
		if (cur->is_resp || cur->method == sipmethod) {
3621
			res = TRUE;
3621
			res = TRUE;
3622
			msg = "Found";
3622
			msg = "Found";
3623
			if (!resp && (seqno == p->pendinginvite)) {
3623
			if (!resp && (seqno == p->pendinginvite)) {
3624
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3624
				ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
3625
				p->pendinginvite = 0;
3625
				p->pendinginvite = 0;
3626
			}
3626
			}
3627
			if (cur->retransid > -1) {
3627
			if (cur->retransid > -1) {
3628
				if (sipdebug)
3628
				if (sipdebug)
3629
					ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3629
					ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
3630
			}
3630
			}
3631
			/* This odd section is designed to thwart a
3631
			/* This odd section is designed to thwart a
3632
			 * race condition in the packet scheduler. There are
3632
			 * race condition in the packet scheduler. There are
3633
			 * two conditions under which deleting the packet from the
3633
			 * two conditions under which deleting the packet from the
3634
			 * scheduler can fail.
3634
			 * scheduler can fail.
3635
			 *
3635
			 *
3636
			 * 1. The packet has been removed from the scheduler because retransmission
3636
			 * 1. The packet has been removed from the scheduler because retransmission
3637
			 * is being attempted. The problem is that if the packet is currently attempting
3637
			 * is being attempted. The problem is that if the packet is currently attempting
3638
			 * retransmission and we are at this point in the code, then that MUST mean
3638
			 * retransmission and we are at this point in the code, then that MUST mean
3639
			 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3639
			 * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
3640
			 * lock temporarily to allow retransmission.
3640
			 * lock temporarily to allow retransmission.
3641
			 *
3641
			 *
3642
			 * 2. The packet has reached its maximum number of retransmissions and has
3642
			 * 2. The packet has reached its maximum number of retransmissions and has
3643
			 * been permanently removed from the packet scheduler. If this is the case, then
3643
			 * been permanently removed from the packet scheduler. If this is the case, then
3644
			 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3644
			 * the packet's retransid will be set to -1. The atomicity of the setting and checking
3645
			 * of the retransid to -1 is ensured since in both cases p's lock is held.
3645
			 * of the retransid to -1 is ensured since in both cases p's lock is held.
3646
			 */
3646
			 */
3647
			while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3647
			while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
3648
				sip_pvt_unlock(p);
3648
				sip_pvt_unlock(p);
3649
				usleep(1);
3649
				usleep(1);
3650
				sip_pvt_lock(p);
3650
				sip_pvt_lock(p);
3651
			}
3651
			}
3652
			UNLINK(cur, p->packets, prev);
3652
			UNLINK(cur, p->packets, prev);
3653
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3653
			dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
3654
			if (cur->data)
3654
			if (cur->data)
3655
				ast_free(cur->data);
3655
				ast_free(cur->data);
3656
			ast_free(cur);
3656
			ast_free(cur);
3657
			break;
3657
			break;
3658
		}
3658
		}
3659
	}
3659
	}
3660
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3660
	ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
3661
		p->callid, resp ? "Response" : "Request", seqno, msg);
3661
		p->callid, resp ? "Response" : "Request", seqno, msg);
3662
	return res;
3662
	return res;
3663
}
3663
}
3664

    
   
3664

   
3665
/*! \brief Pretend to ack all packets
3665
/*! \brief Pretend to ack all packets
3666
 * called with p locked */
3666
 * called with p locked */
3667
void __sip_pretend_ack(struct sip_pvt *p)
3667
void __sip_pretend_ack(struct sip_pvt *p)
3668
{
3668
{
3669
	struct sip_pkt *cur = NULL;
3669
	struct sip_pkt *cur = NULL;
3670

    
   
3670

   
3671
	while (p->packets) {
3671
	while (p->packets) {
3672
		int method;
3672
		int method;
3673
		if (cur == p->packets) {
3673
		if (cur == p->packets) {
3674
			ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3674
			ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
3675
			return;
3675
			return;
3676
		}
3676
		}
3677
		cur = p->packets;
3677
		cur = p->packets;
3678
		method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3678
		method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
3679
		__sip_ack(p, cur->seqno, cur->is_resp, method);
3679
		__sip_ack(p, cur->seqno, cur->is_resp, method);
3680
	}
3680
	}
3681
}
3681
}
3682

    
   
3682

   
3683
/*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3683
/*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
3684
int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3684
int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
3685
{
3685
{
3686
	struct sip_pkt *cur;
3686
	struct sip_pkt *cur;
3687
	int res = FALSE;
3687
	int res = FALSE;
3688

    
   
3688

   
3689
	for (cur = p->packets; cur; cur = cur->next) {
3689
	for (cur = p->packets; cur; cur = cur->next) {
3690
		if (cur->seqno == seqno && cur->is_resp == resp &&
3690
		if (cur->seqno == seqno && cur->is_resp == resp &&
3691
			(cur->is_resp || method_match(sipmethod, cur->data->str))) {
3691
			(cur->is_resp || method_match(sipmethod, cur->data->str))) {
3692
			/* this is our baby */
3692
			/* this is our baby */
3693
			if (cur->retransid > -1) {
3693
			if (cur->retransid > -1) {
3694
				if (sipdebug)
3694
				if (sipdebug)
3695
					ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3695
					ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
3696
			}
3696
			}
3697
			AST_SCHED_DEL(sched, cur->retransid);
3697
			AST_SCHED_DEL(sched, cur->retransid);
3698
			res = TRUE;
3698
			res = TRUE;
3699
			break;
3699
			break;
3700
		}
3700
		}
3701
	}
3701
	}
3702
	ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
3702
	ast_debug(1, "(Provisional) Stopping retransmission (but retaining packet) on '%s' %s %d: %s\n", p->callid, resp ? "Response" : "Request", seqno, res == -1 ? "Not Found" : "Found");
3703
	return res;
3703
	return res;
3704
}
3704
}
3705

    
   
3705

   
3706

    
   
3706

   
3707
/*! \brief Copy SIP request, parse it */
3707
/*! \brief Copy SIP request, parse it */
3708
static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3708
static void parse_copy(struct sip_request *dst, const struct sip_request *src)
3709
{
3709
{
3710
	copy_request(dst, src);
3710
	copy_request(dst, src);
3711
	parse_request(dst);
3711
	parse_request(dst);
3712
}
3712
}
3713

    
   
3713

   
3714
/*! \brief add a blank line if no body */
3714
/*! \brief add a blank line if no body */
3715
static void add_blank(struct sip_request *req)
3715
static void add_blank(struct sip_request *req)
3716
{
3716
{
3717
	if (!req->lines) {
3717
	if (!req->lines) {
3718
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3718
		/* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
3719
		ast_str_append(&req->data, 0, "\r\n");
3719
		ast_str_append(&req->data, 0, "\r\n");
3720
		req->len = ast_str_strlen(req->data);
3720
		req->len = ast_str_strlen(req->data);
3721
	}
3721
	}
3722
}
3722
}
3723

    
   
3723

   
3724
static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
3724
static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
3725
{
3725
{
3726
	const char *msg = NULL;
3726
	const char *msg = NULL;
3727

    
   
3727

   
3728
	if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
3728
	if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
3729
		msg = "183 Session Progress";
3729
		msg = "183 Session Progress";
3730
	}
3730
	}
3731

    
   
3731

   
3732
	if (pvt->invitestate < INV_COMPLETED) {
3732
	if (pvt->invitestate < INV_COMPLETED) {
3733
		if (with_sdp) {
3733
		if (with_sdp) {
3734
			transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
3734
			transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE, FALSE);
3735
		} else {
3735
		} else {
3736
			transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
3736
			transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
3737
		}
3737
		}
3738
		return PROVIS_KEEPALIVE_TIMEOUT;
3738