Review Board 1.7.16


chan_iax2 - unprotected access of iaxs[peer->callno] potentially results in segfault

Review Request #4599 - Created April 7, 2015 and submitted

Jaco Kroon
trunk
ASTERISK-21211
Reviewers
asterisk-dev
Asterisk
chan_iax2.c, specifically in function iax2_poke_peer, a completely unprotected access to iaxs[peer->callno] is made. Specifically I had a segfault trigger on line 12230, an access to iaxs[peer->callno] - the second in a sequence, so peer->callno can definitely change between the two

It is my understanding that:

1. peer->callno can change outside of the function , thus it's probably unsafe to use the raw value as per lines 12223, 12229 and 12230. I believe this should be callno, and not peer->callno. Please correct me if I'm wrong. This can either happen by us calling iax2_destroy, or simply another thread also scheduling a POKE on the same peer.

2. All reads and writes to iaxs[X] should be protected by a lock of iaxsl[X]. Lines 12229 and 12230 violates this currently.

I suspect my crash resulted from a sequence where a POKE was in process of being scheduled, another thread then called iax2_poke_peer for the same peer, called iax2_destroy on the iaxs[] busy being set up, and boom major catastrophe.
Been running since 11.2.1 with this patch, specifically 6/3/2013 (more than two years) in multiple production environments.  Many fewer segfaults.

Diff revision 1 (Latest)

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

    
   
18

   
19
/*! \file
19
/*! \file
20
 *
20
 *
21
 * \brief Implementation of Inter-Asterisk eXchange Version 2
21
 * \brief Implementation of Inter-Asterisk eXchange Version 2
22
 *        as specified in RFC 5456
22
 *        as specified in RFC 5456
23
 *
23
 *
24
 * \author Mark Spencer <markster@digium.com>
24
 * \author Mark Spencer <markster@digium.com>
25
 *
25
 *
26
 * \par See also
26
 * \par See also
27
 * \arg \ref Config_iax
27
 * \arg \ref Config_iax
28
 *
28
 *
29
 * \ingroup channel_drivers
29
 * \ingroup channel_drivers
30
 *
30
 *
31
 * \todo Implement musicclass settings for IAX2 devices
31
 * \todo Implement musicclass settings for IAX2 devices
32
 */
32
 */
33

    
   
33

   
34
/*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
34
/*! \li \ref chan_iax2.c uses the configuration file \ref iax.conf
35
 * \addtogroup configuration_file
35
 * \addtogroup configuration_file
36
 */
36
 */
37

    
   
37

   
38
/*! \page iax.conf iax.conf
38
/*! \page iax.conf iax.conf
39
 * \verbinclude iax.conf.sample
39
 * \verbinclude iax.conf.sample
40
 */
40
 */
41

    
   
41

   
42
/*!
42
/*!
43
 * \todo XXX The IAX2 channel driver needs its native bridge
43
 * \todo XXX The IAX2 channel driver needs its native bridge
44
 * code converted to the new bridge technology scheme.
44
 * code converted to the new bridge technology scheme.
45
 *
45
 *
46
 * \note The chan_dahdi native bridge code can be used as an
46
 * \note The chan_dahdi native bridge code can be used as an
47
 * example.  It also appears that chan_iax2 also has a native
47
 * example.  It also appears that chan_iax2 also has a native
48
 * transfer check like chan_dahdi to eliminate tromboned calls.
48
 * transfer check like chan_dahdi to eliminate tromboned calls.
49
 *
49
 *
50
 * \note The existing native bridge code is marked with the
50
 * \note The existing native bridge code is marked with the
51
 * IAX2_NATIVE_BRIDGING conditional.
51
 * IAX2_NATIVE_BRIDGING conditional.
52
 */
52
 */
53

    
   
53

   
54
/*** MODULEINFO
54
/*** MODULEINFO
55
	<use type="external">crypto</use>
55
	<use type="external">crypto</use>
56
	<support_level>core</support_level>
56
	<support_level>core</support_level>
57
 ***/
57
 ***/
58

    
   
58

   
59
#include "asterisk.h"
59
#include "asterisk.h"
60

    
   
60

   
61
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
61
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
62

    
   
62

   
63
#include <sys/mman.h>
63
#include <sys/mman.h>
64
#include <dirent.h>
64
#include <dirent.h>
65
#include <sys/socket.h>
65
#include <sys/socket.h>
66
#include <netinet/in.h>
66
#include <netinet/in.h>
67
#include <arpa/inet.h>
67
#include <arpa/inet.h>
68
#include <netinet/in_systm.h>
68
#include <netinet/in_systm.h>
69
#include <netinet/ip.h>
69
#include <netinet/ip.h>
70
#include <sys/time.h>
70
#include <sys/time.h>
71
#include <sys/signal.h>
71
#include <sys/signal.h>
72
#include <signal.h>
72
#include <signal.h>
73
#include <strings.h>
73
#include <strings.h>
74
#include <netdb.h>
74
#include <netdb.h>
75
#include <fcntl.h>
75
#include <fcntl.h>
76
#include <sys/stat.h>
76
#include <sys/stat.h>
77
#include <regex.h>
77
#include <regex.h>
78

    
   
78

   
79
#include "asterisk/paths.h"
79
#include "asterisk/paths.h"
80

    
   
80

   
81
#include "asterisk/lock.h"
81
#include "asterisk/lock.h"
82
#include "asterisk/frame.h"
82
#include "asterisk/frame.h"
83
#include "asterisk/channel.h"
83
#include "asterisk/channel.h"
84
#include "asterisk/module.h"
84
#include "asterisk/module.h"
85
#include "asterisk/pbx.h"
85
#include "asterisk/pbx.h"
86
#include "asterisk/sched.h"
86
#include "asterisk/sched.h"
87
#include "asterisk/io.h"
87
#include "asterisk/io.h"
88
#include "asterisk/config.h"
88
#include "asterisk/config.h"
89
#include "asterisk/cli.h"
89
#include "asterisk/cli.h"
90
#include "asterisk/translate.h"
90
#include "asterisk/translate.h"
91
#include "asterisk/md5.h"
91
#include "asterisk/md5.h"
92
#include "asterisk/crypto.h"
92
#include "asterisk/crypto.h"
93
#include "asterisk/acl.h"
93
#include "asterisk/acl.h"
94
#include "asterisk/manager.h"
94
#include "asterisk/manager.h"
95
#include "asterisk/callerid.h"
95
#include "asterisk/callerid.h"
96
#include "asterisk/app.h"
96
#include "asterisk/app.h"
97
#include "asterisk/astdb.h"
97
#include "asterisk/astdb.h"
98
#include "asterisk/musiconhold.h"
98
#include "asterisk/musiconhold.h"
99
#include "asterisk/features.h"
99
#include "asterisk/features.h"
100
#include "asterisk/utils.h"
100
#include "asterisk/utils.h"
101
#include "asterisk/causes.h"
101
#include "asterisk/causes.h"
102
#include "asterisk/localtime.h"
102
#include "asterisk/localtime.h"
103
#include "asterisk/dnsmgr.h"
103
#include "asterisk/dnsmgr.h"
104
#include "asterisk/devicestate.h"
104
#include "asterisk/devicestate.h"
105
#include "asterisk/netsock.h"
105
#include "asterisk/netsock.h"
106
#include "asterisk/stringfields.h"
106
#include "asterisk/stringfields.h"
107
#include "asterisk/linkedlists.h"
107
#include "asterisk/linkedlists.h"
108
#include "asterisk/astobj2.h"
108
#include "asterisk/astobj2.h"
109
#include "asterisk/timing.h"
109
#include "asterisk/timing.h"
110
#include "asterisk/taskprocessor.h"
110
#include "asterisk/taskprocessor.h"
111
#include "asterisk/test.h"
111
#include "asterisk/test.h"
112
#include "asterisk/data.h"
112
#include "asterisk/data.h"
113
#include "asterisk/security_events.h"
113
#include "asterisk/security_events.h"
114
#include "asterisk/stasis_endpoints.h"
114
#include "asterisk/stasis_endpoints.h"
115
#include "asterisk/bridge.h"
115
#include "asterisk/bridge.h"
116
#include "asterisk/stasis.h"
116
#include "asterisk/stasis.h"
117
#include "asterisk/stasis_system.h"
117
#include "asterisk/stasis_system.h"
118
#include "asterisk/stasis_channels.h"
118
#include "asterisk/stasis_channels.h"
119
#include "asterisk/format_cache.h"
119
#include "asterisk/format_cache.h"
120
#include "asterisk/format_compatibility.h"
120
#include "asterisk/format_compatibility.h"
121
#include "asterisk/format_cap.h"
121
#include "asterisk/format_cap.h"
122

    
   
122

   
123
#include "iax2/include/iax2.h"
123
#include "iax2/include/iax2.h"
124
#include "iax2/include/firmware.h"
124
#include "iax2/include/firmware.h"
125
#include "iax2/include/parser.h"
125
#include "iax2/include/parser.h"
126
#include "iax2/include/provision.h"
126
#include "iax2/include/provision.h"
127
#include "iax2/include/codec_pref.h"
127
#include "iax2/include/codec_pref.h"
128
#include "iax2/include/format_compatibility.h"
128
#include "iax2/include/format_compatibility.h"
129

    
   
129

   
130
#include "jitterbuf.h"
130
#include "jitterbuf.h"
131

    
   
131

   
132
/*** DOCUMENTATION
132
/*** DOCUMENTATION
133
	<application name="IAX2Provision" language="en_US">
133
	<application name="IAX2Provision" language="en_US">
134
		<synopsis>
134
		<synopsis>
135
			Provision a calling IAXy with a given template.
135
			Provision a calling IAXy with a given template.
136
		</synopsis>
136
		</synopsis>
137
		<syntax>
137
		<syntax>
138
			<parameter name="template">
138
			<parameter name="template">
139
				<para>If not specified, defaults to <literal>default</literal>.</para>
139
				<para>If not specified, defaults to <literal>default</literal>.</para>
140
			</parameter>
140
			</parameter>
141
		</syntax>
141
		</syntax>
142
		<description>
142
		<description>
143
			<para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
143
			<para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
144
			given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
144
			given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
145
			or <literal>0</literal> on success.</para>
145
			or <literal>0</literal> on success.</para>
146
		</description>
146
		</description>
147
	</application>
147
	</application>
148
	<function name="IAXPEER" language="en_US">
148
	<function name="IAXPEER" language="en_US">
149
		<synopsis>
149
		<synopsis>
150
			Gets IAX peer information.
150
			Gets IAX peer information.
151
		</synopsis>
151
		</synopsis>
152
		<syntax>
152
		<syntax>
153
			<parameter name="peername" required="true">
153
			<parameter name="peername" required="true">
154
				<enumlist>
154
				<enumlist>
155
					<enum name="CURRENTCHANNEL">
155
					<enum name="CURRENTCHANNEL">
156
						<para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
156
						<para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
157
						endpoint of the current channel</para>
157
						endpoint of the current channel</para>
158
					</enum>
158
					</enum>
159
				</enumlist>
159
				</enumlist>
160
			</parameter>
160
			</parameter>
161
			<parameter name="item">
161
			<parameter name="item">
162
				<para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
162
				<para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
163
				<enumlist>
163
				<enumlist>
164
					<enum name="ip">
164
					<enum name="ip">
165
						<para>(default) The IP address.</para>
165
						<para>(default) The IP address.</para>
166
					</enum>
166
					</enum>
167
					<enum name="status">
167
					<enum name="status">
168
						<para>The peer's status (if <literal>qualify=yes</literal>)</para>
168
						<para>The peer's status (if <literal>qualify=yes</literal>)</para>
169
					</enum>
169
					</enum>
170
					<enum name="mailbox">
170
					<enum name="mailbox">
171
						<para>The configured mailbox.</para>
171
						<para>The configured mailbox.</para>
172
					</enum>
172
					</enum>
173
					<enum name="context">
173
					<enum name="context">
174
						<para>The configured context.</para>
174
						<para>The configured context.</para>
175
					</enum>
175
					</enum>
176
					<enum name="expire">
176
					<enum name="expire">
177
						<para>The epoch time of the next expire.</para>
177
						<para>The epoch time of the next expire.</para>
178
					</enum>
178
					</enum>
179
					<enum name="dynamic">
179
					<enum name="dynamic">
180
						<para>Is it dynamic? (yes/no).</para>
180
						<para>Is it dynamic? (yes/no).</para>
181
					</enum>
181
					</enum>
182
					<enum name="callerid_name">
182
					<enum name="callerid_name">
183
						<para>The configured Caller ID name.</para>
183
						<para>The configured Caller ID name.</para>
184
					</enum>
184
					</enum>
185
					<enum name="callerid_num">
185
					<enum name="callerid_num">
186
						<para>The configured Caller ID number.</para>
186
						<para>The configured Caller ID number.</para>
187
					</enum>
187
					</enum>
188
					<enum name="codecs">
188
					<enum name="codecs">
189
						<para>The configured codecs.</para>
189
						<para>The configured codecs.</para>
190
					</enum>
190
					</enum>
191
					<enum name="codec[x]">
191
					<enum name="codec[x]">
192
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning
192
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning
193
						with <literal>0</literal>)</para>
193
						with <literal>0</literal>)</para>
194
					</enum>
194
					</enum>
195
				</enumlist>
195
				</enumlist>
196
			</parameter>
196
			</parameter>
197
		</syntax>
197
		</syntax>
198
		<description>
198
		<description>
199
			<para>Gets information associated with the specified IAX2 peer.</para>
199
			<para>Gets information associated with the specified IAX2 peer.</para>
200
		</description>
200
		</description>
201
		<see-also>
201
		<see-also>
202
			<ref type="function">SIPPEER</ref>
202
			<ref type="function">SIPPEER</ref>
203
		</see-also>
203
		</see-also>
204
	</function>
204
	</function>
205
	<function name="IAXVAR" language="en_US">
205
	<function name="IAXVAR" language="en_US">
206
		<synopsis>
206
		<synopsis>
207
			Sets or retrieves a remote variable.
207
			Sets or retrieves a remote variable.
208
		</synopsis>
208
		</synopsis>
209
		<syntax>
209
		<syntax>
210
			<parameter name="varname" required="true" />
210
			<parameter name="varname" required="true" />
211
		</syntax>
211
		</syntax>
212
		<description>
212
		<description>
213
			<para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
213
			<para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
214
		</description>
214
		</description>
215
	</function>
215
	</function>
216
	<manager name="IAXpeers" language="en_US">
216
	<manager name="IAXpeers" language="en_US">
217
		<synopsis>
217
		<synopsis>
218
			List IAX peers.
218
			List IAX peers.
219
		</synopsis>
219
		</synopsis>
220
		<syntax>
220
		<syntax>
221
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
221
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
222
		</syntax>
222
		</syntax>
223
		<description>
223
		<description>
224
		</description>
224
		</description>
225
	</manager>
225
	</manager>
226
	<manager name="IAXpeerlist" language="en_US">
226
	<manager name="IAXpeerlist" language="en_US">
227
		<synopsis>
227
		<synopsis>
228
			List IAX Peers.
228
			List IAX Peers.
229
		</synopsis>
229
		</synopsis>
230
		<syntax>
230
		<syntax>
231
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
231
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
232
		</syntax>
232
		</syntax>
233
		<description>
233
		<description>
234
			<para>List all the IAX peers.</para>
234
			<para>List all the IAX peers.</para>
235
		</description>
235
		</description>
236
	</manager>
236
	</manager>
237
	<manager name="IAXnetstats" language="en_US">
237
	<manager name="IAXnetstats" language="en_US">
238
		<synopsis>
238
		<synopsis>
239
			Show IAX Netstats.
239
			Show IAX Netstats.
240
		</synopsis>
240
		</synopsis>
241
		<syntax />
241
		<syntax />
242
		<description>
242
		<description>
243
			<para>Show IAX channels network statistics.</para>
243
			<para>Show IAX channels network statistics.</para>
244
		</description>
244
		</description>
245
	</manager>
245
	</manager>
246
	<manager name="IAXregistry" language="en_US">
246
	<manager name="IAXregistry" language="en_US">
247
		<synopsis>
247
		<synopsis>
248
			Show IAX registrations.
248
			Show IAX registrations.
249
		</synopsis>
249
		</synopsis>
250
		<syntax>
250
		<syntax>
251
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
251
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
252
		</syntax>
252
		</syntax>
253
		<description>
253
		<description>
254
			<para>Show IAX registrations.</para>
254
			<para>Show IAX registrations.</para>
255
		</description>
255
		</description>
256
	</manager>
256
	</manager>
257
 ***/
257
 ***/
258

    
   
258

   
259
/* Define SCHED_MULTITHREADED to run the scheduler in a special
259
/* Define SCHED_MULTITHREADED to run the scheduler in a special
260
   multithreaded mode. */
260
   multithreaded mode. */
261
#define SCHED_MULTITHREADED
261
#define SCHED_MULTITHREADED
262

    
   
262

   
263
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
263
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
264
   thread is actually doing. */
264
   thread is actually doing. */
265
#define DEBUG_SCHED_MULTITHREAD
265
#define DEBUG_SCHED_MULTITHREAD
266

    
   
266

   
267

    
   
267

   
268
#ifdef SO_NO_CHECK
268
#ifdef SO_NO_CHECK
269
static int nochecksums = 0;
269
static int nochecksums = 0;
270
#endif
270
#endif
271

    
   
271

   
272
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
272
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
273
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
273
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
274

    
   
274

   
275
#define DEFAULT_THREAD_COUNT 10
275
#define DEFAULT_THREAD_COUNT 10
276
#define DEFAULT_MAX_THREAD_COUNT 100
276
#define DEFAULT_MAX_THREAD_COUNT 100
277
#define DEFAULT_RETRY_TIME 1000
277
#define DEFAULT_RETRY_TIME 1000
278
#define MEMORY_SIZE 100
278
#define MEMORY_SIZE 100
279
#define DEFAULT_DROP 3
279
#define DEFAULT_DROP 3
280

    
   
280

   
281
#define DEBUG_SUPPORT
281
#define DEBUG_SUPPORT
282

    
   
282

   
283
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
283
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
284

    
   
284

   
285
/* Sample over last 100 units to determine historic jitter */
285
/* Sample over last 100 units to determine historic jitter */
286
#define GAMMA (0.01)
286
#define GAMMA (0.01)
287

    
   
287

   
288
static struct iax2_codec_pref prefs_global;
288
static struct iax2_codec_pref prefs_global;
289

    
   
289

   
290
static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
290
static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
291

    
   
291

   
292

    
   
292

   
293
/*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
293
/*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
294
    fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
294
    fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
295
#define MAX_TRUNK_MTU 1240
295
#define MAX_TRUNK_MTU 1240
296

    
   
296

   
297
static int global_max_trunk_mtu;	/*!< Maximum MTU, 0 if not used */
297
static int global_max_trunk_mtu;	/*!< Maximum MTU, 0 if not used */
298
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;	/*!< Trunk MTU statistics */
298
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;	/*!< Trunk MTU statistics */
299

    
   
299

   
300
#define DEFAULT_CONTEXT "default"
300
#define DEFAULT_CONTEXT "default"
301

    
   
301

   
302
static char default_parkinglot[AST_MAX_CONTEXT];
302
static char default_parkinglot[AST_MAX_CONTEXT];
303

    
   
303

   
304
static char language[MAX_LANGUAGE] = "";
304
static char language[MAX_LANGUAGE] = "";
305
static char regcontext[AST_MAX_CONTEXT] = "";
305
static char regcontext[AST_MAX_CONTEXT] = "";
306

    
   
306

   
307
static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
307
static struct stasis_subscription *network_change_sub; /*!< subscription id for network change events */
308
static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
308
static struct stasis_subscription *acl_change_sub; /*!< subscription id for ACL change events */
309
static int network_change_sched_id = -1;
309
static int network_change_sched_id = -1;
310

    
   
310

   
311
static int maxauthreq = 3;
311
static int maxauthreq = 3;
312
static int max_retries = 4;
312
static int max_retries = 4;
313
static int ping_time = 21;
313
static int ping_time = 21;
314
static int lagrq_time = 10;
314
static int lagrq_time = 10;
315
static int maxjitterbuffer=1000;
315
static int maxjitterbuffer=1000;
316
static int resyncthreshold=1000;
316
static int resyncthreshold=1000;
317
static int maxjitterinterps=10;
317
static int maxjitterinterps=10;
318
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
318
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
319

    
   
319

   
320
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
320
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
321

    
   
321

   
322
static int trunkfreq = 20;
322
static int trunkfreq = 20;
323
static int trunkmaxsize = MAX_TRUNKDATA;
323
static int trunkmaxsize = MAX_TRUNKDATA;
324

    
   
324

   
325
static int authdebug = 0;
325
static int authdebug = 0;
326
static int autokill = 0;
326
static int autokill = 0;
327
static int iaxcompat = 0;
327
static int iaxcompat = 0;
328
static int last_authmethod = 0;
328
static int last_authmethod = 0;
329

    
   
329

   
330
static int iaxdefaultdpcache=10 * 60;	/* Cache dialplan entries for 10 minutes by default */
330
static int iaxdefaultdpcache=10 * 60;	/* Cache dialplan entries for 10 minutes by default */
331

    
   
331

   
332
static int iaxdefaulttimeout = 5;		/* Default to wait no more than 5 seconds for a reply to come back */
332
static int iaxdefaulttimeout = 5;		/* Default to wait no more than 5 seconds for a reply to come back */
333

    
   
333

   
334
static struct {
334
static struct {
335
	unsigned int tos;
335
	unsigned int tos;
336
	unsigned int cos;
336
	unsigned int cos;
337
} qos = { 0, 0 };
337
} qos = { 0, 0 };
338

    
   
338

   
339
static int min_reg_expire;
339
static int min_reg_expire;
340
static int max_reg_expire;
340
static int max_reg_expire;
341

    
   
341

   
342
static int srvlookup = 0;
342
static int srvlookup = 0;
343

    
   
343

   
344
static struct ast_timer *timer;				/* Timer for trunking */
344
static struct ast_timer *timer;				/* Timer for trunking */
345

    
   
345

   
346
static struct ast_netsock_list *netsock;
346
static struct ast_netsock_list *netsock;
347
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
347
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
348
static int defaultsockfd = -1;
348
static int defaultsockfd = -1;
349

    
   
349

   
350
static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
350
static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
351

    
   
351

   
352
/* Ethernet, etc */
352
/* Ethernet, etc */
353
#define IAX_CAPABILITY_FULLBANDWIDTH	0xFFFF
353
#define IAX_CAPABILITY_FULLBANDWIDTH	0xFFFF
354
/* T1, maybe ISDN */
354
/* T1, maybe ISDN */
355
#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
355
#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
356
                     ~AST_FORMAT_SLIN &      \
356
                     ~AST_FORMAT_SLIN &      \
357
                     ~AST_FORMAT_SLIN16 &    \
357
                     ~AST_FORMAT_SLIN16 &    \
358
                     ~AST_FORMAT_SIREN7 &       \
358
                     ~AST_FORMAT_SIREN7 &       \
359
                     ~AST_FORMAT_SIREN14 &      \
359
                     ~AST_FORMAT_SIREN14 &      \
360
                     ~AST_FORMAT_G719 &         \
360
                     ~AST_FORMAT_G719 &         \
361
                     ~AST_FORMAT_ULAW &         \
361
                     ~AST_FORMAT_ULAW &         \
362
                     ~AST_FORMAT_ALAW &         \
362
                     ~AST_FORMAT_ALAW &         \
363
                     ~AST_FORMAT_G722)
363
                     ~AST_FORMAT_G722)
364
/* A modem */
364
/* A modem */
365
#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
365
#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
366
                     ~AST_FORMAT_G726 &         \
366
                     ~AST_FORMAT_G726 &         \
367
                     ~AST_FORMAT_G726_AAL2 &    \
367
                     ~AST_FORMAT_G726_AAL2 &    \
368
                     ~AST_FORMAT_ADPCM)
368
                     ~AST_FORMAT_ADPCM)
369

    
   
369

   
370
#define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
370
#define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
371
                     ~AST_FORMAT_G723)
371
                     ~AST_FORMAT_G723)
372

    
   
372

   
373

    
   
373

   
374
#define DEFAULT_MAXMS		2000		/* Must be faster than 2 seconds by default */
374
#define DEFAULT_MAXMS		2000		/* Must be faster than 2 seconds by default */
375
#define DEFAULT_FREQ_OK		60 * 1000	/* How often to check for the host to be up */
375
#define DEFAULT_FREQ_OK		60 * 1000	/* How often to check for the host to be up */
376
#define DEFAULT_FREQ_NOTOK	10 * 1000	/* How often to check, if the host is down... */
376
#define DEFAULT_FREQ_NOTOK	10 * 1000	/* How often to check, if the host is down... */
377

    
   
377

   
378
/* if a pvt has encryption setup done and is running on the call */
378
/* if a pvt has encryption setup done and is running on the call */
379
#define IAX_CALLENCRYPTED(pvt) \
379
#define IAX_CALLENCRYPTED(pvt) \
380
	(ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
380
	(ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
381

    
   
381

   
382
#define IAX_DEBUGDIGEST(msg, key) do { \
382
#define IAX_DEBUGDIGEST(msg, key) do { \
383
		int idx; \
383
		int idx; \
384
		char digest[33] = ""; \
384
		char digest[33] = ""; \
385
		\
385
		\
386
		if (!iaxdebug) \
386
		if (!iaxdebug) \
387
			break; \
387
			break; \
388
		\
388
		\
389
		for (idx = 0; idx < 16; idx++) \
389
		for (idx = 0; idx < 16; idx++) \
390
			sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
390
			sprintf(digest + (idx << 1), "%02hhx", (unsigned char) key[idx]); \
391
		\
391
		\
392
		ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
392
		ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
393
	} while(0)
393
	} while(0)
394

    
   
394

   
395
static struct io_context *io;
395
static struct io_context *io;
396
static struct ast_sched_context *sched;
396
static struct ast_sched_context *sched;
397

    
   
397

   
398
#define DONT_RESCHEDULE -2
398
#define DONT_RESCHEDULE -2
399

    
   
399

   
400
static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
400
static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
401

    
   
401

   
402
static int iaxdebug = 0;
402
static int iaxdebug = 0;
403

    
   
403

   
404
static int iaxtrunkdebug = 0;
404
static int iaxtrunkdebug = 0;
405

    
   
405

   
406
static int test_losspct = 0;
406
static int test_losspct = 0;
407
#ifdef IAXTESTS
407
#ifdef IAXTESTS
408
static int test_late = 0;
408
static int test_late = 0;
409
static int test_resync = 0;
409
static int test_resync = 0;
410
static int test_jit = 0;
410
static int test_jit = 0;
411
static int test_jitpct = 0;
411
static int test_jitpct = 0;
412
#endif /* IAXTESTS */
412
#endif /* IAXTESTS */
413

    
   
413

   
414
static char accountcode[AST_MAX_ACCOUNT_CODE];
414
static char accountcode[AST_MAX_ACCOUNT_CODE];
415
static char mohinterpret[MAX_MUSICCLASS];
415
static char mohinterpret[MAX_MUSICCLASS];
416
static char mohsuggest[MAX_MUSICCLASS];
416
static char mohsuggest[MAX_MUSICCLASS];
417
static int amaflags = 0;
417
static int amaflags = 0;
418
static int adsi = 0;
418
static int adsi = 0;
419
static int delayreject = 0;
419
static int delayreject = 0;
420
static int iax2_encryption = 0;
420
static int iax2_encryption = 0;
421

    
   
421

   
422
static struct ast_flags64 globalflags = { 0 };
422
static struct ast_flags64 globalflags = { 0 };
423

    
   
423

   
424
static pthread_t netthreadid = AST_PTHREADT_NULL;
424
static pthread_t netthreadid = AST_PTHREADT_NULL;
425

    
   
425

   
426
enum iax2_state {
426
enum iax2_state {
427
	IAX_STATE_STARTED =			(1 << 0),
427
	IAX_STATE_STARTED =			(1 << 0),
428
	IAX_STATE_AUTHENTICATED =	(1 << 1),
428
	IAX_STATE_AUTHENTICATED =	(1 << 1),
429
	IAX_STATE_TBD =				(1 << 2),
429
	IAX_STATE_TBD =				(1 << 2),
430
};
430
};
431

    
   
431

   
432
struct iax2_context {
432
struct iax2_context {
433
	char context[AST_MAX_CONTEXT];
433
	char context[AST_MAX_CONTEXT];
434
	struct iax2_context *next;
434
	struct iax2_context *next;
435
};
435
};
436

    
   
436

   
437

    
   
437

   
438
#define	IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
438
#define	IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
439
#define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
439
#define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
440
#define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
440
#define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
441
#define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
441
#define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
442
#define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
442
#define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
443
#define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
443
#define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
444
#define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
444
#define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
445
#define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
445
#define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
446
#define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
446
#define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
447
#define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
447
#define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
448
#define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
448
#define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
449
#define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
449
#define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
450
#define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
450
#define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
451
#define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
451
#define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
452
#define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
452
#define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
453
#define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
453
#define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
454
#define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
454
#define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
455
#define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
455
#define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
456
#define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
456
#define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
457
#define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
457
#define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
458
#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
458
#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
459
#define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
459
#define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
460
#define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
460
#define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
461
#define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
461
#define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
462
#define IAX_DELAYPBXSTART       (uint64_t)(1 << 25)   /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
462
#define IAX_DELAYPBXSTART       (uint64_t)(1 << 25)   /*!< Don't start a PBX on the channel until the peer sends us a response, so that we've achieved a three-way handshake with them before sending voice or anything else */
463
#define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
463
#define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
464
#define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
464
#define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
465
#define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
465
#define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
466
#define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
466
#define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
467
#define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
467
#define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
468
#define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
468
#define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
469
static int global_rtautoclear = 120;
469
static int global_rtautoclear = 120;
470

    
   
470

   
471
static int reload_config(int forced_reload);
471
static int reload_config(int forced_reload);
472

    
   
472

   
473
/*!
473
/*!
474
 * \brief Call token validation settings.
474
 * \brief Call token validation settings.
475
 */
475
 */
476
enum calltoken_peer_enum {
476
enum calltoken_peer_enum {
477
	/*! \brief Default calltoken required unless the ip is in the ignorelist */
477
	/*! \brief Default calltoken required unless the ip is in the ignorelist */
478
	CALLTOKEN_DEFAULT = 0,
478
	CALLTOKEN_DEFAULT = 0,
479
	/*! \brief Require call token validation. */
479
	/*! \brief Require call token validation. */
480
	CALLTOKEN_YES = 1,
480
	CALLTOKEN_YES = 1,
481
	/*! \brief Require call token validation after a successful registration
481
	/*! \brief Require call token validation after a successful registration
482
	 *         using call token validation occurs. */
482
	 *         using call token validation occurs. */
483
	CALLTOKEN_AUTO = 2,
483
	CALLTOKEN_AUTO = 2,
484
	/*! \brief Do not require call token validation. */
484
	/*! \brief Do not require call token validation. */
485
	CALLTOKEN_NO = 3,
485
	CALLTOKEN_NO = 3,
486
};
486
};
487

    
   
487

   
488
struct iax2_user {
488
struct iax2_user {
489
	AST_DECLARE_STRING_FIELDS(
489
	AST_DECLARE_STRING_FIELDS(
490
		AST_STRING_FIELD(name);
490
		AST_STRING_FIELD(name);
491
		AST_STRING_FIELD(secret);
491
		AST_STRING_FIELD(secret);
492
		AST_STRING_FIELD(dbsecret);
492
		AST_STRING_FIELD(dbsecret);
493
		AST_STRING_FIELD(accountcode);
493
		AST_STRING_FIELD(accountcode);
494
		AST_STRING_FIELD(mohinterpret);
494
		AST_STRING_FIELD(mohinterpret);
495
		AST_STRING_FIELD(mohsuggest);
495
		AST_STRING_FIELD(mohsuggest);
496
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
496
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
497
		AST_STRING_FIELD(language);
497
		AST_STRING_FIELD(language);
498
		AST_STRING_FIELD(cid_num);
498
		AST_STRING_FIELD(cid_num);
499
		AST_STRING_FIELD(cid_name);
499
		AST_STRING_FIELD(cid_name);
500
		AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
500
		AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
501
	);
501
	);
502

    
   
502

   
503
	int authmethods;
503
	int authmethods;
504
	int encmethods;
504
	int encmethods;
505
	int amaflags;
505
	int amaflags;
506
	int adsi;
506
	int adsi;
507
	uint64_t flags;
507
	uint64_t flags;
508
	iax2_format capability;
508
	iax2_format capability;
509
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
509
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
510
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
510
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
511
	struct iax2_codec_pref prefs;
511
	struct iax2_codec_pref prefs;
512
	struct ast_acl_list *acl;
512
	struct ast_acl_list *acl;
513
	struct iax2_context *contexts;
513
	struct iax2_context *contexts;
514
	struct ast_variable *vars;
514
	struct ast_variable *vars;
515
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
515
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
516
};
516
};
517

    
   
517

   
518
struct iax2_peer {
518
struct iax2_peer {
519
	AST_DECLARE_STRING_FIELDS(
519
	AST_DECLARE_STRING_FIELDS(
520
		AST_STRING_FIELD(name);
520
		AST_STRING_FIELD(name);
521
		AST_STRING_FIELD(username);
521
		AST_STRING_FIELD(username);
522
		AST_STRING_FIELD(description);		/*!< Description of the peer */
522
		AST_STRING_FIELD(description);		/*!< Description of the peer */
523
		AST_STRING_FIELD(secret);
523
		AST_STRING_FIELD(secret);
524
		AST_STRING_FIELD(dbsecret);
524
		AST_STRING_FIELD(dbsecret);
525
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
525
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
526

    
   
526

   
527
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
527
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
528
		AST_STRING_FIELD(context);      /*!< For transfers only */
528
		AST_STRING_FIELD(context);      /*!< For transfers only */
529
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
529
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
530
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
530
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
531
		AST_STRING_FIELD(mohinterpret);
531
		AST_STRING_FIELD(mohinterpret);
532
		AST_STRING_FIELD(mohsuggest);
532
		AST_STRING_FIELD(mohsuggest);
533
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
533
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
534
		/* Suggested caller id if registering */
534
		/* Suggested caller id if registering */
535
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
535
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
536
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
536
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
537
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
537
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
538
		AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
538
		AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
539
	);
539
	);
540
	struct iax2_codec_pref prefs;
540
	struct iax2_codec_pref prefs;
541
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
541
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
542
	struct ast_sockaddr addr;
542
	struct ast_sockaddr addr;
543
	int formats;
543
	int formats;
544
	int sockfd;					/*!< Socket to use for transmission */
544
	int sockfd;					/*!< Socket to use for transmission */
545
	struct ast_sockaddr mask;
545
	struct ast_sockaddr mask;
546
	int adsi;
546
	int adsi;
547
	uint64_t flags;
547
	uint64_t flags;
548

    
   
548

   
549
	/* Dynamic Registration fields */
549
	/* Dynamic Registration fields */
550
	struct ast_sockaddr defaddr;			/*!< Default address if there is one */
550
	struct ast_sockaddr defaddr;			/*!< Default address if there is one */
551
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
551
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
552
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
552
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
553

    
   
553

   
554
	int expire;					/*!< Schedule entry for expiry */
554
	int expire;					/*!< Schedule entry for expiry */
555
	int expiry;					/*!< How soon to expire */
555
	int expiry;					/*!< How soon to expire */
556
	iax2_format capability;				/*!< Capability */
556
	iax2_format capability;				/*!< Capability */
557

    
   
557

   
558
	/* Qualification */
558
	/* Qualification */
559
	int callno;					/*!< Call number of POKE request */
559
	int callno;					/*!< Call number of POKE request */
560
	int pokeexpire;					/*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
560
	int pokeexpire;					/*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
561
	int lastms;					/*!< How long last response took (in ms), or -1 for no response */
561
	int lastms;					/*!< How long last response took (in ms), or -1 for no response */
562
	int maxms;					/*!< Max ms we will accept for the host to be up, 0 to not monitor */
562
	int maxms;					/*!< Max ms we will accept for the host to be up, 0 to not monitor */
563

    
   
563

   
564
	int pokefreqok;					/*!< How often to check if the host is up */
564
	int pokefreqok;					/*!< How often to check if the host is up */
565
	int pokefreqnotok;				/*!< How often to check when the host has been determined to be down */
565
	int pokefreqnotok;				/*!< How often to check when the host has been determined to be down */
566
	int historicms;					/*!< How long recent average responses took */
566
	int historicms;					/*!< How long recent average responses took */
567
	int smoothing;					/*!< Sample over how many units to determine historic ms */
567
	int smoothing;					/*!< Sample over how many units to determine historic ms */
568
	uint16_t maxcallno;				/*!< Max call number limit for this peer.  Set on registration */
568
	uint16_t maxcallno;				/*!< Max call number limit for this peer.  Set on registration */
569

    
   
569

   
570
	struct stasis_subscription *mwi_event_sub;	/*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
570
	struct stasis_subscription *mwi_event_sub;	/*!< This subscription lets pollmailboxes know which mailboxes need to be polled */
571

    
   
571

   
572
	struct ast_acl_list *acl;
572
	struct ast_acl_list *acl;
573
	enum calltoken_peer_enum calltoken_required;	/*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
573
	enum calltoken_peer_enum calltoken_required;	/*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
574

    
   
574

   
575
	struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
575
	struct ast_endpoint *endpoint; /*!< Endpoint structure for this peer */
576
};
576
};
577

    
   
577

   
578
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
578
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
579

    
   
579

   
580
struct iax2_trunk_peer {
580
struct iax2_trunk_peer {
581
	ast_mutex_t lock;
581
	ast_mutex_t lock;
582
	int sockfd;
582
	int sockfd;
583
	struct ast_sockaddr addr;
583
	struct ast_sockaddr addr;
584
	struct timeval txtrunktime;		/*!< Transmit trunktime */
584
	struct timeval txtrunktime;		/*!< Transmit trunktime */
585
	struct timeval rxtrunktime;		/*!< Receive trunktime */
585
	struct timeval rxtrunktime;		/*!< Receive trunktime */
586
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
586
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
587
	struct timeval trunkact;		/*!< Last trunk activity */
587
	struct timeval trunkact;		/*!< Last trunk activity */
588
	unsigned int lastsent;			/*!< Last sent time */
588
	unsigned int lastsent;			/*!< Last sent time */
589
	/* Trunk data and length */
589
	/* Trunk data and length */
590
	unsigned char *trunkdata;
590
	unsigned char *trunkdata;
591
	unsigned int trunkdatalen;
591
	unsigned int trunkdatalen;
592
	unsigned int trunkdataalloc;
592
	unsigned int trunkdataalloc;
593
	int trunkmaxmtu;
593
	int trunkmaxmtu;
594
	int trunkerror;
594
	int trunkerror;
595
	int calls;
595
	int calls;
596
	AST_LIST_ENTRY(iax2_trunk_peer) list;
596
	AST_LIST_ENTRY(iax2_trunk_peer) list;
597
};
597
};
598

    
   
598

   
599
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
599
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
600

    
   
600

   
601
enum iax_reg_state {
601
enum iax_reg_state {
602
	REG_STATE_UNREGISTERED = 0,
602
	REG_STATE_UNREGISTERED = 0,
603
	REG_STATE_REGSENT,
603
	REG_STATE_REGSENT,
604
	REG_STATE_AUTHSENT,
604
	REG_STATE_AUTHSENT,
605
	REG_STATE_REGISTERED,
605
	REG_STATE_REGISTERED,
606
	REG_STATE_REJECTED,
606
	REG_STATE_REJECTED,
607
	REG_STATE_TIMEOUT,
607
	REG_STATE_TIMEOUT,
608
	REG_STATE_NOAUTH
608
	REG_STATE_NOAUTH
609
};
609
};
610

    
   
610

   
611
enum iax_transfer_state {
611
enum iax_transfer_state {
612
	TRANSFER_NONE = 0,
612
	TRANSFER_NONE = 0,
613
	TRANSFER_BEGIN,
613
	TRANSFER_BEGIN,
614
	TRANSFER_READY,
614
	TRANSFER_READY,
615
	TRANSFER_RELEASED,
615
	TRANSFER_RELEASED,
616
	TRANSFER_PASSTHROUGH,
616
	TRANSFER_PASSTHROUGH,
617
	TRANSFER_MBEGIN,
617
	TRANSFER_MBEGIN,
618
	TRANSFER_MREADY,
618
	TRANSFER_MREADY,
619
	TRANSFER_MRELEASED,
619
	TRANSFER_MRELEASED,
620
	TRANSFER_MPASSTHROUGH,
620
	TRANSFER_MPASSTHROUGH,
621
	TRANSFER_MEDIA,
621
	TRANSFER_MEDIA,
622
	TRANSFER_MEDIAPASS
622
	TRANSFER_MEDIAPASS
623
};
623
};
624

    
   
624

   
625
struct iax2_registry {
625
struct iax2_registry {
626
	struct ast_sockaddr addr;		/*!< Who we connect to for registration purposes */
626
	struct ast_sockaddr addr;		/*!< Who we connect to for registration purposes */
627
	char username[80];
627
	char username[80];
628
	char secret[80];			/*!< Password or key name in []'s */
628
	char secret[80];			/*!< Password or key name in []'s */
629
	int expire;				/*!< Sched ID of expiration */
629
	int expire;				/*!< Sched ID of expiration */
630
	int refresh;				/*!< How often to refresh */
630
	int refresh;				/*!< How often to refresh */
631
	enum iax_reg_state regstate;
631
	enum iax_reg_state regstate;
632
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
632
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
633
	int callno;				/*!< Associated call number if applicable */
633
	int callno;				/*!< Associated call number if applicable */
634
	struct ast_sockaddr us;			/*!< Who the server thinks we are */
634
	struct ast_sockaddr us;			/*!< Who the server thinks we are */
635
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
635
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
636
	AST_LIST_ENTRY(iax2_registry) entry;
636
	AST_LIST_ENTRY(iax2_registry) entry;
637
	int port;
637
	int port;
638
	char hostname[];
638
	char hostname[];
639
};
639
};
640

    
   
640

   
641
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
641
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
642

    
   
642

   
643
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
643
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
644
#define MIN_RETRY_TIME		100
644
#define MIN_RETRY_TIME		100
645
#define MAX_RETRY_TIME		10000
645
#define MAX_RETRY_TIME		10000
646

    
   
646

   
647
#define MAX_JITTER_BUFFER	50
647
#define MAX_JITTER_BUFFER	50
648
#define MIN_JITTER_BUFFER	10
648
#define MIN_JITTER_BUFFER	10
649

    
   
649

   
650
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
650
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
651

    
   
651

   
652
#define MAX_TIMESTAMP_SKEW	160		/*!< maximum difference between actual and predicted ts for sending */
652
#define MAX_TIMESTAMP_SKEW	160		/*!< maximum difference between actual and predicted ts for sending */
653

    
   
653

   
654
/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
654
/* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
655
#define TS_GAP_FOR_JB_RESYNC	5000
655
#define TS_GAP_FOR_JB_RESYNC	5000
656

    
   
656

   
657
/* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
657
/* used for first_iax_message and last_iax_message.  If this bit is set it was TX, else RX */
658
#define MARK_IAX_SUBCLASS_TX	0x8000
658
#define MARK_IAX_SUBCLASS_TX	0x8000
659

    
   
659

   
660
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
660
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
661
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
661
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
662
static int iaxdynamicthreadcount = 0;
662
static int iaxdynamicthreadcount = 0;
663
static int iaxdynamicthreadnum = 0;
663
static int iaxdynamicthreadnum = 0;
664
static int iaxactivethreadcount = 0;
664
static int iaxactivethreadcount = 0;
665

    
   
665

   
666
struct iax_rr {
666
struct iax_rr {
667
	int jitter;
667
	int jitter;
668
	int losspct;
668
	int losspct;
669
	int losscnt;
669
	int losscnt;
670
	int packets;
670
	int packets;
671
	int delay;
671
	int delay;
672
	int dropped;
672
	int dropped;
673
	int ooo;
673
	int ooo;
674
};
674
};
675

    
   
675

   
676
struct iax2_pvt_ref;
676
struct iax2_pvt_ref;
677

    
   
677

   
678
/* We use the high order bit as the validated flag, and the lower 15 as the
678
/* We use the high order bit as the validated flag, and the lower 15 as the
679
 * actual call number */
679
 * actual call number */
680
typedef uint16_t callno_entry;
680
typedef uint16_t callno_entry;
681

    
   
681

   
682
struct chan_iax2_pvt {
682
struct chan_iax2_pvt {
683
	/*! Socket to send/receive on for this call */
683
	/*! Socket to send/receive on for this call */
684
	int sockfd;
684
	int sockfd;
685
	/*! ast_callid bound to dialog */
685
	/*! ast_callid bound to dialog */
686
	ast_callid callid;
686
	ast_callid callid;
687
	/*! Last received voice format */
687
	/*! Last received voice format */
688
	iax2_format voiceformat;
688
	iax2_format voiceformat;
689
	/*! Last received video format */
689
	/*! Last received video format */
690
	iax2_format videoformat;
690
	iax2_format videoformat;
691
	/*! Last sent voice format */
691
	/*! Last sent voice format */
692
	iax2_format svoiceformat;
692
	iax2_format svoiceformat;
693
	/*! Last sent video format */
693
	/*! Last sent video format */
694
	iax2_format svideoformat;
694
	iax2_format svideoformat;
695
	/*! What we are capable of sending */
695
	/*! What we are capable of sending */
696
	iax2_format capability;
696
	iax2_format capability;
697
	/*! Last received timestamp */
697
	/*! Last received timestamp */
698
	unsigned int last;
698
	unsigned int last;
699
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
699
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
700
	unsigned int lastsent;
700
	unsigned int lastsent;
701
	/*! Timestamp of the last video frame sent */
701
	/*! Timestamp of the last video frame sent */
702
	unsigned int lastvsent;
702
	unsigned int lastvsent;
703
	/*! Next outgoing timestamp if everything is good */
703
	/*! Next outgoing timestamp if everything is good */
704
	unsigned int nextpred;
704
	unsigned int nextpred;
705
	/*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
705
	/*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
706
	int first_iax_message;
706
	int first_iax_message;
707
	/*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
707
	/*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
708
	int last_iax_message;
708
	int last_iax_message;
709
	/*! True if the last voice we transmitted was not silence/CNG */
709
	/*! True if the last voice we transmitted was not silence/CNG */
710
	unsigned int notsilenttx:1;
710
	unsigned int notsilenttx:1;
711
	/*! Ping time */
711
	/*! Ping time */
712
	unsigned int pingtime;
712
	unsigned int pingtime;
713
	/*! Max time for initial response */
713
	/*! Max time for initial response */
714
	int maxtime;
714
	int maxtime;
715
	/*! Peer Address */
715
	/*! Peer Address */
716
	struct ast_sockaddr addr;
716
	struct ast_sockaddr addr;
717
	/*! Actual used codec preferences */
717
	/*! Actual used codec preferences */
718
	struct iax2_codec_pref prefs;
718
	struct iax2_codec_pref prefs;
719
	/*! Requested codec preferences */
719
	/*! Requested codec preferences */
720
	struct iax2_codec_pref rprefs;
720
	struct iax2_codec_pref rprefs;
721
	/*! Our call number */
721
	/*! Our call number */
722
	unsigned short callno;
722
	unsigned short callno;
723
	/*! Our callno_entry entry */
723
	/*! Our callno_entry entry */
724
	callno_entry callno_entry;
724
	callno_entry callno_entry;
725
	/*! Peer callno */
725
	/*! Peer callno */
726
	unsigned short peercallno;
726
	unsigned short peercallno;
727
	/*! Negotiated format, this is only used to remember what format was
727
	/*! Negotiated format, this is only used to remember what format was
728
	    chosen for an unauthenticated call so that the channel can get
728
	    chosen for an unauthenticated call so that the channel can get
729
	    created later using the right format */
729
	    created later using the right format */
730
	iax2_format chosenformat;
730
	iax2_format chosenformat;
731
	/*! Peer selected format */
731
	/*! Peer selected format */
732
	iax2_format peerformat;
732
	iax2_format peerformat;
733
	/*! Peer capability */
733
	/*! Peer capability */
734
	iax2_format peercapability;
734
	iax2_format peercapability;
735
	/*! timeval that we base our transmission on */
735
	/*! timeval that we base our transmission on */
736
	struct timeval offset;
736
	struct timeval offset;
737
	/*! timeval that we base our delivery on */
737
	/*! timeval that we base our delivery on */
738
	struct timeval rxcore;
738
	struct timeval rxcore;
739
	/*! The jitterbuffer */
739
	/*! The jitterbuffer */
740
	jitterbuf *jb;
740
	jitterbuf *jb;
741
	/*! active jb read scheduler id */
741
	/*! active jb read scheduler id */
742
	int jbid;
742
	int jbid;
743
	/*! LAG */
743
	/*! LAG */
744
	int lag;
744
	int lag;
745
	/*! Error, as discovered by the manager */
745
	/*! Error, as discovered by the manager */
746
	int error;
746
	int error;
747
	/*! Owner if we have one */
747
	/*! Owner if we have one */
748
	struct ast_channel *owner;
748
	struct ast_channel *owner;
749
	/*! What's our state? */
749
	/*! What's our state? */
750
	struct ast_flags state;
750
	struct ast_flags state;
751
	/*! Expiry (optional) */
751
	/*! Expiry (optional) */
752
	int expiry;
752
	int expiry;
753
	/*! Next outgoing sequence number */
753
	/*! Next outgoing sequence number */
754
	unsigned char oseqno;
754
	unsigned char oseqno;
755
	/*! Next sequence number they have not yet acknowledged */
755
	/*! Next sequence number they have not yet acknowledged */
756
	unsigned char rseqno;
756
	unsigned char rseqno;
757
	/*! Next incoming sequence number */
757
	/*! Next incoming sequence number */
758
	unsigned char iseqno;
758
	unsigned char iseqno;
759
	/*! Last incoming sequence number we have acknowledged */
759
	/*! Last incoming sequence number we have acknowledged */
760
	unsigned char aseqno;
760
	unsigned char aseqno;
761

    
   
761

   
762
	AST_DECLARE_STRING_FIELDS(
762
	AST_DECLARE_STRING_FIELDS(
763
		/*! Peer name */
763
		/*! Peer name */
764
		AST_STRING_FIELD(peer);
764
		AST_STRING_FIELD(peer);
765
		/*! Default Context */
765
		/*! Default Context */
766
		AST_STRING_FIELD(context);
766
		AST_STRING_FIELD(context);
767
		/*! Caller ID if available */
767
		/*! Caller ID if available */
768
		AST_STRING_FIELD(cid_num);
768
		AST_STRING_FIELD(cid_num);
769
		AST_STRING_FIELD(cid_name);
769
		AST_STRING_FIELD(cid_name);
770
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
770
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
771
		AST_STRING_FIELD(ani);
771
		AST_STRING_FIELD(ani);
772
		/*! DNID */
772
		/*! DNID */
773
		AST_STRING_FIELD(dnid);
773
		AST_STRING_FIELD(dnid);
774
		/*! RDNIS */
774
		/*! RDNIS */
775
		AST_STRING_FIELD(rdnis);
775
		AST_STRING_FIELD(rdnis);
776
		/*! Requested Extension */
776
		/*! Requested Extension */
777
		AST_STRING_FIELD(exten);
777
		AST_STRING_FIELD(exten);
778
		/*! Expected Username */
778
		/*! Expected Username */
779
		AST_STRING_FIELD(username);
779
		AST_STRING_FIELD(username);
780
		/*! Expected Secret */
780
		/*! Expected Secret */
781
		AST_STRING_FIELD(secret);
781
		AST_STRING_FIELD(secret);
782
		/*! MD5 challenge */
782
		/*! MD5 challenge */
783
		AST_STRING_FIELD(challenge);
783
		AST_STRING_FIELD(challenge);
784
		/*! Public keys permitted keys for incoming authentication */
784
		/*! Public keys permitted keys for incoming authentication */
785
		AST_STRING_FIELD(inkeys);
785
		AST_STRING_FIELD(inkeys);
786
		/*! Private key for outgoing authentication */
786
		/*! Private key for outgoing authentication */
787
		AST_STRING_FIELD(outkey);
787
		AST_STRING_FIELD(outkey);
788
		/*! Preferred language */
788
		/*! Preferred language */
789
		AST_STRING_FIELD(language);
789
		AST_STRING_FIELD(language);
790
		/*! Hostname/peername for naming purposes */
790
		/*! Hostname/peername for naming purposes */
791
		AST_STRING_FIELD(host);
791
		AST_STRING_FIELD(host);
792

    
   
792

   
793
		AST_STRING_FIELD(dproot);
793
		AST_STRING_FIELD(dproot);
794
		AST_STRING_FIELD(accountcode);
794
		AST_STRING_FIELD(accountcode);
795
		AST_STRING_FIELD(mohinterpret);
795
		AST_STRING_FIELD(mohinterpret);
796
		AST_STRING_FIELD(mohsuggest);
796
		AST_STRING_FIELD(mohsuggest);
797
		/*! received OSP token */
797
		/*! received OSP token */
798
		AST_STRING_FIELD(osptoken);
798
		AST_STRING_FIELD(osptoken);
799
		/*! Default parkinglot */
799
		/*! Default parkinglot */
800
		AST_STRING_FIELD(parkinglot);
800
		AST_STRING_FIELD(parkinglot);
801
	);
801
	);
802
	/*! AUTHREJ all AUTHREP frames */
802
	/*! AUTHREJ all AUTHREP frames */
803
	int authrej;
803
	int authrej;
804
	/*! permitted authentication methods */
804
	/*! permitted authentication methods */
805
	int authmethods;
805
	int authmethods;
806
	/*! permitted encryption methods */
806
	/*! permitted encryption methods */
807
	int encmethods;
807
	int encmethods;
808
	/*! Encryption AES-128 Key */
808
	/*! Encryption AES-128 Key */
809
	ast_aes_encrypt_key ecx;
809
	ast_aes_encrypt_key ecx;
810
	/*! Decryption AES-128 Key corresponding to ecx */
810
	/*! Decryption AES-128 Key corresponding to ecx */
811
	ast_aes_decrypt_key mydcx;
811
	ast_aes_decrypt_key mydcx;
812
	/*! Decryption AES-128 Key used to decrypt peer frames */
812
	/*! Decryption AES-128 Key used to decrypt peer frames */
813
	ast_aes_decrypt_key dcx;
813
	ast_aes_decrypt_key dcx;
814
	/*! scheduler id associated with iax_key_rotate
814
	/*! scheduler id associated with iax_key_rotate
815
	 * for encrypted calls*/
815
	 * for encrypted calls*/
816
	int keyrotateid;
816
	int keyrotateid;
817
	/*! 32 bytes of semi-random data */
817
	/*! 32 bytes of semi-random data */
818
	unsigned char semirand[32];
818
	unsigned char semirand[32];
819
	/*! Associated registry */
819
	/*! Associated registry */
820
	struct iax2_registry *reg;
820
	struct iax2_registry *reg;
821
	/*! Associated peer for poking */
821
	/*! Associated peer for poking */
822
	struct iax2_peer *peerpoke;
822
	struct iax2_peer *peerpoke;
823
	/*! IAX_ flags */
823
	/*! IAX_ flags */
824
	uint64_t flags;
824
	uint64_t flags;
825
	int adsi;
825
	int adsi;
826

    
   
826

   
827
	/*! Transferring status */
827
	/*! Transferring status */
828
	enum iax_transfer_state transferring;
828
	enum iax_transfer_state transferring;
829
	/*! Transfer identifier */
829
	/*! Transfer identifier */
830
	int transferid;
830
	int transferid;
831
	/*! Who we are IAX transferring to */
831
	/*! Who we are IAX transferring to */
832
	struct ast_sockaddr transfer;
832
	struct ast_sockaddr transfer;
833
	/*! What's the new call number for the transfer */
833
	/*! What's the new call number for the transfer */
834
	unsigned short transfercallno;
834
	unsigned short transfercallno;
835
	/*! Transfer encrypt AES-128 Key */
835
	/*! Transfer encrypt AES-128 Key */
836
	ast_aes_encrypt_key tdcx;
836
	ast_aes_encrypt_key tdcx;
837

    
   
837

   
838
	/*! Status of knowledge of peer ADSI capability */
838
	/*! Status of knowledge of peer ADSI capability */
839
	int peeradsicpe;
839
	int peeradsicpe;
840

    
   
840

   
841
	/*! Callno of native bridge peer. (Valid if nonzero) */
841
	/*! Callno of native bridge peer. (Valid if nonzero) */
842
	unsigned short bridgecallno;
842
	unsigned short bridgecallno;
843

    
   
843

   
844
	int pingid;			/*!< Transmit PING request */
844
	int pingid;			/*!< Transmit PING request */
845
	int lagid;			/*!< Retransmit lag request */
845
	int lagid;			/*!< Retransmit lag request */
846
	int autoid;			/*!< Auto hangup for Dialplan requestor */
846
	int autoid;			/*!< Auto hangup for Dialplan requestor */
847
	int authid;			/*!< Authentication rejection ID */
847
	int authid;			/*!< Authentication rejection ID */
848
	int authfail;			/*!< Reason to report failure */
848
	int authfail;			/*!< Reason to report failure */
849
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
849
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
850
	int calling_ton;
850
	int calling_ton;
851
	int calling_tns;
851
	int calling_tns;
852
	int calling_pres;
852
	int calling_pres;
853
	int amaflags;
853
	int amaflags;
854
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
854
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
855
	/*! variables inherited from the user definition */
855
	/*! variables inherited from the user definition */
856
	struct ast_variable *vars;
856
	struct ast_variable *vars;
857
	/*! variables transmitted in a NEW packet */
857
	/*! variables transmitted in a NEW packet */
858
	struct ast_variable *iaxvars;
858
	struct ast_variable *iaxvars;
859
	/*! last received remote rr */
859
	/*! last received remote rr */
860
	struct iax_rr remote_rr;
860
	struct iax_rr remote_rr;
861
	/*! Current base time: (just for stats) */
861
	/*! Current base time: (just for stats) */
862
	int min;
862
	int min;
863
	/*! Dropped frame count: (just for stats) */
863
	/*! Dropped frame count: (just for stats) */
864
	int frames_dropped;
864
	int frames_dropped;
865
	/*! received frame count: (just for stats) */
865
	/*! received frame count: (just for stats) */
866
	int frames_received;
866
	int frames_received;
867
	/*! num bytes used for calltoken ie, even an empty ie should contain 2 */
867
	/*! num bytes used for calltoken ie, even an empty ie should contain 2 */
868
	unsigned char calltoken_ie_len;
868
	unsigned char calltoken_ie_len;
869
	/*! hold all signaling frames from the pbx thread until we have a destination callno */
869
	/*! hold all signaling frames from the pbx thread until we have a destination callno */
870
	char hold_signaling;
870
	char hold_signaling;
871
	/*! frame queue for signaling frames from pbx thread waiting for destination callno */
871
	/*! frame queue for signaling frames from pbx thread waiting for destination callno */
872
	AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
872
	AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
873
};
873
};
874

    
   
874

   
875
struct signaling_queue_entry {
875
struct signaling_queue_entry {
876
	struct ast_frame f;
876
	struct ast_frame f;
877
	AST_LIST_ENTRY(signaling_queue_entry) next;
877
	AST_LIST_ENTRY(signaling_queue_entry) next;
878
};
878
};
879

    
   
879

   
880
enum callno_type {
880
enum callno_type {
881
	CALLNO_TYPE_NORMAL,
881
	CALLNO_TYPE_NORMAL,
882
	CALLNO_TYPE_TRUNK,
882
	CALLNO_TYPE_TRUNK,
883
};
883
};
884

    
   
884

   
885
#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
885
#define PTR_TO_CALLNO_ENTRY(a) ((uint16_t)(unsigned long)(a))
886
#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
886
#define CALLNO_ENTRY_TO_PTR(a) ((void *)(unsigned long)(a))
887

    
   
887

   
888
#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
888
#define CALLNO_ENTRY_SET_VALIDATED(a) ((a) |= 0x8000)
889
#define CALLNO_ENTRY_IS_VALIDATED(a)  ((a) & 0x8000)
889
#define CALLNO_ENTRY_IS_VALIDATED(a)  ((a) & 0x8000)
890
#define CALLNO_ENTRY_GET_CALLNO(a)    ((a) & 0x7FFF)
890
#define CALLNO_ENTRY_GET_CALLNO(a)    ((a) & 0x7FFF)
891

    
   
891

   
892
struct call_number_pool {
892
struct call_number_pool {
893
	size_t capacity;
893
	size_t capacity;
894
	size_t available;
894
	size_t available;
895
	callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
895
	callno_entry numbers[IAX_MAX_CALLS / 2 + 1];
896
};
896
};
897

    
   
897

   
898
AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
898
AST_MUTEX_DEFINE_STATIC(callno_pool_lock);
899

    
   
899

   
900
/*! table of available call numbers */
900
/*! table of available call numbers */
901
static struct call_number_pool callno_pool;
901
static struct call_number_pool callno_pool;
902

    
   
902

   
903
/*! table of available trunk call numbers */
903
/*! table of available trunk call numbers */
904
static struct call_number_pool callno_pool_trunk;
904
static struct call_number_pool callno_pool_trunk;
905

    
   
905

   
906
/*!
906
/*!
907
 * \brief a list of frames that may need to be retransmitted
907
 * \brief a list of frames that may need to be retransmitted
908
 *
908
 *
909
 * \note The contents of this list do not need to be explicitly destroyed
909
 * \note The contents of this list do not need to be explicitly destroyed
910
 * on module unload.  This is because all active calls are destroyed, and
910
 * on module unload.  This is because all active calls are destroyed, and
911
 * all frames in this queue will get destroyed as a part of that process.
911
 * all frames in this queue will get destroyed as a part of that process.
912
 *
912
 *
913
 * \note Contents protected by the iaxsl[] locks
913
 * \note Contents protected by the iaxsl[] locks
914
 */
914
 */
915
static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
915
static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
916

    
   
916

   
917
static struct ast_taskprocessor *transmit_processor;
917
static struct ast_taskprocessor *transmit_processor;
918

    
   
918

   
919
static int randomcalltokendata;
919
static int randomcalltokendata;
920

    
   
920

   
921
static const time_t MAX_CALLTOKEN_DELAY = 10;
921
static const time_t MAX_CALLTOKEN_DELAY = 10;
922

    
   
922

   
923
/*!
923
/*!
924
 * This module will get much higher performance when doing a lot of
924
 * This module will get much higher performance when doing a lot of
925
 * user and peer lookups if the number of buckets is increased from 1.
925
 * user and peer lookups if the number of buckets is increased from 1.
926
 * However, to maintain old behavior for Asterisk 1.4, these are set to
926
 * However, to maintain old behavior for Asterisk 1.4, these are set to
927
 * 1 by default.  When using multiple buckets, search order through these
927
 * 1 by default.  When using multiple buckets, search order through these
928
 * containers is considered random, so you will not be able to depend on
928
 * containers is considered random, so you will not be able to depend on
929
 * the order the entires are specified in iax.conf for matching order. */
929
 * the order the entires are specified in iax.conf for matching order. */
930
#ifdef LOW_MEMORY
930
#ifdef LOW_MEMORY
931
#define MAX_PEER_BUCKETS 17
931
#define MAX_PEER_BUCKETS 17
932
#else
932
#else
933
#define MAX_PEER_BUCKETS 563
933
#define MAX_PEER_BUCKETS 563
934
#endif
934
#endif
935
static struct ao2_container *peers;
935
static struct ao2_container *peers;
936

    
   
936

   
937
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
937
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
938
static struct ao2_container *users;
938
static struct ao2_container *users;
939

    
   
939

   
940
/*! Table containing peercnt objects for every ip address consuming a callno */
940
/*! Table containing peercnt objects for every ip address consuming a callno */
941
static struct ao2_container *peercnts;
941
static struct ao2_container *peercnts;
942

    
   
942

   
943
/*! Table containing custom callno limit rules for a range of ip addresses. */
943
/*! Table containing custom callno limit rules for a range of ip addresses. */
944
static struct ao2_container *callno_limits;
944
static struct ao2_container *callno_limits;
945

    
   
945

   
946
/*! Table containing ip addresses not requiring calltoken validation */
946
/*! Table containing ip addresses not requiring calltoken validation */
947
static struct ao2_container *calltoken_ignores;
947
static struct ao2_container *calltoken_ignores;
948

    
   
948

   
949
static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
949
static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
950

    
   
950

   
951
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
951
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
952

    
   
952

   
953
static uint16_t global_maxcallno;
953
static uint16_t global_maxcallno;
954

    
   
954

   
955
/*! Total num of call numbers allowed to be allocated without calltoken validation */
955
/*! Total num of call numbers allowed to be allocated without calltoken validation */
956
static uint16_t global_maxcallno_nonval;
956
static uint16_t global_maxcallno_nonval;
957

    
   
957

   
958
static uint16_t total_nonval_callno_used = 0;
958
static uint16_t total_nonval_callno_used = 0;
959

    
   
959

   
960
/*! peer connection private, keeps track of all the call numbers
960
/*! peer connection private, keeps track of all the call numbers
961
 *  consumed by a single ip address */
961
 *  consumed by a single ip address */
962
struct peercnt {
962
struct peercnt {
963
	/*! ip address consuming call numbers */
963
	/*! ip address consuming call numbers */
964
	struct ast_sockaddr addr;
964
	struct ast_sockaddr addr;
965
	/*! Number of call numbers currently used by this ip address */
965
	/*! Number of call numbers currently used by this ip address */
966
	uint16_t cur;
966
	uint16_t cur;
967
	/*! Max call numbers allowed for this ip address */
967
	/*! Max call numbers allowed for this ip address */
968
	uint16_t limit;
968
	uint16_t limit;
969
	/*! Specifies whether limit is set by a registration or not, if so normal
969
	/*! Specifies whether limit is set by a registration or not, if so normal
970
	 *  limit setting rules do not apply to this address. */
970
	 *  limit setting rules do not apply to this address. */
971
	unsigned char reg;
971
	unsigned char reg;
972
};
972
};
973

    
   
973

   
974
/*! used by both callno_limits and calltoken_ignores containers */
974
/*! used by both callno_limits and calltoken_ignores containers */
975
struct addr_range {
975
struct addr_range {
976
	/*! ip address range for custom callno limit rule */
976
	/*! ip address range for custom callno limit rule */
977
	struct ast_ha ha;
977
	struct ast_ha ha;
978
	/*! callno limit for this ip address range, only used in callno_limits container */
978
	/*! callno limit for this ip address range, only used in callno_limits container */
979
	uint16_t limit;
979
	uint16_t limit;
980
	/*! delete me marker for reloads */
980
	/*! delete me marker for reloads */
981
	unsigned char delme;
981
	unsigned char delme;
982
};
982
};
983

    
   
983

   
984
enum {
984
enum {
985
	/*! Extension exists */
985
	/*! Extension exists */
986
	CACHE_FLAG_EXISTS      = (1 << 0),
986
	CACHE_FLAG_EXISTS      = (1 << 0),
987
	/*! Extension is nonexistent */
987
	/*! Extension is nonexistent */
988
	CACHE_FLAG_NONEXISTENT = (1 << 1),
988
	CACHE_FLAG_NONEXISTENT = (1 << 1),
989
	/*! Extension can exist */
989
	/*! Extension can exist */
990
	CACHE_FLAG_CANEXIST    = (1 << 2),
990
	CACHE_FLAG_CANEXIST    = (1 << 2),
991
	/*! Waiting to hear back response */
991
	/*! Waiting to hear back response */
992
	CACHE_FLAG_PENDING     = (1 << 3),
992
	CACHE_FLAG_PENDING     = (1 << 3),
993
	/*! Timed out */
993
	/*! Timed out */
994
	CACHE_FLAG_TIMEOUT     = (1 << 4),
994
	CACHE_FLAG_TIMEOUT     = (1 << 4),
995
	/*! Request transmitted */
995
	/*! Request transmitted */
996
	CACHE_FLAG_TRANSMITTED = (1 << 5),
996
	CACHE_FLAG_TRANSMITTED = (1 << 5),
997
	/*! Timeout */
997
	/*! Timeout */
998
	CACHE_FLAG_UNKNOWN     = (1 << 6),
998
	CACHE_FLAG_UNKNOWN     = (1 << 6),
999
	/*! Matchmore */
999
	/*! Matchmore */
1000
	CACHE_FLAG_MATCHMORE   = (1 << 7),
1000
	CACHE_FLAG_MATCHMORE   = (1 << 7),
1001
};
1001
};
1002

    
   
1002

   
1003
struct iax2_dpcache {
1003
struct iax2_dpcache {
1004
	char peercontext[AST_MAX_CONTEXT];
1004
	char peercontext[AST_MAX_CONTEXT];
1005
	char exten[AST_MAX_EXTENSION];
1005
	char exten[AST_MAX_EXTENSION];
1006
	struct timeval orig;
1006
	struct timeval orig;
1007
	struct timeval expiry;
1007
	struct timeval expiry;
1008
	int flags;
1008
	int flags;
1009
	unsigned short callno;
1009
	unsigned short callno;
1010
	int waiters[256];
1010
	int waiters[256];
1011
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
1011
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
1012
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
1012
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
1013
};
1013
};
1014

    
   
1014

   
1015
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1015
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
1016

    
   
1016

   
1017
static void reg_source_db(struct iax2_peer *p);
1017
static void reg_source_db(struct iax2_peer *p);
1018
static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1018
static struct iax2_peer *realtime_peer(const char *peername, struct ast_sockaddr *addr);
1019
static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1019
static struct iax2_user *realtime_user(const char *username, struct ast_sockaddr *addr);
1020

    
   
1020

   
1021
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1021
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
1022
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1022
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
1023
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1023
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
1024

    
   
1024

   
1025
enum iax2_thread_iostate {
1025
enum iax2_thread_iostate {
1026
	IAX_IOSTATE_IDLE,
1026
	IAX_IOSTATE_IDLE,
1027
	IAX_IOSTATE_READY,
1027
	IAX_IOSTATE_READY,
1028
	IAX_IOSTATE_PROCESSING,
1028
	IAX_IOSTATE_PROCESSING,
1029
	IAX_IOSTATE_SCHEDREADY,
1029
	IAX_IOSTATE_SCHEDREADY,
1030
};
1030
};
1031

    
   
1031

   
1032
enum iax2_thread_type {
1032
enum iax2_thread_type {
1033
	IAX_THREAD_TYPE_POOL,
1033
	IAX_THREAD_TYPE_POOL,
1034
	IAX_THREAD_TYPE_DYNAMIC,
1034
	IAX_THREAD_TYPE_DYNAMIC,
1035
};
1035
};
1036

    
   
1036

   
1037
struct iax2_pkt_buf {
1037
struct iax2_pkt_buf {
1038
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
1038
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
1039
	size_t len;
1039
	size_t len;
1040
	unsigned char buf[1];
1040
	unsigned char buf[1];
1041
};
1041
};
1042

    
   
1042

   
1043
struct iax2_thread {
1043
struct iax2_thread {
1044
	AST_LIST_ENTRY(iax2_thread) list;
1044
	AST_LIST_ENTRY(iax2_thread) list;
1045
	enum iax2_thread_type type;
1045
	enum iax2_thread_type type;
1046
	enum iax2_thread_iostate iostate;
1046
	enum iax2_thread_iostate iostate;
1047
#ifdef SCHED_MULTITHREADED
1047
#ifdef SCHED_MULTITHREADED
1048
	void (*schedfunc)(const void *);
1048
	void (*schedfunc)(const void *);
1049
	const void *scheddata;
1049
	const void *scheddata;
1050
#endif
1050
#endif
1051
#ifdef DEBUG_SCHED_MULTITHREAD
1051
#ifdef DEBUG_SCHED_MULTITHREAD
1052
	char curfunc[80];
1052
	char curfunc[80];
1053
#endif
1053
#endif
1054
	int actions;
1054
	int actions;
1055
	pthread_t threadid;
1055
	pthread_t threadid;
1056
	int threadnum;
1056
	int threadnum;
1057
	struct ast_sockaddr ioaddr;
1057
	struct ast_sockaddr ioaddr;
1058
	unsigned char readbuf[4096];
1058
	unsigned char readbuf[4096];
1059
	unsigned char *buf;
1059
	unsigned char *buf;
1060
	ssize_t buf_len;
1060
	ssize_t buf_len;
1061
	size_t buf_size;
1061
	size_t buf_size;
1062
	int iofd;
1062
	int iofd;
1063
	time_t checktime;
1063
	time_t checktime;
1064
	ast_mutex_t lock;
1064
	ast_mutex_t lock;
1065
	ast_cond_t cond;
1065
	ast_cond_t cond;
1066
	ast_mutex_t init_lock;
1066
	ast_mutex_t init_lock;
1067
	ast_cond_t init_cond;
1067
	ast_cond_t init_cond;
1068
	/*! if this thread is processing a full frame,
1068
	/*! if this thread is processing a full frame,
1069
	  some information about that frame will be stored
1069
	  some information about that frame will be stored
1070
	  here, so we can avoid dispatching any more full
1070
	  here, so we can avoid dispatching any more full
1071
	  frames for that callno to other threads */
1071
	  frames for that callno to other threads */
1072
	struct {
1072
	struct {
1073
		unsigned short callno;
1073
		unsigned short callno;
1074
		struct ast_sockaddr addr;
1074
		struct ast_sockaddr addr;
1075
		unsigned char type;
1075
		unsigned char type;
1076
		unsigned char csub;
1076
		unsigned char csub;
1077
	} ffinfo;
1077
	} ffinfo;
1078
	/*! Queued up full frames for processing.  If more full frames arrive for
1078
	/*! Queued up full frames for processing.  If more full frames arrive for
1079
	 *  a call which this thread is already processing a full frame for, they
1079
	 *  a call which this thread is already processing a full frame for, they
1080
	 *  are queued up here. */
1080
	 *  are queued up here. */
1081
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1081
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1082
	unsigned char stop;
1082
	unsigned char stop;
1083
};
1083
};
1084

    
   
1084

   
1085
/* Thread lists */
1085
/* Thread lists */
1086
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1086
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1087
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1087
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1088
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1088
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1089

    
   
1089

   
1090
static void *iax2_process_thread(void *data);
1090
static void *iax2_process_thread(void *data);
1091
static void iax2_destroy(int callno);
1091
static void iax2_destroy(int callno);
1092

    
   
1092

   
1093
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1093
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1094
{
1094
{
1095
	ast_mutex_lock(lock);
1095
	ast_mutex_lock(lock);
1096
	ast_cond_signal(cond);
1096
	ast_cond_signal(cond);
1097
	ast_mutex_unlock(lock);
1097
	ast_mutex_unlock(lock);
1098
}
1098
}
1099

    
   
1099

   
1100
/*!
1100
/*!
1101
 * \brief an array of iax2 pvt structures
1101
 * \brief an array of iax2 pvt structures
1102
 *
1102
 *
1103
 * The container for active chan_iax2_pvt structures is implemented as an
1103
 * The container for active chan_iax2_pvt structures is implemented as an
1104
 * array for extremely quick direct access to the correct pvt structure
1104
 * array for extremely quick direct access to the correct pvt structure
1105
 * based on the local call number.  The local call number is used as the
1105
 * based on the local call number.  The local call number is used as the
1106
 * index into the array where the associated pvt structure is stored.
1106
 * index into the array where the associated pvt structure is stored.
1107
 */
1107
 */
1108
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1108
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1109

    
   
1109

   
1110
static ast_callid iax_pvt_callid_get(int callno)
1110
static ast_callid iax_pvt_callid_get(int callno)
1111
{
1111
{
1112
	return iaxs[callno]->callid;
1112
	return iaxs[callno]->callid;
1113
}
1113
}
1114

    
   
1114

   
1115
static void iax_pvt_callid_set(int callno, ast_callid callid)
1115
static void iax_pvt_callid_set(int callno, ast_callid callid)
1116
{
1116
{
1117
	iaxs[callno]->callid = callid;
1117
	iaxs[callno]->callid = callid;
1118
}
1118
}
1119

    
   
1119

   
1120
static void iax_pvt_callid_new(int callno)
1120
static void iax_pvt_callid_new(int callno)
1121
{
1121
{
1122
	ast_callid callid = ast_create_callid();
1122
	ast_callid callid = ast_create_callid();
1123
	char buffer[AST_CALLID_BUFFER_LENGTH];
1123
	char buffer[AST_CALLID_BUFFER_LENGTH];
1124
	ast_callid_strnprint(buffer, sizeof(buffer), callid);
1124
	ast_callid_strnprint(buffer, sizeof(buffer), callid);
1125
	iax_pvt_callid_set(callno, callid);
1125
	iax_pvt_callid_set(callno, callid);
1126
}
1126
}
1127

    
   
1127

   
1128
/*!
1128
/*!
1129
 * \brief Another container of iax2_pvt structures
1129
 * \brief Another container of iax2_pvt structures
1130
 *
1130
 *
1131
 * Active IAX2 pvt structs are also stored in this container, if they are a part
1131
 * Active IAX2 pvt structs are also stored in this container, if they are a part
1132
 * of an active call where we know the remote side's call number.  The reason
1132
 * of an active call where we know the remote side's call number.  The reason
1133
 * for this is that incoming media frames do not contain our call number.  So,
1133
 * for this is that incoming media frames do not contain our call number.  So,
1134
 * instead of having to iterate the entire iaxs array, we use this container to
1134
 * instead of having to iterate the entire iaxs array, we use this container to
1135
 * look up calls where the remote side is using a given call number.
1135
 * look up calls where the remote side is using a given call number.
1136
 */
1136
 */
1137
static struct ao2_container *iax_peercallno_pvts;
1137
static struct ao2_container *iax_peercallno_pvts;
1138

    
   
1138

   
1139
/*!
1139
/*!
1140
 * \brief chan_iax2_pvt structure locks
1140
 * \brief chan_iax2_pvt structure locks
1141
 *
1141
 *
1142
 * These locks are used when accessing a pvt structure in the iaxs array.
1142
 * These locks are used when accessing a pvt structure in the iaxs array.
1143
 * The index used here is the same as used in the iaxs array.  It is the
1143
 * The index used here is the same as used in the iaxs array.  It is the
1144
 * local call number for the associated pvt struct.
1144
 * local call number for the associated pvt struct.
1145
 */
1145
 */
1146
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1146
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1147

    
   
1147

   
1148
/*!
1148
/*!
1149
 *  * \brief Another container of iax2_pvt structures
1149
 *  * \brief Another container of iax2_pvt structures
1150
 *
1150
 *
1151
 *  Active IAX2 pvt stucts used during transfering a call are stored here.
1151
 *  Active IAX2 pvt stucts used during transfering a call are stored here.
1152
 */
1152
 */
1153
static struct ao2_container *iax_transfercallno_pvts;
1153
static struct ao2_container *iax_transfercallno_pvts;
1154

    
   
1154

   
1155
/* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
1155
/* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
1156
   but keeps the division between trunked and non-trunked better. */
1156
   but keeps the division between trunked and non-trunked better. */
1157
#define TRUNK_CALL_START	(IAX_MAX_CALLS / 2)
1157
#define TRUNK_CALL_START	(IAX_MAX_CALLS / 2)
1158

    
   
1158

   
1159
/* Debug routines... */
1159
/* Debug routines... */
1160
static struct ast_sockaddr debugaddr;
1160
static struct ast_sockaddr debugaddr;
1161

    
   
1161

   
1162
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1162
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct ast_sockaddr *addr, int datalen)
1163
{
1163
{
1164
	if (iaxdebug ||
1164
	if (iaxdebug ||
1165
	    (addr && !ast_sockaddr_isnull(&debugaddr) &&
1165
	    (addr && !ast_sockaddr_isnull(&debugaddr) &&
1166
		(!ast_sockaddr_port(&debugaddr) ||
1166
		(!ast_sockaddr_port(&debugaddr) ||
1167
		  ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1167
		  ast_sockaddr_port(&debugaddr) == ast_sockaddr_port(addr)) &&
1168
		  !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1168
		  !ast_sockaddr_cmp_addr(&debugaddr, addr))) {
1169

    
   
1169

   
1170
		if (iaxdebug) {
1170
		if (iaxdebug) {
1171
			iax_showframe(f, fhi, rx, addr, datalen);
1171
			iax_showframe(f, fhi, rx, addr, datalen);
1172
		} else {
1172
		} else {
1173
			iaxdebug = 1;
1173
			iaxdebug = 1;
1174
			iax_showframe(f, fhi, rx, addr, datalen);
1174
			iax_showframe(f, fhi, rx, addr, datalen);
1175
			iaxdebug = 0;
1175
			iaxdebug = 0;
1176
		}
1176
		}
1177
	}
1177
	}
1178
}
1178
}
1179

    
   
1179

   
1180
static void iax_debug_output(const char *data)
1180
static void iax_debug_output(const char *data)
1181
{
1181
{
1182
	if (iaxdebug)
1182
	if (iaxdebug)
1183
		ast_verbose("%s", data);
1183
		ast_verbose("%s", data);
1184
}
1184
}
1185

    
   
1185

   
1186
static void iax_error_output(const char *data)
1186
static void iax_error_output(const char *data)
1187
{
1187
{
1188
	ast_log(LOG_WARNING, "%s", data);
1188
	ast_log(LOG_WARNING, "%s", data);
1189
}
1189
}
1190

    
   
1190

   
1191
static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1191
static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1192
{
1192
{
1193
	va_list args;
1193
	va_list args;
1194
	char buf[1024];
1194
	char buf[1024];
1195

    
   
1195

   
1196
	va_start(args, fmt);
1196
	va_start(args, fmt);
1197
	vsnprintf(buf, sizeof(buf), fmt, args);
1197
	vsnprintf(buf, sizeof(buf), fmt, args);
1198
	va_end(args);
1198
	va_end(args);
1199

    
   
1199

   
1200
	ast_log(LOG_ERROR, "%s", buf);
1200
	ast_log(LOG_ERROR, "%s", buf);
1201
}
1201
}
1202

    
   
1202

   
1203
static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1203
static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1204
{
1204
{
1205
	va_list args;
1205
	va_list args;
1206
	char buf[1024];
1206
	char buf[1024];
1207

    
   
1207

   
1208
	va_start(args, fmt);
1208
	va_start(args, fmt);
1209
	vsnprintf(buf, sizeof(buf), fmt, args);
1209
	vsnprintf(buf, sizeof(buf), fmt, args);
1210
	va_end(args);
1210
	va_end(args);
1211

    
   
1211

   
1212
	ast_log(LOG_WARNING, "%s", buf);
1212
	ast_log(LOG_WARNING, "%s", buf);
1213
}
1213
}
1214

    
   
1214

   
1215
static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1215
static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1216
{
1216
{
1217
	va_list args;
1217
	va_list args;
1218
	char buf[1024];
1218
	char buf[1024];
1219

    
   
1219

   
1220
	va_start(args, fmt);
1220
	va_start(args, fmt);
1221
	vsnprintf(buf, sizeof(buf), fmt, args);
1221
	vsnprintf(buf, sizeof(buf), fmt, args);
1222
	va_end(args);
1222
	va_end(args);
1223

    
   
1223

   
1224
	ast_verbose("%s", buf);
1224
	ast_verbose("%s", buf);
1225
}
1225
}
1226

    
   
1226

   
1227
static int expire_registry(const void *data);
1227
static int expire_registry(const void *data);
1228
static int iax2_answer(struct ast_channel *c);
1228
static int iax2_answer(struct ast_channel *c);
1229
static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1229
static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1230
static int iax2_devicestate(const char *data);
1230
static int iax2_devicestate(const char *data);
1231
static int iax2_digit_begin(struct ast_channel *c, char digit);
1231
static int iax2_digit_begin(struct ast_channel *c, char digit);
1232
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1232
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1233
static int iax2_do_register(struct iax2_registry *reg);
1233
static int iax2_do_register(struct iax2_registry *reg);
1234
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1234
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1235
static int iax2_hangup(struct ast_channel *c);
1235
static int iax2_hangup(struct ast_channel *c);
1236
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1236
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1237
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1237
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1238
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1238
static int iax2_provision(struct ast_sockaddr *end, int sockfd, const char *dest, const char *template, int force);
1239
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1239
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1240
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1240
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1241
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1241
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1242
static int iax2_sendtext(struct ast_channel *c, const char *text);
1242
static int iax2_sendtext(struct ast_channel *c, const char *text);
1243
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1243
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1244
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1244
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1245
static int iax2_transfer(struct ast_channel *c, const char *dest);
1245
static int iax2_transfer(struct ast_channel *c, const char *dest);
1246
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1246
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1247
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1247
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1248

    
   
1248

   
1249
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1249
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1250
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1250
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1251
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1251
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1252
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1252
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1253
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1253
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1254
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1254
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1255
static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
1255
static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
1256
static struct ast_frame *iax2_read(struct ast_channel *c);
1256
static struct ast_frame *iax2_read(struct ast_channel *c);
1257
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1257
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1258
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1258
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1259
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1259
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1260
static void *iax2_dup_variable_datastore(void *);
1260
static void *iax2_dup_variable_datastore(void *);
1261
static void prune_peers(void);
1261
static void prune_peers(void);
1262
static void prune_users(void);
1262
static void prune_users(void);
1263
static void iax2_free_variable_datastore(void *);
1263
static void iax2_free_variable_datastore(void *);
1264

    
   
1264

   
1265
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1265
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1266
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1266
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1267
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1267
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1268
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1268
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1269
static void build_rand_pad(unsigned char *buf, ssize_t len);
1269
static void build_rand_pad(unsigned char *buf, ssize_t len);
1270
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1270
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry);
1271
static int replace_callno(const void *obj);
1271
static int replace_callno(const void *obj);
1272
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1272
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry);
1273
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1273
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1274
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1274
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub, struct stasis_message *message);
1275

    
   
1275

   
1276
static struct ast_channel_tech iax2_tech = {
1276
static struct ast_channel_tech iax2_tech = {
1277
	.type = "IAX2",
1277
	.type = "IAX2",
1278
	.description = tdesc,
1278
	.description = tdesc,
1279
	.properties = AST_CHAN_TP_WANTSJITTER,
1279
	.properties = AST_CHAN_TP_WANTSJITTER,
1280
	.requester = iax2_request,
1280
	.requester = iax2_request,
1281
	.devicestate = iax2_devicestate,
1281
	.devicestate = iax2_devicestate,
1282
	.send_digit_begin = iax2_digit_begin,
1282
	.send_digit_begin = iax2_digit_begin,
1283
	.send_digit_end = iax2_digit_end,
1283
	.send_digit_end = iax2_digit_end,
1284
	.send_text = iax2_sendtext,
1284
	.send_text = iax2_sendtext,
1285
	.send_image = iax2_sendimage,
1285
	.send_image = iax2_sendimage,
1286
	.send_html = iax2_sendhtml,
1286
	.send_html = iax2_sendhtml,
1287
	.call = iax2_call,
1287
	.call = iax2_call,
1288
	.hangup = iax2_hangup,
1288
	.hangup = iax2_hangup,
1289
	.answer = iax2_answer,
1289
	.answer = iax2_answer,
1290
	.read = iax2_read,
1290
	.read = iax2_read,
1291
	.write = iax2_write,
1291
	.write = iax2_write,
1292
	.write_video = iax2_write,
1292
	.write_video = iax2_write,
1293
	.indicate = iax2_indicate,
1293
	.indicate = iax2_indicate,
1294
	.setoption = iax2_setoption,
1294
	.setoption = iax2_setoption,
1295
	.queryoption = iax2_queryoption,
1295
	.queryoption = iax2_queryoption,
1296
	.transfer = iax2_transfer,
1296
	.transfer = iax2_transfer,
1297
	.fixup = iax2_fixup,
1297
	.fixup = iax2_fixup,
1298
	.func_channel_read = acf_channel_read,
1298
	.func_channel_read = acf_channel_read,
1299
};
1299
};
1300

    
   
1300

   
1301
/*!
1301
/*!
1302
 * \internal
1302
 * \internal
1303
 * \brief Obtain the owner channel lock if the owner exists.
1303
 * \brief Obtain the owner channel lock if the owner exists.
1304
 *
1304
 *
1305
 * \param callno IAX2 call id.
1305
 * \param callno IAX2 call id.
1306
 *
1306
 *
1307
 * \note Assumes the iaxsl[callno] lock is already obtained.
1307
 * \note Assumes the iaxsl[callno] lock is already obtained.
1308
 *
1308
 *
1309
 * \note
1309
 * \note
1310
 * IMPORTANT NOTE!!!  Any time this function is used, even if
1310
 * IMPORTANT NOTE!!!  Any time this function is used, even if
1311
 * iaxs[callno] was valid before calling it, it may no longer be
1311
 * iaxs[callno] was valid before calling it, it may no longer be
1312
 * valid after calling it.  This function may unlock and lock
1312
 * valid after calling it.  This function may unlock and lock
1313
 * the mutex associated with this callno, meaning that another
1313
 * the mutex associated with this callno, meaning that another
1314
 * thread may grab it and destroy the call.
1314
 * thread may grab it and destroy the call.
1315
 *
1315
 *
1316
 * \return Nothing
1316
 * \return Nothing
1317
 */
1317
 */
1318
static void iax2_lock_owner(int callno)
1318
static void iax2_lock_owner(int callno)
1319
{
1319
{
1320
	for (;;) {
1320
	for (;;) {
1321
		if (!iaxs[callno] || !iaxs[callno]->owner) {
1321
		if (!iaxs[callno] || !iaxs[callno]->owner) {
1322
			/* There is no owner lock to get. */
1322
			/* There is no owner lock to get. */
1323
			break;
1323
			break;
1324
		}
1324
		}
1325
		if (!ast_channel_trylock(iaxs[callno]->owner)) {
1325
		if (!ast_channel_trylock(iaxs[callno]->owner)) {
1326
			/* We got the lock */
1326
			/* We got the lock */
1327
			break;
1327
			break;
1328
		}
1328
		}
1329
		/* Avoid deadlock by pausing and trying again */
1329
		/* Avoid deadlock by pausing and trying again */
1330
		DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1330
		DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1331
	}
1331
	}
1332
}
1332
}
1333

    
   
1333

   
1334
/*!
1334
/*!
1335
 * \internal
1335
 * \internal
1336
 * \brief Check if a control subtype is allowed on the wire.
1336
 * \brief Check if a control subtype is allowed on the wire.
1337
 *
1337
 *
1338
 * \param subtype Control frame subtype to check if allowed to/from the wire.
1338
 * \param subtype Control frame subtype to check if allowed to/from the wire.
1339
 *
1339
 *
1340
 * \retval non-zero if allowed.
1340
 * \retval non-zero if allowed.
1341
 */
1341
 */
1342
static int iax2_is_control_frame_allowed(int subtype)
1342
static int iax2_is_control_frame_allowed(int subtype)
1343
{
1343
{
1344
	enum ast_control_frame_type control = subtype;
1344
	enum ast_control_frame_type control = subtype;
1345
	int is_allowed;
1345
	int is_allowed;
1346

    
   
1346

   
1347
	/*
1347
	/*
1348
	 * Note: If we compare the enumeration type, which does not have any
1348
	 * Note: If we compare the enumeration type, which does not have any
1349
	 * negative constants, the compiler may optimize this code away.
1349
	 * negative constants, the compiler may optimize this code away.
1350
	 * Therefore, we must perform an integer comparison here.
1350
	 * Therefore, we must perform an integer comparison here.
1351
	 */
1351
	 */
1352
	if (subtype == -1) {
1352
	if (subtype == -1) {
1353
		return -1;
1353
		return -1;
1354
	}
1354
	}
1355

    
   
1355

   
1356
	/* Default to not allowing control frames to pass. */
1356
	/* Default to not allowing control frames to pass. */
1357
	is_allowed = 0;
1357
	is_allowed = 0;
1358

    
   
1358

   
1359
	/*
1359
	/*
1360
	 * The switch default is not present in order to take advantage
1360
	 * The switch default is not present in order to take advantage
1361
	 * of the compiler complaining of a missing enum case.
1361
	 * of the compiler complaining of a missing enum case.
1362
	 */
1362
	 */
1363
	switch (control) {
1363
	switch (control) {
1364
	/*
1364
	/*
1365
	 * These control frames make sense to send/receive across the link.
1365
	 * These control frames make sense to send/receive across the link.
1366
	 */
1366
	 */
1367
	case AST_CONTROL_HANGUP:
1367
	case AST_CONTROL_HANGUP:
1368
	case AST_CONTROL_RING:
1368
	case AST_CONTROL_RING:
1369
	case AST_CONTROL_RINGING:
1369
	case AST_CONTROL_RINGING:
1370
	case AST_CONTROL_ANSWER:
1370
	case AST_CONTROL_ANSWER:
1371
	case AST_CONTROL_BUSY:
1371
	case AST_CONTROL_BUSY:
1372
	case AST_CONTROL_TAKEOFFHOOK:
1372
	case AST_CONTROL_TAKEOFFHOOK:
1373
	case AST_CONTROL_OFFHOOK:
1373
	case AST_CONTROL_OFFHOOK:
1374
	case AST_CONTROL_CONGESTION:
1374
	case AST_CONTROL_CONGESTION:
1375
	case AST_CONTROL_FLASH:
1375
	case AST_CONTROL_FLASH:
1376
	case AST_CONTROL_WINK:
1376
	case AST_CONTROL_WINK:
1377
	case AST_CONTROL_OPTION:
1377
	case AST_CONTROL_OPTION:
1378
	case AST_CONTROL_RADIO_KEY:
1378
	case AST_CONTROL_RADIO_KEY:
1379
	case AST_CONTROL_RADIO_UNKEY:
1379
	case AST_CONTROL_RADIO_UNKEY:
1380
	case AST_CONTROL_PROGRESS:
1380
	case AST_CONTROL_PROGRESS:
1381
	case AST_CONTROL_PROCEEDING:
1381
	case AST_CONTROL_PROCEEDING:
1382
	case AST_CONTROL_HOLD:
1382
	case AST_CONTROL_HOLD:
1383
	case AST_CONTROL_UNHOLD:
1383
	case AST_CONTROL_UNHOLD:
1384
	case AST_CONTROL_VIDUPDATE:
1384
	case AST_CONTROL_VIDUPDATE:
1385
	case AST_CONTROL_CONNECTED_LINE:
1385
	case AST_CONTROL_CONNECTED_LINE:
1386
	case AST_CONTROL_REDIRECTING:
1386
	case AST_CONTROL_REDIRECTING:
1387
	case AST_CONTROL_T38_PARAMETERS:
1387
	case AST_CONTROL_T38_PARAMETERS:
1388
	case AST_CONTROL_AOC:
1388
	case AST_CONTROL_AOC:
1389
	case AST_CONTROL_INCOMPLETE:
1389
	case AST_CONTROL_INCOMPLETE:
1390
	case AST_CONTROL_MCID:
1390
	case AST_CONTROL_MCID:
1391
		is_allowed = -1;
1391
		is_allowed = -1;
1392
		break;
1392
		break;
1393

    
   
1393

   
1394
	/*
1394
	/*
1395
	 * These control frames do not make sense to send/receive across the link.
1395
	 * These control frames do not make sense to send/receive across the link.
1396
	 */
1396
	 */
1397
	case _XXX_AST_CONTROL_T38:
1397
	case _XXX_AST_CONTROL_T38:
1398
		/* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1398
		/* The control value is deprecated in favor of AST_CONTROL_T38_PARAMETERS. */
1399
	case AST_CONTROL_SRCUPDATE:
1399
	case AST_CONTROL_SRCUPDATE:
1400
		/* Across an IAX link the source is still the same. */
1400
		/* Across an IAX link the source is still the same. */
1401
	case AST_CONTROL_TRANSFER:
1401
	case AST_CONTROL_TRANSFER:
1402
		/* A success/fail status report from calling ast_transfer() on this machine. */
1402
		/* A success/fail status report from calling ast_transfer() on this machine. */
1403
	case AST_CONTROL_CC:
1403
	case AST_CONTROL_CC:
1404
		/* The payload contains pointers that are valid for the sending machine only. */
1404
		/* The payload contains pointers that are valid for the sending machine only. */
1405
	case AST_CONTROL_SRCCHANGE:
1405
	case AST_CONTROL_SRCCHANGE:
1406
		/* Across an IAX link the source is still the same. */
1406
		/* Across an IAX link the source is still the same. */
1407
	case AST_CONTROL_READ_ACTION:
1407
	case AST_CONTROL_READ_ACTION:
1408
		/* The action can only be done by the sending machine. */
1408
		/* The action can only be done by the sending machine. */
1409
	case AST_CONTROL_END_OF_Q:
1409
	case AST_CONTROL_END_OF_Q:
1410
		/* This frame would cause the call to unexpectedly hangup. */
1410
		/* This frame would cause the call to unexpectedly hangup. */
1411
	case AST_CONTROL_UPDATE_RTP_PEER:
1411
	case AST_CONTROL_UPDATE_RTP_PEER:
1412
		/* Only meaningful across a bridge on this machine for direct-media exchange. */
1412
		/* Only meaningful across a bridge on this machine for direct-media exchange. */
1413
	case AST_CONTROL_PVT_CAUSE_CODE:
1413
	case AST_CONTROL_PVT_CAUSE_CODE:
1414
		/* Intended only for the sending machine's local channel structure. */
1414
		/* Intended only for the sending machine's local channel structure. */
1415
	case AST_CONTROL_MASQUERADE_NOTIFY:
1415
	case AST_CONTROL_MASQUERADE_NOTIFY:
1416
		/* Intended only for masquerades when calling ast_indicate_data(). */
1416
		/* Intended only for masquerades when calling ast_indicate_data(). */
1417
	case AST_CONTROL_STREAM_STOP:
1417
	case AST_CONTROL_STREAM_STOP:
1418
	case AST_CONTROL_STREAM_SUSPEND:
1418
	case AST_CONTROL_STREAM_SUSPEND:
1419
	case AST_CONTROL_STREAM_RESTART:
1419
	case AST_CONTROL_STREAM_RESTART:
1420
	case AST_CONTROL_STREAM_REVERSE:
1420
	case AST_CONTROL_STREAM_REVERSE:
1421
	case AST_CONTROL_STREAM_FORWARD:
1421
	case AST_CONTROL_STREAM_FORWARD:
1422
		/* None of these playback stream control frames should go across the link. */
1422
		/* None of these playback stream control frames should go across the link. */
1423
	case AST_CONTROL_RECORD_CANCEL:
1423
	case AST_CONTROL_RECORD_CANCEL:
1424
	case AST_CONTROL_RECORD_STOP:
1424
	case AST_CONTROL_RECORD_STOP:
1425
	case AST_CONTROL_RECORD_SUSPEND:
1425
	case AST_CONTROL_RECORD_SUSPEND:
1426
	case AST_CONTROL_RECORD_MUTE:
1426
	case AST_CONTROL_RECORD_MUTE:
1427
		/* None of these media recording control frames should go across the link. */
1427
		/* None of these media recording control frames should go across the link. */
1428
		break;
1428
		break;
1429
	}
1429
	}
1430
	return is_allowed;
1430
	return is_allowed;
1431
}
1431
}
1432

    
   
1432

   
1433
static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
1433
static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
1434
{
1434
{
1435
	/* The MWI subscriptions exist just so the core knows we care about those
1435
	/* The MWI subscriptions exist just so the core knows we care about those
1436
	 * mailboxes.  However, we just grab the events out of the cache when it
1436
	 * mailboxes.  However, we just grab the events out of the cache when it
1437
	 * is time to send MWI, since it is only sent with a REGACK. */
1437
	 * is time to send MWI, since it is only sent with a REGACK. */
1438
}
1438
}
1439

    
   
1439

   
1440
static void network_change_stasis_subscribe(void)
1440
static void network_change_stasis_subscribe(void)
1441
{
1441
{
1442
	if (!network_change_sub) {
1442
	if (!network_change_sub) {
1443
		network_change_sub = stasis_subscribe(ast_system_topic(),
1443
		network_change_sub = stasis_subscribe(ast_system_topic(),
1444
			network_change_stasis_cb, NULL);
1444
			network_change_stasis_cb, NULL);
1445
	}
1445
	}
1446
}
1446
}
1447

    
   
1447

   
1448
static void network_change_stasis_unsubscribe(void)
1448
static void network_change_stasis_unsubscribe(void)
1449
{
1449
{
1450
	network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1450
	network_change_sub = stasis_unsubscribe_and_join(network_change_sub);
1451
}
1451
}
1452

    
   
1452

   
1453
static void acl_change_stasis_subscribe(void)
1453
static void acl_change_stasis_subscribe(void)
1454
{
1454
{
1455
	if (!acl_change_sub) {
1455
	if (!acl_change_sub) {
1456
		acl_change_sub = stasis_subscribe(ast_security_topic(),
1456
		acl_change_sub = stasis_subscribe(ast_security_topic(),
1457
			acl_change_stasis_cb, NULL);
1457
			acl_change_stasis_cb, NULL);
1458
	}
1458
	}
1459
}
1459
}
1460

    
   
1460

   
1461
static void acl_change_stasis_unsubscribe(void)
1461
static void acl_change_stasis_unsubscribe(void)
1462
{
1462
{
1463
	acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1463
	acl_change_sub = stasis_unsubscribe_and_join(acl_change_sub);
1464
}
1464
}
1465

    
   
1465

   
1466
static int network_change_sched_cb(const void *data)
1466
static int network_change_sched_cb(const void *data)
1467
{
1467
{
1468
	struct iax2_registry *reg;
1468
	struct iax2_registry *reg;
1469
	network_change_sched_id = -1;
1469
	network_change_sched_id = -1;
1470
	AST_LIST_LOCK(&registrations);
1470
	AST_LIST_LOCK(&registrations);
1471
	AST_LIST_TRAVERSE(&registrations, reg, entry) {
1471
	AST_LIST_TRAVERSE(&registrations, reg, entry) {
1472
		iax2_do_register(reg);
1472
		iax2_do_register(reg);
1473
	}
1473
	}
1474
	AST_LIST_UNLOCK(&registrations);
1474
	AST_LIST_UNLOCK(&registrations);
1475

    
   
1475

   
1476
	return 0;
1476
	return 0;
1477
}
1477
}
1478

    
   
1478

   
1479
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1479
static void network_change_stasis_cb(void *data, struct stasis_subscription *sub,
1480
	struct stasis_message *message)
1480
	struct stasis_message *message)
1481
{
1481
{
1482
	/* This callback is only concerned with network change messages from the system topic. */
1482
	/* This callback is only concerned with network change messages from the system topic. */
1483
	if (stasis_message_type(message) != ast_network_change_type()) {
1483
	if (stasis_message_type(message) != ast_network_change_type()) {
1484
		return;
1484
		return;
1485
	}
1485
	}
1486

    
   
1486

   
1487
	ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1487
	ast_verb(1, "IAX, got a network change message, renewing all IAX registrations.\n");
1488
	if (network_change_sched_id == -1) {
1488
	if (network_change_sched_id == -1) {
1489
		network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1489
		network_change_sched_id = iax2_sched_add(sched, 1000, network_change_sched_cb, NULL);
1490
	}
1490
	}
1491
}
1491
}
1492

    
   
1492

   
1493
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1493
static void acl_change_stasis_cb(void *data, struct stasis_subscription *sub,
1494
	struct stasis_message *message)
1494
	struct stasis_message *message)
1495
{
1495
{
1496
	if (stasis_message_type(message) != ast_named_acl_change_type()) {
1496
	if (stasis_message_type(message) != ast_named_acl_change_type()) {
1497
		return;
1497
		return;
1498
	}
1498
	}
1499

    
   
1499

   
1500
	ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1500
	ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1501
	reload_config(1);
1501
	reload_config(1);
1502
}
1502
}
1503

    
   
1503

   
1504
static const struct ast_datastore_info iax2_variable_datastore_info = {
1504
static const struct ast_datastore_info iax2_variable_datastore_info = {
1505
	.type = "IAX2_VARIABLE",
1505
	.type = "IAX2_VARIABLE",
1506
	.duplicate = iax2_dup_variable_datastore,
1506
	.duplicate = iax2_dup_variable_datastore,
1507
	.destroy = iax2_free_variable_datastore,
1507
	.destroy = iax2_free_variable_datastore,
1508
};
1508
};
1509

    
   
1509

   
1510
static void *iax2_dup_variable_datastore(void *old)
1510
static void *iax2_dup_variable_datastore(void *old)
1511
{
1511
{
1512
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1512
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1513
	struct ast_var_t *oldvar, *newvar;
1513
	struct ast_var_t *oldvar, *newvar;
1514

    
   
1514

   
1515
	newlist = ast_calloc(sizeof(*newlist), 1);
1515
	newlist = ast_calloc(sizeof(*newlist), 1);
1516
	if (!newlist) {
1516
	if (!newlist) {
1517
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1517
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1518
		return NULL;
1518
		return NULL;
1519
	}
1519
	}
1520

    
   
1520

   
1521
	AST_LIST_HEAD_INIT(newlist);
1521
	AST_LIST_HEAD_INIT(newlist);
1522
	AST_LIST_LOCK(oldlist);
1522
	AST_LIST_LOCK(oldlist);
1523
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1523
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1524
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1524
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1525
		if (newvar)
1525
		if (newvar)
1526
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1526
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1527
		else
1527
		else
1528
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1528
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1529
	}
1529
	}
1530
	AST_LIST_UNLOCK(oldlist);
1530
	AST_LIST_UNLOCK(oldlist);
1531
	return newlist;
1531
	return newlist;
1532
}
1532
}
1533

    
   
1533

   
1534
static void iax2_free_variable_datastore(void *old)
1534
static void iax2_free_variable_datastore(void *old)
1535
{
1535
{
1536
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1536
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1537
	struct ast_var_t *oldvar;
1537
	struct ast_var_t *oldvar;
1538

    
   
1538

   
1539
	AST_LIST_LOCK(oldlist);
1539
	AST_LIST_LOCK(oldlist);
1540
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1540
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1541
		ast_free(oldvar);
1541
		ast_free(oldvar);
1542
	}
1542
	}
1543
	AST_LIST_UNLOCK(oldlist);
1543
	AST_LIST_UNLOCK(oldlist);
1544
	AST_LIST_HEAD_DESTROY(oldlist);
1544
	AST_LIST_HEAD_DESTROY(oldlist);
1545
	ast_free(oldlist);
1545
	ast_free(oldlist);
1546
}
1546
}
1547

    
   
1547

   
1548

    
   
1548

   
1549
/* WARNING: insert_idle_thread should only ever be called within the
1549
/* WARNING: insert_idle_thread should only ever be called within the
1550
 * context of an iax2_process_thread() thread.
1550
 * context of an iax2_process_thread() thread.
1551
 */
1551
 */
1552
static void insert_idle_thread(struct iax2_thread *thread)
1552
static void insert_idle_thread(struct iax2_thread *thread)
1553
{
1553
{
1554
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1554
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1555
		AST_LIST_LOCK(&dynamic_list);
1555
		AST_LIST_LOCK(&dynamic_list);
1556
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1556
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1557
		AST_LIST_UNLOCK(&dynamic_list);
1557
		AST_LIST_UNLOCK(&dynamic_list);
1558
	} else {
1558
	} else {
1559
		AST_LIST_LOCK(&idle_list);
1559
		AST_LIST_LOCK(&idle_list);
1560
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1560
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1561
		AST_LIST_UNLOCK(&idle_list);
1561
		AST_LIST_UNLOCK(&idle_list);
1562
	}
1562
	}
1563

    
   
1563

   
1564
	return;
1564
	return;
1565
}
1565
}
1566

    
   
1566

   
1567
static struct iax2_thread *find_idle_thread(void)
1567
static struct iax2_thread *find_idle_thread(void)
1568
{
1568
{
1569
	struct iax2_thread *thread = NULL;
1569
	struct iax2_thread *thread = NULL;
1570

    
   
1570

   
1571
	/* Pop the head of the idle list off */
1571
	/* Pop the head of the idle list off */
1572
	AST_LIST_LOCK(&idle_list);
1572
	AST_LIST_LOCK(&idle_list);
1573
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1573
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1574
	AST_LIST_UNLOCK(&idle_list);
1574
	AST_LIST_UNLOCK(&idle_list);
1575

    
   
1575

   
1576
	/* If we popped a thread off the idle list, just return it */
1576
	/* If we popped a thread off the idle list, just return it */
1577
	if (thread) {
1577
	if (thread) {
1578
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1578
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1579
		return thread;
1579
		return thread;
1580
	}
1580
	}
1581

    
   
1581

   
1582
	/* Pop the head of the dynamic list off */
1582
	/* Pop the head of the dynamic list off */
1583
	AST_LIST_LOCK(&dynamic_list);
1583
	AST_LIST_LOCK(&dynamic_list);
1584
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1584
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1585
	AST_LIST_UNLOCK(&dynamic_list);
1585
	AST_LIST_UNLOCK(&dynamic_list);
1586

    
   
1586

   
1587
	/* If we popped a thread off the dynamic list, just return it */
1587
	/* If we popped a thread off the dynamic list, just return it */
1588
	if (thread) {
1588
	if (thread) {
1589
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1589
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1590
		return thread;
1590
		return thread;
1591
	}
1591
	}
1592

    
   
1592

   
1593
	/* If we can't create a new dynamic thread for any reason, return no thread at all */
1593
	/* If we can't create a new dynamic thread for any reason, return no thread at all */
1594
	if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1594
	if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1595
		return NULL;
1595
		return NULL;
1596

    
   
1596

   
1597
	/* Set default values */
1597
	/* Set default values */
1598
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1598
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1599
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1599
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1600
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1600
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1601

    
   
1601

   
1602
	/* Initialize lock and condition */
1602
	/* Initialize lock and condition */
1603
	ast_mutex_init(&thread->lock);
1603
	ast_mutex_init(&thread->lock);
1604
	ast_cond_init(&thread->cond, NULL);
1604
	ast_cond_init(&thread->cond, NULL);
1605
	ast_mutex_init(&thread->init_lock);
1605
	ast_mutex_init(&thread->init_lock);
1606
	ast_cond_init(&thread->init_cond, NULL);
1606
	ast_cond_init(&thread->init_cond, NULL);
1607
	ast_mutex_lock(&thread->init_lock);
1607
	ast_mutex_lock(&thread->init_lock);
1608

    
   
1608

   
1609
	/* Create thread and send it on it's way */
1609
	/* Create thread and send it on it's way */
1610
	if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1610
	if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1611
		ast_cond_destroy(&thread->cond);
1611
		ast_cond_destroy(&thread->cond);
1612
		ast_mutex_destroy(&thread->lock);
1612
		ast_mutex_destroy(&thread->lock);
1613
		ast_mutex_unlock(&thread->init_lock);
1613
		ast_mutex_unlock(&thread->init_lock);
1614
		ast_cond_destroy(&thread->init_cond);
1614
		ast_cond_destroy(&thread->init_cond);
1615
		ast_mutex_destroy(&thread->init_lock);
1615
		ast_mutex_destroy(&thread->init_lock);
1616
		ast_free(thread);
1616
		ast_free(thread);
1617
		return NULL;
1617
		return NULL;
1618
	}
1618
	}
1619

    
   
1619

   
1620
	/* this thread is not processing a full frame (since it is idle),
1620
	/* this thread is not processing a full frame (since it is idle),
1621
	   so ensure that the field for the full frame call number is empty */
1621
	   so ensure that the field for the full frame call number is empty */
1622
	memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1622
	memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1623

    
   
1623

   
1624
	/* Wait for the thread to be ready before returning it to the caller */
1624
	/* Wait for the thread to be ready before returning it to the caller */
1625
	ast_cond_wait(&thread->init_cond, &thread->init_lock);
1625
	ast_cond_wait(&thread->init_cond, &thread->init_lock);
1626

    
   
1626

   
1627
	/* Done with init_lock */
1627
	/* Done with init_lock */
1628
	ast_mutex_unlock(&thread->init_lock);
1628
	ast_mutex_unlock(&thread->init_lock);
1629

    
   
1629

   
1630
	return thread;
1630
	return thread;
1631
}
1631
}
1632

    
   
1632

   
1633
#ifdef SCHED_MULTITHREADED
1633
#ifdef SCHED_MULTITHREADED
1634
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1634
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1635
{
1635
{
1636
	struct iax2_thread *thread;
1636
	struct iax2_thread *thread;
1637
	static time_t lasterror;
1637
	static time_t lasterror;
1638
	time_t t;
1638
	time_t t;
1639

    
   
1639

   
1640
	thread = find_idle_thread();
1640
	thread = find_idle_thread();
1641
	if (thread != NULL) {
1641
	if (thread != NULL) {
1642
		thread->schedfunc = func;
1642
		thread->schedfunc = func;
1643
		thread->scheddata = data;
1643
		thread->scheddata = data;
1644
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1644
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1645
#ifdef DEBUG_SCHED_MULTITHREAD
1645
#ifdef DEBUG_SCHED_MULTITHREAD
1646
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1646
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1647
#endif
1647
#endif
1648
		signal_condition(&thread->lock, &thread->cond);
1648
		signal_condition(&thread->lock, &thread->cond);
1649
		return 0;
1649
		return 0;
1650
	}
1650
	}
1651
	time(&t);
1651
	time(&t);
1652
	if (t != lasterror) {
1652
	if (t != lasterror) {
1653
		lasterror = t;
1653
		lasterror = t;
1654
		ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1654
		ast_debug(1, "Out of idle IAX2 threads for scheduling! (%s)\n", funcname);
1655
	}
1655
	}
1656

    
   
1656

   
1657
	return -1;
1657
	return -1;
1658
}
1658
}
1659
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1659
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1660
#endif
1660
#endif
1661

    
   
1661

   
1662
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1662
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1663
		ast_sched_cb callback, const void *data)
1663
		ast_sched_cb callback, const void *data)
1664
{
1664
{
1665
	return ast_sched_replace(id, con, when, callback, data);
1665
	return ast_sched_replace(id, con, when, callback, data);
1666
}
1666
}
1667

    
   
1667

   
1668
static int iax2_sched_add(struct ast_sched_context *con, int when,
1668
static int iax2_sched_add(struct ast_sched_context *con, int when,
1669
		ast_sched_cb callback, const void *data)
1669
		ast_sched_cb callback, const void *data)
1670
{
1670
{
1671
	return ast_sched_add(con, when, callback, data);
1671
	return ast_sched_add(con, when, callback, data);
1672
}
1672
}
1673

    
   
1673

   
1674
static int send_ping(const void *data);
1674
static int send_ping(const void *data);
1675

    
   
1675

   
1676
static void __send_ping(const void *data)
1676
static void __send_ping(const void *data)
1677
{
1677
{
1678
	int callno = (long) data;
1678
	int callno = (long) data;
1679

    
   
1679

   
1680
	ast_mutex_lock(&iaxsl[callno]);
1680
	ast_mutex_lock(&iaxsl[callno]);
1681

    
   
1681

   
1682
	if (iaxs[callno]) {
1682
	if (iaxs[callno]) {
1683
		if (iaxs[callno]->peercallno) {
1683
		if (iaxs[callno]->peercallno) {
1684
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1684
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1685
			if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1685
			if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1686
				iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1686
				iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1687
			}
1687
			}
1688
		}
1688
		}
1689
	} else {
1689
	} else {
1690
		ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1690
		ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1691
	}
1691
	}
1692

    
   
1692

   
1693
	ast_mutex_unlock(&iaxsl[callno]);
1693
	ast_mutex_unlock(&iaxsl[callno]);
1694
}
1694
}
1695

    
   
1695

   
1696
static int send_ping(const void *data)
1696
static int send_ping(const void *data)
1697
{
1697
{
1698
	int callno = (long) data;
1698
	int callno = (long) data;
1699
	ast_mutex_lock(&iaxsl[callno]);
1699
	ast_mutex_lock(&iaxsl[callno]);
1700
	if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1700
	if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1701
		iaxs[callno]->pingid = -1;
1701
		iaxs[callno]->pingid = -1;
1702
	}
1702
	}
1703
	ast_mutex_unlock(&iaxsl[callno]);
1703
	ast_mutex_unlock(&iaxsl[callno]);
1704

    
   
1704

   
1705
#ifdef SCHED_MULTITHREADED
1705
#ifdef SCHED_MULTITHREADED
1706
	if (schedule_action(__send_ping, data))
1706
	if (schedule_action(__send_ping, data))
1707
#endif
1707
#endif
1708
		__send_ping(data);
1708
		__send_ping(data);
1709

    
   
1709

   
1710
	return 0;
1710
	return 0;
1711
}
1711
}
1712

    
   
1712

   
1713
static void encmethods_to_str(int e, struct ast_str **buf)
1713
static void encmethods_to_str(int e, struct ast_str **buf)
1714
{
1714
{
1715
	ast_str_set(buf, 0, "(");
1715
	ast_str_set(buf, 0, "(");
1716
	if (e & IAX_ENCRYPT_AES128) {
1716
	if (e & IAX_ENCRYPT_AES128) {
1717
		ast_str_append(buf, 0, "aes128");
1717
		ast_str_append(buf, 0, "aes128");
1718
	}
1718
	}
1719
	if (e & IAX_ENCRYPT_KEYROTATE) {
1719
	if (e & IAX_ENCRYPT_KEYROTATE) {
1720
		ast_str_append(buf, 0, ",keyrotate");
1720
		ast_str_append(buf, 0, ",keyrotate");
1721
	}
1721
	}
1722
	if (ast_str_strlen(*buf) > 1) {
1722
	if (ast_str_strlen(*buf) > 1) {
1723
		ast_str_append(buf, 0, ")");
1723
		ast_str_append(buf, 0, ")");
1724
	} else {
1724
	} else {
1725
		ast_str_set(buf, 0, "No");
1725
		ast_str_set(buf, 0, "No");
1726
	}
1726
	}
1727
}
1727
}
1728

    
   
1728

   
1729
static int get_encrypt_methods(const char *s)
1729
static int get_encrypt_methods(const char *s)
1730
{
1730
{
1731
	int e;
1731
	int e;
1732
	if (!strcasecmp(s, "aes128"))
1732
	if (!strcasecmp(s, "aes128"))
1733
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1733
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1734
	else if (ast_true(s))
1734
	else if (ast_true(s))
1735
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1735
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1736
	else
1736
	else
1737
		e = 0;
1737
		e = 0;
1738
	return e;
1738
	return e;
1739
}
1739
}
1740

    
   
1740

   
1741
static int send_lagrq(const void *data);
1741
static int send_lagrq(const void *data);
1742

    
   
1742

   
1743
static void __send_lagrq(const void *data)
1743
static void __send_lagrq(const void *data)
1744
{
1744
{
1745
	int callno = (long) data;
1745
	int callno = (long) data;
1746

    
   
1746

   
1747
	ast_mutex_lock(&iaxsl[callno]);
1747
	ast_mutex_lock(&iaxsl[callno]);
1748

    
   
1748

   
1749
	if (iaxs[callno]) {
1749
	if (iaxs[callno]) {
1750
		if (iaxs[callno]->peercallno) {
1750
		if (iaxs[callno]->peercallno) {
1751
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1751
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1752
			if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1752
			if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1753
				iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1753
				iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1754
			}
1754
			}
1755
		}
1755
		}
1756
	} else {
1756
	} else {
1757
		ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1757
		ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1758
	}
1758
	}
1759

    
   
1759

   
1760
	ast_mutex_unlock(&iaxsl[callno]);
1760
	ast_mutex_unlock(&iaxsl[callno]);
1761
}
1761
}
1762

    
   
1762

   
1763
static int send_lagrq(const void *data)
1763
static int send_lagrq(const void *data)
1764
{
1764
{
1765
	int callno = (long) data;
1765
	int callno = (long) data;
1766
	ast_mutex_lock(&iaxsl[callno]);
1766
	ast_mutex_lock(&iaxsl[callno]);
1767
	if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1767
	if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1768
		iaxs[callno]->lagid = -1;
1768
		iaxs[callno]->lagid = -1;
1769
	}
1769
	}
1770
	ast_mutex_unlock(&iaxsl[callno]);
1770
	ast_mutex_unlock(&iaxsl[callno]);
1771

    
   
1771

   
1772
#ifdef SCHED_MULTITHREADED
1772
#ifdef SCHED_MULTITHREADED
1773
	if (schedule_action(__send_lagrq, data))
1773
	if (schedule_action(__send_lagrq, data))
1774
#endif
1774
#endif
1775
		__send_lagrq(data);
1775
		__send_lagrq(data);
1776
	return 0;
1776
	return 0;
1777
}
1777
}
1778

    
   
1778

   
1779
static unsigned char compress_subclass(iax2_format subclass)
1779
static unsigned char compress_subclass(iax2_format subclass)
1780
{
1780
{
1781
	int x;
1781
	int x;
1782
	int power=-1;
1782
	int power=-1;
1783
	/* If it's 64 or smaller, just return it */
1783
	/* If it's 64 or smaller, just return it */
1784
	if (subclass < IAX_FLAG_SC_LOG)
1784
	if (subclass < IAX_FLAG_SC_LOG)
1785
		return subclass;
1785
		return subclass;
1786
	/* Otherwise find its power */
1786
	/* Otherwise find its power */
1787
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1787
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1788
		if (subclass & (1LL << x)) {
1788
		if (subclass & (1LL << x)) {
1789
			if (power > -1) {
1789
			if (power > -1) {
1790
				ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1790
				ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1791
				return 0;
1791
				return 0;
1792
			} else
1792
			} else
1793
				power = x;
1793
				power = x;
1794
		}
1794
		}
1795
	}
1795
	}
1796
	return power | IAX_FLAG_SC_LOG;
1796
	return power | IAX_FLAG_SC_LOG;
1797
}
1797
}
1798

    
   
1798

   
1799
static iax2_format uncompress_subclass(unsigned char csub)
1799
static iax2_format uncompress_subclass(unsigned char csub)
1800
{
1800
{
1801
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1801
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1802
	if (csub & IAX_FLAG_SC_LOG) {
1802
	if (csub & IAX_FLAG_SC_LOG) {
1803
		/* special case for 'compressed' -1 */
1803
		/* special case for 'compressed' -1 */
1804
		if (csub == 0xff)
1804
		if (csub == 0xff)
1805
			return -1;
1805
			return -1;
1806
		else
1806
		else
1807
			return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1807
			return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1808
	}
1808
	}
1809
	else
1809
	else
1810
		return csub;
1810
		return csub;
1811
}
1811
}
1812

    
   
1812

   
1813
static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1813
static struct ast_format *codec_choose_from_prefs(struct iax2_codec_pref *pref, struct ast_format_cap *cap)
1814
{
1814
{
1815
	int x;
1815
	int x;
1816
	struct ast_format *found_format = NULL;
1816
	struct ast_format *found_format = NULL;
1817

    
   
1817

   
1818
	for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1818
	for (x = 0; x < ARRAY_LEN(pref->order); ++x) {
1819
		struct ast_format *pref_format;
1819
		struct ast_format *pref_format;
1820
		uint64_t pref_bitfield;
1820
		uint64_t pref_bitfield;
1821

    
   
1821

   
1822
		pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1822
		pref_bitfield = iax2_codec_pref_order_value_to_format_bitfield(pref->order[x]);
1823
		if (!pref_bitfield) {
1823
		if (!pref_bitfield) {
1824
			break;
1824
			break;
1825
		}
1825
		}
1826

    
   
1826

   
1827
		pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1827
		pref_format = ast_format_compatibility_bitfield2format(pref_bitfield);
1828
		if (!pref_format) {
1828
		if (!pref_format) {
1829
			/* The bitfield is not associated with any format. */
1829
			/* The bitfield is not associated with any format. */
1830
			continue;
1830
			continue;
1831
		}
1831
		}
1832
		found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1832
		found_format = ast_format_cap_get_compatible_format(cap, pref_format);
1833
		if (found_format) {
1833
		if (found_format) {
1834
			break;
1834
			break;
1835
		}
1835
		}
1836
	}
1836
	}
1837

    
   
1837

   
1838
	if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1838
	if (found_format && (ast_format_get_type(found_format) == AST_MEDIA_TYPE_AUDIO)) {
1839
		return found_format;
1839
		return found_format;
1840
	}
1840
	}
1841

    
   
1841

   
1842
	ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1842
	ast_debug(4, "Could not find preferred codec - Returning zero codec.\n");
1843
	ao2_cleanup(found_format);
1843
	ao2_cleanup(found_format);
1844
	return NULL;
1844
	return NULL;
1845
}
1845
}
1846

    
   
1846

   
1847
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
1847
static iax2_format iax2_codec_choose(struct iax2_codec_pref *pref, iax2_format formats)
1848
{
1848
{
1849
	struct ast_format_cap *cap;
1849
	struct ast_format_cap *cap;
1850
	struct ast_format *tmpfmt;
1850
	struct ast_format *tmpfmt;
1851
	iax2_format format = 0;
1851
	iax2_format format = 0;
1852

    
   
1852

   
1853
	if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1853
	if ((cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT))) {
1854
		iax2_format_compatibility_bitfield2cap(formats, cap);
1854
		iax2_format_compatibility_bitfield2cap(formats, cap);
1855
		tmpfmt = codec_choose_from_prefs(pref, cap);
1855
		tmpfmt = codec_choose_from_prefs(pref, cap);
1856
		if (!tmpfmt) {
1856
		if (!tmpfmt) {
1857
			ao2_ref(cap, -1);
1857
			ao2_ref(cap, -1);
1858
			return 0;
1858
			return 0;
1859
		}
1859
		}
1860

    
   
1860

   
1861
		format = ast_format_compatibility_format2bitfield(tmpfmt);
1861
		format = ast_format_compatibility_format2bitfield(tmpfmt);
1862
		ao2_ref(tmpfmt, -1);
1862
		ao2_ref(tmpfmt, -1);
1863
		ao2_ref(cap, -1);
1863
		ao2_ref(cap, -1);
1864
	}
1864
	}
1865

    
   
1865

   
1866
	return format;
1866
	return format;
1867
}
1867
}
1868

    
   
1868

   
1869
const char *iax2_getformatname(iax2_format format)
1869
const char *iax2_getformatname(iax2_format format)
1870
{
1870
{
1871
	struct ast_format *tmpfmt;
1871
	struct ast_format *tmpfmt;
1872

    
   
1872

   
1873
	tmpfmt = ast_format_compatibility_bitfield2format(format);
1873
	tmpfmt = ast_format_compatibility_bitfield2format(format);
1874
	if (!tmpfmt) {
1874
	if (!tmpfmt) {
1875
		return "Unknown";
1875
		return "Unknown";
1876
	}
1876
	}
1877

    
   
1877

   
1878
	return ast_format_get_name(tmpfmt);
1878
	return ast_format_get_name(tmpfmt);
1879
}
1879
}
1880

    
   
1880

   
1881
static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1881
static const char *iax2_getformatname_multiple(iax2_format format, struct ast_str **codec_buf)
1882
{
1882
{
1883
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1883
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1884

    
   
1884

   
1885
	if (!cap) {
1885
	if (!cap) {
1886
		return "(Nothing)";
1886
		return "(Nothing)";
1887
	}
1887
	}
1888
	iax2_format_compatibility_bitfield2cap(format, cap);
1888
	iax2_format_compatibility_bitfield2cap(format, cap);
1889
	ast_format_cap_get_names(cap, codec_buf);
1889
	ast_format_cap_get_names(cap, codec_buf);
1890
	ao2_ref(cap, -1);
1890
	ao2_ref(cap, -1);
1891

    
   
1891

   
1892
	return ast_str_buffer(*codec_buf);
1892
	return ast_str_buffer(*codec_buf);
1893
}
1893
}
1894

    
   
1894

   
1895
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1895
static int iax2_parse_allow_disallow(struct iax2_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1896
{
1896
{
1897
	int res, i;
1897
	int res, i;
1898
	struct ast_format_cap *cap;
1898
	struct ast_format_cap *cap;
1899

    
   
1899

   
1900
	/* We want to add the formats to the cap in the preferred order */
1900
	/* We want to add the formats to the cap in the preferred order */
1901
	cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1901
	cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1902
	if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1902
	if (!cap || iax2_codec_pref_to_cap(pref, cap)) {
1903
		ao2_cleanup(cap);
1903
		ao2_cleanup(cap);
1904
		return 1;
1904
		return 1;
1905
	}
1905
	}
1906

    
   
1906

   
1907
	res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1907
	res = ast_format_cap_update_by_allow_disallow(cap, list, allowing);
1908

    
   
1908

   
1909
	/* Adjust formats bitfield and pref list to match. */
1909
	/* Adjust formats bitfield and pref list to match. */
1910
	*formats = iax2_format_compatibility_cap2bitfield(cap);
1910
	*formats = iax2_format_compatibility_cap2bitfield(cap);
1911
	iax2_codec_pref_remove_missing(pref, *formats);
1911
	iax2_codec_pref_remove_missing(pref, *formats);
1912

    
   
1912

   
1913
	for (i = 0; i < ast_format_cap_count(cap); i++) {
1913
	for (i = 0; i < ast_format_cap_count(cap); i++) {
1914
		struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1914
		struct ast_format *fmt = ast_format_cap_get_format(cap, i);
1915

    
   
1915

   
1916
		iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
1916
		iax2_codec_pref_append(pref, fmt, ast_format_cap_get_format_framing(cap, fmt));
1917
		ao2_ref(fmt, -1);
1917
		ao2_ref(fmt, -1);
1918
	}
1918
	}
1919

    
   
1919

   
1920
	ao2_ref(cap, -1);
1920
	ao2_ref(cap, -1);
1921

    
   
1921

   
1922
	return res;
1922
	return res;
1923
}
1923
}
1924

    
   
1924

   
1925
static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1925
static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1926
{
1926
{
1927
	int res;
1927
	int res;
1928
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1928
	struct ast_format_cap *cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
1929
	if (!cap) {
1929
	if (!cap) {
1930
		return -1;
1930
		return -1;
1931
	}
1931
	}
1932
	iax2_format_compatibility_bitfield2cap(formats, cap);
1932
	iax2_format_compatibility_bitfield2cap(formats, cap);
1933
	res = ast_data_add_codecs(root, node_name, cap);
1933
	res = ast_data_add_codecs(root, node_name, cap);
1934
	ao2_ref(cap, -1);
1934
	ao2_ref(cap, -1);
1935
	return res;
1935
	return res;
1936
}
1936
}
1937

    
   
1937

   
1938
/*!
1938
/*!
1939
 * \note The only member of the peer passed here guaranteed to be set is the name field
1939
 * \note The only member of the peer passed here guaranteed to be set is the name field
1940
 */
1940
 */
1941
static int peer_hash_cb(const void *obj, const int flags)
1941
static int peer_hash_cb(const void *obj, const int flags)
1942
{
1942
{
1943
	const struct iax2_peer *peer = obj;
1943
	const struct iax2_peer *peer = obj;
1944
	const char *name = obj;
1944
	const char *name = obj;
1945

    
   
1945

   
1946
	return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1946
	return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1947
}
1947
}
1948

    
   
1948

   
1949
/*!
1949
/*!
1950
 * \note The only member of the peer passed here guaranteed to be set is the name field
1950
 * \note The only member of the peer passed here guaranteed to be set is the name field
1951
 */
1951
 */
1952
static int peer_cmp_cb(void *obj, void *arg, int flags)
1952
static int peer_cmp_cb(void *obj, void *arg, int flags)
1953
{
1953
{
1954
	struct iax2_peer *peer = obj, *peer2 = arg;
1954
	struct iax2_peer *peer = obj, *peer2 = arg;
1955
	const char *name = arg;
1955
	const char *name = arg;
1956

    
   
1956

   
1957
	return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1957
	return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1958
			CMP_MATCH | CMP_STOP : 0;
1958
			CMP_MATCH | CMP_STOP : 0;
1959
}
1959
}
1960

    
   
1960

   
1961
/*!
1961
/*!
1962
 * \note The only member of the user passed here guaranteed to be set is the name field
1962
 * \note The only member of the user passed here guaranteed to be set is the name field
1963
 */
1963
 */
1964
static int user_hash_cb(const void *obj, const int flags)
1964
static int user_hash_cb(const void *obj, const int flags)
1965
{
1965
{
1966
	const struct iax2_user *user = obj;
1966
	const struct iax2_user *user = obj;
1967
	const char *name = obj;
1967
	const char *name = obj;
1968

    
   
1968

   
1969
	return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1969
	return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1970
}
1970
}
1971

    
   
1971

   
1972
/*!
1972
/*!
1973
 * \note The only member of the user passed here guaranteed to be set is the name field
1973
 * \note The only member of the user passed here guaranteed to be set is the name field
1974
 */
1974
 */
1975
static int user_cmp_cb(void *obj, void *arg, int flags)
1975
static int user_cmp_cb(void *obj, void *arg, int flags)
1976
{
1976
{
1977
	struct iax2_user *user = obj, *user2 = arg;
1977
	struct iax2_user *user = obj, *user2 = arg;
1978
	const char *name = arg;
1978
	const char *name = arg;
1979

    
   
1979

   
1980
	return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1980
	return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1981
			CMP_MATCH | CMP_STOP : 0;
1981
			CMP_MATCH | CMP_STOP : 0;
1982
}
1982
}
1983

    
   
1983

   
1984
/*!
1984
/*!
1985
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1985
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1986
 *       so do not call it with a pvt lock held.
1986
 *       so do not call it with a pvt lock held.
1987
 */
1987
 */
1988
static struct iax2_peer *find_peer(const char *name, int realtime)
1988
static struct iax2_peer *find_peer(const char *name, int realtime)
1989
{
1989
{
1990
	struct iax2_peer *peer = NULL;
1990
	struct iax2_peer *peer = NULL;
1991

    
   
1991

   
1992
	peer = ao2_find(peers, name, OBJ_KEY);
1992
	peer = ao2_find(peers, name, OBJ_KEY);
1993

    
   
1993

   
1994
	/* Now go for realtime if applicable */
1994
	/* Now go for realtime if applicable */
1995
	if (!peer && realtime) {
1995
	if (!peer && realtime) {
1996
		peer = realtime_peer(name, NULL);
1996
		peer = realtime_peer(name, NULL);
1997
	}
1997
	}
1998
	return peer;
1998
	return peer;
1999
}
1999
}
2000

    
   
2000

   
2001
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2001
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
2002
{
2002
{
2003
	ao2_ref(peer, +1);
2003
	ao2_ref(peer, +1);
2004
	return peer;
2004
	return peer;
2005
}
2005
}
2006

    
   
2006

   
2007
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2007
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
2008
{
2008
{
2009
	ao2_ref(peer, -1);
2009
	ao2_ref(peer, -1);
2010
	return NULL;
2010
	return NULL;
2011
}
2011
}
2012

    
   
2012

   
2013
static struct iax2_user *find_user(const char *name)
2013
static struct iax2_user *find_user(const char *name)
2014
{
2014
{
2015
	return ao2_find(users, name, OBJ_KEY);
2015
	return ao2_find(users, name, OBJ_KEY);
2016
}
2016
}
2017

    
   
2017

   
2018
static inline struct iax2_user *user_unref(struct iax2_user *user)
2018
static inline struct iax2_user *user_unref(struct iax2_user *user)
2019
{
2019
{
2020
	ao2_ref(user, -1);
2020
	ao2_ref(user, -1);
2021
	return NULL;
2021
	return NULL;
2022
}
2022
}
2023

    
   
2023

   
2024
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2024
static int iax2_getpeername(struct ast_sockaddr addr, char *host, int len)
2025
{
2025
{
2026
	struct iax2_peer *peer = NULL;
2026
	struct iax2_peer *peer = NULL;
2027
	int res = 0;
2027
	int res = 0;
2028
	struct ao2_iterator i;
2028
	struct ao2_iterator i;
2029

    
   
2029

   
2030
	i = ao2_iterator_init(peers, 0);
2030
	i = ao2_iterator_init(peers, 0);
2031
	while ((peer = ao2_iterator_next(&i))) {
2031
	while ((peer = ao2_iterator_next(&i))) {
2032

    
   
2032

   
2033
		if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2033
		if (!ast_sockaddr_cmp(&peer->addr, &addr)) {
2034
			ast_copy_string(host, peer->name, len);
2034
			ast_copy_string(host, peer->name, len);
2035
			peer_unref(peer);
2035
			peer_unref(peer);
2036
			res = 1;
2036
			res = 1;
2037
			break;
2037
			break;
2038
		}
2038
		}
2039
		peer_unref(peer);
2039
		peer_unref(peer);
2040
	}
2040
	}
2041
	ao2_iterator_destroy(&i);
2041
	ao2_iterator_destroy(&i);
2042

    
   
2042

   
2043
	if (!peer) {
2043
	if (!peer) {
2044
		peer = realtime_peer(NULL, &addr);
2044
		peer = realtime_peer(NULL, &addr);
2045
		if (peer) {
2045
		if (peer) {
2046
			ast_copy_string(host, peer->name, len);
2046
			ast_copy_string(host, peer->name, len);
2047
			peer_unref(peer);
2047
			peer_unref(peer);
2048
			res = 1;
2048
			res = 1;
2049
		}
2049
		}
2050
	}
2050
	}
2051

    
   
2051

   
2052
	return res;
2052
	return res;
2053
}
2053
}
2054

    
   
2054

   
2055
/*!\note Assumes the lock on the pvt is already held, when
2055
/*!\note Assumes the lock on the pvt is already held, when
2056
 * iax2_destroy_helper() is called. */
2056
 * iax2_destroy_helper() is called. */
2057
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2057
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2058
{
2058
{
2059
	/* Decrement AUTHREQ count if needed */
2059
	/* Decrement AUTHREQ count if needed */
2060
	if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2060
	if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
2061
		struct iax2_user *user;
2061
		struct iax2_user *user;
2062

    
   
2062

   
2063
		user = ao2_find(users, pvt->username, OBJ_KEY);
2063
		user = ao2_find(users, pvt->username, OBJ_KEY);
2064
		if (user) {
2064
		if (user) {
2065
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
2065
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
2066
			user_unref(user);
2066
			user_unref(user);
2067
		}
2067
		}
2068

    
   
2068

   
2069
		ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2069
		ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
2070
	}
2070
	}
2071
	/* No more pings or lagrq's */
2071
	/* No more pings or lagrq's */
2072
	AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
2072
	AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
2073
	pvt->pingid = DONT_RESCHEDULE;
2073
	pvt->pingid = DONT_RESCHEDULE;
2074
	AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
2074
	AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
2075
	pvt->lagid = DONT_RESCHEDULE;
2075
	pvt->lagid = DONT_RESCHEDULE;
2076
	AST_SCHED_DEL(sched, pvt->autoid);
2076
	AST_SCHED_DEL(sched, pvt->autoid);
2077
	AST_SCHED_DEL(sched, pvt->authid);
2077
	AST_SCHED_DEL(sched, pvt->authid);
2078
	AST_SCHED_DEL(sched, pvt->initid);
2078
	AST_SCHED_DEL(sched, pvt->initid);
2079
	AST_SCHED_DEL(sched, pvt->jbid);
2079
	AST_SCHED_DEL(sched, pvt->jbid);
2080
	AST_SCHED_DEL(sched, pvt->keyrotateid);
2080
	AST_SCHED_DEL(sched, pvt->keyrotateid);
2081
}
2081
}
2082

    
   
2082

   
2083
static void iax2_frame_free(struct iax_frame *fr)
2083
static void iax2_frame_free(struct iax_frame *fr)
2084
{
2084
{
2085
	AST_SCHED_DEL(sched, fr->retrans);
2085
	AST_SCHED_DEL(sched, fr->retrans);
2086
	iax_frame_free(fr);
2086
	iax_frame_free(fr);
2087
}
2087
}
2088

    
   
2088

   
2089
static int scheduled_destroy(const void *vid)
2089
static int scheduled_destroy(const void *vid)
2090
{
2090
{
2091
	unsigned short callno = PTR_TO_CALLNO(vid);
2091
	unsigned short callno = PTR_TO_CALLNO(vid);
2092
	ast_mutex_lock(&iaxsl[callno]);
2092
	ast_mutex_lock(&iaxsl[callno]);
2093
	if (iaxs[callno]) {
2093
	if (iaxs[callno]) {
2094
		ast_debug(1, "Really destroying %d now...\n", callno);
2094
		ast_debug(1, "Really destroying %d now...\n", callno);
2095
		iax2_destroy(callno);
2095
		iax2_destroy(callno);
2096
	}
2096
	}
2097
	ast_mutex_unlock(&iaxsl[callno]);
2097
	ast_mutex_unlock(&iaxsl[callno]);
2098
	return 0;
2098
	return 0;
2099
}
2099
}
2100

    
   
2100

   
2101
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2101
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
2102
{
2102
{
2103
	if (s->f.datalen) {
2103
	if (s->f.datalen) {
2104
		ast_free(s->f.data.ptr);
2104
		ast_free(s->f.data.ptr);
2105
	}
2105
	}
2106
	ast_free(s);
2106
	ast_free(s);
2107
}
2107
}
2108

    
   
2108

   
2109
/*! \brief This function must be called once we are sure the other side has
2109
/*! \brief This function must be called once we are sure the other side has
2110
 *  given us a call number.  All signaling is held here until that point. */
2110
 *  given us a call number.  All signaling is held here until that point. */
2111
static void send_signaling(struct chan_iax2_pvt *pvt)
2111
static void send_signaling(struct chan_iax2_pvt *pvt)
2112
{
2112
{
2113
	struct signaling_queue_entry *s = NULL;
2113
	struct signaling_queue_entry *s = NULL;
2114

    
   
2114

   
2115
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2115
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2116
		iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2116
		iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
2117
		free_signaling_queue_entry(s);
2117
		free_signaling_queue_entry(s);
2118
	}
2118
	}
2119
	pvt->hold_signaling = 0;
2119
	pvt->hold_signaling = 0;
2120
}
2120
}
2121

    
   
2121

   
2122
/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2122
/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
2123
 *  we have received a destination call number. */
2123
 *  we have received a destination call number. */
2124
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2124
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
2125
{
2125
{
2126
	struct signaling_queue_entry *qe;
2126
	struct signaling_queue_entry *qe;
2127

    
   
2127

   
2128
	if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2128
	if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
2129
		return 1; /* do not queue this frame */
2129
		return 1; /* do not queue this frame */
2130
	} else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2130
	} else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
2131
		return -1;  /* out of memory */
2131
		return -1;  /* out of memory */
2132
	}
2132
	}
2133

    
   
2133

   
2134
	/* copy ast_frame into our queue entry */
2134
	/* copy ast_frame into our queue entry */
2135
	qe->f = *f;
2135
	qe->f = *f;
2136
	if (qe->f.datalen) {
2136
	if (qe->f.datalen) {
2137
		/* if there is data in this frame copy it over as well */
2137
		/* if there is data in this frame copy it over as well */
2138
		if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2138
		if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
2139
			free_signaling_queue_entry(qe);
2139
			free_signaling_queue_entry(qe);
2140
			return -1;
2140
			return -1;
2141
		}
2141
		}
2142
		memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2142
		memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
2143
	}
2143
	}
2144
	AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2144
	AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
2145

    
   
2145

   
2146
	return 0;
2146
	return 0;
2147
}
2147
}
2148

    
   
2148

   
2149
static void pvt_destructor(void *obj)
2149
static void pvt_destructor(void *obj)
2150
{
2150
{
2151
	struct chan_iax2_pvt *pvt = obj;
2151
	struct chan_iax2_pvt *pvt = obj;
2152
	struct iax_frame *cur = NULL;
2152
	struct iax_frame *cur = NULL;
2153
	struct signaling_queue_entry *s = NULL;
2153
	struct signaling_queue_entry *s = NULL;
2154

    
   
2154

   
2155
	ast_mutex_lock(&iaxsl[pvt->callno]);
2155
	ast_mutex_lock(&iaxsl[pvt->callno]);
2156

    
   
2156

   
2157
	iax2_destroy_helper(pvt);
2157
	iax2_destroy_helper(pvt);
2158

    
   
2158

   
2159
	sched_delay_remove(&pvt->addr, pvt->callno_entry);
2159
	sched_delay_remove(&pvt->addr, pvt->callno_entry);
2160
	pvt->callno_entry = 0;
2160
	pvt->callno_entry = 0;
2161

    
   
2161

   
2162
	/* Already gone */
2162
	/* Already gone */
2163
	ast_set_flag64(pvt, IAX_ALREADYGONE);
2163
	ast_set_flag64(pvt, IAX_ALREADYGONE);
2164

    
   
2164

   
2165
	AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2165
	AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2166
		/* Cancel any pending transmissions */
2166
		/* Cancel any pending transmissions */
2167
		cur->retries = -1;
2167
		cur->retries = -1;
2168
	}
2168
	}
2169

    
   
2169

   
2170
	ast_mutex_unlock(&iaxsl[pvt->callno]);
2170
	ast_mutex_unlock(&iaxsl[pvt->callno]);
2171

    
   
2171

   
2172
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2172
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2173
		free_signaling_queue_entry(s);
2173
		free_signaling_queue_entry(s);
2174
	}
2174
	}
2175

    
   
2175

   
2176
	if (pvt->reg) {
2176
	if (pvt->reg) {
2177
		pvt->reg->callno = 0;
2177
		pvt->reg->callno = 0;
2178
	}
2178
	}
2179

    
   
2179

   
2180
	if (!pvt->owner) {
2180
	if (!pvt->owner) {
2181
		jb_frame frame;
2181
		jb_frame frame;
2182
		if (pvt->vars) {
2182
		if (pvt->vars) {
2183
		    ast_variables_destroy(pvt->vars);
2183
		    ast_variables_destroy(pvt->vars);
2184
		    pvt->vars = NULL;
2184
		    pvt->vars = NULL;
2185
		}
2185
		}
2186

    
   
2186

   
2187
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
2187
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
2188
			iax2_frame_free(frame.data);
2188
			iax2_frame_free(frame.data);
2189
		}
2189
		}
2190

    
   
2190

   
2191
		jb_destroy(pvt->jb);
2191
		jb_destroy(pvt->jb);
2192
		ast_string_field_free_memory(pvt);
2192
		ast_string_field_free_memory(pvt);
2193
	}
2193
	}
2194
}
2194
}
2195

    
   
2195

   
2196
static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2196
static struct chan_iax2_pvt *new_iax(struct ast_sockaddr *addr, const char *host)
2197
{
2197
{
2198
	struct chan_iax2_pvt *tmp;
2198
	struct chan_iax2_pvt *tmp;
2199
	jb_conf jbconf;
2199
	jb_conf jbconf;
2200

    
   
2200

   
2201
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2201
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2202
		return NULL;
2202
		return NULL;
2203
	}
2203
	}
2204

    
   
2204

   
2205
	if (ast_string_field_init(tmp, 32)) {
2205
	if (ast_string_field_init(tmp, 32)) {
2206
		ao2_ref(tmp, -1);
2206
		ao2_ref(tmp, -1);
2207
		tmp = NULL;
2207
		tmp = NULL;
2208
		return NULL;
2208
		return NULL;
2209
	}
2209
	}
2210

    
   
2210

   
2211
	tmp->prefs = prefs_global;
2211
	tmp->prefs = prefs_global;
2212
	tmp->pingid = -1;
2212
	tmp->pingid = -1;
2213
	tmp->lagid = -1;
2213
	tmp->lagid = -1;
2214
	tmp->autoid = -1;
2214
	tmp->autoid = -1;
2215
	tmp->authid = -1;
2215
	tmp->authid = -1;
2216
	tmp->initid = -1;
2216
	tmp->initid = -1;
2217
	tmp->keyrotateid = -1;
2217
	tmp->keyrotateid = -1;
2218

    
   
2218

   
2219
	ast_string_field_set(tmp,exten, "s");
2219
	ast_string_field_set(tmp,exten, "s");
2220
	ast_string_field_set(tmp,host, host);
2220
	ast_string_field_set(tmp,host, host);
2221

    
   
2221

   
2222
	tmp->jb = jb_new();
2222
	tmp->jb = jb_new();
2223
	tmp->jbid = -1;
2223
	tmp->jbid = -1;
2224
	jbconf.max_jitterbuf = maxjitterbuffer;
2224
	jbconf.max_jitterbuf = maxjitterbuffer;
2225
	jbconf.resync_threshold = resyncthreshold;
2225
	jbconf.resync_threshold = resyncthreshold;
2226
	jbconf.max_contig_interp = maxjitterinterps;
2226
	jbconf.max_contig_interp = maxjitterinterps;
2227
	jbconf.target_extra = jittertargetextra;
2227
	jbconf.target_extra = jittertargetextra;
2228
	jb_setconf(tmp->jb,&jbconf);
2228
	jb_setconf(tmp->jb,&jbconf);
2229

    
   
2229

   
2230
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2230
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2231

    
   
2231

   
2232
	tmp->hold_signaling = 1;
2232
	tmp->hold_signaling = 1;
2233
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2233
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2234

    
   
2234

   
2235
	return tmp;
2235
	return tmp;
2236
}
2236
}
2237

    
   
2237

   
2238
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2238
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2239
{
2239
{
2240
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2240
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2241
	if (new) {
2241
	if (new) {
2242
		size_t afdatalen = new->afdatalen;
2242
		size_t afdatalen = new->afdatalen;
2243
		memcpy(new, fr, sizeof(*new));
2243
		memcpy(new, fr, sizeof(*new));
2244
		iax_frame_wrap(new, &fr->af);
2244
		iax_frame_wrap(new, &fr->af);
2245
		new->afdatalen = afdatalen;
2245
		new->afdatalen = afdatalen;
2246
		new->data = NULL;
2246
		new->data = NULL;
2247
		new->datalen = 0;
2247
		new->datalen = 0;
2248
		new->direction = DIRECTION_INGRESS;
2248
		new->direction = DIRECTION_INGRESS;
2249
		new->retrans = -1;
2249
		new->retrans = -1;
2250
	}
2250
	}
2251
	return new;
2251
	return new;
2252
}
2252
}
2253
/* keep these defined in this order.  They are used in find_callno to
2253
/* keep these defined in this order.  They are used in find_callno to
2254
 * determine whether or not a new call number should be allowed. */
2254
 * determine whether or not a new call number should be allowed. */
2255
enum {
2255
enum {
2256
	/* do not allow a new call number, only search ones in use for match */
2256
	/* do not allow a new call number, only search ones in use for match */
2257
	NEW_PREVENT = 0,
2257
	NEW_PREVENT = 0,
2258
	/* search for match first, then allow a new one to be allocated */
2258
	/* search for match first, then allow a new one to be allocated */
2259
	NEW_ALLOW = 1,
2259
	NEW_ALLOW = 1,
2260
	/* do not search for match, force a new call number */
2260
	/* do not search for match, force a new call number */
2261
	NEW_FORCE = 2,
2261
	NEW_FORCE = 2,
2262
	/* do not search for match, force a new call number.  Signifies call number
2262
	/* do not search for match, force a new call number.  Signifies call number
2263
	 * has been calltoken validated */
2263
	 * has been calltoken validated */
2264
	NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2264
	NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2265
};
2265
};
2266

    
   
2266

   
2267
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2267
static int match(struct ast_sockaddr *addr, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2268
{
2268
{
2269
	if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2269
	if (!ast_sockaddr_cmp(&cur->addr, addr)) {
2270
		/* This is the main host */
2270
		/* This is the main host */
2271
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2271
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2272
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
2272
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
2273
			/* That's us.  Be sure we keep track of the peer call number */
2273
			/* That's us.  Be sure we keep track of the peer call number */
2274
			return 1;
2274
			return 1;
2275
		}
2275
		}
2276
	}
2276
	}
2277
	if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2277
	if (!ast_sockaddr_cmp(&cur->transfer, addr) && cur->transferring) {
2278
		/* We're transferring */
2278
		/* We're transferring */
2279
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2279
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2280
			return 1;
2280
			return 1;
2281
	}
2281
	}
2282
	return 0;
2282
	return 0;
2283
}
2283
}
2284

    
   
2284

   
2285
static int make_trunk(unsigned short callno, int locked)
2285
static int make_trunk(unsigned short callno, int locked)
2286
{
2286
{
2287
	int x;
2287
	int x;
2288
	int res= 0;
2288
	int res= 0;
2289
	callno_entry entry;
2289
	callno_entry entry;
2290
	if (iaxs[callno]->oseqno) {
2290
	if (iaxs[callno]->oseqno) {
2291
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2291
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2292
		return -1;
2292
		return -1;
2293
	}
2293
	}
2294
	if (callno >= TRUNK_CALL_START) {
2294
	if (callno >= TRUNK_CALL_START) {
2295
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2295
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2296
		return -1;
2296
		return -1;
2297
	}
2297
	}
2298

    
   
2298

   
2299
	if (get_unused_callno(
2299
	if (get_unused_callno(
2300
			CALLNO_TYPE_TRUNK,
2300
			CALLNO_TYPE_TRUNK,
2301
			CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2301
			CALLNO_ENTRY_IS_VALIDATED(iaxs[callno]->callno_entry),
2302
			&entry)) {
2302
			&entry)) {
2303
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2303
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2304
		return -1;
2304
		return -1;
2305
	}
2305
	}
2306

    
   
2306

   
2307
	x = CALLNO_ENTRY_GET_CALLNO(entry);
2307
	x = CALLNO_ENTRY_GET_CALLNO(entry);
2308
	ast_mutex_lock(&iaxsl[x]);
2308
	ast_mutex_lock(&iaxsl[x]);
2309

    
   
2309

   
2310
	/*!
2310
	/*!
2311
	 * \note We delete these before switching the slot, because if
2311
	 * \note We delete these before switching the slot, because if
2312
	 * they fire in the meantime, they will generate a warning.
2312
	 * they fire in the meantime, they will generate a warning.
2313
	 */
2313
	 */
2314
	AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2314
	AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2315
	AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2315
	AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2316
	iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2316
	iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2317
	iaxs[x] = iaxs[callno];
2317
	iaxs[x] = iaxs[callno];
2318
	iaxs[x]->callno = x;
2318
	iaxs[x]->callno = x;
2319

    
   
2319

   
2320
	/* since we copied over the pvt from a different callno, make sure the old entry is replaced
2320
	/* since we copied over the pvt from a different callno, make sure the old entry is replaced
2321
	 * before assigning the new one */
2321
	 * before assigning the new one */
2322
	if (iaxs[x]->callno_entry) {
2322
	if (iaxs[x]->callno_entry) {
2323
		iax2_sched_add(
2323
		iax2_sched_add(
2324
			sched,
2324
			sched,
2325
			MIN_REUSE_TIME * 1000,
2325
			MIN_REUSE_TIME * 1000,
2326
			replace_callno,
2326
			replace_callno,
2327
			CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2327
			CALLNO_ENTRY_TO_PTR(iaxs[x]->callno_entry));
2328

    
   
2328

   
2329
	}
2329
	}
2330
	iaxs[x]->callno_entry = entry;
2330
	iaxs[x]->callno_entry = entry;
2331

    
   
2331

   
2332
	iaxs[callno] = NULL;
2332
	iaxs[callno] = NULL;
2333
	/* Update the two timers that should have been started */
2333
	/* Update the two timers that should have been started */
2334
	iaxs[x]->pingid = iax2_sched_add(sched,
2334
	iaxs[x]->pingid = iax2_sched_add(sched,
2335
		ping_time * 1000, send_ping, (void *)(long)x);
2335
		ping_time * 1000, send_ping, (void *)(long)x);
2336
	iaxs[x]->lagid = iax2_sched_add(sched,
2336
	iaxs[x]->lagid = iax2_sched_add(sched,
2337
		lagrq_time * 1000, send_lagrq, (void *)(long)x);
2337
		lagrq_time * 1000, send_lagrq, (void *)(long)x);
2338

    
   
2338

   
2339
	if (locked)
2339
	if (locked)
2340
		ast_mutex_unlock(&iaxsl[callno]);
2340
		ast_mutex_unlock(&iaxsl[callno]);
2341
	res = x;
2341
	res = x;
2342
	if (!locked)
2342
	if (!locked)
2343
		ast_mutex_unlock(&iaxsl[x]);
2343
		ast_mutex_unlock(&iaxsl[x]);
2344

    
   
2344

   
2345
	/* We moved this call from a non-trunked to a trunked call */
2345
	/* We moved this call from a non-trunked to a trunked call */
2346
	ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2346
	ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
2347

    
   
2347

   
2348
	return res;
2348
	return res;
2349
}
2349
}
2350

    
   
2350

   
2351
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2351
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2352
{
2352
{
2353
	if (!pvt->transfercallno) {
2353
	if (!pvt->transfercallno) {
2354
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2354
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2355
		return;
2355
		return;
2356
	}
2356
	}
2357

    
   
2357

   
2358
	ao2_link(iax_transfercallno_pvts, pvt);
2358
	ao2_link(iax_transfercallno_pvts, pvt);
2359
}
2359
}
2360

    
   
2360

   
2361
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2361
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2362
{
2362
{
2363
	if (!pvt->transfercallno) {
2363
	if (!pvt->transfercallno) {
2364
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2364
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2365
		return;
2365
		return;
2366
	}
2366
	}
2367

    
   
2367

   
2368
	ao2_unlink(iax_transfercallno_pvts, pvt);
2368
	ao2_unlink(iax_transfercallno_pvts, pvt);
2369
}
2369
}
2370
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2370
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2371
{
2371
{
2372
	if (!pvt->peercallno) {
2372
	if (!pvt->peercallno) {
2373
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2373
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2374
		return;
2374
		return;
2375
	}
2375
	}
2376

    
   
2376

   
2377
	ao2_link(iax_peercallno_pvts, pvt);
2377
	ao2_link(iax_peercallno_pvts, pvt);
2378
}
2378
}
2379

    
   
2379

   
2380
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2380
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2381
{
2381
{
2382
	if (!pvt->peercallno) {
2382
	if (!pvt->peercallno) {
2383
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2383
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2384
		return;
2384
		return;
2385
	}
2385
	}
2386

    
   
2386

   
2387
	ao2_unlink(iax_peercallno_pvts, pvt);
2387
	ao2_unlink(iax_peercallno_pvts, pvt);
2388
}
2388
}
2389

    
   
2389

   
2390
static int addr_range_delme_cb(void *obj, void *arg, int flags)
2390
static int addr_range_delme_cb(void *obj, void *arg, int flags)
2391
{
2391
{
2392
	struct addr_range *lim = obj;
2392
	struct addr_range *lim = obj;
2393
	lim->delme = 1;
2393
	lim->delme = 1;
2394
	return 0;
2394
	return 0;
2395
}
2395
}
2396

    
   
2396

   
2397
static int addr_range_hash_cb(const void *obj, const int flags)
2397
static int addr_range_hash_cb(const void *obj, const int flags)
2398
{
2398
{
2399
	const struct addr_range *lim = obj;
2399
	const struct addr_range *lim = obj;
2400
	return abs(ast_sockaddr_hash(&lim->ha.addr));
2400
	return abs(ast_sockaddr_hash(&lim->ha.addr));
2401
}
2401
}
2402

    
   
2402

   
2403
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2403
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2404
{
2404
{
2405
	struct addr_range *lim1 = obj, *lim2 = arg;
2405
	struct addr_range *lim1 = obj, *lim2 = arg;
2406
	return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2406
	return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2407
			!(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2407
			!(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2408
			CMP_MATCH | CMP_STOP : 0;
2408
			CMP_MATCH | CMP_STOP : 0;
2409
}
2409
}
2410

    
   
2410

   
2411
static int peercnt_hash_cb(const void *obj, const int flags)
2411
static int peercnt_hash_cb(const void *obj, const int flags)
2412
{
2412
{
2413
	const struct peercnt *peercnt = obj;
2413
	const struct peercnt *peercnt = obj;
2414

    
   
2414

   
2415
	if (ast_sockaddr_isnull(&peercnt->addr)) {
2415
	if (ast_sockaddr_isnull(&peercnt->addr)) {
2416
		return 0;
2416
		return 0;
2417
	}
2417
	}
2418
	return ast_sockaddr_hash(&peercnt->addr);
2418
	return ast_sockaddr_hash(&peercnt->addr);
2419
}
2419
}
2420

    
   
2420

   
2421
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2421
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2422
{
2422
{
2423
	struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2423
	struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2424
	return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2424
	return !ast_sockaddr_cmp_addr(&peercnt1->addr, &peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2425
}
2425
}
2426

    
   
2426

   
2427
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2427
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2428
{
2428
{
2429
	struct addr_range *addr_range = obj;
2429
	struct addr_range *addr_range = obj;
2430
	struct ast_sockaddr *addr = arg;
2430
	struct ast_sockaddr *addr = arg;
2431
	struct ast_sockaddr tmp_addr;
2431
	struct ast_sockaddr tmp_addr;
2432

    
   
2432

   
2433
	ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2433
	ast_sockaddr_apply_netmask(addr, &addr_range->ha.netmask, &tmp_addr);
2434

    
   
2434

   
2435
	if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2435
	if (!ast_sockaddr_cmp_addr(&tmp_addr, &addr_range->ha.addr)) {
2436
		return CMP_MATCH | CMP_STOP;
2436
		return CMP_MATCH | CMP_STOP;
2437
	}
2437
	}
2438
	return 0;
2438
	return 0;
2439
}
2439
}
2440

    
   
2440

   
2441
/*!
2441
/*!
2442
 * \internal
2442
 * \internal
2443
 *
2443
 *
2444
 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2444
 * \brief compares addr to calltoken_ignores table to determine if validation is required.
2445
 */
2445
 */
2446
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2446
static int calltoken_required(struct ast_sockaddr *addr, const char *name, int subclass)
2447
{
2447
{
2448
	struct addr_range *addr_range;
2448
	struct addr_range *addr_range;
2449
	struct iax2_peer *peer = NULL;
2449
	struct iax2_peer *peer = NULL;
2450
	struct iax2_user *user = NULL;
2450
	struct iax2_user *user = NULL;
2451
	/* if no username is given, check for guest accounts */
2451
	/* if no username is given, check for guest accounts */
2452
	const char *find = S_OR(name, "guest");
2452
	const char *find = S_OR(name, "guest");
2453
	int res = 1;  /* required by default */
2453
	int res = 1;  /* required by default */
2454
	int optional = 0;
2454
	int optional = 0;
2455
	enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2455
	enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2456
	/* There are only two cases in which calltoken validation is not required.
2456
	/* There are only two cases in which calltoken validation is not required.
2457
	 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2457
	 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2458
	 *         the peer definition has not set the requirecalltoken option.
2458
	 *         the peer definition has not set the requirecalltoken option.
2459
	 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2459
	 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2460
	 */
2460
	 */
2461

    
   
2461

   
2462
	/* ----- Case 1 ----- */
2462
	/* ----- Case 1 ----- */
2463
	if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2463
	if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, addr))) {
2464
		ao2_ref(addr_range, -1);
2464
		ao2_ref(addr_range, -1);
2465
		optional = 1;
2465
		optional = 1;
2466
	}
2466
	}
2467

    
   
2467

   
2468
	/* ----- Case 2 ----- */
2468
	/* ----- Case 2 ----- */
2469
	if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2469
	if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2470
		calltoken_required = user->calltoken_required;
2470
		calltoken_required = user->calltoken_required;
2471
	} else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2471
	} else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, addr))) {
2472
		calltoken_required = user->calltoken_required;
2472
		calltoken_required = user->calltoken_required;
2473
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2473
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2474
		calltoken_required = peer->calltoken_required;
2474
		calltoken_required = peer->calltoken_required;
2475
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2475
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, addr))) {
2476
		calltoken_required = peer->calltoken_required;
2476
		calltoken_required = peer->calltoken_required;
2477
	}
2477
	}
2478

    
   
2478

   
2479
	if (peer) {
2479
	if (peer) {
2480
		peer_unref(peer);
2480
		peer_unref(peer);
2481
	}
2481
	}
2482
	if (user) {
2482
	if (user) {
2483
		user_unref(user);
2483
		user_unref(user);
2484
	}
2484
	}
2485

    
   
2485

   
2486
	ast_debug(1, "Determining if address %s with username %s requires calltoken validation.  Optional = %d  calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2486
	ast_debug(1, "Determining if address %s with username %s requires calltoken validation.  Optional = %d  calltoken_required = %u \n", ast_sockaddr_stringify_addr(addr), name, optional, calltoken_required);
2487
	if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2487
	if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2488
		(optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2488
		(optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2489
		res = 0;
2489
		res = 0;
2490
	}
2490
	}
2491

    
   
2491

   
2492
	return res;
2492
	return res;
2493
}
2493
}
2494

    
   
2494

   
2495
/*!
2495
/*!
2496
 * \internal
2496
 * \internal
2497
 *
2497
 *
2498
 * \brief set peercnt callno limit.
2498
 * \brief set peercnt callno limit.
2499
 *
2499
 *
2500
 * \details
2500
 * \details
2501
 * First looks in custom definitions. If not found, global limit
2501
 * First looks in custom definitions. If not found, global limit
2502
 * is used.  Entries marked as reg already have
2502
 * is used.  Entries marked as reg already have
2503
 * a custom limit set by a registration and are not modified.
2503
 * a custom limit set by a registration and are not modified.
2504
 */
2504
 */
2505
static void set_peercnt_limit(struct peercnt *peercnt)
2505
static void set_peercnt_limit(struct peercnt *peercnt)
2506
{
2506
{
2507
	uint16_t limit = global_maxcallno;
2507
	uint16_t limit = global_maxcallno;
2508
	struct addr_range *addr_range;
2508
	struct addr_range *addr_range;
2509
	struct ast_sockaddr addr;
2509
	struct ast_sockaddr addr;
2510

    
   
2510

   
2511
	ast_sockaddr_copy(&addr, &peercnt->addr);
2511
	ast_sockaddr_copy(&addr, &peercnt->addr);
2512

    
   
2512

   
2513
	if (peercnt->reg && peercnt->limit) {
2513
	if (peercnt->reg && peercnt->limit) {
2514
		return; /* this peercnt has a custom limit set by a registration */
2514
		return; /* this peercnt has a custom limit set by a registration */
2515
	}
2515
	}
2516

    
   
2516

   
2517
	if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2517
	if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &addr))) {
2518
		limit = addr_range->limit;
2518
		limit = addr_range->limit;
2519
		ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2519
		ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_sockaddr_stringify(&addr));
2520
		ao2_ref(addr_range, -1);
2520
		ao2_ref(addr_range, -1);
2521
	}
2521
	}
2522

    
   
2522

   
2523
	peercnt->limit = limit;
2523
	peercnt->limit = limit;
2524
}
2524
}
2525

    
   
2525

   
2526
/*!
2526
/*!
2527
 * \internal
2527
 * \internal
2528
 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2528
 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2529
 */
2529
 */
2530
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2530
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2531
{
2531
{
2532
	struct peercnt *peercnt = obj;
2532
	struct peercnt *peercnt = obj;
2533

    
   
2533

   
2534
	set_peercnt_limit(peercnt);
2534
	set_peercnt_limit(peercnt);
2535
	ast_debug(1, "Reset limits for peercnts table\n");
2535
	ast_debug(1, "Reset limits for peercnts table\n");
2536

    
   
2536

   
2537
	return 0;
2537
	return 0;
2538
}
2538
}
2539

    
   
2539

   
2540
/*!
2540
/*!
2541
 * \internal
2541
 * \internal
2542
 * \brief returns match if delme is set.
2542
 * \brief returns match if delme is set.
2543
 */
2543
 */
2544
static int prune_addr_range_cb(void *obj, void *arg, int flags)
2544
static int prune_addr_range_cb(void *obj, void *arg, int flags)
2545
{
2545
{
2546
	struct addr_range *addr_range = obj;
2546
	struct addr_range *addr_range = obj;
2547

    
   
2547

   
2548
	return addr_range->delme ? CMP_MATCH : 0;
2548
	return addr_range->delme ? CMP_MATCH : 0;
2549
}
2549
}
2550

    
   
2550

   
2551
/*!
2551
/*!
2552
 * \internal
2552
 * \internal
2553
 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2553
 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2554
 */
2554
 */
2555
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2555
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2556
{
2556
{
2557
	/* this function turns off and on custom callno limits set by peer registration */
2557
	/* this function turns off and on custom callno limits set by peer registration */
2558
	struct peercnt *peercnt;
2558
	struct peercnt *peercnt;
2559
	struct peercnt tmp;
2559
	struct peercnt tmp;
2560

    
   
2560

   
2561
	ast_sockaddr_copy(&tmp.addr, sockaddr);
2561
	ast_sockaddr_copy(&tmp.addr, sockaddr);
2562

    
   
2562

   
2563
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2563
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2564
		peercnt->reg = reg;
2564
		peercnt->reg = reg;
2565
		if (limit) {
2565
		if (limit) {
2566
			peercnt->limit = limit;
2566
			peercnt->limit = limit;
2567
		} else {
2567
		} else {
2568
			set_peercnt_limit(peercnt);
2568
			set_peercnt_limit(peercnt);
2569
		}
2569
		}
2570
		ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2570
		ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_sockaddr_stringify_addr(sockaddr), peercnt->limit, peercnt->reg);
2571
		ao2_ref(peercnt, -1); /* decrement ref from find */
2571
		ao2_ref(peercnt, -1); /* decrement ref from find */
2572
	}
2572
	}
2573
}
2573
}
2574

    
   
2574

   
2575
/*!
2575
/*!
2576
 * \internal
2576
 * \internal
2577
 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2577
 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2578
 *
2578
 *
2579
 * \details First searches for the address in the peercnts table.  If found
2579
 * \details First searches for the address in the peercnts table.  If found
2580
 * the current count is incremented.  If not found a new peercnt is allocated
2580
 * the current count is incremented.  If not found a new peercnt is allocated
2581
 * and linked into the peercnts table with a call number count of 1.
2581
 * and linked into the peercnts table with a call number count of 1.
2582
 */
2582
 */
2583
static int peercnt_add(struct ast_sockaddr *addr)
2583
static int peercnt_add(struct ast_sockaddr *addr)
2584
{
2584
{
2585
	struct peercnt *peercnt;
2585
	struct peercnt *peercnt;
2586
	int res = 0;
2586
	int res = 0;
2587
	struct peercnt tmp;
2587
	struct peercnt tmp;
2588

    
   
2588

   
2589
	ast_sockaddr_copy(&tmp.addr, addr);
2589
	ast_sockaddr_copy(&tmp.addr, addr);
2590

    
   
2590

   
2591
	/* Reasoning for peercnts container lock:  Two identical ip addresses
2591
	/* Reasoning for peercnts container lock:  Two identical ip addresses
2592
	 * could be added by different threads at the "same time". Without the container
2592
	 * could be added by different threads at the "same time". Without the container
2593
	 * lock, both threads could alloc space for the same object and attempt
2593
	 * lock, both threads could alloc space for the same object and attempt
2594
	 * to link to table.  With the lock, one would create the object and link
2594
	 * to link to table.  With the lock, one would create the object and link
2595
	 * to table while the other would find the already created peercnt object
2595
	 * to table while the other would find the already created peercnt object
2596
	 * rather than creating a new one. */
2596
	 * rather than creating a new one. */
2597
	ao2_lock(peercnts);
2597
	ao2_lock(peercnts);
2598
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2598
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2599
		ao2_lock(peercnt);
2599
		ao2_lock(peercnt);
2600
	} else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2600
	} else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2601
		ao2_lock(peercnt);
2601
		ao2_lock(peercnt);
2602
		/* create and set defaults */
2602
		/* create and set defaults */
2603
		ast_sockaddr_copy(&peercnt->addr, addr);
2603
		ast_sockaddr_copy(&peercnt->addr, addr);
2604
		set_peercnt_limit(peercnt);
2604
		set_peercnt_limit(peercnt);
2605
		/* guarantees it does not go away after unlocking table
2605
		/* guarantees it does not go away after unlocking table
2606
		 * ao2_find automatically adds this */
2606
		 * ao2_find automatically adds this */
2607
		ao2_link(peercnts, peercnt);
2607
		ao2_link(peercnts, peercnt);
2608
	} else {
2608
	} else {
2609
		ao2_unlock(peercnts);
2609
		ao2_unlock(peercnts);
2610
		return -1;
2610
		return -1;
2611
	}
2611
	}
2612

    
   
2612

   
2613
	/* check to see if the address has hit its callno limit.  If not increment cur. */
2613
	/* check to see if the address has hit its callno limit.  If not increment cur. */
2614
	if (peercnt->limit > peercnt->cur) {
2614
	if (peercnt->limit > peercnt->cur) {
2615
		peercnt->cur++;
2615
		peercnt->cur++;
2616
		ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2616
		ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(addr));
2617
	} else { /* max num call numbers for this peer has been reached! */
2617
	} else { /* max num call numbers for this peer has been reached! */
2618
		ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2618
		ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_sockaddr_stringify_addr(addr));
2619
		res = -1;
2619
		res = -1;
2620
	}
2620
	}
2621

    
   
2621

   
2622
	/* clean up locks and ref count */
2622
	/* clean up locks and ref count */
2623
	ao2_unlock(peercnt);
2623
	ao2_unlock(peercnt);
2624
	ao2_unlock(peercnts);
2624
	ao2_unlock(peercnts);
2625
	ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2625
	ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2626

    
   
2626

   
2627
	return res;
2627
	return res;
2628
}
2628
}
2629

    
   
2629

   
2630
/*!
2630
/*!
2631
 * \internal
2631
 * \internal
2632
 * \brief decrements a peercnts table entry
2632
 * \brief decrements a peercnts table entry
2633
 */
2633
 */
2634
static void peercnt_remove(struct peercnt *peercnt)
2634
static void peercnt_remove(struct peercnt *peercnt)
2635
{
2635
{
2636
	struct ast_sockaddr addr;
2636
	struct ast_sockaddr addr;
2637

    
   
2637

   
2638
	ast_sockaddr_copy(&addr, &peercnt->addr);
2638
	ast_sockaddr_copy(&addr, &peercnt->addr);
2639

    
   
2639

   
2640
	/*
2640
	/*
2641
	 * Container locked here since peercnt may be unlinked from
2641
	 * Container locked here since peercnt may be unlinked from
2642
	 * list.  If left unlocked, peercnt_add could try and grab this
2642
	 * list.  If left unlocked, peercnt_add could try and grab this
2643
	 * entry from the table and modify it at the "same time" this
2643
	 * entry from the table and modify it at the "same time" this
2644
	 * thread attemps to unlink it.
2644
	 * thread attemps to unlink it.
2645
	 */
2645
	 */
2646
	ao2_lock(peercnts);
2646
	ao2_lock(peercnts);
2647
	peercnt->cur--;
2647
	peercnt->cur--;
2648
	ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2648
	ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_sockaddr_stringify_addr(&addr));
2649
	/* if this was the last connection from the peer remove it from table */
2649
	/* if this was the last connection from the peer remove it from table */
2650
	if (peercnt->cur == 0) {
2650
	if (peercnt->cur == 0) {
2651
		ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2651
		ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2652
	}
2652
	}
2653
	ao2_unlock(peercnts);
2653
	ao2_unlock(peercnts);
2654
}
2654
}
2655

    
   
2655

   
2656
/*!
2656
/*!
2657
 * \internal
2657
 * \internal
2658
 * \brief called by scheduler to decrement object
2658
 * \brief called by scheduler to decrement object
2659
 */
2659
 */
2660
static int peercnt_remove_cb(const void *obj)
2660
static int peercnt_remove_cb(const void *obj)
2661
{
2661
{
2662
	struct peercnt *peercnt = (struct peercnt *) obj;
2662
	struct peercnt *peercnt = (struct peercnt *) obj;
2663

    
   
2663

   
2664
	peercnt_remove(peercnt);
2664
	peercnt_remove(peercnt);
2665
	ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2665
	ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2666

    
   
2666

   
2667
	return 0;
2667
	return 0;
2668
}
2668
}
2669

    
   
2669

   
2670
/*!
2670
/*!
2671
 * \internal
2671
 * \internal
2672
 * \brief decrements peercnts connection count, finds by addr
2672
 * \brief decrements peercnts connection count, finds by addr
2673
 */
2673
 */
2674
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2674
static int peercnt_remove_by_addr(struct ast_sockaddr *addr)
2675
{
2675
{
2676
	struct peercnt *peercnt;
2676
	struct peercnt *peercnt;
2677
	struct peercnt tmp;
2677
	struct peercnt tmp;
2678

    
   
2678

   
2679
	ast_sockaddr_copy(&tmp.addr, addr);
2679
	ast_sockaddr_copy(&tmp.addr, addr);
2680

    
   
2680

   
2681
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2681
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2682
		peercnt_remove(peercnt);
2682
		peercnt_remove(peercnt);
2683
		ao2_ref(peercnt, -1); /* decrement ref from find */
2683
		ao2_ref(peercnt, -1); /* decrement ref from find */
2684
	}
2684
	}
2685
	return 0;
2685
	return 0;
2686
}
2686
}
2687

    
   
2687

   
2688
/*!
2688
/*!
2689
 * \internal
2689
 * \internal
2690
 * \brief Create callno_limit entry based on configuration
2690
 * \brief Create callno_limit entry based on configuration
2691
 */
2691
 */
2692
static void build_callno_limits(struct ast_variable *v)
2692
static void build_callno_limits(struct ast_variable *v)
2693
{
2693
{
2694
	struct addr_range *addr_range = NULL;
2694
	struct addr_range *addr_range = NULL;
2695
	struct addr_range tmp;
2695
	struct addr_range tmp;
2696
	struct ast_ha *ha;
2696
	struct ast_ha *ha;
2697
	int limit;
2697
	int limit;
2698
	int error;
2698
	int error;
2699
	int found;
2699
	int found;
2700

    
   
2700

   
2701
	for (; v; v = v->next) {
2701
	for (; v; v = v->next) {
2702
		limit = -1;
2702
		limit = -1;
2703
		error = 0;
2703
		error = 0;
2704
		found = 0;
2704
		found = 0;
2705
		ha = ast_append_ha("permit", v->name, NULL, &error);
2705
		ha = ast_append_ha("permit", v->name, NULL, &error);
2706

    
   
2706

   
2707
		/* check for valid config information */
2707
		/* check for valid config information */
2708
		if (error) {
2708
		if (error) {
2709
			ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2709
			ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2710
			continue;
2710
			continue;
2711
		} else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2711
		} else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2712
			ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2712
			ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2713
			ast_free_ha(ha);
2713
			ast_free_ha(ha);
2714
			continue;
2714
			continue;
2715
		}
2715
		}
2716

    
   
2716

   
2717
		ast_copy_ha(ha, &tmp.ha);
2717
		ast_copy_ha(ha, &tmp.ha);
2718
		/* find or create the addr_range */
2718
		/* find or create the addr_range */
2719
		if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2719
		if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2720
			ao2_lock(addr_range);
2720
			ao2_lock(addr_range);
2721
			found = 1;
2721
			found = 1;
2722
		} else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2722
		} else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2723
			ast_free_ha(ha);
2723
			ast_free_ha(ha);
2724
			return; /* out of memory */
2724
			return; /* out of memory */
2725
		}
2725
		}
2726

    
   
2726

   
2727
		/* copy over config data into addr_range object */
2727
		/* copy over config data into addr_range object */
2728
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2728
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2729
		ast_free_ha(ha); /* cleanup the tmp ha */
2729
		ast_free_ha(ha); /* cleanup the tmp ha */
2730
		addr_range->limit = limit;
2730
		addr_range->limit = limit;
2731
		addr_range->delme = 0;
2731
		addr_range->delme = 0;
2732

    
   
2732

   
2733
		/* cleanup */
2733
		/* cleanup */
2734
		if (found) {
2734
		if (found) {
2735
			ao2_unlock(addr_range);
2735
			ao2_unlock(addr_range);
2736
		} else {
2736
		} else {
2737
			ao2_link(callno_limits, addr_range);
2737
			ao2_link(callno_limits, addr_range);
2738
		}
2738
		}
2739
		ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2739
		ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2740
	}
2740
	}
2741
}
2741
}
2742

    
   
2742

   
2743
/*!
2743
/*!
2744
 * \internal
2744
 * \internal
2745
 * \brief Create calltoken_ignores entry based on configuration
2745
 * \brief Create calltoken_ignores entry based on configuration
2746
 */
2746
 */
2747
static int add_calltoken_ignore(const char *addr)
2747
static int add_calltoken_ignore(const char *addr)
2748
{
2748
{
2749
	struct addr_range tmp;
2749
	struct addr_range tmp;
2750
	struct addr_range *addr_range = NULL;
2750
	struct addr_range *addr_range = NULL;
2751
	struct ast_ha *ha = NULL;
2751
	struct ast_ha *ha = NULL;
2752
	int error = 0;
2752
	int error = 0;
2753

    
   
2753

   
2754
	if (ast_strlen_zero(addr)) {
2754
	if (ast_strlen_zero(addr)) {
2755
		ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2755
		ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2756
		return -1;
2756
		return -1;
2757
	}
2757
	}
2758

    
   
2758

   
2759
	ha = ast_append_ha("permit", addr, NULL, &error);
2759
	ha = ast_append_ha("permit", addr, NULL, &error);
2760

    
   
2760

   
2761
	/* check for valid config information */
2761
	/* check for valid config information */
2762
	if (error) {
2762
	if (error) {
2763
		ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2763
		ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2764
		return -1;
2764
		return -1;
2765
	}
2765
	}
2766

    
   
2766

   
2767
	ast_copy_ha(ha, &tmp.ha);
2767
	ast_copy_ha(ha, &tmp.ha);
2768
	/* find or create the addr_range */
2768
	/* find or create the addr_range */
2769
	if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2769
	if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2770
		ao2_lock(addr_range);
2770
		ao2_lock(addr_range);
2771
		addr_range->delme = 0;
2771
		addr_range->delme = 0;
2772
		ao2_unlock(addr_range);
2772
		ao2_unlock(addr_range);
2773
	} else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2773
	} else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2774
		/* copy over config data into addr_range object */
2774
		/* copy over config data into addr_range object */
2775
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2775
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2776
		ao2_link(calltoken_ignores, addr_range);
2776
		ao2_link(calltoken_ignores, addr_range);
2777
	} else {
2777
	} else {
2778
		ast_free_ha(ha);
2778
		ast_free_ha(ha);
2779
		return -1;
2779
		return -1;
2780
	}
2780
	}
2781

    
   
2781

   
2782
	ast_free_ha(ha);
2782
	ast_free_ha(ha);
2783
	ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2783
	ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2784

    
   
2784

   
2785
	return 0;
2785
	return 0;
2786
}
2786
}
2787

    
   
2787

   
2788
static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2788
static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2789
{
2789
{
2790
	struct ao2_iterator i;
2790
	struct ao2_iterator i;
2791
	struct peercnt *peercnt;
2791
	struct peercnt *peercnt;
2792
	struct ast_sockaddr addr;
2792
	struct ast_sockaddr addr;
2793
	int found = 0;
2793
	int found = 0;
2794

    
   
2794

   
2795
	switch (cmd) {
2795
	switch (cmd) {
2796
	case CLI_INIT:
2796
	case CLI_INIT:
2797
		e->command = "iax2 show callnumber usage";
2797
		e->command = "iax2 show callnumber usage";
2798
		e->usage =
2798
		e->usage =
2799
			"Usage: iax2 show callnumber usage [IP address]\n"
2799
			"Usage: iax2 show callnumber usage [IP address]\n"
2800
			"       Shows current IP addresses which are consuming iax2 call numbers\n";
2800
			"       Shows current IP addresses which are consuming iax2 call numbers\n";
2801
		return NULL;
2801
		return NULL;
2802
	case CLI_GENERATE:
2802
	case CLI_GENERATE:
2803
		return NULL;
2803
		return NULL;
2804
	case CLI_HANDLER:
2804
	case CLI_HANDLER:
2805
		if (a->argc < 4 || a->argc > 5)
2805
		if (a->argc < 4 || a->argc > 5)
2806
			return CLI_SHOWUSAGE;
2806
			return CLI_SHOWUSAGE;
2807

    
   
2807

   
2808
		if (a->argc == 4) {
2808
		if (a->argc == 4) {
2809
			ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2809
			ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2810
		}
2810
		}
2811

    
   
2811

   
2812
		i = ao2_iterator_init(peercnts, 0);
2812
		i = ao2_iterator_init(peercnts, 0);
2813
		while ((peercnt = ao2_iterator_next(&i))) {
2813
		while ((peercnt = ao2_iterator_next(&i))) {
2814
			ast_sockaddr_copy(&addr, &peercnt->addr);
2814
			ast_sockaddr_copy(&addr, &peercnt->addr);
2815

    
   
2815

   
2816
			if (a->argc == 5) {
2816
			if (a->argc == 5) {
2817
				if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2817
				if (!strcasecmp(a->argv[4], ast_sockaddr_stringify(&addr))) {
2818
					ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2818
					ast_cli(a->fd, "%-45s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2819
					ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2819
					ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2820
					ao2_ref(peercnt, -1);
2820
					ao2_ref(peercnt, -1);
2821
					found = 1;
2821
					found = 1;
2822
					break;
2822
					break;
2823
				}
2823
				}
2824
			} else {
2824
			} else {
2825
				ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2825
				ast_cli(a->fd, "%-45s %-12d %-12d\n", ast_sockaddr_stringify(&addr), peercnt->cur, peercnt->limit);
2826
			}
2826
			}
2827
			ao2_ref(peercnt, -1);
2827
			ao2_ref(peercnt, -1);
2828
		}
2828
		}
2829
		ao2_iterator_destroy(&i);
2829
		ao2_iterator_destroy(&i);
2830

    
   
2830

   
2831
		if (a->argc == 4) {
2831
		if (a->argc == 4) {
2832
			size_t pool_avail = callno_pool.available;
2832
			size_t pool_avail = callno_pool.available;
2833
			size_t trunk_pool_avail = callno_pool_trunk.available;
2833
			size_t trunk_pool_avail = callno_pool_trunk.available;
2834

    
   
2834

   
2835
			ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2835
			ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2836
			                 "Non-CallToken Validated Callno Used:   %d\n",
2836
			                 "Non-CallToken Validated Callno Used:   %d\n",
2837
				global_maxcallno_nonval,
2837
				global_maxcallno_nonval,
2838
				total_nonval_callno_used);
2838
				total_nonval_callno_used);
2839

    
   
2839

   
2840
			ast_cli(a->fd,   "Total Available Callno:                %zu\n"
2840
			ast_cli(a->fd,   "Total Available Callno:                %zu\n"
2841
			                 "Regular Callno Available:              %zu\n"
2841
			                 "Regular Callno Available:              %zu\n"
2842
			                 "Trunk Callno Available:                %zu\n",
2842
			                 "Trunk Callno Available:                %zu\n",
2843
				pool_avail + trunk_pool_avail,
2843
				pool_avail + trunk_pool_avail,
2844
				pool_avail,
2844
				pool_avail,
2845
				trunk_pool_avail);
2845
				trunk_pool_avail);
2846
		} else if (a->argc == 5 && !found) {
2846
		} else if (a->argc == 5 && !found) {
2847
			ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2847
			ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2848
		}
2848
		}
2849

    
   
2849

   
2850

    
   
2850

   
2851
		return CLI_SUCCESS;
2851
		return CLI_SUCCESS;
2852
	default:
2852
	default:
2853
		return NULL;
2853
		return NULL;
2854
	}
2854
	}
2855
}
2855
}
2856

    
   
2856

   
2857
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2857
static int get_unused_callno(enum callno_type type, int validated, callno_entry *entry)
2858
{
2858
{
2859
	struct call_number_pool *pool = NULL;
2859
	struct call_number_pool *pool = NULL;
2860
	callno_entry swap;
2860
	callno_entry swap;
2861
	size_t choice;
2861
	size_t choice;
2862

    
   
2862

   
2863
	switch (type) {
2863
	switch (type) {
2864
	case CALLNO_TYPE_NORMAL:
2864
	case CALLNO_TYPE_NORMAL:
2865
		pool = &callno_pool;
2865
		pool = &callno_pool;
2866
		break;
2866
		break;
2867
	case CALLNO_TYPE_TRUNK:
2867
	case CALLNO_TYPE_TRUNK:
2868
		pool = &callno_pool_trunk;
2868
		pool = &callno_pool_trunk;
2869
		break;
2869
		break;
2870
	default:
2870
	default:
2871
		ast_assert(0);
2871
		ast_assert(0);
2872
		break;
2872
		break;
2873
	}
2873
	}
2874

    
   
2874

   
2875
	/* If we fail, make sure this has a defined value */
2875
	/* If we fail, make sure this has a defined value */
2876
	*entry = 0;
2876
	*entry = 0;
2877

    
   
2877

   
2878
	/* We lock here primarily to ensure thread safety of the
2878
	/* We lock here primarily to ensure thread safety of the
2879
	 * total_nonval_callno_used check and increment */
2879
	 * total_nonval_callno_used check and increment */
2880
	ast_mutex_lock(&callno_pool_lock);
2880
	ast_mutex_lock(&callno_pool_lock);
2881

    
   
2881

   
2882
	/* Bail out if we don't have any available call numbers */
2882
	/* Bail out if we don't have any available call numbers */
2883
	if (!pool->available) {
2883
	if (!pool->available) {
2884
		ast_log(LOG_WARNING, "Out of call numbers\n");
2884
		ast_log(LOG_WARNING, "Out of call numbers\n");
2885
		ast_mutex_unlock(&callno_pool_lock);
2885
		ast_mutex_unlock(&callno_pool_lock);
2886
		return 1;
2886
		return 1;
2887
	}
2887
	}
2888

    
   
2888

   
2889
	/* Only a certain number of non-validated call numbers should be allocated.
2889
	/* Only a certain number of non-validated call numbers should be allocated.
2890
	 * If there ever is an attack, this separates the calltoken validating users
2890
	 * If there ever is an attack, this separates the calltoken validating users
2891
	 * from the non-calltoken validating users. */
2891
	 * from the non-calltoken validating users. */
2892
	if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2892
	if (!validated && total_nonval_callno_used >= global_maxcallno_nonval) {
2893
		ast_log(LOG_WARNING,
2893
		ast_log(LOG_WARNING,
2894
			"NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2894
			"NON-CallToken callnumber limit is reached. Current: %d Max: %d\n",
2895
			total_nonval_callno_used,
2895
			total_nonval_callno_used,
2896
			global_maxcallno_nonval);
2896
			global_maxcallno_nonval);
2897
		ast_mutex_unlock(&callno_pool_lock);
2897
		ast_mutex_unlock(&callno_pool_lock);
2898
		return 1;
2898
		return 1;
2899
	}
2899
	}
2900

    
   
2900

   
2901
	/* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2901
	/* We use a modified Fisher-Yates-Durstenfeld Shuffle to maintain a list of
2902
	 * available call numbers.  The array of call numbers begins as an ordered
2902
	 * available call numbers.  The array of call numbers begins as an ordered
2903
	 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2903
	 * list from 1 -> n, and we keep a running tally of how many remain unclaimed
2904
	 * - let's call that x.  When a call number is needed we pick a random index
2904
	 * - let's call that x.  When a call number is needed we pick a random index
2905
	 * into the array between 0 and x and use that as our call number.  In a
2905
	 * into the array between 0 and x and use that as our call number.  In a
2906
	 * typical FYD shuffle, we would swap the value that we are extracting with
2906
	 * typical FYD shuffle, we would swap the value that we are extracting with
2907
	 * the number at x, but in our case we swap and don't touch the value at x
2907
	 * the number at x, but in our case we swap and don't touch the value at x
2908
	 * because it is effectively invisible.  We rely on the rest of the IAX2 core
2908
	 * because it is effectively invisible.  We rely on the rest of the IAX2 core
2909
	 * to return the number to us at some point.  Finally, we decrement x by 1
2909
	 * to return the number to us at some point.  Finally, we decrement x by 1
2910
	 * which establishes our new unused range.
2910
	 * which establishes our new unused range.
2911
	 *
2911
	 *
2912
	 * When numbers are returned to the pool, we put them just past x and bump x
2912
	 * When numbers are returned to the pool, we put them just past x and bump x
2913
	 * by 1 so that this number is now available for re-use. */
2913
	 * by 1 so that this number is now available for re-use. */
2914

    
   
2914

   
2915
	choice = ast_random() % pool->available;
2915
	choice = ast_random() % pool->available;
2916

    
   
2916

   
2917
	*entry = pool->numbers[choice];
2917
	*entry = pool->numbers[choice];
2918
	swap = pool->numbers[pool->available - 1];
2918
	swap = pool->numbers[pool->available - 1];
2919

    
   
2919

   
2920
	pool->numbers[choice] = swap;
2920
	pool->numbers[choice] = swap;
2921
	pool->available--;
2921
	pool->available--;
2922

    
   
2922

   
2923
	if (validated) {
2923
	if (validated) {
2924
		CALLNO_ENTRY_SET_VALIDATED(*entry);
2924
		CALLNO_ENTRY_SET_VALIDATED(*entry);
2925
	} else {
2925
	} else {
2926
		total_nonval_callno_used++;
2926
		total_nonval_callno_used++;
2927
	}
2927
	}
2928

    
   
2928

   
2929
	ast_mutex_unlock(&callno_pool_lock);
2929
	ast_mutex_unlock(&callno_pool_lock);
2930

    
   
2930

   
2931
	return 0;
2931
	return 0;
2932
}
2932
}
2933

    
   
2933

   
2934
static int replace_callno(const void *obj)
2934
static int replace_callno(const void *obj)
2935
{
2935
{
2936
	callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2936
	callno_entry entry = PTR_TO_CALLNO_ENTRY(obj);
2937
	struct call_number_pool *pool;
2937
	struct call_number_pool *pool;
2938

    
   
2938

   
2939
	/* We lock here primarily to ensure thread safety of the
2939
	/* We lock here primarily to ensure thread safety of the
2940
	 * total_nonval_callno_used check and decrement */
2940
	 * total_nonval_callno_used check and decrement */
2941
	ast_mutex_lock(&callno_pool_lock);
2941
	ast_mutex_lock(&callno_pool_lock);
2942

    
   
2942

   
2943
	if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2943
	if (!CALLNO_ENTRY_IS_VALIDATED(entry)) {
2944
		if (total_nonval_callno_used) {
2944
		if (total_nonval_callno_used) {
2945
			total_nonval_callno_used--;
2945
			total_nonval_callno_used--;
2946
		} else {
2946
		} else {
2947
			ast_log(LOG_ERROR,
2947
			ast_log(LOG_ERROR,
2948
				"Attempted to decrement total non calltoken validated "
2948
				"Attempted to decrement total non calltoken validated "
2949
				"callnumbers below zero.  Callno is: %d\n",
2949
				"callnumbers below zero.  Callno is: %d\n",
2950
				CALLNO_ENTRY_GET_CALLNO(entry));
2950
				CALLNO_ENTRY_GET_CALLNO(entry));
2951
		}
2951
		}
2952
	}
2952
	}
2953

    
   
2953

   
2954
	if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2954
	if (CALLNO_ENTRY_GET_CALLNO(entry) < TRUNK_CALL_START) {
2955
		pool = &callno_pool;
2955
		pool = &callno_pool;
2956
	} else {
2956
	} else {
2957
		pool = &callno_pool_trunk;
2957
		pool = &callno_pool_trunk;
2958
	}
2958
	}
2959

    
   
2959

   
2960
	ast_assert(pool->capacity > pool->available);
2960
	ast_assert(pool->capacity > pool->available);
2961

    
   
2961

   
2962
	/* This clears the validated flag */
2962
	/* This clears the validated flag */
2963
	entry = CALLNO_ENTRY_GET_CALLNO(entry);
2963
	entry = CALLNO_ENTRY_GET_CALLNO(entry);
2964

    
   
2964

   
2965
	pool->numbers[pool->available] = entry;
2965
	pool->numbers[pool->available] = entry;
2966
	pool->available++;
2966
	pool->available++;
2967

    
   
2967

   
2968
	ast_mutex_unlock(&callno_pool_lock);
2968
	ast_mutex_unlock(&callno_pool_lock);
2969

    
   
2969

   
2970
	return 0;
2970
	return 0;
2971
}
2971
}
2972

    
   
2972

   
2973
static int create_callno_pools(void)
2973
static int create_callno_pools(void)
2974
{
2974
{
2975
	uint16_t i;
2975
	uint16_t i;
2976

    
   
2976

   
2977
	callno_pool.available = callno_pool_trunk.available = 0;
2977
	callno_pool.available = callno_pool_trunk.available = 0;
2978

    
   
2978

   
2979
	/* We start at 2.  0 and 1 are reserved. */
2979
	/* We start at 2.  0 and 1 are reserved. */
2980
	for (i = 2; i < TRUNK_CALL_START; i++) {
2980
	for (i = 2; i < TRUNK_CALL_START; i++) {
2981
		callno_pool.numbers[callno_pool.available] = i;
2981
		callno_pool.numbers[callno_pool.available] = i;
2982
		callno_pool.available++;
2982
		callno_pool.available++;
2983
	}
2983
	}
2984

    
   
2984

   
2985
	for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2985
	for (i = TRUNK_CALL_START; i < IAX_MAX_CALLS; i++) {
2986
		callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2986
		callno_pool_trunk.numbers[callno_pool_trunk.available] = i;
2987
		callno_pool_trunk.available++;
2987
		callno_pool_trunk.available++;
2988
	}
2988
	}
2989

    
   
2989

   
2990
	callno_pool.capacity = callno_pool.available;
2990
	callno_pool.capacity = callno_pool.available;
2991
	callno_pool_trunk.capacity = callno_pool_trunk.available;
2991
	callno_pool_trunk.capacity = callno_pool_trunk.available;
2992

    
   
2992

   
2993
	ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2993
	ast_assert(callno_pool.capacity && callno_pool_trunk.capacity);
2994

    
   
2994

   
2995
	return 0;
2995
	return 0;
2996
}
2996
}
2997

    
   
2997

   
2998
/*!
2998
/*!
2999
 * \internal
2999
 * \internal
3000
 * \brief Schedules delayed removal of iax2_pvt call number data
3000
 * \brief Schedules delayed removal of iax2_pvt call number data
3001
 *
3001
 *
3002
 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3002
 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
3003
 * available again, and the address from the previous connection must be decremented
3003
 * available again, and the address from the previous connection must be decremented
3004
 * from the peercnts table.  This function schedules these operations to take place.
3004
 * from the peercnts table.  This function schedules these operations to take place.
3005
 */
3005
 */
3006
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3006
static void sched_delay_remove(struct ast_sockaddr *addr, callno_entry entry)
3007
{
3007
{
3008
	int i;
3008
	int i;
3009
	struct peercnt *peercnt;
3009
	struct peercnt *peercnt;
3010
	struct peercnt tmp;
3010
	struct peercnt tmp;
3011

    
   
3011

   
3012
	ast_sockaddr_copy(&tmp.addr, addr);
3012
	ast_sockaddr_copy(&tmp.addr, addr);
3013

    
   
3013

   
3014
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3014
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
3015
		/* refcount is incremented with ao2_find.  keep that ref for the scheduler */
3015
		/* refcount is incremented with ao2_find.  keep that ref for the scheduler */
3016
		ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3016
		ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_sockaddr_stringify_addr(addr), MIN_REUSE_TIME);
3017
		i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3017
		i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
3018
		if (i == -1) {
3018
		if (i == -1) {
3019
			ao2_ref(peercnt, -1);
3019
			ao2_ref(peercnt, -1);
3020
		}
3020
		}
3021
	}
3021
	}
3022

    
   
3022

   
3023
	iax2_sched_add(
3023
	iax2_sched_add(
3024
		sched,
3024
		sched,
3025
		MIN_REUSE_TIME * 1000,
3025
		MIN_REUSE_TIME * 1000,
3026
		replace_callno,
3026
		replace_callno,
3027
		CALLNO_ENTRY_TO_PTR(entry));
3027
		CALLNO_ENTRY_TO_PTR(entry));
3028
}
3028
}
3029

    
   
3029

   
3030
/*!
3030
/*!
3031
 * \internal
3031
 * \internal
3032
 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3032
 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog.
3033
 *
3033
 *
3034
 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3034
 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
3035
 * a new callno.
3035
 * a new callno.
3036
 */
3036
 */
3037
static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3037
static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
3038
{
3038
{
3039
	if (frametype != AST_FRAME_IAX) {
3039
	if (frametype != AST_FRAME_IAX) {
3040
		return 0;
3040
		return 0;
3041
	}
3041
	}
3042
	switch (subclass) {
3042
	switch (subclass) {
3043
	case IAX_COMMAND_NEW:
3043
	case IAX_COMMAND_NEW:
3044
	case IAX_COMMAND_REGREQ:
3044
	case IAX_COMMAND_REGREQ:
3045
	case IAX_COMMAND_FWDOWNL:
3045
	case IAX_COMMAND_FWDOWNL:
3046
	case IAX_COMMAND_REGREL:
3046
	case IAX_COMMAND_REGREL:
3047
		return 1;
3047
		return 1;
3048
	case IAX_COMMAND_POKE:
3048
	case IAX_COMMAND_POKE:
3049
		if (!inbound) {
3049
		if (!inbound) {
3050
			return 1;
3050
			return 1;
3051
		}
3051
		}
3052
		break;
3052
		break;
3053
	}
3053
	}
3054
	return 0;
3054
	return 0;
3055
}
3055
}
3056

    
   
3056

   
3057
/*
3057
/*
3058
 * \note Calling this function while holding another pvt lock can cause a deadlock.
3058
 * \note Calling this function while holding another pvt lock can cause a deadlock.
3059
 */
3059
 */
3060
static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3060
static int __find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int return_locked, int check_dcallno)
3061
{
3061
{
3062
	int res = 0;
3062
	int res = 0;
3063
	int x;
3063
	int x;
3064
	/* this call is calltoken validated as long as it is either NEW_FORCE
3064
	/* this call is calltoken validated as long as it is either NEW_FORCE
3065
	 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3065
	 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
3066
	int validated = (new > NEW_ALLOW) ? 1 : 0;
3066
	int validated = (new > NEW_ALLOW) ? 1 : 0;
3067
	char host[80];
3067
	char host[80];
3068

    
   
3068

   
3069
	if (new <= NEW_ALLOW) {
3069
	if (new <= NEW_ALLOW) {
3070
		if (callno) {
3070
		if (callno) {
3071
			struct chan_iax2_pvt *pvt;
3071
			struct chan_iax2_pvt *pvt;
3072
			struct chan_iax2_pvt tmp_pvt = {
3072
			struct chan_iax2_pvt tmp_pvt = {
3073
				.callno = dcallno,
3073
				.callno = dcallno,
3074
				.peercallno = callno,
3074
				.peercallno = callno,
3075
				.transfercallno = callno,
3075
				.transfercallno = callno,
3076
				/* hack!! */
3076
				/* hack!! */
3077
				.frames_received = check_dcallno,
3077
				.frames_received = check_dcallno,
3078
			};
3078
			};
3079

    
   
3079

   
3080
			ast_sockaddr_copy(&tmp_pvt.addr, addr);
3080
			ast_sockaddr_copy(&tmp_pvt.addr, addr);
3081
			/* this works for finding normal call numbers not involving transfering */
3081
			/* this works for finding normal call numbers not involving transfering */
3082
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3082
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3083
				if (return_locked) {
3083
				if (return_locked) {
3084
					ast_mutex_lock(&iaxsl[pvt->callno]);
3084
					ast_mutex_lock(&iaxsl[pvt->callno]);
3085
				}
3085
				}
3086
				res = pvt->callno;
3086
				res = pvt->callno;
3087
				ao2_ref(pvt, -1);
3087
				ao2_ref(pvt, -1);
3088
				pvt = NULL;
3088
				pvt = NULL;
3089
				return res;
3089
				return res;
3090
			}
3090
			}
3091
			/* this searches for transfer call numbers that might not get caught otherwise */
3091
			/* this searches for transfer call numbers that might not get caught otherwise */
3092
			memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3092
			memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
3093
			ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3093
			ast_sockaddr_copy(&tmp_pvt.transfer, addr);
3094
			if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3094
			if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
3095
				if (return_locked) {
3095
				if (return_locked) {
3096
					ast_mutex_lock(&iaxsl[pvt->callno]);
3096
					ast_mutex_lock(&iaxsl[pvt->callno]);
3097
				}
3097
				}
3098
				res = pvt->callno;
3098
				res = pvt->callno;
3099
				ao2_ref(pvt, -1);
3099
				ao2_ref(pvt, -1);
3100
				pvt = NULL;
3100
				pvt = NULL;
3101
				return res;
3101
				return res;
3102
			}
3102
			}
3103
		}
3103
		}
3104
			/* This will occur on the first response to a message that we initiated,
3104
			/* This will occur on the first response to a message that we initiated,
3105
		 * such as a PING. */
3105
		 * such as a PING. */
3106
		if (dcallno) {
3106
		if (dcallno) {
3107
			ast_mutex_lock(&iaxsl[dcallno]);
3107
			ast_mutex_lock(&iaxsl[dcallno]);
3108
		}
3108
		}
3109
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3109
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(addr, callno, dcallno, iaxs[dcallno], check_dcallno)) {
3110
			iaxs[dcallno]->peercallno = callno;
3110
			iaxs[dcallno]->peercallno = callno;
3111
			res = dcallno;
3111
			res = dcallno;
3112
			store_by_peercallno(iaxs[dcallno]);
3112
			store_by_peercallno(iaxs[dcallno]);
3113
			if (!res || !return_locked) {
3113
			if (!res || !return_locked) {
3114
				ast_mutex_unlock(&iaxsl[dcallno]);
3114
				ast_mutex_unlock(&iaxsl[dcallno]);
3115
			}
3115
			}
3116
			return res;
3116
			return res;
3117
		}
3117
		}
3118
		if (dcallno) {
3118
		if (dcallno) {
3119
			ast_mutex_unlock(&iaxsl[dcallno]);
3119
			ast_mutex_unlock(&iaxsl[dcallno]);
3120
		}
3120
		}
3121
	}
3121
	}
3122
	if (!res && (new >= NEW_ALLOW)) {
3122
	if (!res && (new >= NEW_ALLOW)) {
3123
		callno_entry entry;
3123
		callno_entry entry;
3124

    
   
3124

   
3125
		/* It may seem odd that we look through the peer list for a name for
3125
		/* It may seem odd that we look through the peer list for a name for
3126
		 * this *incoming* call.  Well, it is weird.  However, users don't
3126
		 * this *incoming* call.  Well, it is weird.  However, users don't
3127
		 * have an IP address/port number that we can match against.  So,
3127
		 * have an IP address/port number that we can match against.  So,
3128
		 * this is just checking for a peer that has that IP/port and
3128
		 * this is just checking for a peer that has that IP/port and
3129
		 * assuming that we have a user of the same name.  This isn't always
3129
		 * assuming that we have a user of the same name.  This isn't always
3130
		 * correct, but it will be changed if needed after authentication. */
3130
		 * correct, but it will be changed if needed after authentication. */
3131
		if (!iax2_getpeername(*addr, host, sizeof(host)))
3131
		if (!iax2_getpeername(*addr, host, sizeof(host)))
3132
			snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3132
			snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(addr));
3133

    
   
3133

   
3134
		if (peercnt_add(addr)) {
3134
		if (peercnt_add(addr)) {
3135
			/* This address has hit its callnumber limit.  When the limit
3135
			/* This address has hit its callnumber limit.  When the limit
3136
			 * is reached, the connection is not added to the peercnts table.*/
3136
			 * is reached, the connection is not added to the peercnts table.*/
3137
			return 0;
3137
			return 0;
3138
		}
3138
		}
3139

    
   
3139

   
3140
		if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3140
		if (get_unused_callno(CALLNO_TYPE_NORMAL, validated, &entry)) {
3141
			/* since we ran out of space, remove the peercnt
3141
			/* since we ran out of space, remove the peercnt
3142
			 * entry we added earlier */
3142
			 * entry we added earlier */
3143
			peercnt_remove_by_addr(addr);
3143
			peercnt_remove_by_addr(addr);
3144
			ast_log(LOG_WARNING, "No more space\n");
3144
			ast_log(LOG_WARNING, "No more space\n");
3145
			return 0;
3145
			return 0;
3146
		}
3146
		}
3147
		x = CALLNO_ENTRY_GET_CALLNO(entry);
3147
		x = CALLNO_ENTRY_GET_CALLNO(entry);
3148
		ast_mutex_lock(&iaxsl[x]);
3148
		ast_mutex_lock(&iaxsl[x]);
3149

    
   
3149

   
3150
		iaxs[x] = new_iax(addr, host);
3150
		iaxs[x] = new_iax(addr, host);
3151
		if (iaxs[x]) {
3151
		if (iaxs[x]) {
3152
			if (iaxdebug)
3152
			if (iaxdebug)
3153
				ast_debug(1, "Creating new call structure %d\n", x);
3153
				ast_debug(1, "Creating new call structure %d\n", x);
3154
			iaxs[x]->callno_entry = entry;
3154
			iaxs[x]->callno_entry = entry;
3155
			iaxs[x]->sockfd = sockfd;
3155
			iaxs[x]->sockfd = sockfd;
3156
			ast_sockaddr_copy(&iaxs[x]->addr, addr);
3156
			ast_sockaddr_copy(&iaxs[x]->addr, addr);
3157
			iaxs[x]->peercallno = callno;
3157
			iaxs[x]->peercallno = callno;
3158
			iaxs[x]->callno = x;
3158
			iaxs[x]->callno = x;
3159
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3159
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
3160
			iaxs[x]->expiry = min_reg_expire;
3160
			iaxs[x]->expiry = min_reg_expire;
3161
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3161
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
3162
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3162
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
3163
			iaxs[x]->amaflags = amaflags;
3163
			iaxs[x]->amaflags = amaflags;
3164
			ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3164
			ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
3165
			ast_string_field_set(iaxs[x], accountcode, accountcode);
3165
			ast_string_field_set(iaxs[x], accountcode, accountcode);
3166
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3166
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
3167
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3167
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
3168
			ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3168
			ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
3169

    
   
3169

   
3170
			if (iaxs[x]->peercallno) {
3170
			if (iaxs[x]->peercallno) {
3171
				store_by_peercallno(iaxs[x]);
3171
				store_by_peercallno(iaxs[x]);
3172
			}
3172
			}
3173
		} else {
3173
		} else {
3174
			ast_log(LOG_WARNING, "Out of resources\n");
3174
			ast_log(LOG_WARNING, "Out of resources\n");
3175
			ast_mutex_unlock(&iaxsl[x]);
3175
			ast_mutex_unlock(&iaxsl[x]);
3176
			replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3176
			replace_callno(CALLNO_ENTRY_TO_PTR(entry));
3177
			return 0;
3177
			return 0;
3178
		}
3178
		}
3179
		if (!return_locked)
3179
		if (!return_locked)
3180
			ast_mutex_unlock(&iaxsl[x]);
3180
			ast_mutex_unlock(&iaxsl[x]);
3181
		res = x;
3181
		res = x;
3182
	}
3182
	}
3183
	return res;
3183
	return res;
3184
}
3184
}
3185

    
   
3185

   
3186
static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3186
static int find_callno(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3187
	return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3187
	return __find_callno(callno, dcallno, addr, new, sockfd, 0, full_frame);
3188
}
3188
}
3189

    
   
3189

   
3190
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3190
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct ast_sockaddr *addr, int new, int sockfd, int full_frame) {
3191

    
   
3191

   
3192
	return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3192
	return __find_callno(callno, dcallno, addr, new, sockfd, 1, full_frame);
3193
}
3193
}
3194

    
   
3194

   
3195
/*!
3195
/*!
3196
 * \brief Queue a frame to a call's owning asterisk channel
3196
 * \brief Queue a frame to a call's owning asterisk channel
3197
 *
3197
 *
3198
 * \pre This function assumes that iaxsl[callno] is locked when called.
3198
 * \pre This function assumes that iaxsl[callno] is locked when called.
3199
 *
3199
 *
3200
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3200
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3201
 * was valid before calling it, it may no longer be valid after calling it.
3201
 * was valid before calling it, it may no longer be valid after calling it.
3202
 * This function may unlock and lock the mutex associated with this callno,
3202
 * This function may unlock and lock the mutex associated with this callno,
3203
 * meaning that another thread may grab it and destroy the call.
3203
 * meaning that another thread may grab it and destroy the call.
3204
 */
3204
 */
3205
static int iax2_queue_frame(int callno, struct ast_frame *f)
3205
static int iax2_queue_frame(int callno, struct ast_frame *f)
3206
{
3206
{
3207
	iax2_lock_owner(callno);
3207
	iax2_lock_owner(callno);
3208
	if (iaxs[callno] && iaxs[callno]->owner) {
3208
	if (iaxs[callno] && iaxs[callno]->owner) {
3209
		ast_queue_frame(iaxs[callno]->owner, f);
3209
		ast_queue_frame(iaxs[callno]->owner, f);
3210
		ast_channel_unlock(iaxs[callno]->owner);
3210
		ast_channel_unlock(iaxs[callno]->owner);
3211
	}
3211
	}
3212
	return 0;
3212
	return 0;
3213
}
3213
}
3214

    
   
3214

   
3215
/*!
3215
/*!
3216
 * \brief Queue a hold frame on the ast_channel owner
3216
 * \brief Queue a hold frame on the ast_channel owner
3217
 *
3217
 *
3218
 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3218
 * This function queues a hold frame on the owner of the IAX2 pvt struct that
3219
 * is active for the given call number.
3219
 * is active for the given call number.
3220
 *
3220
 *
3221
 * \pre Assumes lock for callno is already held.
3221
 * \pre Assumes lock for callno is already held.
3222
 *
3222
 *
3223
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3223
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3224
 * was valid before calling it, it may no longer be valid after calling it.
3224
 * was valid before calling it, it may no longer be valid after calling it.
3225
 * This function may unlock and lock the mutex associated with this callno,
3225
 * This function may unlock and lock the mutex associated with this callno,
3226
 * meaning that another thread may grab it and destroy the call.
3226
 * meaning that another thread may grab it and destroy the call.
3227
 */
3227
 */
3228
static int iax2_queue_hold(int callno, const char *musicclass)
3228
static int iax2_queue_hold(int callno, const char *musicclass)
3229
{
3229
{
3230
	iax2_lock_owner(callno);
3230
	iax2_lock_owner(callno);
3231
	if (iaxs[callno] && iaxs[callno]->owner) {
3231
	if (iaxs[callno] && iaxs[callno]->owner) {
3232
		ast_queue_hold(iaxs[callno]->owner, musicclass);
3232
		ast_queue_hold(iaxs[callno]->owner, musicclass);
3233
		ast_channel_unlock(iaxs[callno]->owner);
3233
		ast_channel_unlock(iaxs[callno]->owner);
3234
	}
3234
	}
3235
	return 0;
3235
	return 0;
3236
}
3236
}
3237

    
   
3237

   
3238
/*!
3238
/*!
3239
 * \brief Queue an unhold frame on the ast_channel owner
3239
 * \brief Queue an unhold frame on the ast_channel owner
3240
 *
3240
 *
3241
 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3241
 * This function queues an unhold frame on the owner of the IAX2 pvt struct that
3242
 * is active for the given call number.
3242
 * is active for the given call number.
3243
 *
3243
 *
3244
 * \pre Assumes lock for callno is already held.
3244
 * \pre Assumes lock for callno is already held.
3245
 *
3245
 *
3246
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3246
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3247
 * was valid before calling it, it may no longer be valid after calling it.
3247
 * was valid before calling it, it may no longer be valid after calling it.
3248
 * This function may unlock and lock the mutex associated with this callno,
3248
 * This function may unlock and lock the mutex associated with this callno,
3249
 * meaning that another thread may grab it and destroy the call.
3249
 * meaning that another thread may grab it and destroy the call.
3250
 */
3250
 */
3251
static int iax2_queue_unhold(int callno)
3251
static int iax2_queue_unhold(int callno)
3252
{
3252
{
3253
	iax2_lock_owner(callno);
3253
	iax2_lock_owner(callno);
3254
	if (iaxs[callno] && iaxs[callno]->owner) {
3254
	if (iaxs[callno] && iaxs[callno]->owner) {
3255
		ast_queue_unhold(iaxs[callno]->owner);
3255
		ast_queue_unhold(iaxs[callno]->owner);
3256
		ast_channel_unlock(iaxs[callno]->owner);
3256
		ast_channel_unlock(iaxs[callno]->owner);
3257
	}
3257
	}
3258
	return 0;
3258
	return 0;
3259
}
3259
}
3260

    
   
3260

   
3261
/*!
3261
/*!
3262
 * \brief Queue a hangup frame on the ast_channel owner
3262
 * \brief Queue a hangup frame on the ast_channel owner
3263
 *
3263
 *
3264
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3264
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3265
 * is active for the given call number.
3265
 * is active for the given call number.
3266
 *
3266
 *
3267
 * \pre Assumes lock for callno is already held.
3267
 * \pre Assumes lock for callno is already held.
3268
 *
3268
 *
3269
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3269
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3270
 * was valid before calling it, it may no longer be valid after calling it.
3270
 * was valid before calling it, it may no longer be valid after calling it.
3271
 * This function may unlock and lock the mutex associated with this callno,
3271
 * This function may unlock and lock the mutex associated with this callno,
3272
 * meaning that another thread may grab it and destroy the call.
3272
 * meaning that another thread may grab it and destroy the call.
3273
 */
3273
 */
3274
static int iax2_queue_hangup(int callno)
3274
static int iax2_queue_hangup(int callno)
3275
{
3275
{
3276
	iax2_lock_owner(callno);
3276
	iax2_lock_owner(callno);
3277
	if (iaxs[callno] && iaxs[callno]->owner) {
3277
	if (iaxs[callno] && iaxs[callno]->owner) {
3278
		ast_queue_hangup(iaxs[callno]->owner);
3278
		ast_queue_hangup(iaxs[callno]->owner);
3279
		ast_channel_unlock(iaxs[callno]->owner);
3279
		ast_channel_unlock(iaxs[callno]->owner);
3280
	}
3280
	}
3281
	return 0;
3281
	return 0;
3282
}
3282
}
3283

    
   
3283

   
3284
/*!
3284
/*!
3285
 * \note This function assumes that iaxsl[callno] is locked when called.
3285
 * \note This function assumes that iaxsl[callno] is locked when called.
3286
 *
3286
 *
3287
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3287
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3288
 * was valid before calling it, it may no longer be valid after calling it.
3288
 * was valid before calling it, it may no longer be valid after calling it.
3289
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3289
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
3290
 * associated with this callno, meaning that another thread may grab it and destroy the call.
3290
 * associated with this callno, meaning that another thread may grab it and destroy the call.
3291
 */
3291
 */
3292
static int __do_deliver(void *data)
3292
static int __do_deliver(void *data)
3293
{
3293
{
3294
	/* Just deliver the packet by using queueing.  This is called by
3294
	/* Just deliver the packet by using queueing.  This is called by
3295
	  the IAX thread with the iaxsl lock held. */
3295
	  the IAX thread with the iaxsl lock held. */
3296
	struct iax_frame *fr = data;
3296
	struct iax_frame *fr = data;
3297
	fr->retrans = -1;
3297
	fr->retrans = -1;
3298
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3298
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3299
	if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3299
	if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3300
		iax2_queue_frame(fr->callno, &fr->af);
3300
		iax2_queue_frame(fr->callno, &fr->af);
3301
	/* Free our iax frame */
3301
	/* Free our iax frame */
3302
	iax2_frame_free(fr);
3302
	iax2_frame_free(fr);
3303
	/* And don't run again */
3303
	/* And don't run again */
3304
	return 0;
3304
	return 0;
3305
}
3305
}
3306

    
   
3306

   
3307
static int handle_error(void)
3307
static int handle_error(void)
3308
{
3308
{
3309
	/* XXX Ideally we should figure out why an error occurred and then abort those
3309
	/* XXX Ideally we should figure out why an error occurred and then abort those
3310
	   rather than continuing to try.  Unfortunately, the published interface does
3310
	   rather than continuing to try.  Unfortunately, the published interface does
3311
	   not seem to work XXX */
3311
	   not seem to work XXX */
3312
#if 0
3312
#if 0
3313
	struct sockaddr_in *sin;
3313
	struct sockaddr_in *sin;
3314
	int res;
3314
	int res;
3315
	struct msghdr m;
3315
	struct msghdr m;
3316
	struct sock_extended_err e;
3316
	struct sock_extended_err e;
3317
	m.msg_name = NULL;
3317
	m.msg_name = NULL;
3318
	m.msg_namelen = 0;
3318
	m.msg_namelen = 0;
3319
	m.msg_iov = NULL;
3319
	m.msg_iov = NULL;
3320
	m.msg_control = &e;
3320
	m.msg_control = &e;
3321
	m.msg_controllen = sizeof(e);
3321
	m.msg_controllen = sizeof(e);
3322
	m.msg_flags = 0;
3322
	m.msg_flags = 0;
3323
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3323
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3324
	if (res < 0)
3324
	if (res < 0)
3325
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3325
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3326
	else {
3326
	else {
3327
		if (m.msg_controllen) {
3327
		if (m.msg_controllen) {
3328
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3328
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3329
			if (sin)
3329
			if (sin)
3330
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3330
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3331
			else
3331
			else
3332
				ast_log(LOG_WARNING, "No address detected??\n");
3332
				ast_log(LOG_WARNING, "No address detected??\n");
3333
		} else {
3333
		} else {
3334
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3334
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3335
		}
3335
		}
3336
	}
3336
	}
3337
#endif
3337
#endif
3338
	return 0;
3338
	return 0;
3339
}
3339
}
3340

    
   
3340

   
3341
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3341
static int transmit_trunk(struct iax_frame *f, struct ast_sockaddr *addr, int sockfd)
3342
{
3342
{
3343
	int res;
3343
	int res;
3344
	res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3344
	res = ast_sendto(sockfd, f->data, f->datalen, 0, addr);
3345

    
   
3345

   
3346
	if (res < 0) {
3346
	if (res < 0) {
3347
		ast_debug(1, "Received error: %s\n", strerror(errno));
3347
		ast_debug(1, "Received error: %s\n", strerror(errno));
3348
		handle_error();
3348
		handle_error();
3349
	} else
3349
	} else
3350
		res = 0;
3350
		res = 0;
3351
	return res;
3351
	return res;
3352
}
3352
}
3353

    
   
3353

   
3354
static int send_packet(struct iax_frame *f)
3354
static int send_packet(struct iax_frame *f)
3355
{
3355
{
3356
	int res;
3356
	int res;
3357
	int callno = f->callno;
3357
	int callno = f->callno;
3358

    
   
3358

   
3359
	/* Don't send if there was an error, but return error instead */
3359
	/* Don't send if there was an error, but return error instead */
3360
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
3360
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
3361
	    return -1;
3361
	    return -1;
3362

    
   
3362

   
3363
	/* Called with iaxsl held */
3363
	/* Called with iaxsl held */
3364
	if (iaxdebug) {
3364
	if (iaxdebug) {
3365
		ast_debug(3, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3365
		ast_debug(3, "Sending %u on %d/%d to %s\n", f->ts, callno, iaxs[callno]->peercallno, ast_sockaddr_stringify(&iaxs[callno]->addr));
3366
	}
3366
	}
3367
	if (f->transfer) {
3367
	if (f->transfer) {
3368
		iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3368
		iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3369
		res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3369
		res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->transfer);
3370
	} else {
3370
	} else {
3371
		iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3371
		iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3372
		res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3372
		res = ast_sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0, &iaxs[callno]->addr);
3373
	}
3373
	}
3374
	if (res < 0) {
3374
	if (res < 0) {
3375
		if (iaxdebug)
3375
		if (iaxdebug)
3376
			ast_debug(1, "Received error: %s\n", strerror(errno));
3376
			ast_debug(1, "Received error: %s\n", strerror(errno));
3377
		handle_error();
3377
		handle_error();
3378
	} else
3378
	} else
3379
		res = 0;
3379
		res = 0;
3380

    
   
3380

   
3381
	return res;
3381
	return res;
3382
}
3382
}
3383

    
   
3383

   
3384
/*!
3384
/*!
3385
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3385
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3386
 *       for the given call number may disappear during its execution.
3386
 *       for the given call number may disappear during its execution.
3387
 */
3387
 */
3388
static int iax2_predestroy(int callno)
3388
static int iax2_predestroy(int callno)
3389
{
3389
{
3390
	struct ast_channel *c = NULL;
3390
	struct ast_channel *c = NULL;
3391
	struct chan_iax2_pvt *pvt = iaxs[callno];
3391
	struct chan_iax2_pvt *pvt = iaxs[callno];
3392

    
   
3392

   
3393
	if (!pvt)
3393
	if (!pvt)
3394
		return -1;
3394
		return -1;
3395

    
   
3395

   
3396
	if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3396
	if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3397
		iax2_destroy_helper(pvt);
3397
		iax2_destroy_helper(pvt);
3398
		ast_set_flag64(pvt, IAX_ALREADYGONE);
3398
		ast_set_flag64(pvt, IAX_ALREADYGONE);
3399
	}
3399
	}
3400

    
   
3400

   
3401
	if ((c = pvt->owner)) {
3401
	if ((c = pvt->owner)) {
3402
		ast_channel_tech_pvt_set(c, NULL);
3402
		ast_channel_tech_pvt_set(c, NULL);
3403
		iax2_queue_hangup(callno);
3403
		iax2_queue_hangup(callno);
3404
		pvt->owner = NULL;
3404
		pvt->owner = NULL;
3405
		ast_module_unref(ast_module_info->self);
3405
		ast_module_unref(ast_module_info->self);
3406
	}
3406
	}
3407

    
   
3407

   
3408
	return 0;
3408
	return 0;
3409
}
3409
}
3410

    
   
3410

   
3411
static void iax2_destroy(int callno)
3411
static void iax2_destroy(int callno)
3412
{
3412
{
3413
	struct chan_iax2_pvt *pvt = NULL;
3413
	struct chan_iax2_pvt *pvt = NULL;
3414
	struct ast_channel *owner = NULL;
3414
	struct ast_channel *owner = NULL;
3415

    
   
3415

   
3416
retry:
3416
retry:
3417
	if ((pvt = iaxs[callno])) {
3417
	if ((pvt = iaxs[callno])) {
3418
#if 0
3418
#if 0
3419
		/* iax2_destroy_helper gets called from this function later on.  When
3419
		/* iax2_destroy_helper gets called from this function later on.  When
3420
		 * called twice, we get the (previously) familiar FRACK! errors in
3420
		 * called twice, we get the (previously) familiar FRACK! errors in
3421
		 * devmode, from the scheduler.  An alternative to this approach is to
3421
		 * devmode, from the scheduler.  An alternative to this approach is to
3422
		 * reset the scheduler entries to -1 when they're deleted in
3422
		 * reset the scheduler entries to -1 when they're deleted in
3423
		 * iax2_destroy_helper().  That approach was previously decided to be
3423
		 * iax2_destroy_helper().  That approach was previously decided to be
3424
		 * "wrong" because "the memory is going to be deallocated anyway.  Why
3424
		 * "wrong" because "the memory is going to be deallocated anyway.  Why
3425
		 * should we be resetting those values?" */
3425
		 * should we be resetting those values?" */
3426
		iax2_destroy_helper(pvt);
3426
		iax2_destroy_helper(pvt);
3427
#endif
3427
#endif
3428
	}
3428
	}
3429

    
   
3429

   
3430
	owner = pvt ? pvt->owner : NULL;
3430
	owner = pvt ? pvt->owner : NULL;
3431

    
   
3431

   
3432
	if (owner) {
3432
	if (owner) {
3433
		if (ast_channel_trylock(owner)) {
3433
		if (ast_channel_trylock(owner)) {
3434
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
3434
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
3435
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3435
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3436
			goto retry;
3436
			goto retry;
3437
		}
3437
		}
3438
	}
3438
	}
3439

    
   
3439

   
3440
	if (!owner) {
3440
	if (!owner) {
3441
		iaxs[callno] = NULL;
3441
		iaxs[callno] = NULL;
3442
	}
3442
	}
3443

    
   
3443

   
3444
	if (pvt) {
3444
	if (pvt) {
3445
		if (!owner) {
3445
		if (!owner) {
3446
			pvt->owner = NULL;
3446
			pvt->owner = NULL;
3447
		} else {
3447
		} else {
3448
			/* If there's an owner, prod it to give up */
3448
			/* If there's an owner, prod it to give up */
3449
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3449
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3450
			 * because we already hold the owner channel lock. */
3450
			 * because we already hold the owner channel lock. */
3451
			ast_queue_hangup(owner);
3451
			ast_queue_hangup(owner);
3452
		}
3452
		}
3453

    
   
3453

   
3454
		if (pvt->peercallno) {
3454
		if (pvt->peercallno) {
3455
			remove_by_peercallno(pvt);
3455
			remove_by_peercallno(pvt);
3456
		}
3456
		}
3457

    
   
3457

   
3458
		if (pvt->transfercallno) {
3458
		if (pvt->transfercallno) {
3459
			remove_by_transfercallno(pvt);
3459
			remove_by_transfercallno(pvt);
3460
		}
3460
		}
3461

    
   
3461

   
3462
		if (!owner) {
3462
		if (!owner) {
3463
			ao2_ref(pvt, -1);
3463
			ao2_ref(pvt, -1);
3464
			pvt = NULL;
3464
			pvt = NULL;
3465
		}
3465
		}
3466
	}
3466
	}
3467

    
   
3467

   
3468
	if (owner) {
3468
	if (owner) {
3469
		ast_channel_unlock(owner);
3469
		ast_channel_unlock(owner);
3470
	}
3470
	}
3471
}
3471
}
3472

    
   
3472

   
3473
static int update_packet(struct iax_frame *f)
3473
static int update_packet(struct iax_frame *f)
3474
{
3474
{
3475
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3475
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3476
	struct ast_iax2_full_hdr *fh = f->data;
3476
	struct ast_iax2_full_hdr *fh = f->data;
3477
	struct ast_frame af;
3477
	struct ast_frame af;
3478

    
   
3478

   
3479
	/* if frame is encrypted. decrypt before updating it. */
3479
	/* if frame is encrypted. decrypt before updating it. */
3480
	if (f->encmethods) {
3480
	if (f->encmethods) {
3481
		decode_frame(&f->mydcx, fh, &af, &f->datalen);
3481
		decode_frame(&f->mydcx, fh, &af, &f->datalen);
3482
	}
3482
	}
3483
	/* Mark this as a retransmission */
3483
	/* Mark this as a retransmission */
3484
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3484
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3485
	/* Update iseqno */
3485
	/* Update iseqno */
3486
	f->iseqno = iaxs[f->callno]->iseqno;
3486
	f->iseqno = iaxs[f->callno]->iseqno;
3487
	fh->iseqno = f->iseqno;
3487
	fh->iseqno = f->iseqno;
3488

    
   
3488

   
3489
	/* Now re-encrypt the frame */
3489
	/* Now re-encrypt the frame */
3490
	if (f->encmethods) {
3490
	if (f->encmethods) {
3491
	/* since this is a retransmit frame, create a new random padding
3491
	/* since this is a retransmit frame, create a new random padding
3492
	 * before re-encrypting. */
3492
	 * before re-encrypting. */
3493
		build_rand_pad(f->semirand, sizeof(f->semirand));
3493
		build_rand_pad(f->semirand, sizeof(f->semirand));
3494
		encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3494
		encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3495
	}
3495
	}
3496
	return 0;
3496
	return 0;
3497
}
3497
}
3498

    
   
3498

   
3499
static int attempt_transmit(const void *data);
3499
static int attempt_transmit(const void *data);
3500
static void __attempt_transmit(const void *data)
3500
static void __attempt_transmit(const void *data)
3501
{
3501
{
3502
	/* Attempt to transmit the frame to the remote peer...
3502
	/* Attempt to transmit the frame to the remote peer...
3503
	   Called without iaxsl held. */
3503
	   Called without iaxsl held. */
3504
	struct iax_frame *f = (struct iax_frame *)data;
3504
	struct iax_frame *f = (struct iax_frame *)data;
3505
	int freeme = 0;
3505
	int freeme = 0;
3506
	int callno = f->callno;
3506
	int callno = f->callno;
3507

    
   
3507

   
3508
	/* Make sure this call is still active */
3508
	/* Make sure this call is still active */
3509
	if (callno)
3509
	if (callno)
3510
		ast_mutex_lock(&iaxsl[callno]);
3510
		ast_mutex_lock(&iaxsl[callno]);
3511
	if (callno && iaxs[callno]) {
3511
	if (callno && iaxs[callno]) {
3512
		if (f->retries < 0) {
3512
		if (f->retries < 0) {
3513
			/* Already ACK'd */
3513
			/* Already ACK'd */
3514
			freeme = 1;
3514
			freeme = 1;
3515
		} else if (f->retries >= max_retries) {
3515
		} else if (f->retries >= max_retries) {
3516
			/* Too many attempts.  Record an error. */
3516
			/* Too many attempts.  Record an error. */
3517
			if (f->transfer) {
3517
			if (f->transfer) {
3518
				/* Transfer timeout */
3518
				/* Transfer timeout */
3519
				send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3519
				send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3520
			} else if (f->final) {
3520
			} else if (f->final) {
3521
				iax2_destroy(callno);
3521
				iax2_destroy(callno);
3522
			} else {
3522
			} else {
3523
				if (iaxs[callno]->owner) {
3523
				if (iaxs[callno]->owner) {
3524
					ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3524
					ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %u, subclass = %d, ts=%u, seqno=%d)\n",
3525
						ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3525
						ast_sockaddr_stringify_addr(&iaxs[f->callno]->addr),
3526
						ast_channel_name(iaxs[f->callno]->owner),
3526
						ast_channel_name(iaxs[f->callno]->owner),
3527
						f->af.frametype,
3527
						f->af.frametype,
3528
						f->af.subclass.integer,
3528
						f->af.subclass.integer,
3529
						f->ts,
3529
						f->ts,
3530
						f->oseqno);
3530
						f->oseqno);
3531
				}
3531
				}
3532
				iaxs[callno]->error = ETIMEDOUT;
3532
				iaxs[callno]->error = ETIMEDOUT;
3533
				if (iaxs[callno]->owner) {
3533
				if (iaxs[callno]->owner) {
3534
					struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3534
					struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3535
					/* Hangup the fd */
3535
					/* Hangup the fd */
3536
					iax2_queue_frame(callno, &fr); /* XXX */
3536
					iax2_queue_frame(callno, &fr); /* XXX */
3537
					/* Remember, owner could disappear */
3537
					/* Remember, owner could disappear */
3538
					if (iaxs[callno] && iaxs[callno]->owner)
3538
					if (iaxs[callno] && iaxs[callno]->owner)
3539
						ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3539
						ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3540
				} else {
3540
				} else {
3541
					if (iaxs[callno]->reg) {
3541
					if (iaxs[callno]->reg) {
3542
						memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3542
						memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3543
						iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3543
						iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3544
						iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3544
						iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3545
					}
3545
					}
3546
					iax2_destroy(callno);
3546
					iax2_destroy(callno);
3547
				}
3547
				}
3548
			}
3548
			}
3549
			freeme = 1;
3549
			freeme = 1;
3550
		} else {
3550
		} else {
3551
			/* Update it if it needs it */
3551
			/* Update it if it needs it */
3552
			update_packet(f);
3552
			update_packet(f);
3553
			/* Attempt transmission */
3553
			/* Attempt transmission */
3554
			send_packet(f);
3554
			send_packet(f);
3555
			f->retries++;
3555
			f->retries++;
3556
			/* Try again later after 10 times as long */
3556
			/* Try again later after 10 times as long */
3557
			f->retrytime *= 10;
3557
			f->retrytime *= 10;
3558
			if (f->retrytime > MAX_RETRY_TIME)
3558
			if (f->retrytime > MAX_RETRY_TIME)
3559
				f->retrytime = MAX_RETRY_TIME;
3559
				f->retrytime = MAX_RETRY_TIME;
3560
			/* Transfer messages max out at one second */
3560
			/* Transfer messages max out at one second */
3561
			if (f->transfer && (f->retrytime > 1000))
3561
			if (f->transfer && (f->retrytime > 1000))
3562
				f->retrytime = 1000;
3562
				f->retrytime = 1000;
3563
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3563
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3564
		}
3564
		}
3565
	} else {
3565
	} else {
3566
		/* Make sure it gets freed */
3566
		/* Make sure it gets freed */
3567
		f->retries = -1;
3567
		f->retries = -1;
3568
		freeme = 1;
3568
		freeme = 1;
3569
	}
3569
	}
3570

    
   
3570

   
3571
	if (freeme) {
3571
	if (freeme) {
3572
		/* Don't attempt delivery, just remove it from the queue */
3572
		/* Don't attempt delivery, just remove it from the queue */
3573
		AST_LIST_REMOVE(&frame_queue[callno], f, list);
3573
		AST_LIST_REMOVE(&frame_queue[callno], f, list);
3574
		ast_mutex_unlock(&iaxsl[callno]);
3574
		ast_mutex_unlock(&iaxsl[callno]);
3575
		f->retrans = -1; /* this is safe because this is the scheduled function */
3575
		f->retrans = -1; /* this is safe because this is the scheduled function */
3576
		/* Free the IAX frame */
3576
		/* Free the IAX frame */
3577
		iax2_frame_free(f);
3577
		iax2_frame_free(f);
3578
	} else if (callno) {
3578
	} else if (callno) {
3579
		ast_mutex_unlock(&iaxsl[callno]);
3579
		ast_mutex_unlock(&iaxsl[callno]);
3580
	}
3580
	}
3581
}
3581
}
3582

    
   
3582

   
3583
static int attempt_transmit(const void *data)
3583
static int attempt_transmit(const void *data)
3584
{
3584
{
3585
#ifdef SCHED_MULTITHREADED
3585
#ifdef SCHED_MULTITHREADED
3586
	if (schedule_action(__attempt_transmit, data))
3586
	if (schedule_action(__attempt_transmit, data))
3587
#endif
3587
#endif
3588
		__attempt_transmit(data);
3588
		__attempt_transmit(data);
3589
	return 0;
3589
	return 0;
3590
}
3590
}
3591

    
   
3591

   
3592
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3592
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3593
{
3593
{
3594
	struct iax2_peer *peer = NULL;
3594
	struct iax2_peer *peer = NULL;
3595
	struct iax2_user *user = NULL;
3595
	struct iax2_user *user = NULL;
3596
	static const char * const choices[] = { "all", NULL };
3596
	static const char * const choices[] = { "all", NULL };
3597
	char *cmplt;
3597
	char *cmplt;
3598

    
   
3598

   
3599
	switch (cmd) {
3599
	switch (cmd) {
3600
	case CLI_INIT:
3600
	case CLI_INIT:
3601
		e->command = "iax2 prune realtime";
3601
		e->command = "iax2 prune realtime";
3602
		e->usage =
3602
		e->usage =
3603
			"Usage: iax2 prune realtime [<peername>|all]\n"
3603
			"Usage: iax2 prune realtime [<peername>|all]\n"
3604
			"       Prunes object(s) from the cache\n";
3604
			"       Prunes object(s) from the cache\n";
3605
		return NULL;
3605
		return NULL;
3606
	case CLI_GENERATE:
3606
	case CLI_GENERATE:
3607
		if (a->pos == 3) {
3607
		if (a->pos == 3) {
3608
			cmplt = ast_cli_complete(a->word, choices, a->n);
3608
			cmplt = ast_cli_complete(a->word, choices, a->n);
3609
			if (!cmplt)
3609
			if (!cmplt)
3610
				cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3610
				cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3611
			return cmplt;
3611
			return cmplt;
3612
		}
3612
		}
3613
		return NULL;
3613
		return NULL;
3614
	}
3614
	}
3615
	if (a->argc != 4)
3615
	if (a->argc != 4)
3616
		return CLI_SHOWUSAGE;
3616
		return CLI_SHOWUSAGE;
3617
	if (!strcmp(a->argv[3], "all")) {
3617
	if (!strcmp(a->argv[3], "all")) {
3618
		prune_users();
3618
		prune_users();
3619
		prune_peers();
3619
		prune_peers();
3620
		ast_cli(a->fd, "Cache flushed successfully.\n");
3620
		ast_cli(a->fd, "Cache flushed successfully.\n");
3621
		return CLI_SUCCESS;
3621
		return CLI_SUCCESS;
3622
	}
3622
	}
3623
	peer = find_peer(a->argv[3], 0);
3623
	peer = find_peer(a->argv[3], 0);
3624
	user = find_user(a->argv[3]);
3624
	user = find_user(a->argv[3]);
3625
	if (peer || user) {
3625
	if (peer || user) {
3626
		if (peer) {
3626
		if (peer) {
3627
			if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3627
			if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3628
				ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3628
				ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3629
				expire_registry(peer_ref(peer));
3629
				expire_registry(peer_ref(peer));
3630
				ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3630
				ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3631
			} else {
3631
			} else {
3632
				ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3632
				ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3633
			}
3633
			}
3634
			peer_unref(peer);
3634
			peer_unref(peer);
3635
		}
3635
		}
3636
		if (user) {
3636
		if (user) {
3637
			if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3637
			if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3638
				ast_set_flag64(user, IAX_RTAUTOCLEAR);
3638
				ast_set_flag64(user, IAX_RTAUTOCLEAR);
3639
				ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3639
				ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3640
			} else {
3640
			} else {
3641
				ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3641
				ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3642
			}
3642
			}
3643
			ao2_unlink(users,user);
3643
			ao2_unlink(users,user);
3644
			user_unref(user);
3644
			user_unref(user);
3645
		}
3645
		}
3646
	} else {
3646
	} else {
3647
		ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3647
		ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3648
	}
3648
	}
3649

    
   
3649

   
3650
	return CLI_SUCCESS;
3650
	return CLI_SUCCESS;
3651
}
3651
}
3652

    
   
3652

   
3653
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3653
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3654
{
3654
{
3655
	switch (cmd) {
3655
	switch (cmd) {
3656
	case CLI_INIT:
3656
	case CLI_INIT:
3657
		e->command = "iax2 test losspct";
3657
		e->command = "iax2 test losspct";
3658
		e->usage =
3658
		e->usage =
3659
			"Usage: iax2 test losspct <percentage>\n"
3659
			"Usage: iax2 test losspct <percentage>\n"
3660
			"       For testing, throws away <percentage> percent of incoming packets\n";
3660
			"       For testing, throws away <percentage> percent of incoming packets\n";
3661
		return NULL;
3661
		return NULL;
3662
	case CLI_GENERATE:
3662
	case CLI_GENERATE:
3663
		return NULL;
3663
		return NULL;
3664
	}
3664
	}
3665
	if (a->argc != 4)
3665
	if (a->argc != 4)
3666
		return CLI_SHOWUSAGE;
3666
		return CLI_SHOWUSAGE;
3667

    
   
3667

   
3668
	test_losspct = atoi(a->argv[3]);
3668
	test_losspct = atoi(a->argv[3]);
3669

    
   
3669

   
3670
	return CLI_SUCCESS;
3670
	return CLI_SUCCESS;
3671
}
3671
}
3672

    
   
3672

   
3673
#ifdef IAXTESTS
3673
#ifdef IAXTESTS
3674
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3674
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3675
{
3675
{
3676
	switch (cmd) {
3676
	switch (cmd) {
3677
	case CLI_INIT:
3677
	case CLI_INIT:
3678
		e->command = "iax2 test late";
3678
		e->command = "iax2 test late";
3679
		e->usage =
3679
		e->usage =
3680
			"Usage: iax2 test late <ms>\n"
3680
			"Usage: iax2 test late <ms>\n"
3681
			"       For testing, count the next frame as <ms> ms late\n";
3681
			"       For testing, count the next frame as <ms> ms late\n";
3682
		return NULL;
3682
		return NULL;
3683
	case CLI_GENERATE:
3683
	case CLI_GENERATE:
3684
		return NULL;
3684
		return NULL;
3685
	}
3685
	}
3686

    
   
3686

   
3687
	if (a->argc != 4)
3687
	if (a->argc != 4)
3688
		return CLI_SHOWUSAGE;
3688
		return CLI_SHOWUSAGE;
3689

    
   
3689

   
3690
	test_late = atoi(a->argv[3]);
3690
	test_late = atoi(a->argv[3]);
3691

    
   
3691

   
3692
	return CLI_SUCCESS;
3692
	return CLI_SUCCESS;
3693
}
3693
}
3694

    
   
3694

   
3695
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3695
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3696
{
3696
{
3697
	switch (cmd) {
3697
	switch (cmd) {
3698
	case CLI_INIT:
3698
	case CLI_INIT:
3699
		e->command = "iax2 test resync";
3699
		e->command = "iax2 test resync";
3700
		e->usage =
3700
		e->usage =
3701
			"Usage: iax2 test resync <ms>\n"
3701
			"Usage: iax2 test resync <ms>\n"
3702
			"       For testing, adjust all future frames by <ms> ms\n";
3702
			"       For testing, adjust all future frames by <ms> ms\n";
3703
		return NULL;
3703
		return NULL;
3704
	case CLI_GENERATE:
3704
	case CLI_GENERATE:
3705
		return NULL;
3705
		return NULL;
3706
	}
3706
	}
3707

    
   
3707

   
3708
	if (a->argc != 4)
3708
	if (a->argc != 4)
3709
		return CLI_SHOWUSAGE;
3709
		return CLI_SHOWUSAGE;
3710

    
   
3710

   
3711
	test_resync = atoi(a->argv[3]);
3711
	test_resync = atoi(a->argv[3]);
3712

    
   
3712

   
3713
	return CLI_SUCCESS;
3713
	return CLI_SUCCESS;
3714
}
3714
}
3715

    
   
3715

   
3716
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3716
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3717
{
3717
{
3718
	switch (cmd) {
3718
	switch (cmd) {
3719
	case CLI_INIT:
3719
	case CLI_INIT:
3720
		e->command = "iax2 test jitter";
3720
		e->command = "iax2 test jitter";
3721
		e->usage =
3721
		e->usage =
3722
			"Usage: iax2 test jitter <ms> <pct>\n"
3722
			"Usage: iax2 test jitter <ms> <pct>\n"
3723
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3723
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3724
			"       percentage of packets. If <pct> is not specified, adds\n"
3724
			"       percentage of packets. If <pct> is not specified, adds\n"
3725
			"       jitter to all packets.\n";
3725
			"       jitter to all packets.\n";
3726
		return NULL;
3726
		return NULL;
3727
	case CLI_GENERATE:
3727
	case CLI_GENERATE:
3728
		return NULL;
3728
		return NULL;
3729
	}
3729
	}
3730

    
   
3730

   
3731
	if (a->argc < 4 || a->argc > 5)
3731
	if (a->argc < 4 || a->argc > 5)
3732
		return CLI_SHOWUSAGE;
3732
		return CLI_SHOWUSAGE;
3733

    
   
3733

   
3734
	test_jit = atoi(a->argv[3]);
3734
	test_jit = atoi(a->argv[3]);
3735
	if (a->argc == 5)
3735
	if (a->argc == 5)
3736
		test_jitpct = atoi(a->argv[4]);
3736
		test_jitpct = atoi(a->argv[4]);
3737

    
   
3737

   
3738
	return CLI_SUCCESS;
3738
	return CLI_SUCCESS;
3739
}
3739
}
3740
#endif /* IAXTESTS */
3740
#endif /* IAXTESTS */
3741

    
   
3741

   
3742
/*! \brief  peer_status: Report Peer status in character string */
3742
/*! \brief  peer_status: Report Peer status in character string */
3743
/* 	returns 1 if peer is online, -1 if unmonitored */
3743
/* 	returns 1 if peer is online, -1 if unmonitored */
3744
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3744
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3745
{
3745
{
3746
	int res = 0;
3746
	int res = 0;
3747
	if (peer->maxms) {
3747
	if (peer->maxms) {
3748
		if (peer->lastms < 0) {
3748
		if (peer->lastms < 0) {
3749
			ast_copy_string(status, "UNREACHABLE", statuslen);
3749
			ast_copy_string(status, "UNREACHABLE", statuslen);
3750
		} else if (peer->lastms > peer->maxms) {
3750
		} else if (peer->lastms > peer->maxms) {
3751
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3751
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3752
			res = 1;
3752
			res = 1;
3753
		} else if (peer->lastms) {
3753
		} else if (peer->lastms) {
3754
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3754
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3755
			res = 1;
3755
			res = 1;
3756
		} else {
3756
		} else {
3757
			ast_copy_string(status, "UNKNOWN", statuslen);
3757
			ast_copy_string(status, "UNKNOWN", statuslen);
3758
		}
3758
		}
3759
	} else {
3759
	} else {
3760
		ast_copy_string(status, "Unmonitored", statuslen);
3760
		ast_copy_string(status, "Unmonitored", statuslen);
3761
		res = -1;
3761
		res = -1;
3762
	}
3762
	}
3763
	return res;
3763
	return res;
3764
}
3764
}
3765

    
   
3765

   
3766
/*! \brief Show one peer in detail */
3766
/*! \brief Show one peer in detail */
3767
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3767
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3768
{
3768
{
3769
	char status[30];
3769
	char status[30];
3770
	char cbuf[256];
3770
	char cbuf[256];
3771
	struct iax2_peer *peer;
3771
	struct iax2_peer *peer;
3772
	struct ast_str *codec_buf = ast_str_alloca(256);
3772
	struct ast_str *codec_buf = ast_str_alloca(256);
3773
	struct ast_str *encmethods = ast_str_alloca(256);
3773
	struct ast_str *encmethods = ast_str_alloca(256);
3774
	int load_realtime = 0;
3774
	int load_realtime = 0;
3775

    
   
3775

   
3776
	switch (cmd) {
3776
	switch (cmd) {
3777
	case CLI_INIT:
3777
	case CLI_INIT:
3778
		e->command = "iax2 show peer";
3778
		e->command = "iax2 show peer";
3779
		e->usage =
3779
		e->usage =
3780
			"Usage: iax2 show peer <name>\n"
3780
			"Usage: iax2 show peer <name>\n"
3781
			"       Display details on specific IAX peer\n";
3781
			"       Display details on specific IAX peer\n";
3782
		return NULL;
3782
		return NULL;
3783
	case CLI_GENERATE:
3783
	case CLI_GENERATE:
3784
		if (a->pos == 3)
3784
		if (a->pos == 3)
3785
			return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3785
			return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3786
		return NULL;
3786
		return NULL;
3787
	}
3787
	}
3788

    
   
3788

   
3789
	if (a->argc < 4)
3789
	if (a->argc < 4)
3790
		return CLI_SHOWUSAGE;
3790
		return CLI_SHOWUSAGE;
3791

    
   
3791

   
3792
	load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3792
	load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
3793

    
   
3793

   
3794
	peer = find_peer(a->argv[3], load_realtime);
3794
	peer = find_peer(a->argv[3], load_realtime);
3795
	if (peer) {
3795
	if (peer) {
3796
		char *str_addr, *str_defaddr;
3796
		char *str_addr, *str_defaddr;
3797
		char *str_port, *str_defport;
3797
		char *str_port, *str_defport;
3798

    
   
3798

   
3799
		str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3799
		str_addr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->addr));
3800
		str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3800
		str_port = ast_strdupa(ast_sockaddr_stringify_port(&peer->addr));
3801
		str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3801
		str_defaddr = ast_strdupa(ast_sockaddr_stringify_addr(&peer->defaddr));
3802
		str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3802
		str_defport = ast_strdupa(ast_sockaddr_stringify_port(&peer->defaddr));
3803

    
   
3803

   
3804
		encmethods_to_str(peer->encmethods, &encmethods);
3804
		encmethods_to_str(peer->encmethods, &encmethods);
3805
		ast_cli(a->fd, "\n\n");
3805
		ast_cli(a->fd, "\n\n");
3806
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
3806
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
3807
		ast_cli(a->fd, "  Description  : %s\n", peer->description);
3807
		ast_cli(a->fd, "  Description  : %s\n", peer->description);
3808
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3808
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3809
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
3809
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
3810
 		ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
3810
 		ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
3811
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
3811
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
3812
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3812
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3813
		ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
3813
		ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
3814
		ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3814
		ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3815
		ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3815
		ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3816
		ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3816
		ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3817
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3817
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3818
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
3818
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
3819
		ast_cli(a->fd, "  ACL          : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3819
		ast_cli(a->fd, "  ACL          : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3820
		ast_cli(a->fd, "  Addr->IP     : %s Port %s\n",  str_addr ? str_addr : "(Unspecified)", str_port);
3820
		ast_cli(a->fd, "  Addr->IP     : %s Port %s\n",  str_addr ? str_addr : "(Unspecified)", str_port);
3821
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %s\n", str_defaddr, str_defport);
3821
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %s\n", str_defaddr, str_defport);
3822
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
3822
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
3823
		ast_cli(a->fd, "  Codecs       : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3823
		ast_cli(a->fd, "  Codecs       : %s\n", iax2_getformatname_multiple(peer->capability, &codec_buf));
3824

    
   
3824

   
3825
		if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3825
		if (iax2_codec_pref_string(&peer->prefs, cbuf, sizeof(cbuf)) < 0) {
3826
			strcpy(cbuf, "Error"); /* Safe */
3826
			strcpy(cbuf, "Error"); /* Safe */
3827
		}
3827
		}
3828
		ast_cli(a->fd, "  Codec Order  : %s\n", cbuf);
3828
		ast_cli(a->fd, "  Codec Order  : %s\n", cbuf);
3829

    
   
3829

   
3830
		peer_status(peer, status, sizeof(status));
3830
		peer_status(peer, status, sizeof(status));
3831
		ast_cli(a->fd, "  Status       : %s\n", status);
3831
		ast_cli(a->fd, "  Status       : %s\n", status);
3832
		ast_cli(a->fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3832
		ast_cli(a->fd, "  Qualify      : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
3833
		ast_cli(a->fd, "\n");
3833
		ast_cli(a->fd, "\n");
3834
		peer_unref(peer);
3834
		peer_unref(peer);
3835
	} else {
3835
	} else {
3836
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3836
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3837
		ast_cli(a->fd, "\n");
3837
		ast_cli(a->fd, "\n");
3838
	}
3838
	}
3839

    
   
3839

   
3840
	return CLI_SUCCESS;
3840
	return CLI_SUCCESS;
3841
}
3841
}
3842

    
   
3842

   
3843
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3843
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3844
{
3844
{
3845
	int which = 0;
3845
	int which = 0;
3846
	struct iax2_peer *peer;
3846
	struct iax2_peer *peer;
3847
	char *res = NULL;
3847
	char *res = NULL;
3848
	int wordlen = strlen(word);
3848
	int wordlen = strlen(word);
3849
	struct ao2_iterator i;
3849
	struct ao2_iterator i;
3850

    
   
3850

   
3851
	i = ao2_iterator_init(peers, 0);
3851
	i = ao2_iterator_init(peers, 0);
3852
	while ((peer = ao2_iterator_next(&i))) {
3852
	while ((peer = ao2_iterator_next(&i))) {
3853
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3853
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3854
			&& (!flags || ast_test_flag64(peer, flags))) {
3854
			&& (!flags || ast_test_flag64(peer, flags))) {
3855
			res = ast_strdup(peer->name);
3855
			res = ast_strdup(peer->name);
3856
			peer_unref(peer);
3856
			peer_unref(peer);
3857
			break;
3857
			break;
3858
		}
3858
		}
3859
		peer_unref(peer);
3859
		peer_unref(peer);
3860
	}
3860
	}
3861
	ao2_iterator_destroy(&i);
3861
	ao2_iterator_destroy(&i);
3862

    
   
3862

   
3863
	return res;
3863
	return res;
3864
}
3864
}
3865

    
   
3865

   
3866
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3866
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3867
{
3867
{
3868
	struct iax_frame *cur;
3868
	struct iax_frame *cur;
3869
	int cnt = 0, dead = 0, final = 0, i = 0;
3869
	int cnt = 0, dead = 0, final = 0, i = 0;
3870

    
   
3870

   
3871
	switch (cmd) {
3871
	switch (cmd) {
3872
	case CLI_INIT:
3872
	case CLI_INIT:
3873
		e->command = "iax2 show stats";
3873
		e->command = "iax2 show stats";
3874
		e->usage =
3874
		e->usage =
3875
			"Usage: iax2 show stats\n"
3875
			"Usage: iax2 show stats\n"
3876
			"       Display statistics on IAX channel driver.\n";
3876
			"       Display statistics on IAX channel driver.\n";
3877
		return NULL;
3877
		return NULL;
3878
	case CLI_GENERATE:
3878
	case CLI_GENERATE:
3879
		return NULL;
3879
		return NULL;
3880
	}
3880
	}
3881

    
   
3881

   
3882
	if (a->argc != 3)
3882
	if (a->argc != 3)
3883
		return CLI_SHOWUSAGE;
3883
		return CLI_SHOWUSAGE;
3884

    
   
3884

   
3885
	for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3885
	for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3886
		ast_mutex_lock(&iaxsl[i]);
3886
		ast_mutex_lock(&iaxsl[i]);
3887
		AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3887
		AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3888
			if (cur->retries < 0)
3888
			if (cur->retries < 0)
3889
				dead++;
3889
				dead++;
3890
			if (cur->final)
3890
			if (cur->final)
3891
				final++;
3891
				final++;
3892
			cnt++;
3892
			cnt++;
3893
		}
3893
		}
3894
		ast_mutex_unlock(&iaxsl[i]);
3894
		ast_mutex_unlock(&iaxsl[i]);
3895
	}
3895
	}
3896

    
   
3896

   
3897
	ast_cli(a->fd, "    IAX Statistics\n");
3897
	ast_cli(a->fd, "    IAX Statistics\n");
3898
	ast_cli(a->fd, "---------------------\n");
3898
	ast_cli(a->fd, "---------------------\n");
3899
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3899
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3900
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3900
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3901
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3901
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3902
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3902
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3903

    
   
3903

   
3904
	trunk_timed = trunk_untimed = 0;
3904
	trunk_timed = trunk_untimed = 0;
3905
	if (trunk_maxmtu > trunk_nmaxmtu)
3905
	if (trunk_maxmtu > trunk_nmaxmtu)
3906
		trunk_nmaxmtu = trunk_maxmtu;
3906
		trunk_nmaxmtu = trunk_maxmtu;
3907

    
   
3907

   
3908
	return CLI_SUCCESS;
3908
	return CLI_SUCCESS;
3909
}
3909
}
3910

    
   
3910

   
3911
/*! \brief Set trunk MTU from CLI */
3911
/*! \brief Set trunk MTU from CLI */
3912
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3912
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3913
{
3913
{
3914
	int mtuv;
3914
	int mtuv;
3915

    
   
3915

   
3916
	switch (cmd) {
3916
	switch (cmd) {
3917
	case CLI_INIT:
3917
	case CLI_INIT:
3918
		e->command = "iax2 set mtu";
3918
		e->command = "iax2 set mtu";
3919
		e->usage =
3919
		e->usage =
3920
			"Usage: iax2 set mtu <value>\n"
3920
			"Usage: iax2 set mtu <value>\n"
3921
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
3921
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
3922
			"       zero to disable. Disabling means that the operating system\n"
3922
			"       zero to disable. Disabling means that the operating system\n"
3923
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
3923
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
3924
			"       packet exceeds the UDP payload size. This is substantially\n"
3924
			"       packet exceeds the UDP payload size. This is substantially\n"
3925
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3925
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3926
			"       greater for G.711 samples.\n";
3926
			"       greater for G.711 samples.\n";
3927
		return NULL;
3927
		return NULL;
3928
	case CLI_GENERATE:
3928
	case CLI_GENERATE:
3929
		return NULL;
3929
		return NULL;
3930
	}
3930
	}
3931

    
   
3931

   
3932
	if (a->argc != 4)
3932
	if (a->argc != 4)
3933
		return CLI_SHOWUSAGE;
3933
		return CLI_SHOWUSAGE;
3934
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3934
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3935
		mtuv = MAX_TRUNK_MTU;
3935
		mtuv = MAX_TRUNK_MTU;
3936
	else
3936
	else
3937
		mtuv = atoi(a->argv[3]);
3937
		mtuv = atoi(a->argv[3]);
3938

    
   
3938

   
3939
	if (mtuv == 0) {
3939
	if (mtuv == 0) {
3940
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
3940
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
3941
		global_max_trunk_mtu = 0;
3941
		global_max_trunk_mtu = 0;
3942
		return CLI_SUCCESS;
3942
		return CLI_SUCCESS;
3943
	}
3943
	}
3944
	if (mtuv < 172 || mtuv > 4000) {
3944
	if (mtuv < 172 || mtuv > 4000) {
3945
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
3945
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
3946
		return CLI_SHOWUSAGE;
3946
		return CLI_SHOWUSAGE;
3947
	}
3947
	}
3948
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
3948
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
3949
	global_max_trunk_mtu = mtuv;
3949
	global_max_trunk_mtu = mtuv;
3950
	return CLI_SUCCESS;
3950
	return CLI_SUCCESS;
3951
}
3951
}
3952

    
   
3952

   
3953
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3953
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3954
{
3954
{
3955
	struct iax2_dpcache *dp = NULL;
3955
	struct iax2_dpcache *dp = NULL;
3956
	char tmp[1024], *pc = NULL;
3956
	char tmp[1024], *pc = NULL;
3957
	int s, x, y;
3957
	int s, x, y;
3958
	struct timeval now = ast_tvnow();
3958
	struct timeval now = ast_tvnow();
3959

    
   
3959

   
3960
	switch (cmd) {
3960
	switch (cmd) {
3961
	case CLI_INIT:
3961
	case CLI_INIT:
3962
		e->command = "iax2 show cache";
3962
		e->command = "iax2 show cache";
3963
		e->usage =
3963
		e->usage =
3964
			"Usage: iax2 show cache\n"
3964
			"Usage: iax2 show cache\n"
3965
			"       Display currently cached IAX Dialplan results.\n";
3965
			"       Display currently cached IAX Dialplan results.\n";
3966
		return NULL;
3966
		return NULL;
3967
	case CLI_GENERATE:
3967
	case CLI_GENERATE:
3968
		return NULL;
3968
		return NULL;
3969
	}
3969
	}
3970

    
   
3970

   
3971
	AST_LIST_LOCK(&dpcache);
3971
	AST_LIST_LOCK(&dpcache);
3972

    
   
3972

   
3973
	ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
3973
	ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
3974

    
   
3974

   
3975
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
3975
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
3976
		s = dp->expiry.tv_sec - now.tv_sec;
3976
		s = dp->expiry.tv_sec - now.tv_sec;
3977
		tmp[0] = '\0';
3977
		tmp[0] = '\0';
3978
		if (dp->flags & CACHE_FLAG_EXISTS)
3978
		if (dp->flags & CACHE_FLAG_EXISTS)
3979
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
3979
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
3980
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
3980
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
3981
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
3981
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
3982
		if (dp->flags & CACHE_FLAG_CANEXIST)
3982
		if (dp->flags & CACHE_FLAG_CANEXIST)
3983
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
3983
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
3984
		if (dp->flags & CACHE_FLAG_PENDING)
3984
		if (dp->flags & CACHE_FLAG_PENDING)
3985
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
3985
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
3986
		if (dp->flags & CACHE_FLAG_TIMEOUT)
3986
		if (dp->flags & CACHE_FLAG_TIMEOUT)
3987
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
3987
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
3988
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
3988
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
3989
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
3989
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
3990
		if (dp->flags & CACHE_FLAG_MATCHMORE)
3990
		if (dp->flags & CACHE_FLAG_MATCHMORE)
3991
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
3991
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
3992
		if (dp->flags & CACHE_FLAG_UNKNOWN)
3992
		if (dp->flags & CACHE_FLAG_UNKNOWN)
3993
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
3993
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
3994
		/* Trim trailing pipe */
3994
		/* Trim trailing pipe */
3995
		if (!ast_strlen_zero(tmp)) {
3995
		if (!ast_strlen_zero(tmp)) {
3996
			tmp[strlen(tmp) - 1] = '\0';
3996
			tmp[strlen(tmp) - 1] = '\0';
3997
		} else {
3997
		} else {
3998
			ast_copy_string(tmp, "(none)", sizeof(tmp));
3998
			ast_copy_string(tmp, "(none)", sizeof(tmp));
3999
		}
3999
		}
4000
		y = 0;
4000
		y = 0;
4001
		pc = strchr(dp->peercontext, '@');
4001
		pc = strchr(dp->peercontext, '@');
4002
		if (!pc) {
4002
		if (!pc) {
4003
			pc = dp->peercontext;
4003
			pc = dp->peercontext;
4004
		} else {
4004
		} else {
4005
			pc++;
4005
			pc++;
4006
		}
4006
		}
4007
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4007
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4008
			if (dp->waiters[x] > -1)
4008
			if (dp->waiters[x] > -1)
4009
				y++;
4009
				y++;
4010
		}
4010
		}
4011
		if (s > 0) {
4011
		if (s > 0) {
4012
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4012
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4013
		} else {
4013
		} else {
4014
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4014
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4015
		}
4015
		}
4016
	}
4016
	}
4017

    
   
4017

   
4018
	AST_LIST_UNLOCK(&dpcache);
4018
	AST_LIST_UNLOCK(&dpcache);
4019

    
   
4019

   
4020
	return CLI_SUCCESS;
4020
	return CLI_SUCCESS;
4021
}
4021
}
4022

    
   
4022

   
4023
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4023
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4024

    
   
4024

   
4025
static void unwrap_timestamp(struct iax_frame *fr)
4025
static void unwrap_timestamp(struct iax_frame *fr)
4026
{
4026
{
4027
	/* Video mini frames only encode the lower 15 bits of the session
4027
	/* Video mini frames only encode the lower 15 bits of the session
4028
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4028
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4029
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4029
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4030
	const int lower_mask = (1 << ts_shift) - 1;
4030
	const int lower_mask = (1 << ts_shift) - 1;
4031
	const int upper_mask = ~lower_mask;
4031
	const int upper_mask = ~lower_mask;
4032
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
4032
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
4033

    
   
4033

   
4034
	if ( (fr->ts & upper_mask) == last_upper ) {
4034
	if ( (fr->ts & upper_mask) == last_upper ) {
4035
		const int x = fr->ts - iaxs[fr->callno]->last;
4035
		const int x = fr->ts - iaxs[fr->callno]->last;
4036
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
4036
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
4037

    
   
4037

   
4038
		if (x < -threshold) {
4038
		if (x < -threshold) {
4039
			/* Sudden big jump backwards in timestamp:
4039
			/* Sudden big jump backwards in timestamp:
4040
			   What likely happened here is that miniframe timestamp has circled but we haven't
4040
			   What likely happened here is that miniframe timestamp has circled but we haven't
4041
			   gotten the update from the main packet.  We'll just pretend that we did, and
4041
			   gotten the update from the main packet.  We'll just pretend that we did, and
4042
			   update the timestamp appropriately. */
4042
			   update the timestamp appropriately. */
4043
			fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4043
			fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
4044
			if (iaxdebug)
4044
			if (iaxdebug)
4045
				ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4045
				ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
4046
		} else if (x > threshold) {
4046
		} else if (x > threshold) {
4047
			/* Sudden apparent big jump forwards in timestamp:
4047
			/* Sudden apparent big jump forwards in timestamp:
4048
			   What's likely happened is this is an old miniframe belonging to the previous
4048
			   What's likely happened is this is an old miniframe belonging to the previous
4049
			   top 15 or 16-bit timestamp that has turned up out of order.
4049
			   top 15 or 16-bit timestamp that has turned up out of order.
4050
			   Adjust the timestamp appropriately. */
4050
			   Adjust the timestamp appropriately. */
4051
			fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4051
			fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
4052
			if (iaxdebug)
4052
			if (iaxdebug)
4053
				ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4053
				ast_debug(1, "schedule_delivery: pushed back timestamp\n");
4054
		}
4054
		}
4055
	}
4055
	}
4056
}
4056
}
4057

    
   
4057

   
4058
static int get_from_jb(const void *p);
4058
static int get_from_jb(const void *p);
4059

    
   
4059

   
4060
static void update_jbsched(struct chan_iax2_pvt *pvt)
4060
static void update_jbsched(struct chan_iax2_pvt *pvt)
4061
{
4061
{
4062
	int when;
4062
	int when;
4063

    
   
4063

   
4064
	when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4064
	when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
4065

    
   
4065

   
4066
	when = jb_next(pvt->jb) - when;
4066
	when = jb_next(pvt->jb) - when;
4067

    
   
4067

   
4068
	if (when <= 0) {
4068
	if (when <= 0) {
4069
		/* XXX should really just empty until when > 0.. */
4069
		/* XXX should really just empty until when > 0.. */
4070
		when = 1;
4070
		when = 1;
4071
	}
4071
	}
4072

    
   
4072

   
4073
	pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4073
	pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
4074
		CALLNO_TO_PTR(pvt->callno));
4074
		CALLNO_TO_PTR(pvt->callno));
4075
}
4075
}
4076

    
   
4076

   
4077
static void __get_from_jb(const void *p)
4077
static void __get_from_jb(const void *p)
4078
{
4078
{
4079
	int callno = PTR_TO_CALLNO(p);
4079
	int callno = PTR_TO_CALLNO(p);
4080
	struct chan_iax2_pvt *pvt = NULL;
4080
	struct chan_iax2_pvt *pvt = NULL;
4081
	struct iax_frame *fr;
4081
	struct iax_frame *fr;
4082
	jb_frame frame;
4082
	jb_frame frame;
4083
	int ret;
4083
	int ret;
4084
	long ms;
4084
	long ms;
4085
	long next;
4085
	long next;
4086
	struct timeval now = ast_tvnow();
4086
	struct timeval now = ast_tvnow();
4087

    
   
4087

   
4088
	/* Make sure we have a valid private structure before going on */
4088
	/* Make sure we have a valid private structure before going on */
4089
	ast_mutex_lock(&iaxsl[callno]);
4089
	ast_mutex_lock(&iaxsl[callno]);
4090
	pvt = iaxs[callno];
4090
	pvt = iaxs[callno];
4091
	if (!pvt) {
4091
	if (!pvt) {
4092
		/* No go! */
4092
		/* No go! */
4093
		ast_mutex_unlock(&iaxsl[callno]);
4093
		ast_mutex_unlock(&iaxsl[callno]);
4094
		return;
4094
		return;
4095
	}
4095
	}
4096

    
   
4096

   
4097
	pvt->jbid = -1;
4097
	pvt->jbid = -1;
4098

    
   
4098

   
4099
	/* round up a millisecond since ast_sched_runq does; */
4099
	/* round up a millisecond since ast_sched_runq does; */
4100
	/* prevents us from spinning while waiting for our now */
4100
	/* prevents us from spinning while waiting for our now */
4101
	/* to catch up with runq's now */
4101
	/* to catch up with runq's now */
4102
	now.tv_usec += 1000;
4102
	now.tv_usec += 1000;
4103

    
   
4103

   
4104
	ms = ast_tvdiff_ms(now, pvt->rxcore);
4104
	ms = ast_tvdiff_ms(now, pvt->rxcore);
4105

    
   
4105

   
4106
	if(ms >= (next = jb_next(pvt->jb))) {
4106
	if(ms >= (next = jb_next(pvt->jb))) {
4107
		struct ast_format *voicefmt;
4107
		struct ast_format *voicefmt;
4108
		voicefmt = ast_format_compatibility_bitfield2format(pvt->voiceformat);
4108
		voicefmt = ast_format_compatibility_bitfield2format(pvt->voiceformat);
4109
		ret = jb_get(pvt->jb, &frame, ms, voicefmt ? ast_format_get_default_ms(voicefmt) : 20);
4109
		ret = jb_get(pvt->jb, &frame, ms, voicefmt ? ast_format_get_default_ms(voicefmt) : 20);
4110
		switch(ret) {
4110
		switch(ret) {
4111
		case JB_OK:
4111
		case JB_OK:
4112
			fr = frame.data;
4112
			fr = frame.data;
4113
			__do_deliver(fr);
4113
			__do_deliver(fr);
4114
			/* __do_deliver() can cause the call to disappear */
4114
			/* __do_deliver() can cause the call to disappear */
4115
			pvt = iaxs[callno];
4115
			pvt = iaxs[callno];