Review Board 1.7.16


IAX2: refactor nativebridge transfer.

Review Request #2602 - Created June 8, 2013 and submitted

Alec Davis
1.8 to trunk
Reviewers
asterisk-dev
Asterisk
remove triple checking of iaxs[fr->callno]->transferring

reduce indentation.

I've done this as 2 step, so that reviewers are confident nothing breaks.

 

Changes between revision 2 and 3

1 2 3
1 2 3

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

    
   
18

   
19
/*! \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
/*** MODULEINFO
34
/*** MODULEINFO
35
	<use type="external">crypto</use>
35
	<use type="external">crypto</use>
36
	<support_level>core</support_level>
36
	<support_level>core</support_level>
37
 ***/
37
 ***/
38

    
   
38

   
39
#include "asterisk.h"
39
#include "asterisk.h"
40

    
   
40

   
41
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42

    
   
42

   
43
#include <sys/mman.h>
43
#include <sys/mman.h>
44
#include <dirent.h>
44
#include <dirent.h>
45
#include <sys/socket.h>
45
#include <sys/socket.h>
46
#include <netinet/in.h>
46
#include <netinet/in.h>
47
#include <arpa/inet.h>
47
#include <arpa/inet.h>
48
#include <netinet/in_systm.h>
48
#include <netinet/in_systm.h>
49
#include <netinet/ip.h>
49
#include <netinet/ip.h>
50
#include <sys/time.h>
50
#include <sys/time.h>
51
#include <sys/signal.h>
51
#include <sys/signal.h>
52
#include <signal.h>
52
#include <signal.h>
53
#include <strings.h>
53
#include <strings.h>
54
#include <netdb.h>
54
#include <netdb.h>
55
#include <fcntl.h>
55
#include <fcntl.h>
56
#include <sys/stat.h>
56
#include <sys/stat.h>
57
#include <regex.h>
57
#include <regex.h>
58

    
   
58

   
59
#include "asterisk/paths.h"	/* need ast_config_AST_DATA_DIR for firmware */
59
#include "asterisk/paths.h"	/* need ast_config_AST_DATA_DIR for firmware */
60

    
   
60

   
61
#include "asterisk/lock.h"
61
#include "asterisk/lock.h"
62
#include "asterisk/frame.h" 
62
#include "asterisk/frame.h" 
63
#include "asterisk/channel.h"
63
#include "asterisk/channel.h"
64
#include "asterisk/module.h"
64
#include "asterisk/module.h"
65
#include "asterisk/pbx.h"
65
#include "asterisk/pbx.h"
66
#include "asterisk/sched.h"
66
#include "asterisk/sched.h"
67
#include "asterisk/io.h"
67
#include "asterisk/io.h"
68
#include "asterisk/config.h"
68
#include "asterisk/config.h"
69
#include "asterisk/cli.h"
69
#include "asterisk/cli.h"
70
#include "asterisk/translate.h"
70
#include "asterisk/translate.h"
71
#include "asterisk/md5.h"
71
#include "asterisk/md5.h"
72
#include "asterisk/cdr.h"
72
#include "asterisk/cdr.h"
73
#include "asterisk/crypto.h"
73
#include "asterisk/crypto.h"
74
#include "asterisk/acl.h"
74
#include "asterisk/acl.h"
75
#include "asterisk/manager.h"
75
#include "asterisk/manager.h"
76
#include "asterisk/callerid.h"
76
#include "asterisk/callerid.h"
77
#include "asterisk/app.h"
77
#include "asterisk/app.h"
78
#include "asterisk/astdb.h"
78
#include "asterisk/astdb.h"
79
#include "asterisk/musiconhold.h"
79
#include "asterisk/musiconhold.h"
80
#include "asterisk/features.h"
80
#include "asterisk/features.h"
81
#include "asterisk/utils.h"
81
#include "asterisk/utils.h"
82
#include "asterisk/causes.h"
82
#include "asterisk/causes.h"
83
#include "asterisk/localtime.h"
83
#include "asterisk/localtime.h"
84
#include "asterisk/dnsmgr.h"
84
#include "asterisk/dnsmgr.h"
85
#include "asterisk/devicestate.h"
85
#include "asterisk/devicestate.h"
86
#include "asterisk/netsock.h"
86
#include "asterisk/netsock.h"
87
#include "asterisk/stringfields.h"
87
#include "asterisk/stringfields.h"
88
#include "asterisk/linkedlists.h"
88
#include "asterisk/linkedlists.h"
89
#include "asterisk/event.h"
89
#include "asterisk/event.h"
90
#include "asterisk/astobj2.h"
90
#include "asterisk/astobj2.h"
91
#include "asterisk/timing.h"
91
#include "asterisk/timing.h"
92
#include "asterisk/taskprocessor.h"
92
#include "asterisk/taskprocessor.h"
93
#include "asterisk/test.h"
93
#include "asterisk/test.h"
94
#include "asterisk/data.h"
94
#include "asterisk/data.h"
95
#include "asterisk/netsock2.h"
95
#include "asterisk/netsock2.h"
96

    
   
96

   
97
#include "iax2.h"
97
#include "iax2.h"
98
#include "iax2-parser.h"
98
#include "iax2-parser.h"
99
#include "iax2-provision.h"
99
#include "iax2-provision.h"
100
#include "jitterbuf.h"
100
#include "jitterbuf.h"
101

    
   
101

   
102
/*** DOCUMENTATION
102
/*** DOCUMENTATION
103
	<application name="IAX2Provision" language="en_US">
103
	<application name="IAX2Provision" language="en_US">
104
		<synopsis>
104
		<synopsis>
105
			Provision a calling IAXy with a given template.
105
			Provision a calling IAXy with a given template.
106
		</synopsis>
106
		</synopsis>
107
		<syntax>
107
		<syntax>
108
			<parameter name="template">
108
			<parameter name="template">
109
				<para>If not specified, defaults to <literal>default</literal>.</para>
109
				<para>If not specified, defaults to <literal>default</literal>.</para>
110
			</parameter>
110
			</parameter>
111
		</syntax>
111
		</syntax>
112
		<description>
112
		<description>
113
			<para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
113
			<para>Provisions the calling IAXy (assuming the calling entity is in fact an IAXy) with the
114
			given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
114
			given <replaceable>template</replaceable>. Returns <literal>-1</literal> on error
115
			or <literal>0</literal> on success.</para>
115
			or <literal>0</literal> on success.</para>
116
		</description>
116
		</description>
117
	</application>
117
	</application>
118
	<function name="IAXPEER" language="en_US">
118
	<function name="IAXPEER" language="en_US">
119
		<synopsis>
119
		<synopsis>
120
			Gets IAX peer information.
120
			Gets IAX peer information.
121
		</synopsis>
121
		</synopsis>
122
		<syntax>
122
		<syntax>
123
			<parameter name="peername" required="true">
123
			<parameter name="peername" required="true">
124
				<enumlist>
124
				<enumlist>
125
					<enum name="CURRENTCHANNEL">
125
					<enum name="CURRENTCHANNEL">
126
						<para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
126
						<para>If <replaceable>peername</replaceable> is specified to this value, return the IP address of the
127
						endpoint of the current channel</para>
127
						endpoint of the current channel</para>
128
					</enum>
128
					</enum>
129
				</enumlist>
129
				</enumlist>
130
			</parameter>
130
			</parameter>
131
			<parameter name="item">
131
			<parameter name="item">
132
				<para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
132
				<para>If <replaceable>peername</replaceable> is specified, valid items are:</para>
133
				<enumlist>
133
				<enumlist>
134
					<enum name="ip">
134
					<enum name="ip">
135
						<para>(default) The IP address.</para>
135
						<para>(default) The IP address.</para>
136
					</enum>
136
					</enum>
137
					<enum name="status">
137
					<enum name="status">
138
						<para>The peer's status (if <literal>qualify=yes</literal>)</para>
138
						<para>The peer's status (if <literal>qualify=yes</literal>)</para>
139
					</enum>
139
					</enum>
140
					<enum name="mailbox">
140
					<enum name="mailbox">
141
						<para>The configured mailbox.</para>
141
						<para>The configured mailbox.</para>
142
					</enum>
142
					</enum>
143
					<enum name="context">
143
					<enum name="context">
144
						<para>The configured context.</para>
144
						<para>The configured context.</para>
145
					</enum>
145
					</enum>
146
					<enum name="expire">
146
					<enum name="expire">
147
						<para>The epoch time of the next expire.</para>
147
						<para>The epoch time of the next expire.</para>
148
					</enum>
148
					</enum>
149
					<enum name="dynamic">
149
					<enum name="dynamic">
150
						<para>Is it dynamic? (yes/no).</para>
150
						<para>Is it dynamic? (yes/no).</para>
151
					</enum>
151
					</enum>
152
					<enum name="callerid_name">
152
					<enum name="callerid_name">
153
						<para>The configured Caller ID name.</para>
153
						<para>The configured Caller ID name.</para>
154
					</enum>
154
					</enum>
155
					<enum name="callerid_num">
155
					<enum name="callerid_num">
156
						<para>The configured Caller ID number.</para>
156
						<para>The configured Caller ID number.</para>
157
					</enum>
157
					</enum>
158
					<enum name="codecs">
158
					<enum name="codecs">
159
						<para>The configured codecs.</para>
159
						<para>The configured codecs.</para>
160
					</enum>
160
					</enum>
161
					<enum name="codec[x]">
161
					<enum name="codec[x]">
162
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning
162
						<para>Preferred codec index number <replaceable>x</replaceable> (beginning
163
						with <literal>0</literal>)</para>
163
						with <literal>0</literal>)</para>
164
					</enum>
164
					</enum>
165
				</enumlist>
165
				</enumlist>
166
			</parameter>
166
			</parameter>
167
		</syntax>
167
		</syntax>
168
		<description>
168
		<description>
169
			<para>Gets information associated with the specified IAX2 peer.</para>
169
			<para>Gets information associated with the specified IAX2 peer.</para>
170
		</description>
170
		</description>
171
		<see-also>
171
		<see-also>
172
			<ref type="function">SIPPEER</ref>
172
			<ref type="function">SIPPEER</ref>
173
		</see-also>
173
		</see-also>
174
	</function>
174
	</function>
175
	<function name="IAXVAR" language="en_US">
175
	<function name="IAXVAR" language="en_US">
176
		<synopsis>
176
		<synopsis>
177
			Sets or retrieves a remote variable.
177
			Sets or retrieves a remote variable.
178
		</synopsis>
178
		</synopsis>
179
		<syntax>
179
		<syntax>
180
			<parameter name="varname" required="true" />
180
			<parameter name="varname" required="true" />
181
		</syntax>
181
		</syntax>
182
		<description>
182
		<description>
183
			<para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
183
			<para>Gets or sets a variable that is sent to a remote IAX2 peer during call setup.</para>
184
		</description>
184
		</description>
185
	</function>
185
	</function>
186
	<manager name="IAXpeers" language="en_US">
186
	<manager name="IAXpeers" language="en_US">
187
		<synopsis>
187
		<synopsis>
188
			List IAX peers.
188
			List IAX peers.
189
		</synopsis>
189
		</synopsis>
190
		<syntax>
190
		<syntax>
191
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
191
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
192
		</syntax>
192
		</syntax>
193
		<description>
193
		<description>
194
		</description>
194
		</description>
195
	</manager>
195
	</manager>
196
	<manager name="IAXpeerlist" language="en_US">
196
	<manager name="IAXpeerlist" language="en_US">
197
		<synopsis>
197
		<synopsis>
198
			List IAX Peers.
198
			List IAX Peers.
199
		</synopsis>
199
		</synopsis>
200
		<syntax>
200
		<syntax>
201
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
201
			<xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
202
		</syntax>
202
		</syntax>
203
		<description>
203
		<description>
204
			<para>List all the IAX peers.</para>
204
			<para>List all the IAX peers.</para>
205
		</description>
205
		</description>
206
	</manager>
206
	</manager>
207
	<manager name="IAXnetstats" language="en_US">
207
	<manager name="IAXnetstats" language="en_US">
208
		<synopsis>
208
		<synopsis>
209
			Show IAX Netstats.
209
			Show IAX Netstats.
210
		</synopsis>
210
		</synopsis>
211
		<syntax />
211
		<syntax />
212
		<description>
212
		<description>
213
			<para>Show IAX channels network statistics.</para>
213
			<para>Show IAX channels network statistics.</para>
214
		</description>
214
		</description>
215
	</manager>
215
	</manager>
216
	<manager name="IAXregistry" language="en_US">
216
	<manager name="IAXregistry" language="en_US">
217
		<synopsis>
217
		<synopsis>
218
			Show IAX registrations.
218
			Show IAX registrations.
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
			<para>Show IAX registrations.</para>
224
			<para>Show IAX registrations.</para>
225
		</description>
225
		</description>
226
	</manager>
226
	</manager>
227
 ***/
227
 ***/
228

    
   
228

   
229
/* Define SCHED_MULTITHREADED to run the scheduler in a special
229
/* Define SCHED_MULTITHREADED to run the scheduler in a special
230
   multithreaded mode. */
230
   multithreaded mode. */
231
#define SCHED_MULTITHREADED
231
#define SCHED_MULTITHREADED
232

    
   
232

   
233
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
233
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
234
   thread is actually doing. */
234
   thread is actually doing. */
235
#define DEBUG_SCHED_MULTITHREAD
235
#define DEBUG_SCHED_MULTITHREAD
236

    
   
236

   
237

    
   
237

   
238
#ifdef SO_NO_CHECK
238
#ifdef SO_NO_CHECK
239
static int nochecksums = 0;
239
static int nochecksums = 0;
240
#endif
240
#endif
241

    
   
241

   
242
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
242
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
243
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
243
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
244

    
   
244

   
245
#define DEFAULT_THREAD_COUNT 10
245
#define DEFAULT_THREAD_COUNT 10
246
#define DEFAULT_MAX_THREAD_COUNT 100
246
#define DEFAULT_MAX_THREAD_COUNT 100
247
#define DEFAULT_RETRY_TIME 1000
247
#define DEFAULT_RETRY_TIME 1000
248
#define MEMORY_SIZE 100
248
#define MEMORY_SIZE 100
249
#define DEFAULT_DROP 3
249
#define DEFAULT_DROP 3
250

    
   
250

   
251
#define DEBUG_SUPPORT
251
#define DEBUG_SUPPORT
252

    
   
252

   
253
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
253
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
254

    
   
254

   
255
/* Sample over last 100 units to determine historic jitter */
255
/* Sample over last 100 units to determine historic jitter */
256
#define GAMMA (0.01)
256
#define GAMMA (0.01)
257

    
   
257

   
258
static struct ast_codec_pref prefs;
258
static struct ast_codec_pref prefs;
259

    
   
259

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

    
   
261

   
262

    
   
262

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

    
   
266

   
267
static int global_max_trunk_mtu;	/*!< Maximum MTU, 0 if not used */
267
static int global_max_trunk_mtu;	/*!< Maximum MTU, 0 if not used */
268
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;	/*!< Trunk MTU statistics */
268
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;	/*!< Trunk MTU statistics */
269

    
   
269

   
270
#define DEFAULT_CONTEXT "default"
270
#define DEFAULT_CONTEXT "default"
271

    
   
271

   
272
static char default_parkinglot[AST_MAX_CONTEXT];
272
static char default_parkinglot[AST_MAX_CONTEXT];
273

    
   
273

   
274
static char language[MAX_LANGUAGE] = "";
274
static char language[MAX_LANGUAGE] = "";
275
static char regcontext[AST_MAX_CONTEXT] = "";
275
static char regcontext[AST_MAX_CONTEXT] = "";
276

    
   
276

   
277
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
277
static struct ast_event_sub *network_change_event_subscription; /*!< subscription id for network change events */
278
static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
278
static struct ast_event_sub *acl_change_event_subscription; /*!< subscription id for ACL change events */
279
static int network_change_event_sched_id = -1;
279
static int network_change_event_sched_id = -1;
280

    
   
280

   
281
static int maxauthreq = 3;
281
static int maxauthreq = 3;
282
static int max_retries = 4;
282
static int max_retries = 4;
283
static int ping_time = 21;
283
static int ping_time = 21;
284
static int lagrq_time = 10;
284
static int lagrq_time = 10;
285
static int maxjitterbuffer=1000;
285
static int maxjitterbuffer=1000;
286
static int resyncthreshold=1000;
286
static int resyncthreshold=1000;
287
static int maxjitterinterps=10;
287
static int maxjitterinterps=10;
288
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
288
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
289

    
   
289

   
290
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
290
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
291

    
   
291

   
292
static int trunkfreq = 20;
292
static int trunkfreq = 20;
293
static int trunkmaxsize = MAX_TRUNKDATA;
293
static int trunkmaxsize = MAX_TRUNKDATA;
294

    
   
294

   
295
static int authdebug = 0;
295
static int authdebug = 0;
296
static int autokill = 0;
296
static int autokill = 0;
297
static int iaxcompat = 0;
297
static int iaxcompat = 0;
298
static int last_authmethod = 0;
298
static int last_authmethod = 0;
299

    
   
299

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

    
   
301

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

    
   
303

   
304
static struct {
304
static struct {
305
	unsigned int tos;
305
	unsigned int tos;
306
	unsigned int cos;
306
	unsigned int cos;
307
} qos = { 0, 0 };
307
} qos = { 0, 0 };
308

    
   
308

   
309
static int min_reg_expire;
309
static int min_reg_expire;
310
static int max_reg_expire;
310
static int max_reg_expire;
311

    
   
311

   
312
static int srvlookup = 0;
312
static int srvlookup = 0;
313

    
   
313

   
314
static struct ast_timer *timer;				/* Timer for trunking */
314
static struct ast_timer *timer;				/* Timer for trunking */
315

    
   
315

   
316
static struct ast_netsock_list *netsock;
316
static struct ast_netsock_list *netsock;
317
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
317
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
318
static int defaultsockfd = -1;
318
static int defaultsockfd = -1;
319

    
   
319

   
320
static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
320
static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
321

    
   
321

   
322
/* Ethernet, etc */
322
/* Ethernet, etc */
323
#define IAX_CAPABILITY_FULLBANDWIDTH	0xFFFF
323
#define IAX_CAPABILITY_FULLBANDWIDTH	0xFFFF
324
/* T1, maybe ISDN */
324
/* T1, maybe ISDN */
325
#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
325
#define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
326
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) &      \
326
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR) &      \
327
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) &    \
327
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SLINEAR16) &    \
328
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) &       \
328
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN7) &       \
329
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) &      \
329
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_SIREN14) &      \
330
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) &         \
330
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G719) &         \
331
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) &         \
331
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ULAW) &         \
332
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) &         \
332
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ALAW) &         \
333
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
333
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G722))
334
/* A modem */
334
/* A modem */
335
#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
335
#define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
336
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) &         \
336
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G726) &         \
337
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) &    \
337
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G726_AAL2) &    \
338
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
338
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_ADPCM))
339

    
   
339

   
340
#define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
340
#define IAX_CAPABILITY_LOWFREE      (IAX_CAPABILITY_LOWBANDWIDTH & \
341
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
341
                     ~ast_format_id_to_old_bitfield(AST_FORMAT_G723_1))
342

    
   
342

   
343

    
   
343

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

    
   
347

   
348
/* if a pvt has encryption setup done and is running on the call */
348
/* if a pvt has encryption setup done and is running on the call */
349
#define IAX_CALLENCRYPTED(pvt) \
349
#define IAX_CALLENCRYPTED(pvt) \
350
	(ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
350
	(ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
351

    
   
351

   
352
#define IAX_DEBUGDIGEST(msg, key) do { \
352
#define IAX_DEBUGDIGEST(msg, key) do { \
353
		int idx; \
353
		int idx; \
354
		char digest[33] = ""; \
354
		char digest[33] = ""; \
355
		\
355
		\
356
		if (!iaxdebug) \
356
		if (!iaxdebug) \
357
			break; \
357
			break; \
358
		\
358
		\
359
		for (idx = 0; idx < 16; idx++) \
359
		for (idx = 0; idx < 16; idx++) \
360
			sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
360
			sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
361
		\
361
		\
362
		ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
362
		ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
363
	} while(0)
363
	} while(0)
364

    
   
364

   
365
static struct io_context *io;
365
static struct io_context *io;
366
static struct ast_sched_context *sched;
366
static struct ast_sched_context *sched;
367

    
   
367

   
368
#define DONT_RESCHEDULE -2
368
#define DONT_RESCHEDULE -2
369

    
   
369

   
370
static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
370
static iax2_format iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
371

    
   
371

   
372
static int iaxdebug = 0;
372
static int iaxdebug = 0;
373

    
   
373

   
374
static int iaxtrunkdebug = 0;
374
static int iaxtrunkdebug = 0;
375

    
   
375

   
376
static int test_losspct = 0;
376
static int test_losspct = 0;
377
#ifdef IAXTESTS
377
#ifdef IAXTESTS
378
static int test_late = 0;
378
static int test_late = 0;
379
static int test_resync = 0;
379
static int test_resync = 0;
380
static int test_jit = 0;
380
static int test_jit = 0;
381
static int test_jitpct = 0;
381
static int test_jitpct = 0;
382
#endif /* IAXTESTS */
382
#endif /* IAXTESTS */
383

    
   
383

   
384
static char accountcode[AST_MAX_ACCOUNT_CODE];
384
static char accountcode[AST_MAX_ACCOUNT_CODE];
385
static char mohinterpret[MAX_MUSICCLASS];
385
static char mohinterpret[MAX_MUSICCLASS];
386
static char mohsuggest[MAX_MUSICCLASS];
386
static char mohsuggest[MAX_MUSICCLASS];
387
static int amaflags = 0;
387
static int amaflags = 0;
388
static int adsi = 0;
388
static int adsi = 0;
389
static int delayreject = 0;
389
static int delayreject = 0;
390
static int iax2_encryption = 0;
390
static int iax2_encryption = 0;
391

    
   
391

   
392
static struct ast_flags64 globalflags = { 0 };
392
static struct ast_flags64 globalflags = { 0 };
393

    
   
393

   
394
static pthread_t netthreadid = AST_PTHREADT_NULL;
394
static pthread_t netthreadid = AST_PTHREADT_NULL;
395

    
   
395

   
396
enum iax2_state {
396
enum iax2_state {
397
	IAX_STATE_STARTED =			(1 << 0),
397
	IAX_STATE_STARTED =			(1 << 0),
398
	IAX_STATE_AUTHENTICATED =	(1 << 1),
398
	IAX_STATE_AUTHENTICATED =	(1 << 1),
399
	IAX_STATE_TBD =				(1 << 2),
399
	IAX_STATE_TBD =				(1 << 2),
400
};
400
};
401

    
   
401

   
402
struct iax2_context {
402
struct iax2_context {
403
	char context[AST_MAX_CONTEXT];
403
	char context[AST_MAX_CONTEXT];
404
	struct iax2_context *next;
404
	struct iax2_context *next;
405
};
405
};
406

    
   
406

   
407

    
   
407

   
408
#define	IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
408
#define	IAX_HASCALLERID         (uint64_t)(1 << 0)    /*!< CallerID has been specified */
409
#define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
409
#define IAX_DELME               (uint64_t)(1 << 1)    /*!< Needs to be deleted */
410
#define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
410
#define IAX_TEMPONLY            (uint64_t)(1 << 2)    /*!< Temporary (realtime) */
411
#define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
411
#define IAX_TRUNK               (uint64_t)(1 << 3)    /*!< Treat as a trunk */
412
#define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
412
#define IAX_NOTRANSFER          (uint64_t)(1 << 4)    /*!< Don't native bridge */
413
#define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
413
#define IAX_USEJITTERBUF        (uint64_t)(1 << 5)    /*!< Use jitter buffer */
414
#define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
414
#define IAX_DYNAMIC             (uint64_t)(1 << 6)    /*!< dynamic peer */
415
#define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
415
#define IAX_SENDANI             (uint64_t)(1 << 7)    /*!< Send ANI along with CallerID */
416
#define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
416
#define IAX_RTSAVE_SYSNAME      (uint64_t)(1 << 8)    /*!< Save Systname on Realtime Updates */
417
#define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
417
#define IAX_ALREADYGONE         (uint64_t)(1 << 9)    /*!< Already disconnected */
418
#define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
418
#define IAX_PROVISION           (uint64_t)(1 << 10)   /*!< This is a provisioning request */
419
#define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
419
#define IAX_QUELCH              (uint64_t)(1 << 11)   /*!< Whether or not we quelch audio */
420
#define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
420
#define IAX_ENCRYPTED           (uint64_t)(1 << 12)   /*!< Whether we should assume encrypted tx/rx */
421
#define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
421
#define IAX_KEYPOPULATED        (uint64_t)(1 << 13)   /*!< Whether we have a key populated */
422
#define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
422
#define IAX_CODEC_USER_FIRST    (uint64_t)(1 << 14)   /*!< are we willing to let the other guy choose the codec? */
423
#define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
423
#define IAX_CODEC_NOPREFS       (uint64_t)(1 << 15)   /*!< Force old behaviour by turning off prefs */
424
#define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
424
#define IAX_CODEC_NOCAP         (uint64_t)(1 << 16)   /*!< only consider requested format and ignore capabilities*/
425
#define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
425
#define IAX_RTCACHEFRIENDS      (uint64_t)(1 << 17)   /*!< let realtime stay till your reload */
426
#define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
426
#define IAX_RTUPDATE            (uint64_t)(1 << 18)   /*!< Send a realtime update */
427
#define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
427
#define IAX_RTAUTOCLEAR         (uint64_t)(1 << 19)   /*!< erase me on expire */
428
#define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
428
#define IAX_FORCEJITTERBUF      (uint64_t)(1 << 20)   /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
429
#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
429
#define IAX_RTIGNOREREGEXPIRE   (uint64_t)(1 << 21)   /*!< When using realtime, ignore registration expiration */
430
#define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
430
#define IAX_TRUNKTIMESTAMPS     (uint64_t)(1 << 22)   /*!< Send trunk timestamps */
431
#define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
431
#define IAX_TRANSFERMEDIA       (uint64_t)(1 << 23)   /*!< When doing IAX2 transfers, transfer media only */
432
#define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
432
#define IAX_MAXAUTHREQ          (uint64_t)(1 << 24)   /*!< Maximum outstanding AUTHREQ restriction is in place */
433
#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 */
433
#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 */
434
#define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
434
#define IAX_ALLOWFWDOWNLOAD     (uint64_t)(1 << 26)   /*!< Allow the FWDOWNL command? */
435
#define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
435
#define IAX_IMMEDIATE           (uint64_t)(1 << 27)   /*!< Allow immediate off-hook to extension s */
436
#define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
436
#define IAX_SENDCONNECTEDLINE   (uint64_t)(1 << 28)   /*!< Allow sending of connected line updates */
437
#define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
437
#define IAX_RECVCONNECTEDLINE   (uint64_t)(1 << 29)   /*!< Allow receiving of connected line updates */
438
#define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
438
#define IAX_FORCE_ENCRYPT       (uint64_t)(1 << 30)   /*!< Forces call encryption, if encryption not possible hangup */
439
#define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
439
#define IAX_SHRINKCALLERID      (uint64_t)(1 << 31)   /*!< Turn on and off caller id shrinking */
440
static int global_rtautoclear = 120;
440
static int global_rtautoclear = 120;
441

    
   
441

   
442
static int reload_config(int forced_reload);
442
static int reload_config(int forced_reload);
443

    
   
443

   
444
/*!
444
/*!
445
 * \brief Call token validation settings.
445
 * \brief Call token validation settings.
446
 */
446
 */
447
enum calltoken_peer_enum {
447
enum calltoken_peer_enum {
448
	/*! \brief Default calltoken required unless the ip is in the ignorelist */
448
	/*! \brief Default calltoken required unless the ip is in the ignorelist */
449
	CALLTOKEN_DEFAULT = 0,
449
	CALLTOKEN_DEFAULT = 0,
450
	/*! \brief Require call token validation. */
450
	/*! \brief Require call token validation. */
451
	CALLTOKEN_YES = 1,
451
	CALLTOKEN_YES = 1,
452
	/*! \brief Require call token validation after a successful registration
452
	/*! \brief Require call token validation after a successful registration
453
	 *         using call token validation occurs. */
453
	 *         using call token validation occurs. */
454
	CALLTOKEN_AUTO = 2,
454
	CALLTOKEN_AUTO = 2,
455
	/*! \brief Do not require call token validation. */
455
	/*! \brief Do not require call token validation. */
456
	CALLTOKEN_NO = 3,
456
	CALLTOKEN_NO = 3,
457
};
457
};
458

    
   
458

   
459
struct iax2_user {
459
struct iax2_user {
460
	AST_DECLARE_STRING_FIELDS(
460
	AST_DECLARE_STRING_FIELDS(
461
		AST_STRING_FIELD(name);
461
		AST_STRING_FIELD(name);
462
		AST_STRING_FIELD(secret);
462
		AST_STRING_FIELD(secret);
463
		AST_STRING_FIELD(dbsecret);
463
		AST_STRING_FIELD(dbsecret);
464
		AST_STRING_FIELD(accountcode);
464
		AST_STRING_FIELD(accountcode);
465
		AST_STRING_FIELD(mohinterpret);
465
		AST_STRING_FIELD(mohinterpret);
466
		AST_STRING_FIELD(mohsuggest);
466
		AST_STRING_FIELD(mohsuggest);
467
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
467
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
468
		AST_STRING_FIELD(language);
468
		AST_STRING_FIELD(language);
469
		AST_STRING_FIELD(cid_num);
469
		AST_STRING_FIELD(cid_num);
470
		AST_STRING_FIELD(cid_name);
470
		AST_STRING_FIELD(cid_name);
471
		AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
471
		AST_STRING_FIELD(parkinglot);           /*!< Default parkinglot for device */
472
	);
472
	);
473

    
   
473

   
474
	int authmethods;
474
	int authmethods;
475
	int encmethods;
475
	int encmethods;
476
	int amaflags;
476
	int amaflags;
477
	int adsi;
477
	int adsi;
478
	uint64_t flags;
478
	uint64_t flags;
479
	iax2_format capability;
479
	iax2_format capability;
480
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
480
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
481
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
481
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
482
	struct ast_codec_pref prefs;
482
	struct ast_codec_pref prefs;
483
	struct ast_acl_list *acl;
483
	struct ast_acl_list *acl;
484
	struct iax2_context *contexts;
484
	struct iax2_context *contexts;
485
	struct ast_variable *vars;
485
	struct ast_variable *vars;
486
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
486
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
487
};
487
};
488

    
   
488

   
489
struct iax2_peer {
489
struct iax2_peer {
490
	AST_DECLARE_STRING_FIELDS(
490
	AST_DECLARE_STRING_FIELDS(
491
		AST_STRING_FIELD(name);
491
		AST_STRING_FIELD(name);
492
		AST_STRING_FIELD(username);
492
		AST_STRING_FIELD(username);
493
		AST_STRING_FIELD(description);		/*!< Description of the peer */
493
		AST_STRING_FIELD(description);		/*!< Description of the peer */
494
		AST_STRING_FIELD(secret);
494
		AST_STRING_FIELD(secret);
495
		AST_STRING_FIELD(dbsecret);
495
		AST_STRING_FIELD(dbsecret);
496
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
496
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
497

    
   
497

   
498
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
498
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
499
		AST_STRING_FIELD(context);      /*!< For transfers only */
499
		AST_STRING_FIELD(context);      /*!< For transfers only */
500
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
500
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
501
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
501
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
502
		AST_STRING_FIELD(mohinterpret);
502
		AST_STRING_FIELD(mohinterpret);
503
		AST_STRING_FIELD(mohsuggest);
503
		AST_STRING_FIELD(mohsuggest);
504
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
504
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
505
		/* Suggested caller id if registering */
505
		/* Suggested caller id if registering */
506
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
506
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
507
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
507
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
508
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
508
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
509
		AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
509
		AST_STRING_FIELD(parkinglot);   /*!< Default parkinglot for device */
510
	);
510
	);
511
	struct ast_codec_pref prefs;
511
	struct ast_codec_pref prefs;
512
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
512
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
513
	struct ast_sockaddr addr;
513
	struct ast_sockaddr addr;
514
	int formats;
514
	int formats;
515
	int sockfd;					/*!< Socket to use for transmission */
515
	int sockfd;					/*!< Socket to use for transmission */
516
	struct in_addr mask;
516
	struct in_addr mask;
517
	int adsi;
517
	int adsi;
518
	uint64_t flags;
518
	uint64_t flags;
519

    
   
519

   
520
	/* Dynamic Registration fields */
520
	/* Dynamic Registration fields */
521
	struct sockaddr_in defaddr;			/*!< Default address if there is one */
521
	struct sockaddr_in defaddr;			/*!< Default address if there is one */
522
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
522
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
523
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
523
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
524

    
   
524

   
525
	int expire;					/*!< Schedule entry for expiry */
525
	int expire;					/*!< Schedule entry for expiry */
526
	int expiry;					/*!< How soon to expire */
526
	int expiry;					/*!< How soon to expire */
527
	iax2_format capability;        /*!< Capability */
527
	iax2_format capability;        /*!< Capability */
528

    
   
528

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

    
   
534

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

    
   
540

   
541
	struct ast_event_sub *mwi_event_sub;
541
	struct ast_event_sub *mwi_event_sub;
542

    
   
542

   
543
	struct ast_acl_list *acl;
543
	struct ast_acl_list *acl;
544
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
544
	enum calltoken_peer_enum calltoken_required;        /*!< Is calltoken validation required or not, can be YES, NO, or AUTO */
545
};
545
};
546

    
   
546

   
547
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
547
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
548

    
   
548

   
549
struct iax2_trunk_peer {
549
struct iax2_trunk_peer {
550
	ast_mutex_t lock;
550
	ast_mutex_t lock;
551
	int sockfd;
551
	int sockfd;
552
	struct sockaddr_in addr;
552
	struct sockaddr_in addr;
553
	struct timeval txtrunktime;		/*!< Transmit trunktime */
553
	struct timeval txtrunktime;		/*!< Transmit trunktime */
554
	struct timeval rxtrunktime;		/*!< Receive trunktime */
554
	struct timeval rxtrunktime;		/*!< Receive trunktime */
555
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
555
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
556
	struct timeval trunkact;		/*!< Last trunk activity */
556
	struct timeval trunkact;		/*!< Last trunk activity */
557
	unsigned int lastsent;			/*!< Last sent time */
557
	unsigned int lastsent;			/*!< Last sent time */
558
	/* Trunk data and length */
558
	/* Trunk data and length */
559
	unsigned char *trunkdata;
559
	unsigned char *trunkdata;
560
	unsigned int trunkdatalen;
560
	unsigned int trunkdatalen;
561
	unsigned int trunkdataalloc;
561
	unsigned int trunkdataalloc;
562
	int trunkmaxmtu;
562
	int trunkmaxmtu;
563
	int trunkerror;
563
	int trunkerror;
564
	int calls;
564
	int calls;
565
	AST_LIST_ENTRY(iax2_trunk_peer) list;
565
	AST_LIST_ENTRY(iax2_trunk_peer) list;
566
};
566
};
567

    
   
567

   
568
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
568
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
569

    
   
569

   
570
struct iax_firmware {
570
struct iax_firmware {
571
	AST_LIST_ENTRY(iax_firmware) list;
571
	AST_LIST_ENTRY(iax_firmware) list;
572
	int fd;
572
	int fd;
573
	int mmaplen;
573
	int mmaplen;
574
	int dead;
574
	int dead;
575
	struct ast_iax2_firmware_header *fwh;
575
	struct ast_iax2_firmware_header *fwh;
576
	unsigned char *buf;
576
	unsigned char *buf;
577
};
577
};
578

    
   
578

   
579
enum iax_reg_state {
579
enum iax_reg_state {
580
	REG_STATE_UNREGISTERED = 0,
580
	REG_STATE_UNREGISTERED = 0,
581
	REG_STATE_REGSENT,
581
	REG_STATE_REGSENT,
582
	REG_STATE_AUTHSENT,
582
	REG_STATE_AUTHSENT,
583
	REG_STATE_REGISTERED,
583
	REG_STATE_REGISTERED,
584
	REG_STATE_REJECTED,
584
	REG_STATE_REJECTED,
585
	REG_STATE_TIMEOUT,
585
	REG_STATE_TIMEOUT,
586
	REG_STATE_NOAUTH
586
	REG_STATE_NOAUTH
587
};
587
};
588

    
   
588

   
589
enum iax_transfer_state {
589
enum iax_transfer_state {
590
	TRANSFER_NONE = 0,
590
	TRANSFER_NONE = 0,
591
	TRANSFER_BEGIN,
591
	TRANSFER_BEGIN,
592
	TRANSFER_READY,
592
	TRANSFER_READY,
593
	TRANSFER_RELEASED,
593
	TRANSFER_RELEASED,
594
	TRANSFER_PASSTHROUGH,
594
	TRANSFER_PASSTHROUGH,
595
	TRANSFER_MBEGIN,
595
	TRANSFER_MBEGIN,
596
	TRANSFER_MREADY,
596
	TRANSFER_MREADY,
597
	TRANSFER_MRELEASED,
597
	TRANSFER_MRELEASED,
598
	TRANSFER_MPASSTHROUGH,
598
	TRANSFER_MPASSTHROUGH,
599
	TRANSFER_MEDIA,
599
	TRANSFER_MEDIA,
600
	TRANSFER_MEDIAPASS
600
	TRANSFER_MEDIAPASS
601
};
601
};
602

    
   
602

   
603
struct iax2_registry {
603
struct iax2_registry {
604
	struct ast_sockaddr addr;		/*!< Who we connect to for registration purposes */
604
	struct ast_sockaddr addr;		/*!< Who we connect to for registration purposes */
605
	char username[80];
605
	char username[80];
606
	char secret[80];			/*!< Password or key name in []'s */
606
	char secret[80];			/*!< Password or key name in []'s */
607
	int expire;				/*!< Sched ID of expiration */
607
	int expire;				/*!< Sched ID of expiration */
608
	int refresh;				/*!< How often to refresh */
608
	int refresh;				/*!< How often to refresh */
609
	enum iax_reg_state regstate;
609
	enum iax_reg_state regstate;
610
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
610
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
611
	int callno;				/*!< Associated call number if applicable */
611
	int callno;				/*!< Associated call number if applicable */
612
	struct sockaddr_in us;			/*!< Who the server thinks we are */
612
	struct sockaddr_in us;			/*!< Who the server thinks we are */
613
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
613
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
614
	AST_LIST_ENTRY(iax2_registry) entry;
614
	AST_LIST_ENTRY(iax2_registry) entry;
615
};
615
};
616

    
   
616

   
617
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
617
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
618

    
   
618

   
619
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
619
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
620
#define MIN_RETRY_TIME		100
620
#define MIN_RETRY_TIME		100
621
#define MAX_RETRY_TIME		10000
621
#define MAX_RETRY_TIME		10000
622

    
   
622

   
623
#define MAX_JITTER_BUFFER	50
623
#define MAX_JITTER_BUFFER	50
624
#define MIN_JITTER_BUFFER	10
624
#define MIN_JITTER_BUFFER	10
625

    
   
625

   
626
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
626
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
627

    
   
627

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

    
   
629

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

    
   
632

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

    
   
635

   
636
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
636
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
637
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
637
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
638
static int iaxdynamicthreadcount = 0;
638
static int iaxdynamicthreadcount = 0;
639
static int iaxdynamicthreadnum = 0;
639
static int iaxdynamicthreadnum = 0;
640
static int iaxactivethreadcount = 0;
640
static int iaxactivethreadcount = 0;
641

    
   
641

   
642
struct iax_rr {
642
struct iax_rr {
643
	int jitter;
643
	int jitter;
644
	int losspct;
644
	int losspct;
645
	int losscnt;
645
	int losscnt;
646
	int packets;
646
	int packets;
647
	int delay;
647
	int delay;
648
	int dropped;
648
	int dropped;
649
	int ooo;
649
	int ooo;
650
};
650
};
651

    
   
651

   
652
struct iax2_pvt_ref;
652
struct iax2_pvt_ref;
653

    
   
653

   
654
struct chan_iax2_pvt {
654
struct chan_iax2_pvt {
655
	/*! Socket to send/receive on for this call */
655
	/*! Socket to send/receive on for this call */
656
	int sockfd;
656
	int sockfd;
657
	/*! ast_callid bound to dialog */
657
	/*! ast_callid bound to dialog */
658
	struct ast_callid *callid;
658
	struct ast_callid *callid;
659
	/*! Last received voice format */
659
	/*! Last received voice format */
660
	iax2_format voiceformat;
660
	iax2_format voiceformat;
661
	/*! Last received video format */
661
	/*! Last received video format */
662
	iax2_format videoformat;
662
	iax2_format videoformat;
663
	/*! Last sent voice format */
663
	/*! Last sent voice format */
664
	iax2_format svoiceformat;
664
	iax2_format svoiceformat;
665
	/*! Last sent video format */
665
	/*! Last sent video format */
666
	iax2_format svideoformat;
666
	iax2_format svideoformat;
667
	/*! What we are capable of sending */
667
	/*! What we are capable of sending */
668
	iax2_format capability;
668
	iax2_format capability;
669
	/*! Last received timestamp */
669
	/*! Last received timestamp */
670
	unsigned int last;
670
	unsigned int last;
671
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
671
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
672
	unsigned int lastsent;
672
	unsigned int lastsent;
673
	/*! Timestamp of the last video frame sent */
673
	/*! Timestamp of the last video frame sent */
674
	unsigned int lastvsent;
674
	unsigned int lastvsent;
675
	/*! Next outgoing timestamp if everything is good */
675
	/*! Next outgoing timestamp if everything is good */
676
	unsigned int nextpred;
676
	unsigned int nextpred;
677
	/*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
677
	/*! iax frame subclass that began iax2_pvt entry. 0x8000 bit is set on TX */
678
	int first_iax_message;
678
	int first_iax_message;
679
	/*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
679
	/*! Last iax frame subclass sent or received for a iax2_pvt. 0x8000 bit is set on TX */
680
	int last_iax_message;
680
	int last_iax_message;
681
	/*! True if the last voice we transmitted was not silence/CNG */
681
	/*! True if the last voice we transmitted was not silence/CNG */
682
	unsigned int notsilenttx:1;
682
	unsigned int notsilenttx:1;
683
	/*! Ping time */
683
	/*! Ping time */
684
	unsigned int pingtime;
684
	unsigned int pingtime;
685
	/*! Max time for initial response */
685
	/*! Max time for initial response */
686
	int maxtime;
686
	int maxtime;
687
	/*! Peer Address */
687
	/*! Peer Address */
688
	struct sockaddr_in addr;
688
	struct sockaddr_in addr;
689
	/*! Actual used codec preferences */
689
	/*! Actual used codec preferences */
690
	struct ast_codec_pref prefs;
690
	struct ast_codec_pref prefs;
691
	/*! Requested codec preferences */
691
	/*! Requested codec preferences */
692
	struct ast_codec_pref rprefs;
692
	struct ast_codec_pref rprefs;
693
	/*! Our call number */
693
	/*! Our call number */
694
	unsigned short callno;
694
	unsigned short callno;
695
	/*! Our callno_entry entry */
695
	/*! Our callno_entry entry */
696
	struct callno_entry *callno_entry;
696
	struct callno_entry *callno_entry;
697
	/*! Peer callno */
697
	/*! Peer callno */
698
	unsigned short peercallno;
698
	unsigned short peercallno;
699
	/*! Negotiated format, this is only used to remember what format was
699
	/*! Negotiated format, this is only used to remember what format was
700
	    chosen for an unauthenticated call so that the channel can get
700
	    chosen for an unauthenticated call so that the channel can get
701
	    created later using the right format */
701
	    created later using the right format */
702
	iax2_format chosenformat;
702
	iax2_format chosenformat;
703
	/*! Peer selected format */
703
	/*! Peer selected format */
704
	iax2_format peerformat;
704
	iax2_format peerformat;
705
	/*! Peer capability */
705
	/*! Peer capability */
706
	iax2_format peercapability;
706
	iax2_format peercapability;
707
	/*! timeval that we base our transmission on */
707
	/*! timeval that we base our transmission on */
708
	struct timeval offset;
708
	struct timeval offset;
709
	/*! timeval that we base our delivery on */
709
	/*! timeval that we base our delivery on */
710
	struct timeval rxcore;
710
	struct timeval rxcore;
711
	/*! The jitterbuffer */
711
	/*! The jitterbuffer */
712
	jitterbuf *jb;
712
	jitterbuf *jb;
713
	/*! active jb read scheduler id */
713
	/*! active jb read scheduler id */
714
	int jbid;
714
	int jbid;
715
	/*! LAG */
715
	/*! LAG */
716
	int lag;
716
	int lag;
717
	/*! Error, as discovered by the manager */
717
	/*! Error, as discovered by the manager */
718
	int error;
718
	int error;
719
	/*! Owner if we have one */
719
	/*! Owner if we have one */
720
	struct ast_channel *owner;
720
	struct ast_channel *owner;
721
	/*! What's our state? */
721
	/*! What's our state? */
722
	struct ast_flags state;
722
	struct ast_flags state;
723
	/*! Expiry (optional) */
723
	/*! Expiry (optional) */
724
	int expiry;
724
	int expiry;
725
	/*! Next outgoing sequence number */
725
	/*! Next outgoing sequence number */
726
	unsigned char oseqno;
726
	unsigned char oseqno;
727
	/*! Next sequence number they have not yet acknowledged */
727
	/*! Next sequence number they have not yet acknowledged */
728
	unsigned char rseqno;
728
	unsigned char rseqno;
729
	/*! Next incoming sequence number */
729
	/*! Next incoming sequence number */
730
	unsigned char iseqno;
730
	unsigned char iseqno;
731
	/*! Last incoming sequence number we have acknowledged */
731
	/*! Last incoming sequence number we have acknowledged */
732
	unsigned char aseqno;
732
	unsigned char aseqno;
733

    
   
733

   
734
	AST_DECLARE_STRING_FIELDS(
734
	AST_DECLARE_STRING_FIELDS(
735
		/*! Peer name */
735
		/*! Peer name */
736
		AST_STRING_FIELD(peer);
736
		AST_STRING_FIELD(peer);
737
		/*! Default Context */
737
		/*! Default Context */
738
		AST_STRING_FIELD(context);
738
		AST_STRING_FIELD(context);
739
		/*! Caller ID if available */
739
		/*! Caller ID if available */
740
		AST_STRING_FIELD(cid_num);
740
		AST_STRING_FIELD(cid_num);
741
		AST_STRING_FIELD(cid_name);
741
		AST_STRING_FIELD(cid_name);
742
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
742
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
743
		AST_STRING_FIELD(ani);
743
		AST_STRING_FIELD(ani);
744
		/*! DNID */
744
		/*! DNID */
745
		AST_STRING_FIELD(dnid);
745
		AST_STRING_FIELD(dnid);
746
		/*! RDNIS */
746
		/*! RDNIS */
747
		AST_STRING_FIELD(rdnis);
747
		AST_STRING_FIELD(rdnis);
748
		/*! Requested Extension */
748
		/*! Requested Extension */
749
		AST_STRING_FIELD(exten);
749
		AST_STRING_FIELD(exten);
750
		/*! Expected Username */
750
		/*! Expected Username */
751
		AST_STRING_FIELD(username);
751
		AST_STRING_FIELD(username);
752
		/*! Expected Secret */
752
		/*! Expected Secret */
753
		AST_STRING_FIELD(secret);
753
		AST_STRING_FIELD(secret);
754
		/*! MD5 challenge */
754
		/*! MD5 challenge */
755
		AST_STRING_FIELD(challenge);
755
		AST_STRING_FIELD(challenge);
756
		/*! Public keys permitted keys for incoming authentication */
756
		/*! Public keys permitted keys for incoming authentication */
757
		AST_STRING_FIELD(inkeys);
757
		AST_STRING_FIELD(inkeys);
758
		/*! Private key for outgoing authentication */
758
		/*! Private key for outgoing authentication */
759
		AST_STRING_FIELD(outkey);
759
		AST_STRING_FIELD(outkey);
760
		/*! Preferred language */
760
		/*! Preferred language */
761
		AST_STRING_FIELD(language);
761
		AST_STRING_FIELD(language);
762
		/*! Hostname/peername for naming purposes */
762
		/*! Hostname/peername for naming purposes */
763
		AST_STRING_FIELD(host);
763
		AST_STRING_FIELD(host);
764

    
   
764

   
765
		AST_STRING_FIELD(dproot);
765
		AST_STRING_FIELD(dproot);
766
		AST_STRING_FIELD(accountcode);
766
		AST_STRING_FIELD(accountcode);
767
		AST_STRING_FIELD(mohinterpret);
767
		AST_STRING_FIELD(mohinterpret);
768
		AST_STRING_FIELD(mohsuggest);
768
		AST_STRING_FIELD(mohsuggest);
769
		/*! received OSP token */
769
		/*! received OSP token */
770
		AST_STRING_FIELD(osptoken);
770
		AST_STRING_FIELD(osptoken);
771
		/*! Default parkinglot */
771
		/*! Default parkinglot */
772
		AST_STRING_FIELD(parkinglot);
772
		AST_STRING_FIELD(parkinglot);
773
	);
773
	);
774
	/*! AUTHREJ all AUTHREP frames */
774
	/*! AUTHREJ all AUTHREP frames */
775
	int authrej;
775
	int authrej;
776
	/*! permitted authentication methods */
776
	/*! permitted authentication methods */
777
	int authmethods;
777
	int authmethods;
778
	/*! permitted encryption methods */
778
	/*! permitted encryption methods */
779
	int encmethods;
779
	int encmethods;
780
	/*! Encryption AES-128 Key */
780
	/*! Encryption AES-128 Key */
781
	ast_aes_encrypt_key ecx;
781
	ast_aes_encrypt_key ecx;
782
	/*! Decryption AES-128 Key corresponding to ecx */
782
	/*! Decryption AES-128 Key corresponding to ecx */
783
	ast_aes_decrypt_key mydcx;
783
	ast_aes_decrypt_key mydcx;
784
	/*! Decryption AES-128 Key used to decrypt peer frames */
784
	/*! Decryption AES-128 Key used to decrypt peer frames */
785
	ast_aes_decrypt_key dcx;
785
	ast_aes_decrypt_key dcx;
786
	/*! scheduler id associated with iax_key_rotate 
786
	/*! scheduler id associated with iax_key_rotate 
787
	 * for encrypted calls*/
787
	 * for encrypted calls*/
788
	int keyrotateid;
788
	int keyrotateid;
789
	/*! 32 bytes of semi-random data */
789
	/*! 32 bytes of semi-random data */
790
	unsigned char semirand[32];
790
	unsigned char semirand[32];
791
	/*! Associated registry */
791
	/*! Associated registry */
792
	struct iax2_registry *reg;
792
	struct iax2_registry *reg;
793
	/*! Associated peer for poking */
793
	/*! Associated peer for poking */
794
	struct iax2_peer *peerpoke;
794
	struct iax2_peer *peerpoke;
795
	/*! IAX_ flags */
795
	/*! IAX_ flags */
796
	uint64_t flags;
796
	uint64_t flags;
797
	int adsi;
797
	int adsi;
798

    
   
798

   
799
	/*! Transferring status */
799
	/*! Transferring status */
800
	enum iax_transfer_state transferring;
800
	enum iax_transfer_state transferring;
801
	/*! Transfer identifier */
801
	/*! Transfer identifier */
802
	int transferid;
802
	int transferid;
803
	/*! Who we are IAX transferring to */
803
	/*! Who we are IAX transferring to */
804
	struct sockaddr_in transfer;
804
	struct sockaddr_in transfer;
805
	/*! What's the new call number for the transfer */
805
	/*! What's the new call number for the transfer */
806
	unsigned short transfercallno;
806
	unsigned short transfercallno;
807
	/*! Transfer encrypt AES-128 Key */
807
	/*! Transfer encrypt AES-128 Key */
808
	ast_aes_encrypt_key tdcx;
808
	ast_aes_encrypt_key tdcx;
809

    
   
809

   
810
	/*! Status of knowledge of peer ADSI capability */
810
	/*! Status of knowledge of peer ADSI capability */
811
	int peeradsicpe;
811
	int peeradsicpe;
812

    
   
812

   
813
	/*! Who we are bridged to */
813
	/*! Who we are bridged to */
814
	unsigned short bridgecallno;
814
	unsigned short bridgecallno;
815

    
   
815

   
816
	int pingid;			/*!< Transmit PING request */
816
	int pingid;			/*!< Transmit PING request */
817
	int lagid;			/*!< Retransmit lag request */
817
	int lagid;			/*!< Retransmit lag request */
818
	int autoid;			/*!< Auto hangup for Dialplan requestor */
818
	int autoid;			/*!< Auto hangup for Dialplan requestor */
819
	int authid;			/*!< Authentication rejection ID */
819
	int authid;			/*!< Authentication rejection ID */
820
	int authfail;			/*!< Reason to report failure */
820
	int authfail;			/*!< Reason to report failure */
821
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
821
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
822
	int calling_ton;
822
	int calling_ton;
823
	int calling_tns;
823
	int calling_tns;
824
	int calling_pres;
824
	int calling_pres;
825
	int amaflags;
825
	int amaflags;
826
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
826
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
827
	/*! variables inherited from the user definition */
827
	/*! variables inherited from the user definition */
828
	struct ast_variable *vars;
828
	struct ast_variable *vars;
829
	/*! variables transmitted in a NEW packet */
829
	/*! variables transmitted in a NEW packet */
830
	struct ast_variable *iaxvars;
830
	struct ast_variable *iaxvars;
831
	/*! last received remote rr */
831
	/*! last received remote rr */
832
	struct iax_rr remote_rr;
832
	struct iax_rr remote_rr;
833
	/*! Current base time: (just for stats) */
833
	/*! Current base time: (just for stats) */
834
	int min;
834
	int min;
835
	/*! Dropped frame count: (just for stats) */
835
	/*! Dropped frame count: (just for stats) */
836
	int frames_dropped;
836
	int frames_dropped;
837
	/*! received frame count: (just for stats) */
837
	/*! received frame count: (just for stats) */
838
	int frames_received;
838
	int frames_received;
839
	/*! num bytes used for calltoken ie, even an empty ie should contain 2 */
839
	/*! num bytes used for calltoken ie, even an empty ie should contain 2 */
840
	unsigned char calltoken_ie_len;
840
	unsigned char calltoken_ie_len;
841
	/*! hold all signaling frames from the pbx thread until we have a destination callno */
841
	/*! hold all signaling frames from the pbx thread until we have a destination callno */
842
	char hold_signaling;
842
	char hold_signaling;
843
	/*! frame queue for signaling frames from pbx thread waiting for destination callno */
843
	/*! frame queue for signaling frames from pbx thread waiting for destination callno */
844
	AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
844
	AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
845
};
845
};
846

    
   
846

   
847
struct signaling_queue_entry {
847
struct signaling_queue_entry {
848
	struct ast_frame f;
848
	struct ast_frame f;
849
	AST_LIST_ENTRY(signaling_queue_entry) next;
849
	AST_LIST_ENTRY(signaling_queue_entry) next;
850
};
850
};
851

    
   
851

   
852
/*! table of available call numbers */
852
/*! table of available call numbers */
853
static struct ao2_container *callno_pool;
853
static struct ao2_container *callno_pool;
854

    
   
854

   
855
/*! table of available trunk call numbers */
855
/*! table of available trunk call numbers */
856
static struct ao2_container *callno_pool_trunk;
856
static struct ao2_container *callno_pool_trunk;
857

    
   
857

   
858
static const unsigned int CALLNO_POOL_BUCKETS = 2699;
858
static const unsigned int CALLNO_POOL_BUCKETS = 2699;
859

    
   
859

   
860
/*!
860
/*!
861
 * \brief a list of frames that may need to be retransmitted
861
 * \brief a list of frames that may need to be retransmitted
862
 *
862
 *
863
 * \note The contents of this list do not need to be explicitly destroyed
863
 * \note The contents of this list do not need to be explicitly destroyed
864
 * on module unload.  This is because all active calls are destroyed, and
864
 * on module unload.  This is because all active calls are destroyed, and
865
 * all frames in this queue will get destroyed as a part of that process.
865
 * all frames in this queue will get destroyed as a part of that process.
866
 *
866
 *
867
 * \note Contents protected by the iaxsl[] locks
867
 * \note Contents protected by the iaxsl[] locks
868
 */
868
 */
869
static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
869
static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS];
870

    
   
870

   
871
static struct ast_taskprocessor *transmit_processor;
871
static struct ast_taskprocessor *transmit_processor;
872

    
   
872

   
873
static int randomcalltokendata;
873
static int randomcalltokendata;
874

    
   
874

   
875
static const time_t MAX_CALLTOKEN_DELAY = 10;
875
static const time_t MAX_CALLTOKEN_DELAY = 10;
876

    
   
876

   
877
/*!
877
/*!
878
 * This module will get much higher performance when doing a lot of
878
 * This module will get much higher performance when doing a lot of
879
 * user and peer lookups if the number of buckets is increased from 1.
879
 * user and peer lookups if the number of buckets is increased from 1.
880
 * However, to maintain old behavior for Asterisk 1.4, these are set to
880
 * However, to maintain old behavior for Asterisk 1.4, these are set to
881
 * 1 by default.  When using multiple buckets, search order through these
881
 * 1 by default.  When using multiple buckets, search order through these
882
 * containers is considered random, so you will not be able to depend on
882
 * containers is considered random, so you will not be able to depend on
883
 * the order the entires are specified in iax.conf for matching order. */
883
 * the order the entires are specified in iax.conf for matching order. */
884
#ifdef LOW_MEMORY
884
#ifdef LOW_MEMORY
885
#define MAX_PEER_BUCKETS 17
885
#define MAX_PEER_BUCKETS 17
886
#else
886
#else
887
#define MAX_PEER_BUCKETS 563
887
#define MAX_PEER_BUCKETS 563
888
#endif
888
#endif
889
static struct ao2_container *peers;
889
static struct ao2_container *peers;
890

    
   
890

   
891
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
891
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
892
static struct ao2_container *users;
892
static struct ao2_container *users;
893

    
   
893

   
894
/*! Table containing peercnt objects for every ip address consuming a callno */
894
/*! Table containing peercnt objects for every ip address consuming a callno */
895
static struct ao2_container *peercnts;
895
static struct ao2_container *peercnts;
896

    
   
896

   
897
/*! Table containing custom callno limit rules for a range of ip addresses. */
897
/*! Table containing custom callno limit rules for a range of ip addresses. */
898
static struct ao2_container *callno_limits;
898
static struct ao2_container *callno_limits;
899

    
   
899

   
900
/*! Table containing ip addresses not requiring calltoken validation */
900
/*! Table containing ip addresses not requiring calltoken validation */
901
static struct ao2_container *calltoken_ignores;
901
static struct ao2_container *calltoken_ignores;
902

    
   
902

   
903
static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
903
static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
904

    
   
904

   
905
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
905
static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
906

    
   
906

   
907
static uint16_t global_maxcallno;
907
static uint16_t global_maxcallno;
908

    
   
908

   
909
/*! Total num of call numbers allowed to be allocated without calltoken validation */
909
/*! Total num of call numbers allowed to be allocated without calltoken validation */
910
static uint16_t global_maxcallno_nonval;
910
static uint16_t global_maxcallno_nonval;
911

    
   
911

   
912
static uint16_t total_nonval_callno_used = 0;
912
static uint16_t total_nonval_callno_used = 0;
913

    
   
913

   
914
/*! peer connection private, keeps track of all the call numbers
914
/*! peer connection private, keeps track of all the call numbers
915
 *  consumed by a single ip address */
915
 *  consumed by a single ip address */
916
struct peercnt {
916
struct peercnt {
917
	/*! ip address consuming call numbers */
917
	/*! ip address consuming call numbers */
918
	unsigned long addr;
918
	unsigned long addr;
919
	/*! Number of call numbers currently used by this ip address */
919
	/*! Number of call numbers currently used by this ip address */
920
	uint16_t cur;
920
	uint16_t cur;
921
	/*! Max call numbers allowed for this ip address */
921
	/*! Max call numbers allowed for this ip address */
922
	uint16_t limit;
922
	uint16_t limit;
923
	/*! Specifies whether limit is set by a registration or not, if so normal
923
	/*! Specifies whether limit is set by a registration or not, if so normal
924
	 *  limit setting rules do not apply to this address. */
924
	 *  limit setting rules do not apply to this address. */
925
	unsigned char reg;
925
	unsigned char reg;
926
};
926
};
927

    
   
927

   
928
/*! used by both callno_limits and calltoken_ignores containers */
928
/*! used by both callno_limits and calltoken_ignores containers */
929
struct addr_range {
929
struct addr_range {
930
	/*! ip address range for custom callno limit rule */
930
	/*! ip address range for custom callno limit rule */
931
	struct ast_ha ha;
931
	struct ast_ha ha;
932
	/*! callno limit for this ip address range, only used in callno_limits container */
932
	/*! callno limit for this ip address range, only used in callno_limits container */
933
	uint16_t limit;
933
	uint16_t limit;
934
	/*! delete me marker for reloads */
934
	/*! delete me marker for reloads */
935
	unsigned char delme;
935
	unsigned char delme;
936
};
936
};
937

    
   
937

   
938
struct callno_entry {
938
struct callno_entry {
939
	/*! callno used for this entry */
939
	/*! callno used for this entry */
940
	uint16_t callno;
940
	uint16_t callno;
941
	/*! was this callno calltoken validated or not */
941
	/*! was this callno calltoken validated or not */
942
	unsigned char validated;
942
	unsigned char validated;
943
};
943
};
944

    
   
944

   
945
static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
945
static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
946

    
   
946

   
947
enum {
947
enum {
948
	/*! Extension exists */
948
	/*! Extension exists */
949
	CACHE_FLAG_EXISTS      = (1 << 0),
949
	CACHE_FLAG_EXISTS      = (1 << 0),
950
	/*! Extension is nonexistent */
950
	/*! Extension is nonexistent */
951
	CACHE_FLAG_NONEXISTENT = (1 << 1),
951
	CACHE_FLAG_NONEXISTENT = (1 << 1),
952
	/*! Extension can exist */
952
	/*! Extension can exist */
953
	CACHE_FLAG_CANEXIST    = (1 << 2),
953
	CACHE_FLAG_CANEXIST    = (1 << 2),
954
	/*! Waiting to hear back response */
954
	/*! Waiting to hear back response */
955
	CACHE_FLAG_PENDING     = (1 << 3),
955
	CACHE_FLAG_PENDING     = (1 << 3),
956
	/*! Timed out */
956
	/*! Timed out */
957
	CACHE_FLAG_TIMEOUT     = (1 << 4),
957
	CACHE_FLAG_TIMEOUT     = (1 << 4),
958
	/*! Request transmitted */
958
	/*! Request transmitted */
959
	CACHE_FLAG_TRANSMITTED = (1 << 5),
959
	CACHE_FLAG_TRANSMITTED = (1 << 5),
960
	/*! Timeout */
960
	/*! Timeout */
961
	CACHE_FLAG_UNKNOWN     = (1 << 6),
961
	CACHE_FLAG_UNKNOWN     = (1 << 6),
962
	/*! Matchmore */
962
	/*! Matchmore */
963
	CACHE_FLAG_MATCHMORE   = (1 << 7),
963
	CACHE_FLAG_MATCHMORE   = (1 << 7),
964
};
964
};
965

    
   
965

   
966
struct iax2_dpcache {
966
struct iax2_dpcache {
967
	char peercontext[AST_MAX_CONTEXT];
967
	char peercontext[AST_MAX_CONTEXT];
968
	char exten[AST_MAX_EXTENSION];
968
	char exten[AST_MAX_EXTENSION];
969
	struct timeval orig;
969
	struct timeval orig;
970
	struct timeval expiry;
970
	struct timeval expiry;
971
	int flags;
971
	int flags;
972
	unsigned short callno;
972
	unsigned short callno;
973
	int waiters[256];
973
	int waiters[256];
974
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
974
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
975
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
975
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
976
};
976
};
977

    
   
977

   
978
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
978
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
979

    
   
979

   
980
static void reg_source_db(struct iax2_peer *p);
980
static void reg_source_db(struct iax2_peer *p);
981
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
981
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
982
static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
982
static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
983

    
   
983

   
984
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
984
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
985
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
985
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
986
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
986
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
987

    
   
987

   
988
enum iax2_thread_iostate {
988
enum iax2_thread_iostate {
989
	IAX_IOSTATE_IDLE,
989
	IAX_IOSTATE_IDLE,
990
	IAX_IOSTATE_READY,
990
	IAX_IOSTATE_READY,
991
	IAX_IOSTATE_PROCESSING,
991
	IAX_IOSTATE_PROCESSING,
992
	IAX_IOSTATE_SCHEDREADY,
992
	IAX_IOSTATE_SCHEDREADY,
993
};
993
};
994

    
   
994

   
995
enum iax2_thread_type {
995
enum iax2_thread_type {
996
	IAX_THREAD_TYPE_POOL,
996
	IAX_THREAD_TYPE_POOL,
997
	IAX_THREAD_TYPE_DYNAMIC,
997
	IAX_THREAD_TYPE_DYNAMIC,
998
};
998
};
999

    
   
999

   
1000
struct iax2_pkt_buf {
1000
struct iax2_pkt_buf {
1001
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
1001
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
1002
	size_t len;
1002
	size_t len;
1003
	unsigned char buf[1];
1003
	unsigned char buf[1];
1004
};
1004
};
1005

    
   
1005

   
1006
struct iax2_thread {
1006
struct iax2_thread {
1007
	AST_LIST_ENTRY(iax2_thread) list;
1007
	AST_LIST_ENTRY(iax2_thread) list;
1008
	enum iax2_thread_type type;
1008
	enum iax2_thread_type type;
1009
	enum iax2_thread_iostate iostate;
1009
	enum iax2_thread_iostate iostate;
1010
#ifdef SCHED_MULTITHREADED
1010
#ifdef SCHED_MULTITHREADED
1011
	void (*schedfunc)(const void *);
1011
	void (*schedfunc)(const void *);
1012
	const void *scheddata;
1012
	const void *scheddata;
1013
#endif
1013
#endif
1014
#ifdef DEBUG_SCHED_MULTITHREAD
1014
#ifdef DEBUG_SCHED_MULTITHREAD
1015
	char curfunc[80];
1015
	char curfunc[80];
1016
#endif	
1016
#endif	
1017
	int actions;
1017
	int actions;
1018
	pthread_t threadid;
1018
	pthread_t threadid;
1019
	int threadnum;
1019
	int threadnum;
1020
	struct sockaddr_in iosin;
1020
	struct sockaddr_in iosin;
1021
	unsigned char readbuf[4096]; 
1021
	unsigned char readbuf[4096]; 
1022
	unsigned char *buf;
1022
	unsigned char *buf;
1023
	ssize_t buf_len;
1023
	ssize_t buf_len;
1024
	size_t buf_size;
1024
	size_t buf_size;
1025
	int iofd;
1025
	int iofd;
1026
	time_t checktime;
1026
	time_t checktime;
1027
	ast_mutex_t lock;
1027
	ast_mutex_t lock;
1028
	ast_cond_t cond;
1028
	ast_cond_t cond;
1029
	ast_mutex_t init_lock;
1029
	ast_mutex_t init_lock;
1030
	ast_cond_t init_cond;
1030
	ast_cond_t init_cond;
1031
	/*! if this thread is processing a full frame,
1031
	/*! if this thread is processing a full frame,
1032
	  some information about that frame will be stored
1032
	  some information about that frame will be stored
1033
	  here, so we can avoid dispatching any more full
1033
	  here, so we can avoid dispatching any more full
1034
	  frames for that callno to other threads */
1034
	  frames for that callno to other threads */
1035
	struct {
1035
	struct {
1036
		unsigned short callno;
1036
		unsigned short callno;
1037
		struct sockaddr_in sin;
1037
		struct sockaddr_in sin;
1038
		unsigned char type;
1038
		unsigned char type;
1039
		unsigned char csub;
1039
		unsigned char csub;
1040
	} ffinfo;
1040
	} ffinfo;
1041
	/*! Queued up full frames for processing.  If more full frames arrive for
1041
	/*! Queued up full frames for processing.  If more full frames arrive for
1042
	 *  a call which this thread is already processing a full frame for, they
1042
	 *  a call which this thread is already processing a full frame for, they
1043
	 *  are queued up here. */
1043
	 *  are queued up here. */
1044
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1044
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
1045
	unsigned char stop;
1045
	unsigned char stop;
1046
};
1046
};
1047

    
   
1047

   
1048
/* Thread lists */
1048
/* Thread lists */
1049
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1049
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
1050
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1050
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
1051
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1051
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
1052

    
   
1052

   
1053
static void *iax2_process_thread(void *data);
1053
static void *iax2_process_thread(void *data);
1054
static void iax2_destroy(int callno);
1054
static void iax2_destroy(int callno);
1055

    
   
1055

   
1056
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1056
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
1057
{
1057
{
1058
	ast_mutex_lock(lock);
1058
	ast_mutex_lock(lock);
1059
	ast_cond_signal(cond);
1059
	ast_cond_signal(cond);
1060
	ast_mutex_unlock(lock);
1060
	ast_mutex_unlock(lock);
1061
}
1061
}
1062

    
   
1062

   
1063
/*!
1063
/*!
1064
 * \brief an array of iax2 pvt structures
1064
 * \brief an array of iax2 pvt structures
1065
 *
1065
 *
1066
 * The container for active chan_iax2_pvt structures is implemented as an
1066
 * The container for active chan_iax2_pvt structures is implemented as an
1067
 * array for extremely quick direct access to the correct pvt structure
1067
 * array for extremely quick direct access to the correct pvt structure
1068
 * based on the local call number.  The local call number is used as the
1068
 * based on the local call number.  The local call number is used as the
1069
 * index into the array where the associated pvt structure is stored.
1069
 * index into the array where the associated pvt structure is stored.
1070
 */
1070
 */
1071
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1071
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
1072

    
   
1072

   
1073
static struct ast_callid *iax_pvt_callid_get(int callno)
1073
static struct ast_callid *iax_pvt_callid_get(int callno)
1074
{
1074
{
1075
	if (iaxs[callno]->callid) {
1075
	if (iaxs[callno]->callid) {
1076
		return ast_callid_ref(iaxs[callno]->callid);
1076
		return ast_callid_ref(iaxs[callno]->callid);
1077
	}
1077
	}
1078
	return NULL;
1078
	return NULL;
1079
}
1079
}
1080

    
   
1080

   
1081
static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1081
static void iax_pvt_callid_set(int callno, struct ast_callid *callid)
1082
{
1082
{
1083
	if (iaxs[callno]->callid) {
1083
	if (iaxs[callno]->callid) {
1084
		ast_callid_unref(iaxs[callno]->callid);
1084
		ast_callid_unref(iaxs[callno]->callid);
1085
	}
1085
	}
1086
	ast_callid_ref(callid);
1086
	ast_callid_ref(callid);
1087
	iaxs[callno]->callid = callid;
1087
	iaxs[callno]->callid = callid;
1088
}
1088
}
1089

    
   
1089

   
1090
static void iax_pvt_callid_new(int callno)
1090
static void iax_pvt_callid_new(int callno)
1091
{
1091
{
1092
	struct ast_callid *callid = ast_create_callid();
1092
	struct ast_callid *callid = ast_create_callid();
1093
	char buffer[AST_CALLID_BUFFER_LENGTH];
1093
	char buffer[AST_CALLID_BUFFER_LENGTH];
1094
	ast_callid_strnprint(buffer, sizeof(buffer), callid);
1094
	ast_callid_strnprint(buffer, sizeof(buffer), callid);
1095
	iax_pvt_callid_set(callno, callid);
1095
	iax_pvt_callid_set(callno, callid);
1096
	ast_callid_unref(callid);
1096
	ast_callid_unref(callid);
1097
}
1097
}
1098

    
   
1098

   
1099
/*!
1099
/*!
1100
 * \brief Another container of iax2_pvt structures
1100
 * \brief Another container of iax2_pvt structures
1101
 *
1101
 *
1102
 * Active IAX2 pvt structs are also stored in this container, if they are a part
1102
 * Active IAX2 pvt structs are also stored in this container, if they are a part
1103
 * of an active call where we know the remote side's call number.  The reason
1103
 * of an active call where we know the remote side's call number.  The reason
1104
 * for this is that incoming media frames do not contain our call number.  So,
1104
 * for this is that incoming media frames do not contain our call number.  So,
1105
 * instead of having to iterate the entire iaxs array, we use this container to
1105
 * instead of having to iterate the entire iaxs array, we use this container to
1106
 * look up calls where the remote side is using a given call number.
1106
 * look up calls where the remote side is using a given call number.
1107
 */
1107
 */
1108
static struct ao2_container *iax_peercallno_pvts;
1108
static struct ao2_container *iax_peercallno_pvts;
1109

    
   
1109

   
1110
/*!
1110
/*!
1111
 * \brief chan_iax2_pvt structure locks
1111
 * \brief chan_iax2_pvt structure locks
1112
 *
1112
 *
1113
 * These locks are used when accessing a pvt structure in the iaxs array.
1113
 * These locks are used when accessing a pvt structure in the iaxs array.
1114
 * The index used here is the same as used in the iaxs array.  It is the
1114
 * The index used here is the same as used in the iaxs array.  It is the
1115
 * local call number for the associated pvt struct.
1115
 * local call number for the associated pvt struct.
1116
 */
1116
 */
1117
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1117
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
1118

    
   
1118

   
1119
/*!
1119
/*!
1120
 *  * \brief Another container of iax2_pvt structures
1120
 *  * \brief Another container of iax2_pvt structures
1121
 *  
1121
 *  
1122
 *  Active IAX2 pvt stucts used during transfering a call are stored here.  
1122
 *  Active IAX2 pvt stucts used during transfering a call are stored here.  
1123
 */
1123
 */
1124
static struct ao2_container *iax_transfercallno_pvts;
1124
static struct ao2_container *iax_transfercallno_pvts;
1125

    
   
1125

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

    
   
1129

   
1130
/* Debug routines... */
1130
/* Debug routines... */
1131
static struct sockaddr_in debugaddr;
1131
static struct sockaddr_in debugaddr;
1132

    
   
1132

   
1133
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1133
static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
1134
{
1134
{
1135
	if (iaxdebug ||
1135
	if (iaxdebug ||
1136
	    (sin && debugaddr.sin_addr.s_addr && 
1136
	    (sin && debugaddr.sin_addr.s_addr && 
1137
	     (!ntohs(debugaddr.sin_port) ||
1137
	     (!ntohs(debugaddr.sin_port) ||
1138
	      debugaddr.sin_port == sin->sin_port) &&
1138
	      debugaddr.sin_port == sin->sin_port) &&
1139
	     debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1139
	     debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
1140
		if (iaxdebug) {
1140
		if (iaxdebug) {
1141
			iax_showframe(f, fhi, rx, sin, datalen);
1141
			iax_showframe(f, fhi, rx, sin, datalen);
1142
		} else {
1142
		} else {
1143
			iaxdebug = 1;
1143
			iaxdebug = 1;
1144
			iax_showframe(f, fhi, rx, sin, datalen);
1144
			iax_showframe(f, fhi, rx, sin, datalen);
1145
			iaxdebug = 0;
1145
			iaxdebug = 0;
1146
		}
1146
		}
1147
	}
1147
	}
1148
}
1148
}
1149

    
   
1149

   
1150
static void iax_debug_output(const char *data)
1150
static void iax_debug_output(const char *data)
1151
{
1151
{
1152
	if (iaxdebug)
1152
	if (iaxdebug)
1153
		ast_verbose("%s", data);
1153
		ast_verbose("%s", data);
1154
}
1154
}
1155

    
   
1155

   
1156
static void iax_error_output(const char *data)
1156
static void iax_error_output(const char *data)
1157
{
1157
{
1158
	ast_log(LOG_WARNING, "%s", data);
1158
	ast_log(LOG_WARNING, "%s", data);
1159
}
1159
}
1160

    
   
1160

   
1161
static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1161
static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
1162
{
1162
{
1163
	va_list args;
1163
	va_list args;
1164
	char buf[1024];
1164
	char buf[1024];
1165

    
   
1165

   
1166
	va_start(args, fmt);
1166
	va_start(args, fmt);
1167
	vsnprintf(buf, sizeof(buf), fmt, args);
1167
	vsnprintf(buf, sizeof(buf), fmt, args);
1168
	va_end(args);
1168
	va_end(args);
1169

    
   
1169

   
1170
	ast_log(LOG_ERROR, "%s", buf);
1170
	ast_log(LOG_ERROR, "%s", buf);
1171
}
1171
}
1172

    
   
1172

   
1173
static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1173
static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
1174
{
1174
{
1175
	va_list args;
1175
	va_list args;
1176
	char buf[1024];
1176
	char buf[1024];
1177

    
   
1177

   
1178
	va_start(args, fmt);
1178
	va_start(args, fmt);
1179
	vsnprintf(buf, sizeof(buf), fmt, args);
1179
	vsnprintf(buf, sizeof(buf), fmt, args);
1180
	va_end(args);
1180
	va_end(args);
1181

    
   
1181

   
1182
	ast_log(LOG_WARNING, "%s", buf);
1182
	ast_log(LOG_WARNING, "%s", buf);
1183
}
1183
}
1184

    
   
1184

   
1185
static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1185
static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
1186
{
1186
{
1187
	va_list args;
1187
	va_list args;
1188
	char buf[1024];
1188
	char buf[1024];
1189

    
   
1189

   
1190
	va_start(args, fmt);
1190
	va_start(args, fmt);
1191
	vsnprintf(buf, sizeof(buf), fmt, args);
1191
	vsnprintf(buf, sizeof(buf), fmt, args);
1192
	va_end(args);
1192
	va_end(args);
1193

    
   
1193

   
1194
	ast_verbose("%s", buf);
1194
	ast_verbose("%s", buf);
1195
}
1195
}
1196

    
   
1196

   
1197
static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1197
static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
1198
static int expire_registry(const void *data);
1198
static int expire_registry(const void *data);
1199
static int iax2_answer(struct ast_channel *c);
1199
static int iax2_answer(struct ast_channel *c);
1200
static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1200
static int iax2_call(struct ast_channel *c, const char *dest, int timeout);
1201
static int iax2_devicestate(const char *data);
1201
static int iax2_devicestate(const char *data);
1202
static int iax2_digit_begin(struct ast_channel *c, char digit);
1202
static int iax2_digit_begin(struct ast_channel *c, char digit);
1203
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1203
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
1204
static int iax2_do_register(struct iax2_registry *reg);
1204
static int iax2_do_register(struct iax2_registry *reg);
1205
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1205
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
1206
static int iax2_hangup(struct ast_channel *c);
1206
static int iax2_hangup(struct ast_channel *c);
1207
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1207
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
1208
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1208
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
1209
static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1209
static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
1210
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1210
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
1211
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1211
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
1212
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1212
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
1213
static int iax2_sendtext(struct ast_channel *c, const char *text);
1213
static int iax2_sendtext(struct ast_channel *c, const char *text);
1214
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1214
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
1215
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1215
static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
1216
static int iax2_transfer(struct ast_channel *c, const char *dest);
1216
static int iax2_transfer(struct ast_channel *c, const char *dest);
1217
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1217
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
1218
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1218
static int iax2_sched_add(struct ast_sched_context *sched, int when, ast_sched_cb callback, const void *data);
1219

    
   
1219

   
1220
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1220
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
1221
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1221
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1222
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1222
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1223
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1223
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
1224
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1224
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
1225
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1225
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
1226
static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1226
static struct ast_channel *iax2_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1227
static struct ast_frame *iax2_read(struct ast_channel *c);
1227
static struct ast_frame *iax2_read(struct ast_channel *c);
1228
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1228
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1229
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1229
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
1230
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1230
static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
1231
static void *iax2_dup_variable_datastore(void *);
1231
static void *iax2_dup_variable_datastore(void *);
1232
static void prune_peers(void);
1232
static void prune_peers(void);
1233
static void prune_users(void);
1233
static void prune_users(void);
1234
static void iax2_free_variable_datastore(void *);
1234
static void iax2_free_variable_datastore(void *);
1235

    
   
1235

   
1236
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1236
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
1237
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1237
static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
1238
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1238
static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
1239
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1239
static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
1240
static void build_rand_pad(unsigned char *buf, ssize_t len);
1240
static void build_rand_pad(unsigned char *buf, ssize_t len);
1241
static struct callno_entry *get_unused_callno(int trunk, int validated);
1241
static struct callno_entry *get_unused_callno(int trunk, int validated);
1242
static int replace_callno(const void *obj);
1242
static int replace_callno(const void *obj);
1243
static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1243
static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
1244
static void network_change_event_cb(const struct ast_event *, void *);
1244
static void network_change_event_cb(const struct ast_event *, void *);
1245
static void acl_change_event_cb(const struct ast_event *, void *);
1245
static void acl_change_event_cb(const struct ast_event *, void *);
1246

    
   
1246

   
1247
static struct ast_channel_tech iax2_tech = {
1247
static struct ast_channel_tech iax2_tech = {
1248
	.type = "IAX2",
1248
	.type = "IAX2",
1249
	.description = tdesc,
1249
	.description = tdesc,
1250
	.properties = AST_CHAN_TP_WANTSJITTER,
1250
	.properties = AST_CHAN_TP_WANTSJITTER,
1251
	.requester = iax2_request,
1251
	.requester = iax2_request,
1252
	.devicestate = iax2_devicestate,
1252
	.devicestate = iax2_devicestate,
1253
	.send_digit_begin = iax2_digit_begin,
1253
	.send_digit_begin = iax2_digit_begin,
1254
	.send_digit_end = iax2_digit_end,
1254
	.send_digit_end = iax2_digit_end,
1255
	.send_text = iax2_sendtext,
1255
	.send_text = iax2_sendtext,
1256
	.send_image = iax2_sendimage,
1256
	.send_image = iax2_sendimage,
1257
	.send_html = iax2_sendhtml,
1257
	.send_html = iax2_sendhtml,
1258
	.call = iax2_call,
1258
	.call = iax2_call,
1259
	.hangup = iax2_hangup,
1259
	.hangup = iax2_hangup,
1260
	.answer = iax2_answer,
1260
	.answer = iax2_answer,
1261
	.read = iax2_read,
1261
	.read = iax2_read,
1262
	.write = iax2_write,
1262
	.write = iax2_write,
1263
	.write_video = iax2_write,
1263
	.write_video = iax2_write,
1264
	.indicate = iax2_indicate,
1264
	.indicate = iax2_indicate,
1265
	.setoption = iax2_setoption,
1265
	.setoption = iax2_setoption,
1266
	.queryoption = iax2_queryoption,
1266
	.queryoption = iax2_queryoption,
1267
	.bridge = iax2_bridge,
1267
	.bridge = iax2_bridge,
1268
	.transfer = iax2_transfer,
1268
	.transfer = iax2_transfer,
1269
	.fixup = iax2_fixup,
1269
	.fixup = iax2_fixup,
1270
	.func_channel_read = acf_channel_read,
1270
	.func_channel_read = acf_channel_read,
1271
};
1271
};
1272

    
   
1272

   
1273
/*!
1273
/*!
1274
 * \internal
1274
 * \internal
1275
 * \brief Obtain the owner channel lock if the owner exists.
1275
 * \brief Obtain the owner channel lock if the owner exists.
1276
 *
1276
 *
1277
 * \param callno IAX2 call id.
1277
 * \param callno IAX2 call id.
1278
 *
1278
 *
1279
 * \note Assumes the iaxsl[callno] lock is already obtained.
1279
 * \note Assumes the iaxsl[callno] lock is already obtained.
1280
 *
1280
 *
1281
 * \note
1281
 * \note
1282
 * IMPORTANT NOTE!!!  Any time this function is used, even if
1282
 * IMPORTANT NOTE!!!  Any time this function is used, even if
1283
 * iaxs[callno] was valid before calling it, it may no longer be
1283
 * iaxs[callno] was valid before calling it, it may no longer be
1284
 * valid after calling it.  This function may unlock and lock
1284
 * valid after calling it.  This function may unlock and lock
1285
 * the mutex associated with this callno, meaning that another
1285
 * the mutex associated with this callno, meaning that another
1286
 * thread may grab it and destroy the call.
1286
 * thread may grab it and destroy the call.
1287
 *
1287
 *
1288
 * \return Nothing
1288
 * \return Nothing
1289
 */
1289
 */
1290
static void iax2_lock_owner(int callno)
1290
static void iax2_lock_owner(int callno)
1291
{
1291
{
1292
	for (;;) {
1292
	for (;;) {
1293
		if (!iaxs[callno] || !iaxs[callno]->owner) {
1293
		if (!iaxs[callno] || !iaxs[callno]->owner) {
1294
			/* There is no owner lock to get. */
1294
			/* There is no owner lock to get. */
1295
			break;
1295
			break;
1296
		}
1296
		}
1297
		if (!ast_channel_trylock(iaxs[callno]->owner)) {
1297
		if (!ast_channel_trylock(iaxs[callno]->owner)) {
1298
			/* We got the lock */
1298
			/* We got the lock */
1299
			break;
1299
			break;
1300
		}
1300
		}
1301
		/* Avoid deadlock by pausing and trying again */
1301
		/* Avoid deadlock by pausing and trying again */
1302
		DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1302
		DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1303
	}
1303
	}
1304
}
1304
}
1305

    
   
1305

   
1306
static void mwi_event_cb(const struct ast_event *event, void *userdata)
1306
static void mwi_event_cb(const struct ast_event *event, void *userdata)
1307
{
1307
{
1308
	/* The MWI subscriptions exist just so the core knows we care about those
1308
	/* The MWI subscriptions exist just so the core knows we care about those
1309
	 * mailboxes.  However, we just grab the events out of the cache when it
1309
	 * mailboxes.  However, we just grab the events out of the cache when it
1310
	 * is time to send MWI, since it is only sent with a REGACK. */
1310
	 * is time to send MWI, since it is only sent with a REGACK. */
1311
}
1311
}
1312

    
   
1312

   
1313
static void network_change_event_subscribe(void)
1313
static void network_change_event_subscribe(void)
1314
{
1314
{
1315
	if (!network_change_event_subscription) {
1315
	if (!network_change_event_subscription) {
1316
		network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1316
		network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
1317
			network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1317
			network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
1318
	}
1318
	}
1319
}
1319
}
1320

    
   
1320

   
1321
static void network_change_event_unsubscribe(void)
1321
static void network_change_event_unsubscribe(void)
1322
{
1322
{
1323
	if (network_change_event_subscription) {
1323
	if (network_change_event_subscription) {
1324
		network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1324
		network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
1325
	}
1325
	}
1326
}
1326
}
1327

    
   
1327

   
1328
static void acl_change_event_subscribe(void)
1328
static void acl_change_event_subscribe(void)
1329
{
1329
{
1330
	if (!acl_change_event_subscription) {
1330
	if (!acl_change_event_subscription) {
1331
		acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1331
		acl_change_event_subscription = ast_event_subscribe(AST_EVENT_ACL_CHANGE,
1332
			acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
1332
			acl_change_event_cb, "IAX2 ACL Change", NULL, AST_EVENT_IE_END);
1333
	}
1333
	}
1334
}
1334
}
1335

    
   
1335

   
1336
static void acl_change_event_unsubscribe(void)
1336
static void acl_change_event_unsubscribe(void)
1337
{
1337
{
1338
	if (acl_change_event_subscription) {
1338
	if (acl_change_event_subscription) {
1339
		acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1339
		acl_change_event_subscription = ast_event_unsubscribe(acl_change_event_subscription);
1340
	}
1340
	}
1341
}
1341
}
1342

    
   
1342

   
1343
static int network_change_event_sched_cb(const void *data)
1343
static int network_change_event_sched_cb(const void *data)
1344
{
1344
{
1345
	struct iax2_registry *reg;
1345
	struct iax2_registry *reg;
1346
	network_change_event_sched_id = -1;
1346
	network_change_event_sched_id = -1;
1347
	AST_LIST_LOCK(&registrations);
1347
	AST_LIST_LOCK(&registrations);
1348
	AST_LIST_TRAVERSE(&registrations, reg, entry) {
1348
	AST_LIST_TRAVERSE(&registrations, reg, entry) {
1349
		iax2_do_register(reg);
1349
		iax2_do_register(reg);
1350
	}
1350
	}
1351
	AST_LIST_UNLOCK(&registrations);
1351
	AST_LIST_UNLOCK(&registrations);
1352

    
   
1352

   
1353
	return 0;
1353
	return 0;
1354
}
1354
}
1355

    
   
1355

   
1356
static void network_change_event_cb(const struct ast_event *event, void *userdata)
1356
static void network_change_event_cb(const struct ast_event *event, void *userdata)
1357
{
1357
{
1358
	ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1358
	ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
1359
	if (network_change_event_sched_id == -1) {
1359
	if (network_change_event_sched_id == -1) {
1360
		network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1360
		network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
1361
	}
1361
	}
1362

    
   
1362

   
1363
}
1363
}
1364

    
   
1364

   
1365
static void acl_change_event_cb(const struct ast_event *event, void *userdata)
1365
static void acl_change_event_cb(const struct ast_event *event, void *userdata)
1366
{
1366
{
1367
	ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1367
	ast_log(LOG_NOTICE, "Reloading chan_iax2 in response to ACL change event.\n");
1368
	reload_config(1);
1368
	reload_config(1);
1369
}
1369
}
1370

    
   
1370

   
1371

    
   
1371

   
1372
/*! \brief Send manager event at call setup to link between Asterisk channel name
1372
/*! \brief Send manager event at call setup to link between Asterisk channel name
1373
	and IAX2 call identifiers */
1373
	and IAX2 call identifiers */
1374
static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1374
static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1375
{
1375
{
1376
	manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1376
	manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1377
		"Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1377
		"Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1378
		pvt->owner ? ast_channel_name(pvt->owner) : "",
1378
		pvt->owner ? ast_channel_name(pvt->owner) : "",
1379
		pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1379
		pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1380
}
1380
}
1381

    
   
1381

   
1382
static const struct ast_datastore_info iax2_variable_datastore_info = {
1382
static const struct ast_datastore_info iax2_variable_datastore_info = {
1383
	.type = "IAX2_VARIABLE",
1383
	.type = "IAX2_VARIABLE",
1384
	.duplicate = iax2_dup_variable_datastore,
1384
	.duplicate = iax2_dup_variable_datastore,
1385
	.destroy = iax2_free_variable_datastore,
1385
	.destroy = iax2_free_variable_datastore,
1386
};
1386
};
1387

    
   
1387

   
1388
static void *iax2_dup_variable_datastore(void *old)
1388
static void *iax2_dup_variable_datastore(void *old)
1389
{
1389
{
1390
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1390
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1391
	struct ast_var_t *oldvar, *newvar;
1391
	struct ast_var_t *oldvar, *newvar;
1392

    
   
1392

   
1393
	newlist = ast_calloc(sizeof(*newlist), 1);
1393
	newlist = ast_calloc(sizeof(*newlist), 1);
1394
	if (!newlist) {
1394
	if (!newlist) {
1395
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1395
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1396
		return NULL;
1396
		return NULL;
1397
	}
1397
	}
1398

    
   
1398

   
1399
	AST_LIST_HEAD_INIT(newlist);
1399
	AST_LIST_HEAD_INIT(newlist);
1400
	AST_LIST_LOCK(oldlist);
1400
	AST_LIST_LOCK(oldlist);
1401
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1401
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1402
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1402
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1403
		if (newvar)
1403
		if (newvar)
1404
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1404
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1405
		else
1405
		else
1406
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1406
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1407
	}
1407
	}
1408
	AST_LIST_UNLOCK(oldlist);
1408
	AST_LIST_UNLOCK(oldlist);
1409
	return newlist;
1409
	return newlist;
1410
}
1410
}
1411

    
   
1411

   
1412
static void iax2_free_variable_datastore(void *old)
1412
static void iax2_free_variable_datastore(void *old)
1413
{
1413
{
1414
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1414
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1415
	struct ast_var_t *oldvar;
1415
	struct ast_var_t *oldvar;
1416

    
   
1416

   
1417
	AST_LIST_LOCK(oldlist);
1417
	AST_LIST_LOCK(oldlist);
1418
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1418
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1419
		ast_free(oldvar);
1419
		ast_free(oldvar);
1420
	}
1420
	}
1421
	AST_LIST_UNLOCK(oldlist);
1421
	AST_LIST_UNLOCK(oldlist);
1422
	AST_LIST_HEAD_DESTROY(oldlist);
1422
	AST_LIST_HEAD_DESTROY(oldlist);
1423
	ast_free(oldlist);
1423
	ast_free(oldlist);
1424
}
1424
}
1425

    
   
1425

   
1426

    
   
1426

   
1427
/* WARNING: insert_idle_thread should only ever be called within the
1427
/* WARNING: insert_idle_thread should only ever be called within the
1428
 * context of an iax2_process_thread() thread.
1428
 * context of an iax2_process_thread() thread.
1429
 */
1429
 */
1430
static void insert_idle_thread(struct iax2_thread *thread)
1430
static void insert_idle_thread(struct iax2_thread *thread)
1431
{
1431
{
1432
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1432
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1433
		AST_LIST_LOCK(&dynamic_list);
1433
		AST_LIST_LOCK(&dynamic_list);
1434
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1434
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1435
		AST_LIST_UNLOCK(&dynamic_list);
1435
		AST_LIST_UNLOCK(&dynamic_list);
1436
	} else {
1436
	} else {
1437
		AST_LIST_LOCK(&idle_list);
1437
		AST_LIST_LOCK(&idle_list);
1438
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1438
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1439
		AST_LIST_UNLOCK(&idle_list);
1439
		AST_LIST_UNLOCK(&idle_list);
1440
	}
1440
	}
1441

    
   
1441

   
1442
	return;
1442
	return;
1443
}
1443
}
1444

    
   
1444

   
1445
static struct iax2_thread *find_idle_thread(void)
1445
static struct iax2_thread *find_idle_thread(void)
1446
{
1446
{
1447
	struct iax2_thread *thread = NULL;
1447
	struct iax2_thread *thread = NULL;
1448

    
   
1448

   
1449
	/* Pop the head of the idle list off */
1449
	/* Pop the head of the idle list off */
1450
	AST_LIST_LOCK(&idle_list);
1450
	AST_LIST_LOCK(&idle_list);
1451
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1451
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1452
	AST_LIST_UNLOCK(&idle_list);
1452
	AST_LIST_UNLOCK(&idle_list);
1453

    
   
1453

   
1454
	/* If we popped a thread off the idle list, just return it */
1454
	/* If we popped a thread off the idle list, just return it */
1455
	if (thread) {
1455
	if (thread) {
1456
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1456
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1457
		return thread;
1457
		return thread;
1458
	}
1458
	}
1459

    
   
1459

   
1460
	/* Pop the head of the dynamic list off */
1460
	/* Pop the head of the dynamic list off */
1461
	AST_LIST_LOCK(&dynamic_list);
1461
	AST_LIST_LOCK(&dynamic_list);
1462
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1462
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1463
	AST_LIST_UNLOCK(&dynamic_list);
1463
	AST_LIST_UNLOCK(&dynamic_list);
1464

    
   
1464

   
1465
	/* If we popped a thread off the dynamic list, just return it */
1465
	/* If we popped a thread off the dynamic list, just return it */
1466
	if (thread) {
1466
	if (thread) {
1467
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1467
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1468
		return thread;
1468
		return thread;
1469
	}
1469
	}
1470

    
   
1470

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

    
   
1474

   
1475
	/* Set default values */
1475
	/* Set default values */
1476
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1476
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1477
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1477
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1478
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1478
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1479

    
   
1479

   
1480
	/* Initialize lock and condition */
1480
	/* Initialize lock and condition */
1481
	ast_mutex_init(&thread->lock);
1481
	ast_mutex_init(&thread->lock);
1482
	ast_cond_init(&thread->cond, NULL);
1482
	ast_cond_init(&thread->cond, NULL);
1483
	ast_mutex_init(&thread->init_lock);
1483
	ast_mutex_init(&thread->init_lock);
1484
	ast_cond_init(&thread->init_cond, NULL);
1484
	ast_cond_init(&thread->init_cond, NULL);
1485
	ast_mutex_lock(&thread->init_lock);
1485
	ast_mutex_lock(&thread->init_lock);
1486

    
   
1486

   
1487
	/* Create thread and send it on it's way */
1487
	/* Create thread and send it on it's way */
1488
	if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1488
	if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1489
		ast_cond_destroy(&thread->cond);
1489
		ast_cond_destroy(&thread->cond);
1490
		ast_mutex_destroy(&thread->lock);
1490
		ast_mutex_destroy(&thread->lock);
1491
		ast_mutex_unlock(&thread->init_lock);
1491
		ast_mutex_unlock(&thread->init_lock);
1492
		ast_cond_destroy(&thread->init_cond);
1492
		ast_cond_destroy(&thread->init_cond);
1493
		ast_mutex_destroy(&thread->init_lock);
1493
		ast_mutex_destroy(&thread->init_lock);
1494
		ast_free(thread);
1494
		ast_free(thread);
1495
		return NULL;
1495
		return NULL;
1496
	}
1496
	}
1497

    
   
1497

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

    
   
1501

   
1502
	/* Wait for the thread to be ready before returning it to the caller */
1502
	/* Wait for the thread to be ready before returning it to the caller */
1503
	ast_cond_wait(&thread->init_cond, &thread->init_lock);
1503
	ast_cond_wait(&thread->init_cond, &thread->init_lock);
1504

    
   
1504

   
1505
	/* Done with init_lock */
1505
	/* Done with init_lock */
1506
	ast_mutex_unlock(&thread->init_lock);
1506
	ast_mutex_unlock(&thread->init_lock);
1507

    
   
1507

   
1508
	return thread;
1508
	return thread;
1509
}
1509
}
1510

    
   
1510

   
1511
#ifdef SCHED_MULTITHREADED
1511
#ifdef SCHED_MULTITHREADED
1512
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1512
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1513
{
1513
{
1514
	struct iax2_thread *thread = NULL;
1514
	struct iax2_thread *thread = NULL;
1515
	static time_t lasterror;
1515
	static time_t lasterror;
1516
	static time_t t;
1516
	static time_t t;
1517

    
   
1517

   
1518
	thread = find_idle_thread();
1518
	thread = find_idle_thread();
1519

    
   
1519

   
1520
	if (thread != NULL) {
1520
	if (thread != NULL) {
1521
		thread->schedfunc = func;
1521
		thread->schedfunc = func;
1522
		thread->scheddata = data;
1522
		thread->scheddata = data;
1523
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1523
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1524
#ifdef DEBUG_SCHED_MULTITHREAD
1524
#ifdef DEBUG_SCHED_MULTITHREAD
1525
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1525
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1526
#endif
1526
#endif
1527
		signal_condition(&thread->lock, &thread->cond);
1527
		signal_condition(&thread->lock, &thread->cond);
1528
		return 0;
1528
		return 0;
1529
	}
1529
	}
1530
	time(&t);
1530
	time(&t);
1531
	if (t != lasterror)
1531
	if (t != lasterror)
1532
		ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1532
		ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1533
	lasterror = t;
1533
	lasterror = t;
1534

    
   
1534

   
1535
	return -1;
1535
	return -1;
1536
}
1536
}
1537
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1537
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1538
#endif
1538
#endif
1539

    
   
1539

   
1540
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1540
static int iax2_sched_replace(int id, struct ast_sched_context *con, int when,
1541
		ast_sched_cb callback, const void *data)
1541
		ast_sched_cb callback, const void *data)
1542
{
1542
{
1543
	return ast_sched_replace(id, con, when, callback, data);
1543
	return ast_sched_replace(id, con, when, callback, data);
1544
}
1544
}
1545

    
   
1545

   
1546
static int iax2_sched_add(struct ast_sched_context *con, int when,
1546
static int iax2_sched_add(struct ast_sched_context *con, int when,
1547
		ast_sched_cb callback, const void *data)
1547
		ast_sched_cb callback, const void *data)
1548
{
1548
{
1549
	return ast_sched_add(con, when, callback, data);
1549
	return ast_sched_add(con, when, callback, data);
1550
}
1550
}
1551

    
   
1551

   
1552
static int send_ping(const void *data);
1552
static int send_ping(const void *data);
1553

    
   
1553

   
1554
static void __send_ping(const void *data)
1554
static void __send_ping(const void *data)
1555
{
1555
{
1556
	int callno = (long) data;
1556
	int callno = (long) data;
1557

    
   
1557

   
1558
	ast_mutex_lock(&iaxsl[callno]);
1558
	ast_mutex_lock(&iaxsl[callno]);
1559

    
   
1559

   
1560
	if (iaxs[callno]) {
1560
	if (iaxs[callno]) {
1561
		if (iaxs[callno]->peercallno) {
1561
		if (iaxs[callno]->peercallno) {
1562
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1562
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1563
			if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1563
			if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
1564
				iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1564
				iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1565
			}
1565
			}
1566
		}
1566
		}
1567
	} else {
1567
	} else {
1568
		ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1568
		ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
1569
	}
1569
	}
1570

    
   
1570

   
1571
	ast_mutex_unlock(&iaxsl[callno]);
1571
	ast_mutex_unlock(&iaxsl[callno]);
1572
}
1572
}
1573

    
   
1573

   
1574
static int send_ping(const void *data)
1574
static int send_ping(const void *data)
1575
{
1575
{
1576
	int callno = (long) data;
1576
	int callno = (long) data;
1577
	ast_mutex_lock(&iaxsl[callno]);
1577
	ast_mutex_lock(&iaxsl[callno]);
1578
	if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1578
	if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
1579
		iaxs[callno]->pingid = -1;
1579
		iaxs[callno]->pingid = -1;
1580
	}
1580
	}
1581
	ast_mutex_unlock(&iaxsl[callno]);
1581
	ast_mutex_unlock(&iaxsl[callno]);
1582

    
   
1582

   
1583
#ifdef SCHED_MULTITHREADED
1583
#ifdef SCHED_MULTITHREADED
1584
	if (schedule_action(__send_ping, data))
1584
	if (schedule_action(__send_ping, data))
1585
#endif
1585
#endif
1586
		__send_ping(data);
1586
		__send_ping(data);
1587

    
   
1587

   
1588
	return 0;
1588
	return 0;
1589
}
1589
}
1590

    
   
1590

   
1591
static void encmethods_to_str(int e, struct ast_str **buf)
1591
static void encmethods_to_str(int e, struct ast_str **buf)
1592
{
1592
{
1593
	ast_str_set(buf, 0, "(");
1593
	ast_str_set(buf, 0, "(");
1594
	if (e & IAX_ENCRYPT_AES128) {
1594
	if (e & IAX_ENCRYPT_AES128) {
1595
		ast_str_append(buf, 0, "aes128");
1595
		ast_str_append(buf, 0, "aes128");
1596
	}
1596
	}
1597
	if (e & IAX_ENCRYPT_KEYROTATE) {
1597
	if (e & IAX_ENCRYPT_KEYROTATE) {
1598
		ast_str_append(buf, 0, ",keyrotate");
1598
		ast_str_append(buf, 0, ",keyrotate");
1599
	}
1599
	}
1600
	if (ast_str_strlen(*buf) > 1) {
1600
	if (ast_str_strlen(*buf) > 1) {
1601
		ast_str_append(buf, 0, ")");
1601
		ast_str_append(buf, 0, ")");
1602
	} else {
1602
	} else {
1603
		ast_str_set(buf, 0, "No");
1603
		ast_str_set(buf, 0, "No");
1604
	}
1604
	}
1605
}
1605
}
1606

    
   
1606

   
1607
static int get_encrypt_methods(const char *s)
1607
static int get_encrypt_methods(const char *s)
1608
{
1608
{
1609
	int e;
1609
	int e;
1610
	if (!strcasecmp(s, "aes128"))
1610
	if (!strcasecmp(s, "aes128"))
1611
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1611
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1612
	else if (ast_true(s))
1612
	else if (ast_true(s))
1613
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1613
		e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
1614
	else
1614
	else
1615
		e = 0;
1615
		e = 0;
1616
	return e;
1616
	return e;
1617
}
1617
}
1618

    
   
1618

   
1619
static int send_lagrq(const void *data);
1619
static int send_lagrq(const void *data);
1620

    
   
1620

   
1621
static void __send_lagrq(const void *data)
1621
static void __send_lagrq(const void *data)
1622
{
1622
{
1623
	int callno = (long) data;
1623
	int callno = (long) data;
1624

    
   
1624

   
1625
	ast_mutex_lock(&iaxsl[callno]);
1625
	ast_mutex_lock(&iaxsl[callno]);
1626

    
   
1626

   
1627
	if (iaxs[callno]) {
1627
	if (iaxs[callno]) {
1628
		if (iaxs[callno]->peercallno) {
1628
		if (iaxs[callno]->peercallno) {
1629
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1629
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1630
			if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1630
			if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
1631
				iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1631
				iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1632
			}
1632
			}
1633
		}
1633
		}
1634
	} else {
1634
	} else {
1635
		ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1635
		ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
1636
	}
1636
	}
1637

    
   
1637

   
1638
	ast_mutex_unlock(&iaxsl[callno]);
1638
	ast_mutex_unlock(&iaxsl[callno]);
1639
}
1639
}
1640

    
   
1640

   
1641
static int send_lagrq(const void *data)
1641
static int send_lagrq(const void *data)
1642
{
1642
{
1643
	int callno = (long) data;
1643
	int callno = (long) data;
1644
	ast_mutex_lock(&iaxsl[callno]);
1644
	ast_mutex_lock(&iaxsl[callno]);
1645
	if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1645
	if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
1646
		iaxs[callno]->lagid = -1;
1646
		iaxs[callno]->lagid = -1;
1647
	}
1647
	}
1648
	ast_mutex_unlock(&iaxsl[callno]);
1648
	ast_mutex_unlock(&iaxsl[callno]);
1649

    
   
1649

   
1650
#ifdef SCHED_MULTITHREADED
1650
#ifdef SCHED_MULTITHREADED
1651
	if (schedule_action(__send_lagrq, data))
1651
	if (schedule_action(__send_lagrq, data))
1652
#endif
1652
#endif
1653
		__send_lagrq(data);
1653
		__send_lagrq(data);
1654
	return 0;
1654
	return 0;
1655
}
1655
}
1656

    
   
1656

   
1657
static unsigned char compress_subclass(iax2_format subclass)
1657
static unsigned char compress_subclass(iax2_format subclass)
1658
{
1658
{
1659
	int x;
1659
	int x;
1660
	int power=-1;
1660
	int power=-1;
1661
	/* If it's 64 or smaller, just return it */
1661
	/* If it's 64 or smaller, just return it */
1662
	if (subclass < IAX_FLAG_SC_LOG)
1662
	if (subclass < IAX_FLAG_SC_LOG)
1663
		return subclass;
1663
		return subclass;
1664
	/* Otherwise find its power */
1664
	/* Otherwise find its power */
1665
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1665
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1666
		if (subclass & (1LL << x)) {
1666
		if (subclass & (1LL << x)) {
1667
			if (power > -1) {
1667
			if (power > -1) {
1668
				ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1668
				ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
1669
				return 0;
1669
				return 0;
1670
			} else
1670
			} else
1671
				power = x;
1671
				power = x;
1672
		}
1672
		}
1673
	}
1673
	}
1674
	return power | IAX_FLAG_SC_LOG;
1674
	return power | IAX_FLAG_SC_LOG;
1675
}
1675
}
1676

    
   
1676

   
1677
static iax2_format uncompress_subclass(unsigned char csub)
1677
static iax2_format uncompress_subclass(unsigned char csub)
1678
{
1678
{
1679
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1679
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1680
	if (csub & IAX_FLAG_SC_LOG) {
1680
	if (csub & IAX_FLAG_SC_LOG) {
1681
		/* special case for 'compressed' -1 */
1681
		/* special case for 'compressed' -1 */
1682
		if (csub == 0xff)
1682
		if (csub == 0xff)
1683
			return -1;
1683
			return -1;
1684
		else
1684
		else
1685
			return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1685
			return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1686
	}
1686
	}
1687
	else
1687
	else
1688
		return csub;
1688
		return csub;
1689
}
1689
}
1690

    
   
1690

   
1691
static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1691
static iax2_format iax2_codec_choose(struct ast_codec_pref *pref, iax2_format formats, int find_best)
1692
{
1692
{
1693
	struct ast_format_cap *cap;
1693
	struct ast_format_cap *cap;
1694
	struct ast_format tmpfmt;
1694
	struct ast_format tmpfmt;
1695
	iax2_format format = 0;
1695
	iax2_format format = 0;
1696
	if ((cap = ast_format_cap_alloc_nolock())) {
1696
	if ((cap = ast_format_cap_alloc_nolock())) {
1697
		ast_format_clear(&tmpfmt);
1697
		ast_format_clear(&tmpfmt);
1698
		ast_format_cap_from_old_bitfield(cap, formats);
1698
		ast_format_cap_from_old_bitfield(cap, formats);
1699
		ast_codec_choose(pref, cap, find_best, &tmpfmt);
1699
		ast_codec_choose(pref, cap, find_best, &tmpfmt);
1700
		format = ast_format_to_old_bitfield(&tmpfmt);
1700
		format = ast_format_to_old_bitfield(&tmpfmt);
1701
		cap = ast_format_cap_destroy(cap);
1701
		cap = ast_format_cap_destroy(cap);
1702
	}
1702
	}
1703

    
   
1703

   
1704
	return format;
1704
	return format;
1705
}
1705
}
1706

    
   
1706

   
1707
static iax2_format iax2_best_codec(iax2_format formats)
1707
static iax2_format iax2_best_codec(iax2_format formats)
1708
{
1708
{
1709
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1709
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1710
	struct ast_format tmpfmt;
1710
	struct ast_format tmpfmt;
1711
	if (!cap) {
1711
	if (!cap) {
1712
		return 0;
1712
		return 0;
1713
	}
1713
	}
1714

    
   
1714

   
1715
	ast_format_clear(&tmpfmt);
1715
	ast_format_clear(&tmpfmt);
1716
	ast_format_cap_from_old_bitfield(cap, formats);
1716
	ast_format_cap_from_old_bitfield(cap, formats);
1717
	ast_best_codec(cap, &tmpfmt);
1717
	ast_best_codec(cap, &tmpfmt);
1718
	cap = ast_format_cap_destroy(cap);
1718
	cap = ast_format_cap_destroy(cap);
1719
	return ast_format_to_old_bitfield(&tmpfmt);
1719
	return ast_format_to_old_bitfield(&tmpfmt);
1720
}
1720
}
1721

    
   
1721

   
1722
const char *iax2_getformatname(iax2_format format)
1722
const char *iax2_getformatname(iax2_format format)
1723
{
1723
{
1724
	struct ast_format tmpfmt;
1724
	struct ast_format tmpfmt;
1725
	if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1725
	if (!(ast_format_from_old_bitfield(&tmpfmt, format))) {
1726
		return "Unknown";
1726
		return "Unknown";
1727
	}
1727
	}
1728

    
   
1728

   
1729
	return ast_getformatname(&tmpfmt);
1729
	return ast_getformatname(&tmpfmt);
1730
}
1730
}
1731

    
   
1731

   
1732
static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1732
static char *iax2_getformatname_multiple(char *codec_buf, size_t len, iax2_format format)
1733
{
1733
{
1734
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1734
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1735

    
   
1735

   
1736
	if (!cap) {
1736
	if (!cap) {
1737
		return "(Nothing)";
1737
		return "(Nothing)";
1738
	}
1738
	}
1739
	ast_format_cap_from_old_bitfield(cap, format);
1739
	ast_format_cap_from_old_bitfield(cap, format);
1740
	ast_getformatname_multiple(codec_buf, len, cap);
1740
	ast_getformatname_multiple(codec_buf, len, cap);
1741
	cap = ast_format_cap_destroy(cap);
1741
	cap = ast_format_cap_destroy(cap);
1742

    
   
1742

   
1743
	return codec_buf;
1743
	return codec_buf;
1744
}
1744
}
1745

    
   
1745

   
1746
static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1746
static int iax2_parse_allow_disallow(struct ast_codec_pref *pref, iax2_format *formats, const char *list, int allowing)
1747
{
1747
{
1748
	int res;
1748
	int res;
1749
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1749
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1750
	if (!cap) {
1750
	if (!cap) {
1751
		return 1;
1751
		return 1;
1752
	}
1752
	}
1753

    
   
1753

   
1754
	ast_format_cap_from_old_bitfield(cap, *formats);
1754
	ast_format_cap_from_old_bitfield(cap, *formats);
1755
	res = ast_parse_allow_disallow(pref, cap, list, allowing);
1755
	res = ast_parse_allow_disallow(pref, cap, list, allowing);
1756
	*formats = ast_format_cap_to_old_bitfield(cap);
1756
	*formats = ast_format_cap_to_old_bitfield(cap);
1757
	cap = ast_format_cap_destroy(cap);
1757
	cap = ast_format_cap_destroy(cap);
1758

    
   
1758

   
1759
	return res;
1759
	return res;
1760
}
1760
}
1761

    
   
1761

   
1762
static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1762
static int iax2_data_add_codecs(struct ast_data *root, const char *node_name, iax2_format formats)
1763
{
1763
{
1764
	int res;
1764
	int res;
1765
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1765
	struct ast_format_cap *cap = ast_format_cap_alloc_nolock();
1766
	if (!cap) {
1766
	if (!cap) {
1767
		return -1;
1767
		return -1;
1768
	}
1768
	}
1769
	ast_format_cap_from_old_bitfield(cap, formats);
1769
	ast_format_cap_from_old_bitfield(cap, formats);
1770
	res = ast_data_add_codecs(root, node_name, cap);
1770
	res = ast_data_add_codecs(root, node_name, cap);
1771
	cap = ast_format_cap_destroy(cap);
1771
	cap = ast_format_cap_destroy(cap);
1772
	return res;
1772
	return res;
1773
}
1773
}
1774

    
   
1774

   
1775
/*!
1775
/*!
1776
 * \note The only member of the peer passed here guaranteed to be set is the name field
1776
 * \note The only member of the peer passed here guaranteed to be set is the name field
1777
 */
1777
 */
1778
static int peer_hash_cb(const void *obj, const int flags)
1778
static int peer_hash_cb(const void *obj, const int flags)
1779
{
1779
{
1780
	const struct iax2_peer *peer = obj;
1780
	const struct iax2_peer *peer = obj;
1781
	const char *name = obj;
1781
	const char *name = obj;
1782

    
   
1782

   
1783
	return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1783
	return ast_str_hash(flags & OBJ_KEY ? name : peer->name);
1784
}
1784
}
1785

    
   
1785

   
1786
/*!
1786
/*!
1787
 * \note The only member of the peer passed here guaranteed to be set is the name field
1787
 * \note The only member of the peer passed here guaranteed to be set is the name field
1788
 */
1788
 */
1789
static int peer_cmp_cb(void *obj, void *arg, int flags)
1789
static int peer_cmp_cb(void *obj, void *arg, int flags)
1790
{
1790
{
1791
	struct iax2_peer *peer = obj, *peer2 = arg;
1791
	struct iax2_peer *peer = obj, *peer2 = arg;
1792
	const char *name = arg;
1792
	const char *name = arg;
1793

    
   
1793

   
1794
	return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1794
	return !strcmp(peer->name, flags & OBJ_KEY ? name : peer2->name) ?
1795
			CMP_MATCH | CMP_STOP : 0;
1795
			CMP_MATCH | CMP_STOP : 0;
1796
}
1796
}
1797

    
   
1797

   
1798
/*!
1798
/*!
1799
 * \note The only member of the user passed here guaranteed to be set is the name field
1799
 * \note The only member of the user passed here guaranteed to be set is the name field
1800
 */
1800
 */
1801
static int user_hash_cb(const void *obj, const int flags)
1801
static int user_hash_cb(const void *obj, const int flags)
1802
{
1802
{
1803
	const struct iax2_user *user = obj;
1803
	const struct iax2_user *user = obj;
1804
	const char *name = obj;
1804
	const char *name = obj;
1805

    
   
1805

   
1806
	return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1806
	return ast_str_hash(flags & OBJ_KEY ? name : user->name);
1807
}
1807
}
1808

    
   
1808

   
1809
/*!
1809
/*!
1810
 * \note The only member of the user passed here guaranteed to be set is the name field
1810
 * \note The only member of the user passed here guaranteed to be set is the name field
1811
 */
1811
 */
1812
static int user_cmp_cb(void *obj, void *arg, int flags)
1812
static int user_cmp_cb(void *obj, void *arg, int flags)
1813
{
1813
{
1814
	struct iax2_user *user = obj, *user2 = arg;
1814
	struct iax2_user *user = obj, *user2 = arg;
1815
	const char *name = arg;
1815
	const char *name = arg;
1816

    
   
1816

   
1817
	return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1817
	return !strcmp(user->name, flags & OBJ_KEY ? name : user2->name) ?
1818
			CMP_MATCH | CMP_STOP : 0;
1818
			CMP_MATCH | CMP_STOP : 0;
1819
}
1819
}
1820

    
   
1820

   
1821
/*!
1821
/*!
1822
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1822
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1823
 *       so do not call it with a pvt lock held.
1823
 *       so do not call it with a pvt lock held.
1824
 */
1824
 */
1825
static struct iax2_peer *find_peer(const char *name, int realtime) 
1825
static struct iax2_peer *find_peer(const char *name, int realtime) 
1826
{
1826
{
1827
	struct iax2_peer *peer = NULL;
1827
	struct iax2_peer *peer = NULL;
1828

    
   
1828

   
1829
	peer = ao2_find(peers, name, OBJ_KEY);
1829
	peer = ao2_find(peers, name, OBJ_KEY);
1830

    
   
1830

   
1831
	/* Now go for realtime if applicable */
1831
	/* Now go for realtime if applicable */
1832
	if(!peer && realtime)
1832
	if(!peer && realtime)
1833
		peer = realtime_peer(name, NULL);
1833
		peer = realtime_peer(name, NULL);
1834

    
   
1834

   
1835
	return peer;
1835
	return peer;
1836
}
1836
}
1837

    
   
1837

   
1838
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1838
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1839
{
1839
{
1840
	ao2_ref(peer, +1);
1840
	ao2_ref(peer, +1);
1841
	return peer;
1841
	return peer;
1842
}
1842
}
1843

    
   
1843

   
1844
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1844
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1845
{
1845
{
1846
	ao2_ref(peer, -1);
1846
	ao2_ref(peer, -1);
1847
	return NULL;
1847
	return NULL;
1848
}
1848
}
1849

    
   
1849

   
1850
static struct iax2_user *find_user(const char *name)
1850
static struct iax2_user *find_user(const char *name)
1851
{
1851
{
1852
	return ao2_find(users, name, OBJ_KEY);
1852
	return ao2_find(users, name, OBJ_KEY);
1853
}
1853
}
1854
static inline struct iax2_user *user_ref(struct iax2_user *user)
1854
static inline struct iax2_user *user_ref(struct iax2_user *user)
1855
{
1855
{
1856
	ao2_ref(user, +1);
1856
	ao2_ref(user, +1);
1857
	return user;
1857
	return user;
1858
}
1858
}
1859

    
   
1859

   
1860
static inline struct iax2_user *user_unref(struct iax2_user *user)
1860
static inline struct iax2_user *user_unref(struct iax2_user *user)
1861
{
1861
{
1862
	ao2_ref(user, -1);
1862
	ao2_ref(user, -1);
1863
	return NULL;
1863
	return NULL;
1864
}
1864
}
1865

    
   
1865

   
1866
static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1866
static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1867
{
1867
{
1868
	struct iax2_peer *peer = NULL;
1868
	struct iax2_peer *peer = NULL;
1869
	int res = 0;
1869
	int res = 0;
1870
	struct ao2_iterator i;
1870
	struct ao2_iterator i;
1871

    
   
1871

   
1872
	i = ao2_iterator_init(peers, 0);
1872
	i = ao2_iterator_init(peers, 0);
1873
	while ((peer = ao2_iterator_next(&i))) {
1873
	while ((peer = ao2_iterator_next(&i))) {
1874
		struct sockaddr_in peer_addr;
1874
		struct sockaddr_in peer_addr;
1875

    
   
1875

   
1876
		ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1876
		ast_sockaddr_to_sin(&peer->addr, &peer_addr);
1877

    
   
1877

   
1878
		if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1878
		if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1879
		    (peer_addr.sin_port == sin.sin_port)) {
1879
		    (peer_addr.sin_port == sin.sin_port)) {
1880
			ast_copy_string(host, peer->name, len);
1880
			ast_copy_string(host, peer->name, len);
1881
			peer_unref(peer);
1881
			peer_unref(peer);
1882
			res = 1;
1882
			res = 1;
1883
			break;
1883
			break;
1884
		}
1884
		}
1885
		peer_unref(peer);
1885
		peer_unref(peer);
1886
	}
1886
	}
1887
	ao2_iterator_destroy(&i);
1887
	ao2_iterator_destroy(&i);
1888

    
   
1888

   
1889
	if (!peer) {
1889
	if (!peer) {
1890
		peer = realtime_peer(NULL, &sin);
1890
		peer = realtime_peer(NULL, &sin);
1891
		if (peer) {
1891
		if (peer) {
1892
			ast_copy_string(host, peer->name, len);
1892
			ast_copy_string(host, peer->name, len);
1893
			peer_unref(peer);
1893
			peer_unref(peer);
1894
			res = 1;
1894
			res = 1;
1895
		}
1895
		}
1896
	}
1896
	}
1897

    
   
1897

   
1898
	return res;
1898
	return res;
1899
}
1899
}
1900

    
   
1900

   
1901
/*!\note Assumes the lock on the pvt is already held, when
1901
/*!\note Assumes the lock on the pvt is already held, when
1902
 * iax2_destroy_helper() is called. */
1902
 * iax2_destroy_helper() is called. */
1903
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1903
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1904
{
1904
{
1905
	/* Decrement AUTHREQ count if needed */
1905
	/* Decrement AUTHREQ count if needed */
1906
	if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1906
	if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
1907
		struct iax2_user *user;
1907
		struct iax2_user *user;
1908

    
   
1908

   
1909
		user = ao2_find(users, pvt->username, OBJ_KEY);
1909
		user = ao2_find(users, pvt->username, OBJ_KEY);
1910
		if (user) {
1910
		if (user) {
1911
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
1911
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
1912
			user_unref(user);
1912
			user_unref(user);
1913
		}
1913
		}
1914

    
   
1914

   
1915
		ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1915
		ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
1916
	}
1916
	}
1917
	/* No more pings or lagrq's */
1917
	/* No more pings or lagrq's */
1918
	AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1918
	AST_SCHED_DEL_SPINLOCK(sched, pvt->pingid, &iaxsl[pvt->callno]);
1919
	pvt->pingid = DONT_RESCHEDULE;
1919
	pvt->pingid = DONT_RESCHEDULE;
1920
	AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1920
	AST_SCHED_DEL_SPINLOCK(sched, pvt->lagid, &iaxsl[pvt->callno]);
1921
	pvt->lagid = DONT_RESCHEDULE;
1921
	pvt->lagid = DONT_RESCHEDULE;
1922
	AST_SCHED_DEL(sched, pvt->autoid);
1922
	AST_SCHED_DEL(sched, pvt->autoid);
1923
	AST_SCHED_DEL(sched, pvt->authid);
1923
	AST_SCHED_DEL(sched, pvt->authid);
1924
	AST_SCHED_DEL(sched, pvt->initid);
1924
	AST_SCHED_DEL(sched, pvt->initid);
1925
	AST_SCHED_DEL(sched, pvt->jbid);
1925
	AST_SCHED_DEL(sched, pvt->jbid);
1926
	AST_SCHED_DEL(sched, pvt->keyrotateid);
1926
	AST_SCHED_DEL(sched, pvt->keyrotateid);
1927
}
1927
}
1928

    
   
1928

   
1929
static void iax2_frame_free(struct iax_frame *fr)
1929
static void iax2_frame_free(struct iax_frame *fr)
1930
{
1930
{
1931
	AST_SCHED_DEL(sched, fr->retrans);
1931
	AST_SCHED_DEL(sched, fr->retrans);
1932
	iax_frame_free(fr);
1932
	iax_frame_free(fr);
1933
}
1933
}
1934

    
   
1934

   
1935
static int scheduled_destroy(const void *vid)
1935
static int scheduled_destroy(const void *vid)
1936
{
1936
{
1937
	unsigned short callno = PTR_TO_CALLNO(vid);
1937
	unsigned short callno = PTR_TO_CALLNO(vid);
1938
	ast_mutex_lock(&iaxsl[callno]);
1938
	ast_mutex_lock(&iaxsl[callno]);
1939
	if (iaxs[callno]) {
1939
	if (iaxs[callno]) {
1940
		ast_debug(1, "Really destroying %d now...\n", callno);
1940
		ast_debug(1, "Really destroying %d now...\n", callno);
1941
		iax2_destroy(callno);
1941
		iax2_destroy(callno);
1942
	}
1942
	}
1943
	ast_mutex_unlock(&iaxsl[callno]);
1943
	ast_mutex_unlock(&iaxsl[callno]);
1944
	return 0;
1944
	return 0;
1945
}
1945
}
1946

    
   
1946

   
1947
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1947
static void free_signaling_queue_entry(struct signaling_queue_entry *s)
1948
{
1948
{
1949
	if (s->f.datalen) {
1949
	if (s->f.datalen) {
1950
		ast_free(s->f.data.ptr);
1950
		ast_free(s->f.data.ptr);
1951
	}
1951
	}
1952
	ast_free(s);
1952
	ast_free(s);
1953
}
1953
}
1954

    
   
1954

   
1955
/*! \brief This function must be called once we are sure the other side has
1955
/*! \brief This function must be called once we are sure the other side has
1956
 *  given us a call number.  All signaling is held here until that point. */
1956
 *  given us a call number.  All signaling is held here until that point. */
1957
static void send_signaling(struct chan_iax2_pvt *pvt)
1957
static void send_signaling(struct chan_iax2_pvt *pvt)
1958
{
1958
{
1959
	struct signaling_queue_entry *s = NULL;
1959
	struct signaling_queue_entry *s = NULL;
1960

    
   
1960

   
1961
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1961
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
1962
		iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1962
		iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
1963
		free_signaling_queue_entry(s);
1963
		free_signaling_queue_entry(s);
1964
	}
1964
	}
1965
	pvt->hold_signaling = 0;
1965
	pvt->hold_signaling = 0;
1966
}
1966
}
1967

    
   
1967

   
1968
/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1968
/*! \brief All frames other than that of type AST_FRAME_IAX must be held until
1969
 *  we have received a destination call number. */
1969
 *  we have received a destination call number. */
1970
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1970
static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
1971
{
1971
{
1972
	struct signaling_queue_entry *qe;
1972
	struct signaling_queue_entry *qe;
1973

    
   
1973

   
1974
	if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1974
	if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
1975
		return 1; /* do not queue this frame */
1975
		return 1; /* do not queue this frame */
1976
	} else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1976
	} else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
1977
		return -1;  /* out of memory */
1977
		return -1;  /* out of memory */
1978
	}
1978
	}
1979

    
   
1979

   
1980
	/* copy ast_frame into our queue entry */
1980
	/* copy ast_frame into our queue entry */
1981
	qe->f = *f;
1981
	qe->f = *f;
1982
	if (qe->f.datalen) {
1982
	if (qe->f.datalen) {
1983
		/* if there is data in this frame copy it over as well */
1983
		/* if there is data in this frame copy it over as well */
1984
		if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1984
		if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
1985
			free_signaling_queue_entry(qe);
1985
			free_signaling_queue_entry(qe);
1986
			return -1;
1986
			return -1;
1987
		}
1987
		}
1988
		memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
1988
		memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
1989
	}
1989
	}
1990
	AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
1990
	AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
1991

    
   
1991

   
1992
	return 0;
1992
	return 0;
1993
}
1993
}
1994

    
   
1994

   
1995
static void pvt_destructor(void *obj)
1995
static void pvt_destructor(void *obj)
1996
{
1996
{
1997
	struct chan_iax2_pvt *pvt = obj;
1997
	struct chan_iax2_pvt *pvt = obj;
1998
	struct iax_frame *cur = NULL;
1998
	struct iax_frame *cur = NULL;
1999
	struct signaling_queue_entry *s = NULL;
1999
	struct signaling_queue_entry *s = NULL;
2000

    
   
2000

   
2001
	ast_mutex_lock(&iaxsl[pvt->callno]);
2001
	ast_mutex_lock(&iaxsl[pvt->callno]);
2002

    
   
2002

   
2003
	iax2_destroy_helper(pvt);
2003
	iax2_destroy_helper(pvt);
2004

    
   
2004

   
2005
	sched_delay_remove(&pvt->addr, pvt->callno_entry);
2005
	sched_delay_remove(&pvt->addr, pvt->callno_entry);
2006
	pvt->callno_entry = NULL;
2006
	pvt->callno_entry = NULL;
2007

    
   
2007

   
2008
	/* Already gone */
2008
	/* Already gone */
2009
	ast_set_flag64(pvt, IAX_ALREADYGONE);
2009
	ast_set_flag64(pvt, IAX_ALREADYGONE);
2010

    
   
2010

   
2011
	AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2011
	AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
2012
		/* Cancel any pending transmissions */
2012
		/* Cancel any pending transmissions */
2013
		cur->retries = -1;
2013
		cur->retries = -1;
2014
	}
2014
	}
2015

    
   
2015

   
2016
	ast_mutex_unlock(&iaxsl[pvt->callno]);
2016
	ast_mutex_unlock(&iaxsl[pvt->callno]);
2017

    
   
2017

   
2018
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2018
	while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
2019
		free_signaling_queue_entry(s);
2019
		free_signaling_queue_entry(s);
2020
	}
2020
	}
2021

    
   
2021

   
2022
	if (pvt->reg) {
2022
	if (pvt->reg) {
2023
		pvt->reg->callno = 0;
2023
		pvt->reg->callno = 0;
2024
	}
2024
	}
2025

    
   
2025

   
2026
	if (!pvt->owner) {
2026
	if (!pvt->owner) {
2027
		jb_frame frame;
2027
		jb_frame frame;
2028
		if (pvt->vars) {
2028
		if (pvt->vars) {
2029
		    ast_variables_destroy(pvt->vars);
2029
		    ast_variables_destroy(pvt->vars);
2030
		    pvt->vars = NULL;
2030
		    pvt->vars = NULL;
2031
		}
2031
		}
2032

    
   
2032

   
2033
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
2033
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
2034
			iax2_frame_free(frame.data);
2034
			iax2_frame_free(frame.data);
2035
		}
2035
		}
2036

    
   
2036

   
2037
		jb_destroy(pvt->jb);
2037
		jb_destroy(pvt->jb);
2038
		ast_string_field_free_memory(pvt);
2038
		ast_string_field_free_memory(pvt);
2039
	}
2039
	}
2040

    
   
2040

   
2041
	if (pvt->callid) {
2041
	if (pvt->callid) {
2042
		ast_callid_unref(pvt->callid);
2042
		ast_callid_unref(pvt->callid);
2043
	}
2043
	}
2044

    
   
2044

   
2045
}
2045
}
2046

    
   
2046

   
2047
static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2047
static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
2048
{
2048
{
2049
	struct chan_iax2_pvt *tmp;
2049
	struct chan_iax2_pvt *tmp;
2050
	jb_conf jbconf;
2050
	jb_conf jbconf;
2051

    
   
2051

   
2052
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2052
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
2053
		return NULL;
2053
		return NULL;
2054
	}
2054
	}
2055

    
   
2055

   
2056
	if (ast_string_field_init(tmp, 32)) {
2056
	if (ast_string_field_init(tmp, 32)) {
2057
		ao2_ref(tmp, -1);
2057
		ao2_ref(tmp, -1);
2058
		tmp = NULL;
2058
		tmp = NULL;
2059
		return NULL;
2059
		return NULL;
2060
	}
2060
	}
2061
		
2061
		
2062
	tmp->prefs = prefs;
2062
	tmp->prefs = prefs;
2063
	tmp->pingid = -1;
2063
	tmp->pingid = -1;
2064
	tmp->lagid = -1;
2064
	tmp->lagid = -1;
2065
	tmp->autoid = -1;
2065
	tmp->autoid = -1;
2066
	tmp->authid = -1;
2066
	tmp->authid = -1;
2067
	tmp->initid = -1;
2067
	tmp->initid = -1;
2068
	tmp->keyrotateid = -1;
2068
	tmp->keyrotateid = -1;
2069

    
   
2069

   
2070
	ast_string_field_set(tmp,exten, "s");
2070
	ast_string_field_set(tmp,exten, "s");
2071
	ast_string_field_set(tmp,host, host);
2071
	ast_string_field_set(tmp,host, host);
2072

    
   
2072

   
2073
	tmp->jb = jb_new();
2073
	tmp->jb = jb_new();
2074
	tmp->jbid = -1;
2074
	tmp->jbid = -1;
2075
	jbconf.max_jitterbuf = maxjitterbuffer;
2075
	jbconf.max_jitterbuf = maxjitterbuffer;
2076
	jbconf.resync_threshold = resyncthreshold;
2076
	jbconf.resync_threshold = resyncthreshold;
2077
	jbconf.max_contig_interp = maxjitterinterps;
2077
	jbconf.max_contig_interp = maxjitterinterps;
2078
	jbconf.target_extra = jittertargetextra;
2078
	jbconf.target_extra = jittertargetextra;
2079
	jb_setconf(tmp->jb,&jbconf);
2079
	jb_setconf(tmp->jb,&jbconf);
2080

    
   
2080

   
2081
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2081
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
2082

    
   
2082

   
2083
	tmp->hold_signaling = 1;
2083
	tmp->hold_signaling = 1;
2084
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2084
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
2085

    
   
2085

   
2086
	return tmp;
2086
	return tmp;
2087
}
2087
}
2088

    
   
2088

   
2089
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2089
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
2090
{
2090
{
2091
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2091
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
2092
	if (new) {
2092
	if (new) {
2093
		size_t afdatalen = new->afdatalen;
2093
		size_t afdatalen = new->afdatalen;
2094
		memcpy(new, fr, sizeof(*new));
2094
		memcpy(new, fr, sizeof(*new));
2095
		iax_frame_wrap(new, &fr->af);
2095
		iax_frame_wrap(new, &fr->af);
2096
		new->afdatalen = afdatalen;
2096
		new->afdatalen = afdatalen;
2097
		new->data = NULL;
2097
		new->data = NULL;
2098
		new->datalen = 0;
2098
		new->datalen = 0;
2099
		new->direction = DIRECTION_INGRESS;
2099
		new->direction = DIRECTION_INGRESS;
2100
		new->retrans = -1;
2100
		new->retrans = -1;
2101
	}
2101
	}
2102
	return new;
2102
	return new;
2103
}
2103
}
2104
/* keep these defined in this order.  They are used in find_callno to
2104
/* keep these defined in this order.  They are used in find_callno to
2105
 * determine whether or not a new call number should be allowed. */
2105
 * determine whether or not a new call number should be allowed. */
2106
enum {
2106
enum {
2107
	/* do not allow a new call number, only search ones in use for match */
2107
	/* do not allow a new call number, only search ones in use for match */
2108
	NEW_PREVENT = 0,
2108
	NEW_PREVENT = 0,
2109
	/* search for match first, then allow a new one to be allocated */
2109
	/* search for match first, then allow a new one to be allocated */
2110
	NEW_ALLOW = 1,
2110
	NEW_ALLOW = 1,
2111
	/* do not search for match, force a new call number */
2111
	/* do not search for match, force a new call number */
2112
	NEW_FORCE = 2,
2112
	NEW_FORCE = 2,
2113
	/* do not search for match, force a new call number.  Signifies call number
2113
	/* do not search for match, force a new call number.  Signifies call number
2114
	 * has been calltoken validated */
2114
	 * has been calltoken validated */
2115
	NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2115
	NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
2116
};
2116
};
2117

    
   
2117

   
2118
static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2118
static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
2119
{
2119
{
2120
	if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2120
	if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2121
		(cur->addr.sin_port == sin->sin_port)) {
2121
		(cur->addr.sin_port == sin->sin_port)) {
2122
		/* This is the main host */
2122
		/* This is the main host */
2123
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2123
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
2124
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
2124
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
2125
			/* That's us.  Be sure we keep track of the peer call number */
2125
			/* That's us.  Be sure we keep track of the peer call number */
2126
			return 1;
2126
			return 1;
2127
		}
2127
		}
2128
	}
2128
	}
2129
	if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2129
	if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
2130
	    (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2130
	    (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
2131
		/* We're transferring */
2131
		/* We're transferring */
2132
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2132
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
2133
			return 1;
2133
			return 1;
2134
	}
2134
	}
2135
	return 0;
2135
	return 0;
2136
}
2136
}
2137

    
   
2137

   
2138
static int make_trunk(unsigned short callno, int locked)
2138
static int make_trunk(unsigned short callno, int locked)
2139
{
2139
{
2140
	int x;
2140
	int x;
2141
	int res= 0;
2141
	int res= 0;
2142
	struct callno_entry *callno_entry;
2142
	struct callno_entry *callno_entry;
2143
	if (iaxs[callno]->oseqno) {
2143
	if (iaxs[callno]->oseqno) {
2144
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2144
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
2145
		return -1;
2145
		return -1;
2146
	}
2146
	}
2147
	if (callno >= TRUNK_CALL_START) {
2147
	if (callno >= TRUNK_CALL_START) {
2148
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2148
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
2149
		return -1;
2149
		return -1;
2150
	}
2150
	}
2151

    
   
2151

   
2152
	if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2152
	if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
2153
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2153
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
2154
		return -1;
2154
		return -1;
2155
	}
2155
	}
2156

    
   
2156

   
2157
	x = callno_entry->callno;
2157
	x = callno_entry->callno;
2158
	ast_mutex_lock(&iaxsl[x]);
2158
	ast_mutex_lock(&iaxsl[x]);
2159

    
   
2159

   
2160
	/*!
2160
	/*!
2161
	 * \note We delete these before switching the slot, because if
2161
	 * \note We delete these before switching the slot, because if
2162
	 * they fire in the meantime, they will generate a warning.
2162
	 * they fire in the meantime, they will generate a warning.
2163
	 */
2163
	 */
2164
	AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2164
	AST_SCHED_DEL(sched, iaxs[callno]->pingid);
2165
	AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2165
	AST_SCHED_DEL(sched, iaxs[callno]->lagid);
2166
	iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2166
	iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
2167
	iaxs[x] = iaxs[callno];
2167
	iaxs[x] = iaxs[callno];
2168
	iaxs[x]->callno = x;
2168
	iaxs[x]->callno = x;
2169

    
   
2169

   
2170
	/* since we copied over the pvt from a different callno, make sure the old entry is replaced
2170
	/* since we copied over the pvt from a different callno, make sure the old entry is replaced
2171
	 * before assigning the new one */
2171
	 * before assigning the new one */
2172
	if (iaxs[x]->callno_entry) {
2172
	if (iaxs[x]->callno_entry) {
2173
		iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2173
		iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
2174
	}
2174
	}
2175
	iaxs[x]->callno_entry = callno_entry;
2175
	iaxs[x]->callno_entry = callno_entry;
2176

    
   
2176

   
2177
	iaxs[callno] = NULL;
2177
	iaxs[callno] = NULL;
2178
	/* Update the two timers that should have been started */
2178
	/* Update the two timers that should have been started */
2179
	iaxs[x]->pingid = iax2_sched_add(sched, 
2179
	iaxs[x]->pingid = iax2_sched_add(sched, 
2180
		ping_time * 1000, send_ping, (void *)(long)x);
2180
		ping_time * 1000, send_ping, (void *)(long)x);
2181
	iaxs[x]->lagid = iax2_sched_add(sched, 
2181
	iaxs[x]->lagid = iax2_sched_add(sched, 
2182
		lagrq_time * 1000, send_lagrq, (void *)(long)x);
2182
		lagrq_time * 1000, send_lagrq, (void *)(long)x);
2183

    
   
2183

   
2184
	if (locked)
2184
	if (locked)
2185
		ast_mutex_unlock(&iaxsl[callno]);
2185
		ast_mutex_unlock(&iaxsl[callno]);
2186
	res = x;
2186
	res = x;
2187
	if (!locked)
2187
	if (!locked)
2188
		ast_mutex_unlock(&iaxsl[x]);
2188
		ast_mutex_unlock(&iaxsl[x]);
2189

    
   
2189

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

    
   
2192

   
2193
	return res;
2193
	return res;
2194
}
2194
}
2195

    
   
2195

   
2196
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2196
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
2197
{
2197
{
2198
	if (!pvt->transfercallno) {
2198
	if (!pvt->transfercallno) {
2199
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2199
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2200
		return;
2200
		return;
2201
	}
2201
	}
2202

    
   
2202

   
2203
	ao2_link(iax_transfercallno_pvts, pvt);
2203
	ao2_link(iax_transfercallno_pvts, pvt);
2204
}
2204
}
2205

    
   
2205

   
2206
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2206
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
2207
{
2207
{
2208
	if (!pvt->transfercallno) {
2208
	if (!pvt->transfercallno) {
2209
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2209
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
2210
		return;
2210
		return;
2211
	}
2211
	}
2212

    
   
2212

   
2213
	ao2_unlink(iax_transfercallno_pvts, pvt);
2213
	ao2_unlink(iax_transfercallno_pvts, pvt);
2214
}
2214
}
2215
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2215
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
2216
{
2216
{
2217
	if (!pvt->peercallno) {
2217
	if (!pvt->peercallno) {
2218
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2218
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2219
		return;
2219
		return;
2220
	}
2220
	}
2221

    
   
2221

   
2222
	ao2_link(iax_peercallno_pvts, pvt);
2222
	ao2_link(iax_peercallno_pvts, pvt);
2223
}
2223
}
2224

    
   
2224

   
2225
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2225
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
2226
{
2226
{
2227
	if (!pvt->peercallno) {
2227
	if (!pvt->peercallno) {
2228
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2228
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
2229
		return;
2229
		return;
2230
	}
2230
	}
2231

    
   
2231

   
2232
	ao2_unlink(iax_peercallno_pvts, pvt);
2232
	ao2_unlink(iax_peercallno_pvts, pvt);
2233
}
2233
}
2234

    
   
2234

   
2235
static int addr_range_delme_cb(void *obj, void *arg, int flags)
2235
static int addr_range_delme_cb(void *obj, void *arg, int flags)
2236
{
2236
{
2237
	struct addr_range *lim = obj;
2237
	struct addr_range *lim = obj;
2238
	lim->delme = 1;
2238
	lim->delme = 1;
2239
	return 0;
2239
	return 0;
2240
}
2240
}
2241

    
   
2241

   
2242
static int addr_range_hash_cb(const void *obj, const int flags)
2242
static int addr_range_hash_cb(const void *obj, const int flags)
2243
{
2243
{
2244
	const struct addr_range *lim = obj;
2244
	const struct addr_range *lim = obj;
2245
	struct sockaddr_in sin;
2245
	struct sockaddr_in sin;
2246
	ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2246
	ast_sockaddr_to_sin(&lim->ha.addr, &sin);
2247
	return abs((int) sin.sin_addr.s_addr);
2247
	return abs((int) sin.sin_addr.s_addr);
2248
}
2248
}
2249

    
   
2249

   
2250
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2250
static int addr_range_cmp_cb(void *obj, void *arg, int flags)
2251
{
2251
{
2252
	struct addr_range *lim1 = obj, *lim2 = arg;
2252
	struct addr_range *lim1 = obj, *lim2 = arg;
2253
	return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2253
	return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
2254
			!(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2254
			!(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
2255
			CMP_MATCH | CMP_STOP : 0;
2255
			CMP_MATCH | CMP_STOP : 0;
2256
}
2256
}
2257

    
   
2257

   
2258
static int peercnt_hash_cb(const void *obj, const int flags)
2258
static int peercnt_hash_cb(const void *obj, const int flags)
2259
{
2259
{
2260
	const struct peercnt *peercnt = obj;
2260
	const struct peercnt *peercnt = obj;
2261
	return abs((int) peercnt->addr);
2261
	return abs((int) peercnt->addr);
2262
}
2262
}
2263

    
   
2263

   
2264
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2264
static int peercnt_cmp_cb(void *obj, void *arg, int flags)
2265
{
2265
{
2266
	struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2266
	struct peercnt *peercnt1 = obj, *peercnt2 = arg;
2267
	return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2267
	return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
2268
}
2268
}
2269

    
   
2269

   
2270
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2270
static int addr_range_match_address_cb(void *obj, void *arg, int flags)
2271
{
2271
{
2272
	struct addr_range *addr_range = obj;
2272
	struct addr_range *addr_range = obj;
2273
	struct sockaddr_in *sin = arg;
2273
	struct sockaddr_in *sin = arg;
2274
	struct sockaddr_in ha_netmask_sin;
2274
	struct sockaddr_in ha_netmask_sin;
2275
	struct sockaddr_in ha_addr_sin;
2275
	struct sockaddr_in ha_addr_sin;
2276

    
   
2276

   
2277
	ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2277
	ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
2278
	ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2278
	ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
2279

    
   
2279

   
2280
	if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2280
	if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
2281
		return CMP_MATCH | CMP_STOP;
2281
		return CMP_MATCH | CMP_STOP;
2282
	}
2282
	}
2283
	return 0;
2283
	return 0;
2284
}
2284
}
2285

    
   
2285

   
2286
/*! 
2286
/*! 
2287
 * \internal
2287
 * \internal
2288
 *
2288
 *
2289
 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2289
 * \brief compares sin to calltoken_ignores table to determine if validation is required.
2290
 */
2290
 */
2291
static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2291
static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
2292
{
2292
{
2293
	struct addr_range *addr_range;
2293
	struct addr_range *addr_range;
2294
	struct iax2_peer *peer = NULL;
2294
	struct iax2_peer *peer = NULL;
2295
	struct iax2_user *user = NULL;
2295
	struct iax2_user *user = NULL;
2296
	/* if no username is given, check for guest accounts */
2296
	/* if no username is given, check for guest accounts */
2297
	const char *find = S_OR(name, "guest");
2297
	const char *find = S_OR(name, "guest");
2298
	int res = 1;  /* required by default */
2298
	int res = 1;  /* required by default */
2299
	int optional = 0;
2299
	int optional = 0;
2300
	enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2300
	enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
2301
	/* There are only two cases in which calltoken validation is not required.
2301
	/* There are only two cases in which calltoken validation is not required.
2302
	 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2302
	 * Case 1. sin falls within the list of address ranges specified in the calltoken optional table and
2303
	 *         the peer definition has not set the requirecalltoken option.
2303
	 *         the peer definition has not set the requirecalltoken option.
2304
	 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2304
	 * Case 2. Username is a valid peer/user, and that peer has requirecalltoken set either auto or no.
2305
	 */
2305
	 */
2306

    
   
2306

   
2307
	/* ----- Case 1 ----- */
2307
	/* ----- Case 1 ----- */
2308
	if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2308
	if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
2309
		ao2_ref(addr_range, -1);
2309
		ao2_ref(addr_range, -1);
2310
		optional = 1;
2310
		optional = 1;
2311
	}
2311
	}
2312

    
   
2312

   
2313
	/* ----- Case 2 ----- */
2313
	/* ----- Case 2 ----- */
2314
	if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2314
	if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
2315
		calltoken_required = user->calltoken_required;
2315
		calltoken_required = user->calltoken_required;
2316
	} else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2316
	} else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
2317
		calltoken_required = user->calltoken_required;
2317
		calltoken_required = user->calltoken_required;
2318
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2318
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
2319
		calltoken_required = peer->calltoken_required;
2319
		calltoken_required = peer->calltoken_required;
2320
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2320
	} else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
2321
		calltoken_required = peer->calltoken_required;
2321
		calltoken_required = peer->calltoken_required;
2322
	}
2322
	}
2323

    
   
2323

   
2324
	if (peer) {
2324
	if (peer) {
2325
		peer_unref(peer);
2325
		peer_unref(peer);
2326
	}
2326
	}
2327
	if (user) {
2327
	if (user) {
2328
		user_unref(user);
2328
		user_unref(user);
2329
	}
2329
	}
2330

    
   
2330

   
2331
	ast_debug(1, "Determining if address %s with username %s requires calltoken validation.  Optional = %d  calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2331
	ast_debug(1, "Determining if address %s with username %s requires calltoken validation.  Optional = %d  calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
2332
	if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2332
	if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
2333
		(optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2333
		(optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
2334
		res = 0;
2334
		res = 0;
2335
	}
2335
	}
2336

    
   
2336

   
2337
	return res;
2337
	return res;
2338
}
2338
}
2339

    
   
2339

   
2340
/*! 
2340
/*! 
2341
 * \internal
2341
 * \internal
2342
 *
2342
 *
2343
 * \brief set peercnt callno limit.
2343
 * \brief set peercnt callno limit.
2344
 *
2344
 *
2345
 * \details 
2345
 * \details 
2346
 * First looks in custom definitions. If not found, global limit
2346
 * First looks in custom definitions. If not found, global limit
2347
 * is used.  Entries marked as reg already have
2347
 * is used.  Entries marked as reg already have
2348
 * a custom limit set by a registration and are not modified.
2348
 * a custom limit set by a registration and are not modified.
2349
 */
2349
 */
2350
static void set_peercnt_limit(struct peercnt *peercnt)
2350
static void set_peercnt_limit(struct peercnt *peercnt)
2351
{
2351
{
2352
	uint16_t limit = global_maxcallno;
2352
	uint16_t limit = global_maxcallno;
2353
	struct addr_range *addr_range;
2353
	struct addr_range *addr_range;
2354
	struct sockaddr_in sin = {
2354
	struct sockaddr_in sin = {
2355
		.sin_addr.s_addr = peercnt->addr,
2355
		.sin_addr.s_addr = peercnt->addr,
2356
	};
2356
	};
2357

    
   
2357

   
2358

    
   
2358

   
2359
	if (peercnt->reg && peercnt->limit) {
2359
	if (peercnt->reg && peercnt->limit) {
2360
		return; /* this peercnt has a custom limit set by a registration */
2360
		return; /* this peercnt has a custom limit set by a registration */
2361
	}
2361
	}
2362

    
   
2362

   
2363
	if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2363
	if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
2364
		limit = addr_range->limit;
2364
		limit = addr_range->limit;
2365
		ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2365
		ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
2366
		ao2_ref(addr_range, -1);
2366
		ao2_ref(addr_range, -1);
2367
	}
2367
	}
2368

    
   
2368

   
2369
	peercnt->limit = limit;
2369
	peercnt->limit = limit;
2370
}
2370
}
2371

    
   
2371

   
2372
/*! 
2372
/*! 
2373
 * \internal
2373
 * \internal
2374
 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2374
 * \brief sets limits for all peercnts in table. done on reload to reflect changes in conf.
2375
 */
2375
 */
2376
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2376
static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
2377
{
2377
{
2378
	struct peercnt *peercnt = obj;
2378
	struct peercnt *peercnt = obj;
2379

    
   
2379

   
2380
	set_peercnt_limit(peercnt);
2380
	set_peercnt_limit(peercnt);
2381
	ast_debug(1, "Reset limits for peercnts table\n");
2381
	ast_debug(1, "Reset limits for peercnts table\n");
2382

    
   
2382

   
2383
	return 0;
2383
	return 0;
2384
}
2384
}
2385

    
   
2385

   
2386
/*! 
2386
/*! 
2387
 * \internal
2387
 * \internal
2388
 * \brief returns match if delme is set. 
2388
 * \brief returns match if delme is set. 
2389
 */
2389
 */
2390
static int prune_addr_range_cb(void *obj, void *arg, int flags)
2390
static int prune_addr_range_cb(void *obj, void *arg, int flags)
2391
{
2391
{
2392
	struct addr_range *addr_range = obj;
2392
	struct addr_range *addr_range = obj;
2393

    
   
2393

   
2394
	return addr_range->delme ? CMP_MATCH : 0;
2394
	return addr_range->delme ? CMP_MATCH : 0;
2395
}
2395
}
2396

    
   
2396

   
2397
/*! 
2397
/*! 
2398
 * \internal
2398
 * \internal
2399
 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2399
 * \brief modifies peercnt entry in peercnts table. Used to set custom limit or mark a registered ip
2400
 */
2400
 */
2401
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2401
static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
2402
{
2402
{
2403
	/* this function turns off and on custom callno limits set by peer registration */
2403
	/* this function turns off and on custom callno limits set by peer registration */
2404
	struct peercnt *peercnt;
2404
	struct peercnt *peercnt;
2405
	struct peercnt tmp = {
2405
	struct peercnt tmp = {
2406
		.addr = 0,
2406
		.addr = 0,
2407
	};
2407
	};
2408
	struct sockaddr_in sin;
2408
	struct sockaddr_in sin;
2409

    
   
2409

   
2410
	ast_sockaddr_to_sin(sockaddr, &sin);
2410
	ast_sockaddr_to_sin(sockaddr, &sin);
2411

    
   
2411

   
2412
	tmp.addr = sin.sin_addr.s_addr;
2412
	tmp.addr = sin.sin_addr.s_addr;
2413

    
   
2413

   
2414
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2414
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2415
		peercnt->reg = reg;
2415
		peercnt->reg = reg;
2416
		if (limit) {
2416
		if (limit) {
2417
			peercnt->limit = limit;
2417
			peercnt->limit = limit;
2418
		} else {
2418
		} else {
2419
			set_peercnt_limit(peercnt);
2419
			set_peercnt_limit(peercnt);
2420
		}
2420
		}
2421
		ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2421
		ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
2422
		ao2_ref(peercnt, -1); /* decrement ref from find */
2422
		ao2_ref(peercnt, -1); /* decrement ref from find */
2423
	}
2423
	}
2424
}
2424
}
2425

    
   
2425

   
2426
/*! 
2426
/*! 
2427
 * \internal
2427
 * \internal
2428
 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2428
 * \brief adds an ip to the peercnts table, increments connection count if it already exists
2429
 *
2429
 *
2430
 * \details First searches for the address in the peercnts table.  If found
2430
 * \details First searches for the address in the peercnts table.  If found
2431
 * the current count is incremented.  If not found a new peercnt is allocated
2431
 * the current count is incremented.  If not found a new peercnt is allocated
2432
 * and linked into the peercnts table with a call number count of 1.
2432
 * and linked into the peercnts table with a call number count of 1.
2433
 */
2433
 */
2434
static int peercnt_add(struct sockaddr_in *sin)
2434
static int peercnt_add(struct sockaddr_in *sin)
2435
{
2435
{
2436
	struct peercnt *peercnt;
2436
	struct peercnt *peercnt;
2437
	unsigned long addr = sin->sin_addr.s_addr;
2437
	unsigned long addr = sin->sin_addr.s_addr;
2438
	int res = 0;
2438
	int res = 0;
2439
	struct peercnt tmp = {
2439
	struct peercnt tmp = {
2440
		.addr = addr,
2440
		.addr = addr,
2441
	};
2441
	};
2442

    
   
2442

   
2443
	/* Reasoning for peercnts container lock:  Two identical ip addresses
2443
	/* Reasoning for peercnts container lock:  Two identical ip addresses
2444
	 * could be added by different threads at the "same time". Without the container
2444
	 * could be added by different threads at the "same time". Without the container
2445
	 * lock, both threads could alloc space for the same object and attempt
2445
	 * lock, both threads could alloc space for the same object and attempt
2446
	 * to link to table.  With the lock, one would create the object and link
2446
	 * to link to table.  With the lock, one would create the object and link
2447
	 * to table while the other would find the already created peercnt object
2447
	 * to table while the other would find the already created peercnt object
2448
	 * rather than creating a new one. */
2448
	 * rather than creating a new one. */
2449
	ao2_lock(peercnts);
2449
	ao2_lock(peercnts);
2450
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2450
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2451
		ao2_lock(peercnt);
2451
		ao2_lock(peercnt);
2452
	} else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2452
	} else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
2453
		ao2_lock(peercnt);
2453
		ao2_lock(peercnt);
2454
		/* create and set defaults */
2454
		/* create and set defaults */
2455
		peercnt->addr = addr;
2455
		peercnt->addr = addr;
2456
		set_peercnt_limit(peercnt);
2456
		set_peercnt_limit(peercnt);
2457
		/* guarantees it does not go away after unlocking table
2457
		/* guarantees it does not go away after unlocking table
2458
		 * ao2_find automatically adds this */
2458
		 * ao2_find automatically adds this */
2459
		ao2_link(peercnts, peercnt);
2459
		ao2_link(peercnts, peercnt);
2460
	} else {
2460
	} else {
2461
		ao2_unlock(peercnts);
2461
		ao2_unlock(peercnts);
2462
		return -1;
2462
		return -1;
2463
	}
2463
	}
2464

    
   
2464

   
2465
	/* check to see if the address has hit its callno limit.  If not increment cur. */
2465
	/* check to see if the address has hit its callno limit.  If not increment cur. */
2466
	if (peercnt->limit > peercnt->cur) {
2466
	if (peercnt->limit > peercnt->cur) {
2467
		peercnt->cur++;
2467
		peercnt->cur++;
2468
		ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2468
		ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
2469
	} else { /* max num call numbers for this peer has been reached! */
2469
	} else { /* max num call numbers for this peer has been reached! */
2470
		ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2470
		ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
2471
		res = -1;
2471
		res = -1;
2472
	}
2472
	}
2473

    
   
2473

   
2474
	/* clean up locks and ref count */
2474
	/* clean up locks and ref count */
2475
	ao2_unlock(peercnt);
2475
	ao2_unlock(peercnt);
2476
	ao2_unlock(peercnts);
2476
	ao2_unlock(peercnts);
2477
	ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2477
	ao2_ref(peercnt, -1); /* decrement ref from find/alloc, only the container ref remains. */
2478

    
   
2478

   
2479
	return res;
2479
	return res;
2480
}
2480
}
2481

    
   
2481

   
2482
/*! 
2482
/*! 
2483
 * \internal
2483
 * \internal
2484
 * \brief decrements a peercnts table entry
2484
 * \brief decrements a peercnts table entry
2485
 */
2485
 */
2486
static void peercnt_remove(struct peercnt *peercnt)
2486
static void peercnt_remove(struct peercnt *peercnt)
2487
{
2487
{
2488
	struct sockaddr_in sin = {
2488
	struct sockaddr_in sin = {
2489
		.sin_addr.s_addr = peercnt->addr,
2489
		.sin_addr.s_addr = peercnt->addr,
2490
	};
2490
	};
2491

    
   
2491

   
2492
	/*
2492
	/*
2493
	 * Container locked here since peercnt may be unlinked from
2493
	 * Container locked here since peercnt may be unlinked from
2494
	 * list.  If left unlocked, peercnt_add could try and grab this
2494
	 * list.  If left unlocked, peercnt_add could try and grab this
2495
	 * entry from the table and modify it at the "same time" this
2495
	 * entry from the table and modify it at the "same time" this
2496
	 * thread attemps to unlink it.
2496
	 * thread attemps to unlink it.
2497
	 */
2497
	 */
2498
	ao2_lock(peercnts);
2498
	ao2_lock(peercnts);
2499
	peercnt->cur--;
2499
	peercnt->cur--;
2500
	ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2500
	ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
2501
	/* if this was the last connection from the peer remove it from table */
2501
	/* if this was the last connection from the peer remove it from table */
2502
	if (peercnt->cur == 0) {
2502
	if (peercnt->cur == 0) {
2503
		ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2503
		ao2_unlink(peercnts, peercnt);/* decrements ref from table, last ref is left to scheduler */
2504
	}
2504
	}
2505
	ao2_unlock(peercnts);
2505
	ao2_unlock(peercnts);
2506
}
2506
}
2507

    
   
2507

   
2508
/*! 
2508
/*! 
2509
 * \internal
2509
 * \internal
2510
 * \brief called by scheduler to decrement object
2510
 * \brief called by scheduler to decrement object
2511
 */
2511
 */
2512
static int peercnt_remove_cb(const void *obj)
2512
static int peercnt_remove_cb(const void *obj)
2513
{
2513
{
2514
	struct peercnt *peercnt = (struct peercnt *) obj;
2514
	struct peercnt *peercnt = (struct peercnt *) obj;
2515

    
   
2515

   
2516
	peercnt_remove(peercnt);
2516
	peercnt_remove(peercnt);
2517
	ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2517
	ao2_ref(peercnt, -1); /* decrement ref from scheduler */
2518

    
   
2518

   
2519
	return 0;
2519
	return 0;
2520
}
2520
}
2521

    
   
2521

   
2522
/*! 
2522
/*! 
2523
 * \internal
2523
 * \internal
2524
 * \brief decrements peercnts connection count, finds by addr
2524
 * \brief decrements peercnts connection count, finds by addr
2525
 */
2525
 */
2526
static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2526
static int peercnt_remove_by_addr(struct sockaddr_in *sin)
2527
{
2527
{
2528
	struct peercnt *peercnt;
2528
	struct peercnt *peercnt;
2529
	struct peercnt tmp = {
2529
	struct peercnt tmp = {
2530
		.addr = sin->sin_addr.s_addr,
2530
		.addr = sin->sin_addr.s_addr,
2531
	};
2531
	};
2532

    
   
2532

   
2533
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2533
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2534
		peercnt_remove(peercnt);
2534
		peercnt_remove(peercnt);
2535
		ao2_ref(peercnt, -1); /* decrement ref from find */
2535
		ao2_ref(peercnt, -1); /* decrement ref from find */
2536
	}
2536
	}
2537
	return 0;
2537
	return 0;
2538
}
2538
}
2539

    
   
2539

   
2540
/*! 
2540
/*! 
2541
 * \internal
2541
 * \internal
2542
 * \brief Create callno_limit entry based on configuration
2542
 * \brief Create callno_limit entry based on configuration
2543
 */
2543
 */
2544
static void build_callno_limits(struct ast_variable *v)
2544
static void build_callno_limits(struct ast_variable *v)
2545
{
2545
{
2546
	struct addr_range *addr_range = NULL;
2546
	struct addr_range *addr_range = NULL;
2547
	struct addr_range tmp;
2547
	struct addr_range tmp;
2548
	struct ast_ha *ha;
2548
	struct ast_ha *ha;
2549
	int limit;
2549
	int limit;
2550
	int error;
2550
	int error;
2551
	int found;
2551
	int found;
2552

    
   
2552

   
2553
	for (; v; v = v->next) {
2553
	for (; v; v = v->next) {
2554
		limit = -1;
2554
		limit = -1;
2555
		error = 0;
2555
		error = 0;
2556
		found = 0;
2556
		found = 0;
2557
		ha = ast_append_ha("permit", v->name, NULL, &error);
2557
		ha = ast_append_ha("permit", v->name, NULL, &error);
2558

    
   
2558

   
2559
		/* check for valid config information */
2559
		/* check for valid config information */
2560
		if (error) {
2560
		if (error) {
2561
			ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2561
			ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
2562
			continue;
2562
			continue;
2563
		} else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2563
		} else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
2564
			ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2564
			ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
2565
			ast_free_ha(ha);
2565
			ast_free_ha(ha);
2566
			continue;
2566
			continue;
2567
		}
2567
		}
2568

    
   
2568

   
2569
		ast_copy_ha(ha, &tmp.ha);
2569
		ast_copy_ha(ha, &tmp.ha);
2570
		/* find or create the addr_range */
2570
		/* find or create the addr_range */
2571
		if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2571
		if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
2572
			ao2_lock(addr_range);
2572
			ao2_lock(addr_range);
2573
			found = 1;
2573
			found = 1;
2574
		} else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2574
		} else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2575
			ast_free_ha(ha);
2575
			ast_free_ha(ha);
2576
			return; /* out of memory */
2576
			return; /* out of memory */
2577
		}
2577
		}
2578

    
   
2578

   
2579
		/* copy over config data into addr_range object */
2579
		/* copy over config data into addr_range object */
2580
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2580
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible for each limit */
2581
		ast_free_ha(ha); /* cleanup the tmp ha */
2581
		ast_free_ha(ha); /* cleanup the tmp ha */
2582
		addr_range->limit = limit;
2582
		addr_range->limit = limit;
2583
		addr_range->delme = 0;
2583
		addr_range->delme = 0;
2584

    
   
2584

   
2585
		/* cleanup */
2585
		/* cleanup */
2586
		if (found) {
2586
		if (found) {
2587
			ao2_unlock(addr_range);
2587
			ao2_unlock(addr_range);
2588
		} else {
2588
		} else {
2589
			ao2_link(callno_limits, addr_range);
2589
			ao2_link(callno_limits, addr_range);
2590
		}
2590
		}
2591
		ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2591
		ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2592
	}
2592
	}
2593
}
2593
}
2594

    
   
2594

   
2595
/*! 
2595
/*! 
2596
 * \internal
2596
 * \internal
2597
 * \brief Create calltoken_ignores entry based on configuration
2597
 * \brief Create calltoken_ignores entry based on configuration
2598
 */
2598
 */
2599
static int add_calltoken_ignore(const char *addr)
2599
static int add_calltoken_ignore(const char *addr)
2600
{
2600
{
2601
	struct addr_range tmp;
2601
	struct addr_range tmp;
2602
	struct addr_range *addr_range = NULL;
2602
	struct addr_range *addr_range = NULL;
2603
	struct ast_ha *ha = NULL;
2603
	struct ast_ha *ha = NULL;
2604
	int error = 0;
2604
	int error = 0;
2605

    
   
2605

   
2606
	if (ast_strlen_zero(addr)) {
2606
	if (ast_strlen_zero(addr)) {
2607
		ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2607
		ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
2608
		return -1;
2608
		return -1;
2609
	}
2609
	}
2610

    
   
2610

   
2611
	ha = ast_append_ha("permit", addr, NULL, &error);
2611
	ha = ast_append_ha("permit", addr, NULL, &error);
2612

    
   
2612

   
2613
	/* check for valid config information */
2613
	/* check for valid config information */
2614
	if (error) {
2614
	if (error) {
2615
		ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2615
		ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
2616
		return -1;
2616
		return -1;
2617
	}
2617
	}
2618

    
   
2618

   
2619
	ast_copy_ha(ha, &tmp.ha);
2619
	ast_copy_ha(ha, &tmp.ha);
2620
	/* find or create the addr_range */
2620
	/* find or create the addr_range */
2621
	if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2621
	if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
2622
		ao2_lock(addr_range);
2622
		ao2_lock(addr_range);
2623
		addr_range->delme = 0;
2623
		addr_range->delme = 0;
2624
		ao2_unlock(addr_range);
2624
		ao2_unlock(addr_range);
2625
	} else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2625
	} else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
2626
		/* copy over config data into addr_range object */
2626
		/* copy over config data into addr_range object */
2627
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2627
		ast_copy_ha(ha, &addr_range->ha); /* this is safe because only one ha is possible */
2628
		ao2_link(calltoken_ignores, addr_range);
2628
		ao2_link(calltoken_ignores, addr_range);
2629
	} else {
2629
	} else {
2630
		ast_free_ha(ha);
2630
		ast_free_ha(ha);
2631
		return -1;
2631
		return -1;
2632
	}
2632
	}
2633

    
   
2633

   
2634
	ast_free_ha(ha);
2634
	ast_free_ha(ha);
2635
	ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2635
	ao2_ref(addr_range, -1); /* decrement ref from ao2_find and ao2_alloc, only container ref remains */
2636

    
   
2636

   
2637
	return 0;
2637
	return 0;
2638
}
2638
}
2639

    
   
2639

   
2640
static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2640
static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2641
{
2641
{
2642
	struct ao2_iterator i;
2642
	struct ao2_iterator i;
2643
	struct peercnt *peercnt;
2643
	struct peercnt *peercnt;
2644
	struct sockaddr_in sin;
2644
	struct sockaddr_in sin;
2645
	int found = 0;
2645
	int found = 0;
2646

    
   
2646

   
2647
	switch (cmd) {
2647
	switch (cmd) {
2648
	case CLI_INIT:
2648
	case CLI_INIT:
2649
		e->command = "iax2 show callnumber usage";
2649
		e->command = "iax2 show callnumber usage";
2650
		e->usage =
2650
		e->usage =
2651
			"Usage: iax2 show callnumber usage [IP address]\n"
2651
			"Usage: iax2 show callnumber usage [IP address]\n"
2652
			"       Shows current IP addresses which are consuming iax2 call numbers\n";
2652
			"       Shows current IP addresses which are consuming iax2 call numbers\n";
2653
		return NULL;
2653
		return NULL;
2654
	case CLI_GENERATE:
2654
	case CLI_GENERATE:
2655
		return NULL;
2655
		return NULL;
2656
	case CLI_HANDLER:
2656
	case CLI_HANDLER:
2657
		if (a->argc < 4 || a->argc > 5)
2657
		if (a->argc < 4 || a->argc > 5)
2658
			return CLI_SHOWUSAGE;
2658
			return CLI_SHOWUSAGE;
2659

    
   
2659

   
2660
		if (a->argc == 4) {
2660
		if (a->argc == 4) {
2661
			ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2661
			ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2662
		}
2662
		}
2663

    
   
2663

   
2664
		i = ao2_iterator_init(peercnts, 0);
2664
		i = ao2_iterator_init(peercnts, 0);
2665
		while ((peercnt = ao2_iterator_next(&i))) {
2665
		while ((peercnt = ao2_iterator_next(&i))) {
2666
			sin.sin_addr.s_addr = peercnt->addr;
2666
			sin.sin_addr.s_addr = peercnt->addr;
2667
			if (a->argc == 5) {
2667
			if (a->argc == 5) {
2668
				if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2668
				if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
2669
					ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2669
					ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
2670
					ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2670
					ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2671
					ao2_ref(peercnt, -1);
2671
					ao2_ref(peercnt, -1);
2672
					found = 1;
2672
					found = 1;
2673
					break;
2673
					break;
2674
				}
2674
				}
2675
			} else {
2675
			} else {
2676
				ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2676
				ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
2677
			}
2677
			}
2678
			ao2_ref(peercnt, -1);
2678
			ao2_ref(peercnt, -1);
2679
		}
2679
		}
2680
		ao2_iterator_destroy(&i);
2680
		ao2_iterator_destroy(&i);
2681

    
   
2681

   
2682
		if (a->argc == 4) {
2682
		if (a->argc == 4) {
2683
			ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2683
			ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
2684
			                 "Non-CallToken Validated Callno Used:   %d\n",
2684
			                 "Non-CallToken Validated Callno Used:   %d\n",
2685
				global_maxcallno_nonval,
2685
				global_maxcallno_nonval,
2686
				total_nonval_callno_used);
2686
				total_nonval_callno_used);
2687

    
   
2687

   
2688
			ast_cli(a->fd,   "Total Available Callno:                %d\n"
2688
			ast_cli(a->fd,   "Total Available Callno:                %d\n"
2689
			                 "Regular Callno Available:              %d\n"
2689
			                 "Regular Callno Available:              %d\n"
2690
			                 "Trunk Callno Available:                %d\n",
2690
			                 "Trunk Callno Available:                %d\n",
2691
				ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2691
				ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
2692
				ao2_container_count(callno_pool),
2692
				ao2_container_count(callno_pool),
2693
				ao2_container_count(callno_pool_trunk));
2693
				ao2_container_count(callno_pool_trunk));
2694
		} else if (a->argc == 5 && !found) {
2694
		} else if (a->argc == 5 && !found) {
2695
			ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2695
			ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
2696
		}
2696
		}
2697

    
   
2697

   
2698

    
   
2698

   
2699
		return CLI_SUCCESS;
2699
		return CLI_SUCCESS;
2700
	default:
2700
	default:
2701
		return NULL;
2701
		return NULL;
2702
	}
2702
	}
2703
}
2703
}
2704

    
   
2704

   
2705
static struct callno_entry *get_unused_callno(int trunk, int validated)
2705
static struct callno_entry *get_unused_callno(int trunk, int validated)
2706
{
2706
{
2707
	struct callno_entry *callno_entry = NULL;
2707
	struct callno_entry *callno_entry = NULL;
2708
	if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2708
	if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
2709
		ast_log(LOG_WARNING, "Out of CallNumbers\n");
2709
		ast_log(LOG_WARNING, "Out of CallNumbers\n");
2710
		/* Minor optimization for the extreme case. */
2710
		/* Minor optimization for the extreme case. */
2711
		return NULL;
2711
		return NULL;
2712
	}
2712
	}
2713

    
   
2713

   
2714
	/* the callno_pool container is locked here primarily to ensure thread
2714
	/* the callno_pool container is locked here primarily to ensure thread
2715
	 * safety of the total_nonval_callno_used check and increment */
2715
	 * safety of the total_nonval_callno_used check and increment */
2716
	ao2_lock(callno_pool);
2716
	ao2_lock(callno_pool);
2717

    
   
2717

   
2718
	/* only a certain number of nonvalidated call numbers should be allocated.
2718
	/* only a certain number of nonvalidated call numbers should be allocated.
2719
	 * If there ever is an attack, this separates the calltoken validating
2719
	 * If there ever is an attack, this separates the calltoken validating
2720
	 * users from the non calltoken validating users. */
2720
	 * users from the non calltoken validating users. */
2721
	if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2721
	if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
2722
		ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2722
		ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
2723
		ao2_unlock(callno_pool);
2723
		ao2_unlock(callno_pool);
2724
		return NULL;
2724
		return NULL;
2725
	}
2725
	}
2726

    
   
2726

   
2727
	/* unlink the object from the container, taking over ownership
2727
	/* unlink the object from the container, taking over ownership
2728
	 * of the reference the container had to the object */
2728
	 * of the reference the container had to the object */
2729
	callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2729
	callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
2730

    
   
2730

   
2731
	if (callno_entry) {
2731
	if (callno_entry) {
2732
		callno_entry->validated = validated;
2732
		callno_entry->validated = validated;
2733
		if (!validated) {
2733
		if (!validated) {
2734
			total_nonval_callno_used++;
2734
			total_nonval_callno_used++;
2735
		}
2735
		}
2736
	}
2736
	}
2737

    
   
2737

   
2738
	ao2_unlock(callno_pool);
2738
	ao2_unlock(callno_pool);
2739
	return callno_entry;
2739
	return callno_entry;
2740
}
2740
}
2741

    
   
2741

   
2742
static int replace_callno(const void *obj)
2742
static int replace_callno(const void *obj)
2743
{
2743
{
2744
	struct callno_entry *callno_entry = (struct callno_entry *) obj;
2744
	struct callno_entry *callno_entry = (struct callno_entry *) obj;
2745

    
   
2745

   
2746
	/* the callno_pool container is locked here primarily to ensure thread
2746
	/* the callno_pool container is locked here primarily to ensure thread
2747
	 * safety of the total_nonval_callno_used check and decrement */
2747
	 * safety of the total_nonval_callno_used check and decrement */
2748
	ao2_lock(callno_pool);
2748
	ao2_lock(callno_pool);
2749

    
   
2749

   
2750
	if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2750
	if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
2751
		total_nonval_callno_used--;
2751
		total_nonval_callno_used--;
2752
	} else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2752
	} else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
2753
		ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2753
		ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
2754
	}
2754
	}
2755

    
   
2755

   
2756
	if (callno_entry->callno < TRUNK_CALL_START) {
2756
	if (callno_entry->callno < TRUNK_CALL_START) {
2757
		ao2_link(callno_pool, callno_entry);
2757
		ao2_link(callno_pool, callno_entry);
2758
	} else {
2758
	} else {
2759
		ao2_link(callno_pool_trunk, callno_entry);
2759
		ao2_link(callno_pool_trunk, callno_entry);
2760
	}
2760
	}
2761
	ao2_ref(callno_entry, -1); /* only container ref remains */
2761
	ao2_ref(callno_entry, -1); /* only container ref remains */
2762

    
   
2762

   
2763
	ao2_unlock(callno_pool);
2763
	ao2_unlock(callno_pool);
2764
	return 0;
2764
	return 0;
2765
}
2765
}
2766

    
   
2766

   
2767
static int callno_hash(const void *obj, const int flags)
2767
static int callno_hash(const void *obj, const int flags)
2768
{
2768
{
2769
	return abs(ast_random());
2769
	return abs(ast_random());
2770
}
2770
}
2771

    
   
2771

   
2772
static int create_callno_pools(void)
2772
static int create_callno_pools(void)
2773
{
2773
{
2774
	uint16_t i;
2774
	uint16_t i;
2775

    
   
2775

   
2776
	if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2776
	if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2777
		return -1;
2777
		return -1;
2778
	}
2778
	}
2779

    
   
2779

   
2780
	if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2780
	if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
2781
		return -1;
2781
		return -1;
2782
	}
2782
	}
2783

    
   
2783

   
2784
	/* start at 2, 0 and 1 are reserved */
2784
	/* start at 2, 0 and 1 are reserved */
2785
	for (i = 2; i < IAX_MAX_CALLS; i++) {
2785
	for (i = 2; i < IAX_MAX_CALLS; i++) {
2786
		struct callno_entry *callno_entry;
2786
		struct callno_entry *callno_entry;
2787

    
   
2787

   
2788
		if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2788
		if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
2789
			return -1;
2789
			return -1;
2790
		}
2790
		}
2791

    
   
2791

   
2792
		callno_entry->callno = i;
2792
		callno_entry->callno = i;
2793

    
   
2793

   
2794
		if (i < TRUNK_CALL_START) {
2794
		if (i < TRUNK_CALL_START) {
2795
			ao2_link(callno_pool, callno_entry);
2795
			ao2_link(callno_pool, callno_entry);
2796
		} else {
2796
		} else {
2797
			ao2_link(callno_pool_trunk, callno_entry);
2797
			ao2_link(callno_pool_trunk, callno_entry);
2798
		}
2798
		}
2799

    
   
2799

   
2800
		ao2_ref(callno_entry, -1);
2800
		ao2_ref(callno_entry, -1);
2801
	}
2801
	}
2802

    
   
2802

   
2803
	return 0;
2803
	return 0;
2804
}
2804
}
2805

    
   
2805

   
2806
/*!
2806
/*!
2807
 * \internal
2807
 * \internal
2808
 * \brief Schedules delayed removal of iax2_pvt call number data
2808
 * \brief Schedules delayed removal of iax2_pvt call number data
2809
 *
2809
 *
2810
 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2810
 * \note After MIN_REUSE_TIME has passed for a destroyed iax2_pvt, the callno is
2811
 * avaliable again, and the address from the previous connection must be decremented
2811
 * avaliable again, and the address from the previous connection must be decremented
2812
 * from the peercnts table.  This function schedules these operations to take place.
2812
 * from the peercnts table.  This function schedules these operations to take place.
2813
 */
2813
 */
2814
static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2814
static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
2815
{
2815
{
2816
	int i;
2816
	int i;
2817
	struct peercnt *peercnt;
2817
	struct peercnt *peercnt;
2818
	struct peercnt tmp = {
2818
	struct peercnt tmp = {
2819
		.addr = sin->sin_addr.s_addr,
2819
		.addr = sin->sin_addr.s_addr,
2820
	};
2820
	};
2821

    
   
2821

   
2822
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2822
	if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
2823
		/* refcount is incremented with ao2_find.  keep that ref for the scheduler */
2823
		/* refcount is incremented with ao2_find.  keep that ref for the scheduler */
2824
		ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2824
		ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
2825
		i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2825
		i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
2826
		if (i == -1) {
2826
		if (i == -1) {
2827
			ao2_ref(peercnt, -1);
2827
			ao2_ref(peercnt, -1);
2828
		}
2828
		}
2829
	}
2829
	}
2830

    
   
2830

   
2831
	iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2831
	iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
2832
}
2832
}
2833

    
   
2833

   
2834
/*! 
2834
/*! 
2835
 * \internal
2835
 * \internal
2836
 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
2836
 * \brief returns whether or not a frame is capable of starting a new IAX2 dialog. 
2837
 *
2837
 *
2838
 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2838
 * \note For this implementation, inbound pokes should _NOT_ be capable of allocating
2839
 * a new callno.
2839
 * a new callno.
2840
 */
2840
 */
2841
static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2841
static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
2842
{
2842
{
2843
	if (frametype != AST_FRAME_IAX) {
2843
	if (frametype != AST_FRAME_IAX) {
2844
		return 0;
2844
		return 0;
2845
	}
2845
	}
2846
	switch (subclass) {
2846
	switch (subclass) {
2847
	case IAX_COMMAND_NEW:
2847
	case IAX_COMMAND_NEW:
2848
	case IAX_COMMAND_REGREQ:
2848
	case IAX_COMMAND_REGREQ:
2849
	case IAX_COMMAND_FWDOWNL:
2849
	case IAX_COMMAND_FWDOWNL:
2850
	case IAX_COMMAND_REGREL:
2850
	case IAX_COMMAND_REGREL:
2851
		return 1;
2851
		return 1;
2852
	case IAX_COMMAND_POKE:
2852
	case IAX_COMMAND_POKE:
2853
		if (!inbound) {
2853
		if (!inbound) {
2854
			return 1;
2854
			return 1;
2855
		}
2855
		}
2856
		break;
2856
		break;
2857
	}
2857
	}
2858
	return 0;
2858
	return 0;
2859
}
2859
}
2860

    
   
2860

   
2861
/*
2861
/*
2862
 * \note Calling this function while holding another pvt lock can cause a deadlock.
2862
 * \note Calling this function while holding another pvt lock can cause a deadlock.
2863
 */
2863
 */
2864
static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2864
static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
2865
{
2865
{
2866
	int res = 0;
2866
	int res = 0;
2867
	int x;
2867
	int x;
2868
	/* this call is calltoken validated as long as it is either NEW_FORCE
2868
	/* this call is calltoken validated as long as it is either NEW_FORCE
2869
	 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2869
	 * or NEW_ALLOW_CALLTOKEN_VALIDATED */
2870
	int validated = (new > NEW_ALLOW) ? 1 : 0;
2870
	int validated = (new > NEW_ALLOW) ? 1 : 0;
2871
	char host[80];
2871
	char host[80];
2872

    
   
2872

   
2873
	if (new <= NEW_ALLOW) {
2873
	if (new <= NEW_ALLOW) {
2874
		if (callno) {
2874
		if (callno) {
2875
			struct chan_iax2_pvt *pvt;
2875
			struct chan_iax2_pvt *pvt;
2876
			struct chan_iax2_pvt tmp_pvt = {
2876
			struct chan_iax2_pvt tmp_pvt = {
2877
				.callno = dcallno,
2877
				.callno = dcallno,
2878
				.peercallno = callno,
2878
				.peercallno = callno,
2879
				.transfercallno = callno,
2879
				.transfercallno = callno,
2880
				/* hack!! */
2880
				/* hack!! */
2881
				.frames_received = check_dcallno,
2881
				.frames_received = check_dcallno,
2882
			};
2882
			};
2883

    
   
2883

   
2884
			memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2884
			memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
2885
			/* this works for finding normal call numbers not involving transfering */ 
2885
			/* this works for finding normal call numbers not involving transfering */ 
2886
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2886
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2887
				if (return_locked) {
2887
				if (return_locked) {
2888
					ast_mutex_lock(&iaxsl[pvt->callno]);
2888
					ast_mutex_lock(&iaxsl[pvt->callno]);
2889
				}
2889
				}
2890
				res = pvt->callno;
2890
				res = pvt->callno;
2891
				ao2_ref(pvt, -1);
2891
				ao2_ref(pvt, -1);
2892
				pvt = NULL;
2892
				pvt = NULL;
2893
				return res;
2893
				return res;
2894
			}
2894
			}
2895
			/* this searches for transfer call numbers that might not get caught otherwise */
2895
			/* this searches for transfer call numbers that might not get caught otherwise */
2896
			memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2896
			memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
2897
			memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2897
			memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
2898
			if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2898
			if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
2899
				if (return_locked) {
2899
				if (return_locked) {
2900
					ast_mutex_lock(&iaxsl[pvt->callno]);
2900
					ast_mutex_lock(&iaxsl[pvt->callno]);
2901
				}
2901
				}
2902
				res = pvt->callno;
2902
				res = pvt->callno;
2903
				ao2_ref(pvt, -1);
2903
				ao2_ref(pvt, -1);
2904
				pvt = NULL;
2904
				pvt = NULL;
2905
				return res;
2905
				return res;
2906
			}
2906
			}
2907
		}
2907
		}
2908
			/* This will occur on the first response to a message that we initiated,
2908
			/* This will occur on the first response to a message that we initiated,
2909
		 * such as a PING. */
2909
		 * such as a PING. */
2910
		if (dcallno) {
2910
		if (dcallno) {
2911
			ast_mutex_lock(&iaxsl[dcallno]);
2911
			ast_mutex_lock(&iaxsl[dcallno]);
2912
		}
2912
		}
2913
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2913
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
2914
			iaxs[dcallno]->peercallno = callno;
2914
			iaxs[dcallno]->peercallno = callno;
2915
			res = dcallno;
2915
			res = dcallno;
2916
			store_by_peercallno(iaxs[dcallno]);
2916
			store_by_peercallno(iaxs[dcallno]);
2917
			if (!res || !return_locked) {
2917
			if (!res || !return_locked) {
2918
				ast_mutex_unlock(&iaxsl[dcallno]);
2918
				ast_mutex_unlock(&iaxsl[dcallno]);
2919
			}
2919
			}
2920
			return res;
2920
			return res;
2921
		}
2921
		}
2922
		if (dcallno) {
2922
		if (dcallno) {
2923
			ast_mutex_unlock(&iaxsl[dcallno]);
2923
			ast_mutex_unlock(&iaxsl[dcallno]);
2924
		}
2924
		}
2925
	}
2925
	}
2926
	if (!res && (new >= NEW_ALLOW)) {
2926
	if (!res && (new >= NEW_ALLOW)) {
2927
		struct callno_entry *callno_entry;
2927
		struct callno_entry *callno_entry;
2928
		/* It may seem odd that we look through the peer list for a name for
2928
		/* It may seem odd that we look through the peer list for a name for
2929
		 * this *incoming* call.  Well, it is weird.  However, users don't
2929
		 * this *incoming* call.  Well, it is weird.  However, users don't
2930
		 * have an IP address/port number that we can match against.  So,
2930
		 * have an IP address/port number that we can match against.  So,
2931
		 * this is just checking for a peer that has that IP/port and
2931
		 * this is just checking for a peer that has that IP/port and
2932
		 * assuming that we have a user of the same name.  This isn't always
2932
		 * assuming that we have a user of the same name.  This isn't always
2933
		 * correct, but it will be changed if needed after authentication. */
2933
		 * correct, but it will be changed if needed after authentication. */
2934
		if (!iax2_getpeername(*sin, host, sizeof(host)))
2934
		if (!iax2_getpeername(*sin, host, sizeof(host)))
2935
			snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2935
			snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
2936

    
   
2936

   
2937
		if (peercnt_add(sin)) {
2937
		if (peercnt_add(sin)) {
2938
			/* This address has hit its callnumber limit.  When the limit
2938
			/* This address has hit its callnumber limit.  When the limit
2939
			 * is reached, the connection is not added to the peercnts table.*/
2939
			 * is reached, the connection is not added to the peercnts table.*/
2940
			return 0;
2940
			return 0;
2941
		}
2941
		}
2942

    
   
2942

   
2943
		if (!(callno_entry = get_unused_callno(0, validated))) {
2943
		if (!(callno_entry = get_unused_callno(0, validated))) {
2944
			/* since we ran out of space, remove the peercnt
2944
			/* since we ran out of space, remove the peercnt
2945
			 * entry we added earlier */
2945
			 * entry we added earlier */
2946
			peercnt_remove_by_addr(sin);
2946
			peercnt_remove_by_addr(sin);
2947
			ast_log(LOG_WARNING, "No more space\n");
2947
			ast_log(LOG_WARNING, "No more space\n");
2948
			return 0;
2948
			return 0;
2949
		}
2949
		}
2950
		x = callno_entry->callno;
2950
		x = callno_entry->callno;
2951
		ast_mutex_lock(&iaxsl[x]);
2951
		ast_mutex_lock(&iaxsl[x]);
2952

    
   
2952

   
2953
		iaxs[x] = new_iax(sin, host);
2953
		iaxs[x] = new_iax(sin, host);
2954
		if (iaxs[x]) {
2954
		if (iaxs[x]) {
2955
			if (iaxdebug)
2955
			if (iaxdebug)
2956
				ast_debug(1, "Creating new call structure %d\n", x);
2956
				ast_debug(1, "Creating new call structure %d\n", x);
2957
			iaxs[x]->callno_entry = callno_entry;
2957
			iaxs[x]->callno_entry = callno_entry;
2958
			iaxs[x]->sockfd = sockfd;
2958
			iaxs[x]->sockfd = sockfd;
2959
			iaxs[x]->addr.sin_port = sin->sin_port;
2959
			iaxs[x]->addr.sin_port = sin->sin_port;
2960
			iaxs[x]->addr.sin_family = sin->sin_family;
2960
			iaxs[x]->addr.sin_family = sin->sin_family;
2961
			iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2961
			iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
2962
			iaxs[x]->peercallno = callno;
2962
			iaxs[x]->peercallno = callno;
2963
			iaxs[x]->callno = x;
2963
			iaxs[x]->callno = x;
2964
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2964
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
2965
			iaxs[x]->expiry = min_reg_expire;
2965
			iaxs[x]->expiry = min_reg_expire;
2966
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2966
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
2967
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2967
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
2968
			iaxs[x]->amaflags = amaflags;
2968
			iaxs[x]->amaflags = amaflags;
2969
			ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2969
			ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
2970
			ast_string_field_set(iaxs[x], accountcode, accountcode);
2970
			ast_string_field_set(iaxs[x], accountcode, accountcode);
2971
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2971
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
2972
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2972
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
2973
			ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2973
			ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
2974

    
   
2974

   
2975
			if (iaxs[x]->peercallno) {
2975
			if (iaxs[x]->peercallno) {
2976
				store_by_peercallno(iaxs[x]);
2976
				store_by_peercallno(iaxs[x]);
2977
			}
2977
			}
2978
		} else {
2978
		} else {
2979
			ast_log(LOG_WARNING, "Out of resources\n");
2979
			ast_log(LOG_WARNING, "Out of resources\n");
2980
			ast_mutex_unlock(&iaxsl[x]);
2980
			ast_mutex_unlock(&iaxsl[x]);
2981
			replace_callno(callno_entry);
2981
			replace_callno(callno_entry);
2982
			return 0;
2982
			return 0;
2983
		}
2983
		}
2984
		if (!return_locked)
2984
		if (!return_locked)
2985
			ast_mutex_unlock(&iaxsl[x]);
2985
			ast_mutex_unlock(&iaxsl[x]);
2986
		res = x;
2986
		res = x;
2987
	}
2987
	}
2988
	return res;
2988
	return res;
2989
}
2989
}
2990

    
   
2990

   
2991
static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) { 
2991
static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) { 
2992
	return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2992
	return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
2993
}
2993
}
2994

    
   
2994

   
2995
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2995
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
2996

    
   
2996

   
2997
	return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2997
	return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
2998
}
2998
}
2999

    
   
2999

   
3000
/*!
3000
/*!
3001
 * \brief Queue a frame to a call's owning asterisk channel
3001
 * \brief Queue a frame to a call's owning asterisk channel
3002
 *
3002
 *
3003
 * \pre This function assumes that iaxsl[callno] is locked when called.
3003
 * \pre This function assumes that iaxsl[callno] is locked when called.
3004
 *
3004
 *
3005
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3005
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3006
 * was valid before calling it, it may no longer be valid after calling it.
3006
 * was valid before calling it, it may no longer be valid after calling it.
3007
 * This function may unlock and lock the mutex associated with this callno,
3007
 * This function may unlock and lock the mutex associated with this callno,
3008
 * meaning that another thread may grab it and destroy the call.
3008
 * meaning that another thread may grab it and destroy the call.
3009
 */
3009
 */
3010
static int iax2_queue_frame(int callno, struct ast_frame *f)
3010
static int iax2_queue_frame(int callno, struct ast_frame *f)
3011
{
3011
{
3012
	iax2_lock_owner(callno);
3012
	iax2_lock_owner(callno);
3013
	if (iaxs[callno] && iaxs[callno]->owner) {
3013
	if (iaxs[callno] && iaxs[callno]->owner) {
3014
		ast_queue_frame(iaxs[callno]->owner, f);
3014
		ast_queue_frame(iaxs[callno]->owner, f);
3015
		ast_channel_unlock(iaxs[callno]->owner);
3015
		ast_channel_unlock(iaxs[callno]->owner);
3016
	}
3016
	}
3017
	return 0;
3017
	return 0;
3018
}
3018
}
3019

    
   
3019

   
3020
/*!
3020
/*!
3021
 * \brief Queue a hangup frame on the ast_channel owner
3021
 * \brief Queue a hangup frame on the ast_channel owner
3022
 *
3022
 *
3023
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3023
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
3024
 * is active for the given call number.
3024
 * is active for the given call number.
3025
 *
3025
 *
3026
 * \pre Assumes lock for callno is already held.
3026
 * \pre Assumes lock for callno is already held.
3027
 *
3027
 *
3028
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3028
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3029
 * was valid before calling it, it may no longer be valid after calling it.
3029
 * was valid before calling it, it may no longer be valid after calling it.
3030
 * This function may unlock and lock the mutex associated with this callno,
3030
 * This function may unlock and lock the mutex associated with this callno,
3031
 * meaning that another thread may grab it and destroy the call.
3031
 * meaning that another thread may grab it and destroy the call.
3032
 */
3032
 */
3033
static int iax2_queue_hangup(int callno)
3033
static int iax2_queue_hangup(int callno)
3034
{
3034
{
3035
	iax2_lock_owner(callno);
3035
	iax2_lock_owner(callno);
3036
	if (iaxs[callno] && iaxs[callno]->owner) {
3036
	if (iaxs[callno] && iaxs[callno]->owner) {
3037
		ast_queue_hangup(iaxs[callno]->owner);
3037
		ast_queue_hangup(iaxs[callno]->owner);
3038
		ast_channel_unlock(iaxs[callno]->owner);
3038
		ast_channel_unlock(iaxs[callno]->owner);
3039
	}
3039
	}
3040
	return 0;
3040
	return 0;
3041
}
3041
}
3042

    
   
3042

   
3043
/*!
3043
/*!
3044
 * \brief Queue a control frame on the ast_channel owner
3044
 * \brief Queue a control frame on the ast_channel owner
3045
 *
3045
 *
3046
 * This function queues a control frame on the owner of the IAX2 pvt struct that
3046
 * This function queues a control frame on the owner of the IAX2 pvt struct that
3047
 * is active for the given call number.
3047
 * is active for the given call number.
3048
 *
3048
 *
3049
 * \pre Assumes lock for callno is already held.
3049
 * \pre Assumes lock for callno is already held.
3050
 *
3050
 *
3051
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3051
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3052
 * was valid before calling it, it may no longer be valid after calling it.
3052
 * was valid before calling it, it may no longer be valid after calling it.
3053
 * This function may unlock and lock the mutex associated with this callno,
3053
 * This function may unlock and lock the mutex associated with this callno,
3054
 * meaning that another thread may grab it and destroy the call.
3054
 * meaning that another thread may grab it and destroy the call.
3055
 */
3055
 */
3056
static int iax2_queue_control_data(int callno, 
3056
static int iax2_queue_control_data(int callno, 
3057
	enum ast_control_frame_type control, const void *data, size_t datalen)
3057
	enum ast_control_frame_type control, const void *data, size_t datalen)
3058
{
3058
{
3059
	iax2_lock_owner(callno);
3059
	iax2_lock_owner(callno);
3060
	if (iaxs[callno] && iaxs[callno]->owner) {
3060
	if (iaxs[callno] && iaxs[callno]->owner) {
3061
		ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3061
		ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
3062
		ast_channel_unlock(iaxs[callno]->owner);
3062
		ast_channel_unlock(iaxs[callno]->owner);
3063
	}
3063
	}
3064
	return 0;
3064
	return 0;
3065
}
3065
}
3066
static void destroy_firmware(struct iax_firmware *cur)
3066
static void destroy_firmware(struct iax_firmware *cur)
3067
{
3067
{
3068
	/* Close firmware */
3068
	/* Close firmware */
3069
	if (cur->fwh) {
3069
	if (cur->fwh) {
3070
		munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3070
		munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
3071
	}
3071
	}
3072
	close(cur->fd);
3072
	close(cur->fd);
3073
	ast_free(cur);
3073
	ast_free(cur);
3074
}
3074
}
3075

    
   
3075

   
3076
static int try_firmware(char *s)
3076
static int try_firmware(char *s)
3077
{
3077
{
3078
	struct stat stbuf;
3078
	struct stat stbuf;
3079
	struct iax_firmware *cur = NULL;
3079
	struct iax_firmware *cur = NULL;
3080
	int ifd, fd, res, len, chunk;
3080
	int ifd, fd, res, len, chunk;
3081
	struct ast_iax2_firmware_header *fwh, fwh2;
3081
	struct ast_iax2_firmware_header *fwh, fwh2;
3082
	struct MD5Context md5;
3082
	struct MD5Context md5;
3083
	unsigned char sum[16], buf[1024];
3083
	unsigned char sum[16], buf[1024];
3084
	char *s2, *last;
3084
	char *s2, *last;
3085

    
   
3085

   
3086
	s2 = ast_alloca(strlen(s) + 100);
3086
	s2 = ast_alloca(strlen(s) + 100);
3087

    
   
3087

   
3088
	last = strrchr(s, '/');
3088
	last = strrchr(s, '/');
3089
	if (last)
3089
	if (last)
3090
		last++;
3090
		last++;
3091
	else
3091
	else
3092
		last = s;
3092
		last = s;
3093

    
   
3093

   
3094
	snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3094
	snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
3095

    
   
3095

   
3096
	if (stat(s, &stbuf) < 0) {
3096
	if (stat(s, &stbuf) < 0) {
3097
		ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3097
		ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
3098
		return -1;
3098
		return -1;
3099
	}
3099
	}
3100

    
   
3100

   
3101
	/* Make sure it's not a directory */
3101
	/* Make sure it's not a directory */
3102
	if (S_ISDIR(stbuf.st_mode))
3102
	if (S_ISDIR(stbuf.st_mode))
3103
		return -1;
3103
		return -1;
3104
	ifd = open(s, O_RDONLY);
3104
	ifd = open(s, O_RDONLY);
3105
	if (ifd < 0) {
3105
	if (ifd < 0) {
3106
		ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3106
		ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
3107
		return -1;
3107
		return -1;
3108
	}
3108
	}
3109
	fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3109
	fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
3110
	if (fd < 0) {
3110
	if (fd < 0) {
3111
		ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3111
		ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
3112
		close(ifd);
3112
		close(ifd);
3113
		return -1;
3113
		return -1;
3114
	}
3114
	}
3115
	/* Unlink our newly created file */
3115
	/* Unlink our newly created file */
3116
	unlink(s2);
3116
	unlink(s2);
3117
	
3117
	
3118
	/* Now copy the firmware into it */
3118
	/* Now copy the firmware into it */
3119
	len = stbuf.st_size;
3119
	len = stbuf.st_size;
3120
	while(len) {
3120
	while(len) {
3121
		chunk = len;
3121
		chunk = len;
3122
		if (chunk > sizeof(buf))
3122
		if (chunk > sizeof(buf))
3123
			chunk = sizeof(buf);
3123
			chunk = sizeof(buf);
3124
		res = read(ifd, buf, chunk);
3124
		res = read(ifd, buf, chunk);
3125
		if (res != chunk) {
3125
		if (res != chunk) {
3126
			ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3126
			ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3127
			close(ifd);
3127
			close(ifd);
3128
			close(fd);
3128
			close(fd);
3129
			return -1;
3129
			return -1;
3130
		}
3130
		}
3131
		res = write(fd, buf, chunk);
3131
		res = write(fd, buf, chunk);
3132
		if (res != chunk) {
3132
		if (res != chunk) {
3133
			ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3133
			ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
3134
			close(ifd);
3134
			close(ifd);
3135
			close(fd);
3135
			close(fd);
3136
			return -1;
3136
			return -1;
3137
		}
3137
		}
3138
		len -= chunk;
3138
		len -= chunk;
3139
	}
3139
	}
3140
	close(ifd);
3140
	close(ifd);
3141
	/* Return to the beginning */
3141
	/* Return to the beginning */
3142
	lseek(fd, 0, SEEK_SET);
3142
	lseek(fd, 0, SEEK_SET);
3143
	if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3143
	if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
3144
		ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3144
		ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
3145
		close(fd);
3145
		close(fd);
3146
		return -1;
3146
		return -1;
3147
	}
3147
	}
3148
	if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3148
	if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
3149
		ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3149
		ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
3150
		close(fd);
3150
		close(fd);
3151
		return -1;
3151
		return -1;
3152
	}
3152
	}
3153
	if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3153
	if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
3154
		ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3154
		ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
3155
		close(fd);
3155
		close(fd);
3156
		return -1;
3156
		return -1;
3157
	}
3157
	}
3158
	if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3158
	if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
3159
		ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3159
		ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
3160
		close(fd);
3160
		close(fd);
3161
		return -1;
3161
		return -1;
3162
	}
3162
	}
3163
	fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
3163
	fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
3164
	if (fwh == MAP_FAILED) {
3164
	if (fwh == MAP_FAILED) {
3165
		ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3165
		ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
3166
		close(fd);
3166
		close(fd);
3167
		return -1;
3167
		return -1;
3168
	}
3168
	}
3169
	MD5Init(&md5);
3169
	MD5Init(&md5);
3170
	MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3170
	MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
3171
	MD5Final(sum, &md5);
3171
	MD5Final(sum, &md5);
3172
	if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3172
	if (memcmp(sum, fwh->chksum, sizeof(sum))) {
3173
		ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3173
		ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
3174
		munmap((void*)fwh, stbuf.st_size);
3174
		munmap((void*)fwh, stbuf.st_size);
3175
		close(fd);
3175
		close(fd);
3176
		return -1;
3176
		return -1;
3177
	}
3177
	}
3178

    
   
3178

   
3179
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3179
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3180
		if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3180
		if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
3181
			/* Found a candidate */
3181
			/* Found a candidate */
3182
			if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3182
			if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
3183
				/* The version we have on loaded is older, load this one instead */
3183
				/* The version we have on loaded is older, load this one instead */
3184
				break;
3184
				break;
3185
			/* This version is no newer than what we have.  Don't worry about it.
3185
			/* This version is no newer than what we have.  Don't worry about it.
3186
			   We'll consider it a proper load anyhow though */
3186
			   We'll consider it a proper load anyhow though */
3187
			munmap((void*)fwh, stbuf.st_size);
3187
			munmap((void*)fwh, stbuf.st_size);
3188
			close(fd);
3188
			close(fd);
3189
			return 0;
3189
			return 0;
3190
		}
3190
		}
3191
	}
3191
	}
3192
	
3192
	
3193
	if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3193
	if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
3194
		cur->fd = -1;
3194
		cur->fd = -1;
3195
		AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3195
		AST_LIST_INSERT_TAIL(&firmwares, cur, list);
3196
	}
3196
	}
3197
	
3197
	
3198
	if (cur) {
3198
	if (cur) {
3199
		if (cur->fwh)
3199
		if (cur->fwh)
3200
			munmap((void*)cur->fwh, cur->mmaplen);
3200
			munmap((void*)cur->fwh, cur->mmaplen);
3201
		if (cur->fd > -1)
3201
		if (cur->fd > -1)
3202
			close(cur->fd);
3202
			close(cur->fd);
3203
		cur->fwh = fwh;
3203
		cur->fwh = fwh;
3204
		cur->fd = fd;
3204
		cur->fd = fd;
3205
		cur->mmaplen = stbuf.st_size;
3205
		cur->mmaplen = stbuf.st_size;
3206
		cur->dead = 0;
3206
		cur->dead = 0;
3207
	}
3207
	}
3208
	
3208
	
3209
	return 0;
3209
	return 0;
3210
}
3210
}
3211

    
   
3211

   
3212
static int iax_check_version(char *dev)
3212
static int iax_check_version(char *dev)
3213
{
3213
{
3214
	int res = 0;
3214
	int res = 0;
3215
	struct iax_firmware *cur = NULL;
3215
	struct iax_firmware *cur = NULL;
3216

    
   
3216

   
3217
	if (ast_strlen_zero(dev))
3217
	if (ast_strlen_zero(dev))
3218
		return 0;
3218
		return 0;
3219

    
   
3219

   
3220
	AST_LIST_LOCK(&firmwares);
3220
	AST_LIST_LOCK(&firmwares);
3221
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3221
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3222
		if (!strcmp(dev, (char *)cur->fwh->devname)) {
3222
		if (!strcmp(dev, (char *)cur->fwh->devname)) {
3223
			res = ntohs(cur->fwh->version);
3223
			res = ntohs(cur->fwh->version);
3224
			break;
3224
			break;
3225
		}
3225
		}
3226
	}
3226
	}
3227
	AST_LIST_UNLOCK(&firmwares);
3227
	AST_LIST_UNLOCK(&firmwares);
3228

    
   
3228

   
3229
	return res;
3229
	return res;
3230
}
3230
}
3231

    
   
3231

   
3232
static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3232
static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
3233
{
3233
{
3234
	int res = -1;
3234
	int res = -1;
3235
	unsigned int bs = desc & 0xff;
3235
	unsigned int bs = desc & 0xff;
3236
	unsigned int start = (desc >> 8) & 0xffffff;
3236
	unsigned int start = (desc >> 8) & 0xffffff;
3237
	unsigned int bytes;
3237
	unsigned int bytes;
3238
	struct iax_firmware *cur;
3238
	struct iax_firmware *cur;
3239

    
   
3239

   
3240
	if (ast_strlen_zero((char *)dev) || !bs)
3240
	if (ast_strlen_zero((char *)dev) || !bs)
3241
		return -1;
3241
		return -1;
3242

    
   
3242

   
3243
	start *= bs;
3243
	start *= bs;
3244
	
3244
	
3245
	AST_LIST_LOCK(&firmwares);
3245
	AST_LIST_LOCK(&firmwares);
3246
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3246
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
3247
		if (strcmp((char *)dev, (char *)cur->fwh->devname))
3247
		if (strcmp((char *)dev, (char *)cur->fwh->devname))
3248
			continue;
3248
			continue;
3249
		iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3249
		iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
3250
		if (start < ntohl(cur->fwh->datalen)) {
3250
		if (start < ntohl(cur->fwh->datalen)) {
3251
			bytes = ntohl(cur->fwh->datalen) - start;
3251
			bytes = ntohl(cur->fwh->datalen) - start;
3252
			if (bytes > bs)
3252
			if (bytes > bs)
3253
				bytes = bs;
3253
				bytes = bs;
3254
			iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3254
			iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
3255
		} else {
3255
		} else {
3256
			bytes = 0;
3256
			bytes = 0;
3257
			iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3257
			iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
3258
		}
3258
		}
3259
		if (bytes == bs)
3259
		if (bytes == bs)
3260
			res = 0;
3260
			res = 0;
3261
		else
3261
		else
3262
			res = 1;
3262
			res = 1;
3263
		break;
3263
		break;
3264
	}
3264
	}
3265
	AST_LIST_UNLOCK(&firmwares);
3265
	AST_LIST_UNLOCK(&firmwares);
3266

    
   
3266

   
3267
	return res;
3267
	return res;
3268
}
3268
}
3269

    
   
3269

   
3270

    
   
3270

   
3271
static void reload_firmware(int unload)
3271
static void reload_firmware(int unload)
3272
{
3272
{
3273
	struct iax_firmware *cur = NULL;
3273
	struct iax_firmware *cur = NULL;
3274
	DIR *fwd;
3274
	DIR *fwd;
3275
	struct dirent *de;
3275
	struct dirent *de;
3276
	char dir[256], fn[256];
3276
	char dir[256], fn[256];
3277

    
   
3277

   
3278
	AST_LIST_LOCK(&firmwares);
3278
	AST_LIST_LOCK(&firmwares);
3279

    
   
3279

   
3280
	/* Mark all as dead */
3280
	/* Mark all as dead */
3281
	AST_LIST_TRAVERSE(&firmwares, cur, list)
3281
	AST_LIST_TRAVERSE(&firmwares, cur, list)
3282
		cur->dead = 1;
3282
		cur->dead = 1;
3283

    
   
3283

   
3284
	/* Now that we have marked them dead... load new ones */
3284
	/* Now that we have marked them dead... load new ones */
3285
	if (!unload) {
3285
	if (!unload) {
3286
		snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3286
		snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
3287
		fwd = opendir(dir);
3287
		fwd = opendir(dir);
3288
		if (fwd) {
3288
		if (fwd) {
3289
			while((de = readdir(fwd))) {
3289
			while((de = readdir(fwd))) {
3290
				if (de->d_name[0] != '.') {
3290
				if (de->d_name[0] != '.') {
3291
					snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3291
					snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
3292
					if (!try_firmware(fn)) {
3292
					if (!try_firmware(fn)) {
3293
						ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3293
						ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
3294
					}
3294
					}
3295
				}
3295
				}
3296
			}
3296
			}
3297
			closedir(fwd);
3297
			closedir(fwd);
3298
		} else 
3298
		} else 
3299
			ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3299
			ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
3300
	}
3300
	}
3301

    
   
3301

   
3302
	/* Clean up leftovers */
3302
	/* Clean up leftovers */
3303
	AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3303
	AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
3304
		if (!cur->dead)
3304
		if (!cur->dead)
3305
			continue;
3305
			continue;
3306
		AST_LIST_REMOVE_CURRENT(list);
3306
		AST_LIST_REMOVE_CURRENT(list);
3307
		destroy_firmware(cur);
3307
		destroy_firmware(cur);
3308
	}
3308
	}
3309
	AST_LIST_TRAVERSE_SAFE_END;
3309
	AST_LIST_TRAVERSE_SAFE_END;
3310

    
   
3310

   
3311
	AST_LIST_UNLOCK(&firmwares);
3311
	AST_LIST_UNLOCK(&firmwares);
3312
}
3312
}
3313

    
   
3313

   
3314
/*!
3314
/*!
3315
 * \note This function assumes that iaxsl[callno] is locked when called.
3315
 * \note This function assumes that iaxsl[callno] is locked when called.
3316
 *
3316
 *
3317
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3317
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3318
 * was valid before calling it, it may no longer be valid after calling it.
3318
 * was valid before calling it, it may no longer be valid after calling it.
3319
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
3319
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
3320
 * associated with this callno, meaning that another thread may grab it and destroy the call.
3320
 * associated with this callno, meaning that another thread may grab it and destroy the call.
3321
 */
3321
 */
3322
static int __do_deliver(void *data)
3322
static int __do_deliver(void *data)
3323
{
3323
{
3324
	/* Just deliver the packet by using queueing.  This is called by
3324
	/* Just deliver the packet by using queueing.  This is called by
3325
	  the IAX thread with the iaxsl lock held. */
3325
	  the IAX thread with the iaxsl lock held. */
3326
	struct iax_frame *fr = data;
3326
	struct iax_frame *fr = data;
3327
	fr->retrans = -1;
3327
	fr->retrans = -1;
3328
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3328
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
3329
	if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3329
	if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
3330
		iax2_queue_frame(fr->callno, &fr->af);
3330
		iax2_queue_frame(fr->callno, &fr->af);
3331
	/* Free our iax frame */
3331
	/* Free our iax frame */
3332
	iax2_frame_free(fr);
3332
	iax2_frame_free(fr);
3333
	/* And don't run again */
3333
	/* And don't run again */
3334
	return 0;
3334
	return 0;
3335
}
3335
}
3336

    
   
3336

   
3337
static int handle_error(void)
3337
static int handle_error(void)
3338
{
3338
{
3339
	/* XXX Ideally we should figure out why an error occurred and then abort those
3339
	/* XXX Ideally we should figure out why an error occurred and then abort those
3340
	   rather than continuing to try.  Unfortunately, the published interface does
3340
	   rather than continuing to try.  Unfortunately, the published interface does
3341
	   not seem to work XXX */
3341
	   not seem to work XXX */
3342
#if 0
3342
#if 0
3343
	struct sockaddr_in *sin;
3343
	struct sockaddr_in *sin;
3344
	int res;
3344
	int res;
3345
	struct msghdr m;
3345
	struct msghdr m;
3346
	struct sock_extended_err e;
3346
	struct sock_extended_err e;
3347
	m.msg_name = NULL;
3347
	m.msg_name = NULL;
3348
	m.msg_namelen = 0;
3348
	m.msg_namelen = 0;
3349
	m.msg_iov = NULL;
3349
	m.msg_iov = NULL;
3350
	m.msg_control = &e;
3350
	m.msg_control = &e;
3351
	m.msg_controllen = sizeof(e);
3351
	m.msg_controllen = sizeof(e);
3352
	m.msg_flags = 0;
3352
	m.msg_flags = 0;
3353
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3353
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
3354
	if (res < 0)
3354
	if (res < 0)
3355
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3355
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
3356
	else {
3356
	else {
3357
		if (m.msg_controllen) {
3357
		if (m.msg_controllen) {
3358
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3358
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
3359
			if (sin) 
3359
			if (sin) 
3360
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3360
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
3361
			else
3361
			else
3362
				ast_log(LOG_WARNING, "No address detected??\n");
3362
				ast_log(LOG_WARNING, "No address detected??\n");
3363
		} else {
3363
		} else {
3364
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3364
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
3365
		}
3365
		}
3366
	}
3366
	}
3367
#endif
3367
#endif
3368
	return 0;
3368
	return 0;
3369
}
3369
}
3370

    
   
3370

   
3371
static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3371
static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
3372
{
3372
{
3373
	int res;
3373
	int res;
3374
	res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3374
	res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
3375
					sizeof(*sin));
3375
					sizeof(*sin));
3376
	if (res < 0) {
3376
	if (res < 0) {
3377
		ast_debug(1, "Received error: %s\n", strerror(errno));
3377
		ast_debug(1, "Received error: %s\n", strerror(errno));
3378
		handle_error();
3378
		handle_error();
3379
	} else
3379
	} else
3380
		res = 0;
3380
		res = 0;
3381
	return res;
3381
	return res;
3382
}
3382
}
3383

    
   
3383

   
3384
static int send_packet(struct iax_frame *f)
3384
static int send_packet(struct iax_frame *f)
3385
{
3385
{
3386
	int res;
3386
	int res;
3387
	int callno = f->callno;
3387
	int callno = f->callno;
3388

    
   
3388

   
3389
	/* Don't send if there was an error, but return error instead */
3389
	/* Don't send if there was an error, but return error instead */
3390
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
3390
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
3391
	    return -1;
3391
	    return -1;
3392

    
   
3392

   
3393
	/* Called with iaxsl held */
3393
	/* Called with iaxsl held */
3394
	if (iaxdebug)
3394
	if (iaxdebug)
3395
		ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3395
		ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
3396

    
   
3396

   
3397
	if (f->transfer) {
3397
	if (f->transfer) {
3398
		iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3398
		iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
3399
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3399
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
3400
	} else {
3400
	} else {
3401
		iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3401
		iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
3402
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3402
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
3403
	}
3403
	}
3404
	if (res < 0) {
3404
	if (res < 0) {
3405
		if (iaxdebug)
3405
		if (iaxdebug)
3406
			ast_debug(1, "Received error: %s\n", strerror(errno));
3406
			ast_debug(1, "Received error: %s\n", strerror(errno));
3407
		handle_error();
3407
		handle_error();
3408
	} else
3408
	} else
3409
		res = 0;
3409
		res = 0;
3410

    
   
3410

   
3411
	return res;
3411
	return res;
3412
}
3412
}
3413

    
   
3413

   
3414
/*!
3414
/*!
3415
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3415
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
3416
 *       for the given call number may disappear during its execution.
3416
 *       for the given call number may disappear during its execution.
3417
 */
3417
 */
3418
static int iax2_predestroy(int callno)
3418
static int iax2_predestroy(int callno)
3419
{
3419
{
3420
	struct ast_channel *c = NULL;
3420
	struct ast_channel *c = NULL;
3421
	struct chan_iax2_pvt *pvt = iaxs[callno];
3421
	struct chan_iax2_pvt *pvt = iaxs[callno];
3422

    
   
3422

   
3423
	if (!pvt)
3423
	if (!pvt)
3424
		return -1;
3424
		return -1;
3425

    
   
3425

   
3426
	if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3426
	if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
3427
		iax2_destroy_helper(pvt);
3427
		iax2_destroy_helper(pvt);
3428
		ast_set_flag64(pvt, IAX_ALREADYGONE);
3428
		ast_set_flag64(pvt, IAX_ALREADYGONE);
3429
	}
3429
	}
3430

    
   
3430

   
3431
	if ((c = pvt->owner)) {
3431
	if ((c = pvt->owner)) {
3432
		ast_channel_tech_pvt_set(c, NULL);
3432
		ast_channel_tech_pvt_set(c, NULL);
3433
		iax2_queue_hangup(callno);
3433
		iax2_queue_hangup(callno);
3434
		pvt->owner = NULL;
3434
		pvt->owner = NULL;
3435
		ast_module_unref(ast_module_info->self);
3435
		ast_module_unref(ast_module_info->self);
3436
	}
3436
	}
3437

    
   
3437

   
3438
	return 0;
3438
	return 0;
3439
}
3439
}
3440

    
   
3440

   
3441
static void iax2_destroy(int callno)
3441
static void iax2_destroy(int callno)
3442
{
3442
{
3443
	struct chan_iax2_pvt *pvt = NULL;
3443
	struct chan_iax2_pvt *pvt = NULL;
3444
	struct ast_channel *owner = NULL;
3444
	struct ast_channel *owner = NULL;
3445

    
   
3445

   
3446
retry:
3446
retry:
3447
	if ((pvt = iaxs[callno])) {
3447
	if ((pvt = iaxs[callno])) {
3448
#if 0
3448
#if 0
3449
		/* iax2_destroy_helper gets called from this function later on.  When
3449
		/* iax2_destroy_helper gets called from this function later on.  When
3450
		 * called twice, we get the (previously) familiar FRACK! errors in
3450
		 * called twice, we get the (previously) familiar FRACK! errors in
3451
		 * devmode, from the scheduler.  An alternative to this approach is to
3451
		 * devmode, from the scheduler.  An alternative to this approach is to
3452
		 * reset the scheduler entries to -1 when they're deleted in
3452
		 * reset the scheduler entries to -1 when they're deleted in
3453
		 * iax2_destroy_helper().  That approach was previously decided to be
3453
		 * iax2_destroy_helper().  That approach was previously decided to be
3454
		 * "wrong" because "the memory is going to be deallocated anyway.  Why
3454
		 * "wrong" because "the memory is going to be deallocated anyway.  Why
3455
		 * should we be resetting those values?" */
3455
		 * should we be resetting those values?" */
3456
		iax2_destroy_helper(pvt);
3456
		iax2_destroy_helper(pvt);
3457
#endif
3457
#endif
3458
	}
3458
	}
3459

    
   
3459

   
3460
	owner = pvt ? pvt->owner : NULL;
3460
	owner = pvt ? pvt->owner : NULL;
3461

    
   
3461

   
3462
	if (owner) {
3462
	if (owner) {
3463
		if (ast_channel_trylock(owner)) {
3463
		if (ast_channel_trylock(owner)) {
3464
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
3464
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
3465
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3465
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3466
			goto retry;
3466
			goto retry;
3467
		}
3467
		}
3468
	}
3468
	}
3469

    
   
3469

   
3470
	if (!owner) {
3470
	if (!owner) {
3471
		iaxs[callno] = NULL;
3471
		iaxs[callno] = NULL;
3472
	}
3472
	}
3473

    
   
3473

   
3474
	if (pvt) {
3474
	if (pvt) {
3475
		if (!owner) {
3475
		if (!owner) {
3476
			pvt->owner = NULL;
3476
			pvt->owner = NULL;
3477
		} else {
3477
		} else {
3478
			/* If there's an owner, prod it to give up */
3478
			/* If there's an owner, prod it to give up */
3479
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3479
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
3480
			 * because we already hold the owner channel lock. */
3480
			 * because we already hold the owner channel lock. */
3481
			ast_queue_hangup(owner);
3481
			ast_queue_hangup(owner);
3482
		}
3482
		}
3483

    
   
3483

   
3484
		if (pvt->peercallno) {
3484
		if (pvt->peercallno) {
3485
			remove_by_peercallno(pvt);
3485
			remove_by_peercallno(pvt);
3486
		}
3486
		}
3487

    
   
3487

   
3488
		if (pvt->transfercallno) {
3488
		if (pvt->transfercallno) {
3489
			remove_by_transfercallno(pvt);
3489
			remove_by_transfercallno(pvt);
3490
		}
3490
		}
3491

    
   
3491

   
3492
		if (!owner) {
3492
		if (!owner) {
3493
			ao2_ref(pvt, -1);
3493
			ao2_ref(pvt, -1);
3494
			pvt = NULL;
3494
			pvt = NULL;
3495
		}
3495
		}
3496
	}
3496
	}
3497

    
   
3497

   
3498
	if (owner) {
3498
	if (owner) {
3499
		ast_channel_unlock(owner);
3499
		ast_channel_unlock(owner);
3500
	}
3500
	}
3501
}
3501
}
3502

    
   
3502

   
3503
static int update_packet(struct iax_frame *f)
3503
static int update_packet(struct iax_frame *f)
3504
{
3504
{
3505
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3505
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
3506
	struct ast_iax2_full_hdr *fh = f->data;
3506
	struct ast_iax2_full_hdr *fh = f->data;
3507
	struct ast_frame af;
3507
	struct ast_frame af;
3508

    
   
3508

   
3509
	/* if frame is encrypted. decrypt before updating it. */
3509
	/* if frame is encrypted. decrypt before updating it. */
3510
	if (f->encmethods) {
3510
	if (f->encmethods) {
3511
		decode_frame(&f->mydcx, fh, &af, &f->datalen);
3511
		decode_frame(&f->mydcx, fh, &af, &f->datalen);
3512
	}
3512
	}
3513
	/* Mark this as a retransmission */
3513
	/* Mark this as a retransmission */
3514
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3514
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
3515
	/* Update iseqno */
3515
	/* Update iseqno */
3516
	f->iseqno = iaxs[f->callno]->iseqno;
3516
	f->iseqno = iaxs[f->callno]->iseqno;
3517
	fh->iseqno = f->iseqno;
3517
	fh->iseqno = f->iseqno;
3518

    
   
3518

   
3519
	/* Now re-encrypt the frame */
3519
	/* Now re-encrypt the frame */
3520
	if (f->encmethods) {
3520
	if (f->encmethods) {
3521
	/* since this is a retransmit frame, create a new random padding
3521
	/* since this is a retransmit frame, create a new random padding
3522
	 * before re-encrypting. */
3522
	 * before re-encrypting. */
3523
		build_rand_pad(f->semirand, sizeof(f->semirand));
3523
		build_rand_pad(f->semirand, sizeof(f->semirand));
3524
		encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3524
		encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
3525
	}
3525
	}
3526
	return 0;
3526
	return 0;
3527
}
3527
}
3528

    
   
3528

   
3529
static int attempt_transmit(const void *data);
3529
static int attempt_transmit(const void *data);
3530
static void __attempt_transmit(const void *data)
3530
static void __attempt_transmit(const void *data)
3531
{
3531
{
3532
	/* Attempt to transmit the frame to the remote peer...
3532
	/* Attempt to transmit the frame to the remote peer...
3533
	   Called without iaxsl held. */
3533
	   Called without iaxsl held. */
3534
	struct iax_frame *f = (struct iax_frame *)data;
3534
	struct iax_frame *f = (struct iax_frame *)data;
3535
	int freeme = 0;
3535
	int freeme = 0;
3536
	int callno = f->callno;
3536
	int callno = f->callno;
3537
	/* Make sure this call is still active */
3537
	/* Make sure this call is still active */
3538
	if (callno) 
3538
	if (callno) 
3539
		ast_mutex_lock(&iaxsl[callno]);
3539
		ast_mutex_lock(&iaxsl[callno]);
3540
	if (callno && iaxs[callno]) {
3540
	if (callno && iaxs[callno]) {
3541
		if ((f->retries < 0) /* Already ACK'd */ ||
3541
		if ((f->retries < 0) /* Already ACK'd */ ||
3542
		    (f->retries >= max_retries) /* Too many attempts */) {
3542
		    (f->retries >= max_retries) /* Too many attempts */) {
3543
				/* Record an error if we've transmitted too many times */
3543
				/* Record an error if we've transmitted too many times */
3544
				if (f->retries >= max_retries) {
3544
				if (f->retries >= max_retries) {
3545
					if (f->transfer) {
3545
					if (f->transfer) {
3546
						/* Transfer timeout */
3546
						/* Transfer timeout */
3547
						send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3547
						send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
3548
					} else if (f->final) {
3548
					} else if (f->final) {
3549
						iax2_destroy(callno);
3549
						iax2_destroy(callno);
3550
					} else {
3550
					} else {
3551
						if (iaxs[callno]->owner)
3551
						if (iaxs[callno]->owner)
3552
							ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),ast_channel_name(iaxs[f->callno]->owner), f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3552
							ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),ast_channel_name(iaxs[f->callno]->owner), f->af.frametype, f->af.subclass.integer, f->ts, f->oseqno);
3553
						iaxs[callno]->error = ETIMEDOUT;
3553
						iaxs[callno]->error = ETIMEDOUT;
3554
						if (iaxs[callno]->owner) {
3554
						if (iaxs[callno]->owner) {
3555
							struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3555
							struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
3556
							/* Hangup the fd */
3556
							/* Hangup the fd */
3557
							iax2_queue_frame(callno, &fr); /* XXX */
3557
							iax2_queue_frame(callno, &fr); /* XXX */
3558
							/* Remember, owner could disappear */
3558
							/* Remember, owner could disappear */
3559
							if (iaxs[callno] && iaxs[callno]->owner)
3559
							if (iaxs[callno] && iaxs[callno]->owner)
3560
								ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3560
								ast_channel_hangupcause_set(iaxs[callno]->owner, AST_CAUSE_DESTINATION_OUT_OF_ORDER);
3561
						} else {
3561
						} else {
3562
							if (iaxs[callno]->reg) {
3562
							if (iaxs[callno]->reg) {
3563
								memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3563
								memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
3564
								iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3564
								iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
3565
								iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3565
								iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
3566
							}
3566
							}
3567
							iax2_destroy(callno);
3567
							iax2_destroy(callno);
3568
						}
3568
						}
3569
					}
3569
					}
3570

    
   
3570

   
3571
				}
3571
				}
3572
				freeme = 1;
3572
				freeme = 1;
3573
		} else {
3573
		} else {
3574
			/* Update it if it needs it */
3574
			/* Update it if it needs it */
3575
			update_packet(f);
3575
			update_packet(f);
3576
			/* Attempt transmission */
3576
			/* Attempt transmission */
3577
			send_packet(f);
3577
			send_packet(f);
3578
			f->retries++;
3578
			f->retries++;
3579
			/* Try again later after 10 times as long */
3579
			/* Try again later after 10 times as long */
3580
			f->retrytime *= 10;
3580
			f->retrytime *= 10;
3581
			if (f->retrytime > MAX_RETRY_TIME)
3581
			if (f->retrytime > MAX_RETRY_TIME)
3582
				f->retrytime = MAX_RETRY_TIME;
3582
				f->retrytime = MAX_RETRY_TIME;
3583
			/* Transfer messages max out at one second */
3583
			/* Transfer messages max out at one second */
3584
			if (f->transfer && (f->retrytime > 1000))
3584
			if (f->transfer && (f->retrytime > 1000))
3585
				f->retrytime = 1000;
3585
				f->retrytime = 1000;
3586
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3586
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
3587
		}
3587
		}
3588
	} else {
3588
	} else {
3589
		/* Make sure it gets freed */
3589
		/* Make sure it gets freed */
3590
		f->retries = -1;
3590
		f->retries = -1;
3591
		freeme = 1;
3591
		freeme = 1;
3592
	}
3592
	}
3593

    
   
3593

   
3594
	if (freeme) {
3594
	if (freeme) {
3595
		/* Don't attempt delivery, just remove it from the queue */
3595
		/* Don't attempt delivery, just remove it from the queue */
3596
		AST_LIST_REMOVE(&frame_queue[callno], f, list);
3596
		AST_LIST_REMOVE(&frame_queue[callno], f, list);
3597
		ast_mutex_unlock(&iaxsl[callno]);
3597
		ast_mutex_unlock(&iaxsl[callno]);
3598
		f->retrans = -1; /* this is safe because this is the scheduled function */
3598
		f->retrans = -1; /* this is safe because this is the scheduled function */
3599
		/* Free the IAX frame */
3599
		/* Free the IAX frame */
3600
		iax2_frame_free(f);
3600
		iax2_frame_free(f);
3601
	} else if (callno) {
3601
	} else if (callno) {
3602
		ast_mutex_unlock(&iaxsl[callno]);
3602
		ast_mutex_unlock(&iaxsl[callno]);
3603
	}
3603
	}
3604
}
3604
}
3605

    
   
3605

   
3606
static int attempt_transmit(const void *data)
3606
static int attempt_transmit(const void *data)
3607
{
3607
{
3608
#ifdef SCHED_MULTITHREADED
3608
#ifdef SCHED_MULTITHREADED
3609
	if (schedule_action(__attempt_transmit, data))
3609
	if (schedule_action(__attempt_transmit, data))
3610
#endif		
3610
#endif		
3611
		__attempt_transmit(data);
3611
		__attempt_transmit(data);
3612
	return 0;
3612
	return 0;
3613
}
3613
}
3614

    
   
3614

   
3615
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3615
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3616
{
3616
{
3617
	struct iax2_peer *peer = NULL;
3617
	struct iax2_peer *peer = NULL;
3618
	struct iax2_user *user = NULL;
3618
	struct iax2_user *user = NULL;
3619
	static const char * const choices[] = { "all", NULL };
3619
	static const char * const choices[] = { "all", NULL };
3620
	char *cmplt;
3620
	char *cmplt;
3621

    
   
3621

   
3622
	switch (cmd) {
3622
	switch (cmd) {
3623
	case CLI_INIT:
3623
	case CLI_INIT:
3624
		e->command = "iax2 prune realtime";
3624
		e->command = "iax2 prune realtime";
3625
		e->usage =
3625
		e->usage =
3626
			"Usage: iax2 prune realtime [<peername>|all]\n"
3626
			"Usage: iax2 prune realtime [<peername>|all]\n"
3627
			"       Prunes object(s) from the cache\n";
3627
			"       Prunes object(s) from the cache\n";
3628
		return NULL;
3628
		return NULL;
3629
	case CLI_GENERATE:
3629
	case CLI_GENERATE:
3630
		if (a->pos == 3) {
3630
		if (a->pos == 3) {
3631
			cmplt = ast_cli_complete(a->word, choices, a->n);
3631
			cmplt = ast_cli_complete(a->word, choices, a->n);
3632
			if (!cmplt)
3632
			if (!cmplt)
3633
				cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3633
				cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
3634
			return cmplt;
3634
			return cmplt;
3635
		}
3635
		}
3636
		return NULL;
3636
		return NULL;
3637
	}
3637
	}
3638
	if (a->argc != 4)
3638
	if (a->argc != 4)
3639
		return CLI_SHOWUSAGE;
3639
		return CLI_SHOWUSAGE;
3640
	if (!strcmp(a->argv[3], "all")) {
3640
	if (!strcmp(a->argv[3], "all")) {
3641
		prune_users();
3641
		prune_users();
3642
		prune_peers();
3642
		prune_peers();
3643
		ast_cli(a->fd, "Cache flushed successfully.\n");
3643
		ast_cli(a->fd, "Cache flushed successfully.\n");
3644
		return CLI_SUCCESS;
3644
		return CLI_SUCCESS;
3645
	}
3645
	}
3646
	peer = find_peer(a->argv[3], 0);
3646
	peer = find_peer(a->argv[3], 0);
3647
	user = find_user(a->argv[3]);
3647
	user = find_user(a->argv[3]);
3648
	if (peer || user) {
3648
	if (peer || user) {
3649
		if (peer) {
3649
		if (peer) {
3650
			if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3650
			if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
3651
				ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3651
				ast_set_flag64(peer, IAX_RTAUTOCLEAR);
3652
				expire_registry(peer_ref(peer));
3652
				expire_registry(peer_ref(peer));
3653
				ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3653
				ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
3654
			} else {
3654
			} else {
3655
				ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3655
				ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
3656
			}
3656
			}
3657
			peer_unref(peer);
3657
			peer_unref(peer);
3658
		}
3658
		}
3659
		if (user) {
3659
		if (user) {
3660
			if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3660
			if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
3661
				ast_set_flag64(user, IAX_RTAUTOCLEAR);
3661
				ast_set_flag64(user, IAX_RTAUTOCLEAR);
3662
				ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3662
				ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
3663
			} else {
3663
			} else {
3664
				ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3664
				ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
3665
			}
3665
			}
3666
			ao2_unlink(users,user);
3666
			ao2_unlink(users,user);
3667
			user_unref(user);
3667
			user_unref(user);
3668
		}
3668
		}
3669
	} else {
3669
	} else {
3670
		ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3670
		ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
3671
	}
3671
	}
3672

    
   
3672

   
3673
	return CLI_SUCCESS;
3673
	return CLI_SUCCESS;
3674
}
3674
}
3675

    
   
3675

   
3676
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3676
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3677
{
3677
{
3678
	switch (cmd) {
3678
	switch (cmd) {
3679
	case CLI_INIT:
3679
	case CLI_INIT:
3680
		e->command = "iax2 test losspct";
3680
		e->command = "iax2 test losspct";
3681
		e->usage =
3681
		e->usage =
3682
			"Usage: iax2 test losspct <percentage>\n"
3682
			"Usage: iax2 test losspct <percentage>\n"
3683
			"       For testing, throws away <percentage> percent of incoming packets\n";
3683
			"       For testing, throws away <percentage> percent of incoming packets\n";
3684
		return NULL;
3684
		return NULL;
3685
	case CLI_GENERATE:
3685
	case CLI_GENERATE:
3686
		return NULL;
3686
		return NULL;
3687
	}
3687
	}
3688
	if (a->argc != 4)
3688
	if (a->argc != 4)
3689
		return CLI_SHOWUSAGE;
3689
		return CLI_SHOWUSAGE;
3690

    
   
3690

   
3691
	test_losspct = atoi(a->argv[3]);
3691
	test_losspct = atoi(a->argv[3]);
3692

    
   
3692

   
3693
	return CLI_SUCCESS;
3693
	return CLI_SUCCESS;
3694
}
3694
}
3695

    
   
3695

   
3696
#ifdef IAXTESTS
3696
#ifdef IAXTESTS
3697
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3697
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3698
{
3698
{
3699
	switch (cmd) {
3699
	switch (cmd) {
3700
	case CLI_INIT:
3700
	case CLI_INIT:
3701
		e->command = "iax2 test late";
3701
		e->command = "iax2 test late";
3702
		e->usage =
3702
		e->usage =
3703
			"Usage: iax2 test late <ms>\n"
3703
			"Usage: iax2 test late <ms>\n"
3704
			"       For testing, count the next frame as <ms> ms late\n";
3704
			"       For testing, count the next frame as <ms> ms late\n";
3705
		return NULL;
3705
		return NULL;
3706
	case CLI_GENERATE:
3706
	case CLI_GENERATE:
3707
		return NULL;
3707
		return NULL;
3708
	}
3708
	}
3709

    
   
3709

   
3710
	if (a->argc != 4)
3710
	if (a->argc != 4)
3711
		return CLI_SHOWUSAGE;
3711
		return CLI_SHOWUSAGE;
3712

    
   
3712

   
3713
	test_late = atoi(a->argv[3]);
3713
	test_late = atoi(a->argv[3]);
3714

    
   
3714

   
3715
	return CLI_SUCCESS;
3715
	return CLI_SUCCESS;
3716
}
3716
}
3717

    
   
3717

   
3718
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3718
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3719
{
3719
{
3720
	switch (cmd) {
3720
	switch (cmd) {
3721
	case CLI_INIT:
3721
	case CLI_INIT:
3722
		e->command = "iax2 test resync";
3722
		e->command = "iax2 test resync";
3723
		e->usage =
3723
		e->usage =
3724
			"Usage: iax2 test resync <ms>\n"
3724
			"Usage: iax2 test resync <ms>\n"
3725
			"       For testing, adjust all future frames by <ms> ms\n";
3725
			"       For testing, adjust all future frames by <ms> ms\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)
3731
	if (a->argc != 4)
3732
		return CLI_SHOWUSAGE;
3732
		return CLI_SHOWUSAGE;
3733

    
   
3733

   
3734
	test_resync = atoi(a->argv[3]);
3734
	test_resync = atoi(a->argv[3]);
3735

    
   
3735

   
3736
	return CLI_SUCCESS;
3736
	return CLI_SUCCESS;
3737
}
3737
}
3738

    
   
3738

   
3739
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3739
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3740
{
3740
{
3741
	switch (cmd) {
3741
	switch (cmd) {
3742
	case CLI_INIT:
3742
	case CLI_INIT:
3743
		e->command = "iax2 test jitter";
3743
		e->command = "iax2 test jitter";
3744
		e->usage =
3744
		e->usage =
3745
			"Usage: iax2 test jitter <ms> <pct>\n"
3745
			"Usage: iax2 test jitter <ms> <pct>\n"
3746
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3746
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
3747
			"       percentage of packets. If <pct> is not specified, adds\n"
3747
			"       percentage of packets. If <pct> is not specified, adds\n"
3748
			"       jitter to all packets.\n";
3748
			"       jitter to all packets.\n";
3749
		return NULL;
3749
		return NULL;
3750
	case CLI_GENERATE:
3750
	case CLI_GENERATE:
3751
		return NULL;
3751
		return NULL;
3752
	}
3752
	}
3753

    
   
3753

   
3754
	if (a->argc < 4 || a->argc > 5)
3754
	if (a->argc < 4 || a->argc > 5)
3755
		return CLI_SHOWUSAGE;
3755
		return CLI_SHOWUSAGE;
3756

    
   
3756

   
3757
	test_jit = atoi(a->argv[3]);
3757
	test_jit = atoi(a->argv[3]);
3758
	if (a->argc == 5)
3758
	if (a->argc == 5)
3759
		test_jitpct = atoi(a->argv[4]);
3759
		test_jitpct = atoi(a->argv[4]);
3760

    
   
3760

   
3761
	return CLI_SUCCESS;
3761
	return CLI_SUCCESS;
3762
}
3762
}
3763
#endif /* IAXTESTS */
3763
#endif /* IAXTESTS */
3764

    
   
3764

   
3765
/*! \brief  peer_status: Report Peer status in character string */
3765
/*! \brief  peer_status: Report Peer status in character string */
3766
/* 	returns 1 if peer is online, -1 if unmonitored */
3766
/* 	returns 1 if peer is online, -1 if unmonitored */
3767
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3767
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
3768
{
3768
{
3769
	int res = 0;
3769
	int res = 0;
3770
	if (peer->maxms) {
3770
	if (peer->maxms) {
3771
		if (peer->lastms < 0) {
3771
		if (peer->lastms < 0) {
3772
			ast_copy_string(status, "UNREACHABLE", statuslen);
3772
			ast_copy_string(status, "UNREACHABLE", statuslen);
3773
		} else if (peer->lastms > peer->maxms) {
3773
		} else if (peer->lastms > peer->maxms) {
3774
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3774
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
3775
			res = 1;
3775
			res = 1;
3776
		} else if (peer->lastms) {
3776
		} else if (peer->lastms) {
3777
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3777
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
3778
			res = 1;
3778
			res = 1;
3779
		} else {
3779
		} else {
3780
			ast_copy_string(status, "UNKNOWN", statuslen);
3780
			ast_copy_string(status, "UNKNOWN", statuslen);
3781
		}
3781
		}
3782
	} else { 
3782
	} else { 
3783
		ast_copy_string(status, "Unmonitored", statuslen);
3783
		ast_copy_string(status, "Unmonitored", statuslen);
3784
		res = -1;
3784
		res = -1;
3785
	}
3785
	}
3786
	return res;
3786
	return res;
3787
}
3787
}
3788

    
   
3788

   
3789
/*! \brief Show one peer in detail */
3789
/*! \brief Show one peer in detail */
3790
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3790
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3791
{
3791
{
3792
	char status[30];
3792
	char status[30];
3793
	char cbuf[256];
3793
	char cbuf[256];
3794
	struct iax2_peer *peer;
3794
	struct iax2_peer *peer;
3795
	char codec_buf[512];
3795
	char codec_buf[512];
3796
	struct ast_str *encmethods = ast_str_alloca(256);
3796
	struct ast_str *encmethods = ast_str_alloca(256);
3797
	int x = 0, load_realtime = 0;
3797
	int x = 0, load_realtime = 0;
3798

    
   
3798

   
3799
	switch (cmd) {
3799
	switch (cmd) {
3800
	case CLI_INIT:
3800
	case CLI_INIT:
3801
		e->command = "iax2 show peer";
3801
		e->command = "iax2 show peer";
3802
		e->usage =
3802
		e->usage =
3803
			"Usage: iax2 show peer <name>\n"
3803
			"Usage: iax2 show peer <name>\n"
3804
			"       Display details on specific IAX peer\n";
3804
			"       Display details on specific IAX peer\n";
3805
		return NULL;
3805
		return NULL;
3806
	case CLI_GENERATE:
3806
	case CLI_GENERATE:
3807
		if (a->pos == 3)
3807
		if (a->pos == 3)
3808
			return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3808
			return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
3809
		return NULL;
3809
		return NULL;
3810
	}
3810
	}
3811

    
   
3811

   
3812
	if (a->argc < 4)
3812
	if (a->argc < 4)
3813
		return CLI_SHOWUSAGE;
3813
		return CLI_SHOWUSAGE;
3814

    
   
3814

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

    
   
3816

   
3817
	peer = find_peer(a->argv[3], load_realtime);
3817
	peer = find_peer(a->argv[3], load_realtime);
3818
	if (peer) {
3818
	if (peer) {
3819
		struct sockaddr_in peer_addr;
3819
		struct sockaddr_in peer_addr;
3820

    
   
3820

   
3821
		ast_sockaddr_to_sin(&peer->addr, &peer_addr);
3821
		ast_sockaddr_to_sin(&peer->addr, &peer_addr);
3822

    
   
3822

   
3823
		encmethods_to_str(peer->encmethods, &encmethods);
3823
		encmethods_to_str(peer->encmethods, &encmethods);
3824
		ast_cli(a->fd, "\n\n");
3824
		ast_cli(a->fd, "\n\n");
3825
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
3825
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
3826
		ast_cli(a->fd, "  Description  : %s\n", peer->description);
3826
		ast_cli(a->fd, "  Description  : %s\n", peer->description);
3827
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3827
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
3828
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
3828
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
3829
 		ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
3829
 		ast_cli(a->fd, "  Parking lot  : %s\n", peer->parkinglot);
3830
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
3830
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
3831
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3831
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
3832
		ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
3832
		ast_cli(a->fd, "  Callnum limit: %d\n", peer->maxcallno);
3833
		ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3833
		ast_cli(a->fd, "  Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
3834
		ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3834
		ast_cli(a->fd, "  Trunk        : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
3835
		ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3835
		ast_cli(a->fd, "  Encryption   : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
3836
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3836
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
3837
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
3837
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
3838
		ast_cli(a->fd, "  ACL          : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3838
		ast_cli(a->fd, "  ACL          : %s\n", (ast_acl_list_is_empty(peer->acl) ? "No" : "Yes"));
3839
		ast_cli(a->fd, "  Addr->IP     : %s Port %d\n",  peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
3839
		ast_cli(a->fd, "  Addr->IP     : %s Port %d\n",  peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
3840
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3840
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
3841
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
3841
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
3842
		ast_cli(a->fd, "  Codecs       : ");
3842
		ast_cli(a->fd, "  Codecs       : ");
3843
		iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3843
		iax2_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
3844
		ast_cli(a->fd, "%s\n", codec_buf);
3844
		ast_cli(a->fd, "%s\n", codec_buf);
3845

    
   
3845

   
3846
		ast_cli(a->fd, "  Codec Order  : (");
3846
		ast_cli(a->fd, "  Codec Order  : (");
3847
		for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
3847
		for(x = 0; x < AST_CODEC_PREF_SIZE; x++) {
3848
			struct ast_format tmpfmt;
3848
			struct ast_format tmpfmt;
3849
			if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
3849
			if(!(ast_codec_pref_index(&peer->prefs, x, &tmpfmt)))
3850
				break;
3850
				break;
3851
			ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
3851
			ast_cli(a->fd, "%s", ast_getformatname(&tmpfmt));
3852
			if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
3852
			if(x < 31 && ast_codec_pref_index(&peer->prefs, x+1, &tmpfmt))
3853
				ast_cli(a->fd, "|");
3853
				ast_cli(a->fd, "|");
3854
		}
3854
		}
3855

    
   
3855

   
3856
		if (!x)
3856
		if (!x)
3857
			ast_cli(a->fd, "none");
3857
			ast_cli(a->fd, "none");
3858
		ast_cli(a->fd, ")\n");
3858
		ast_cli(a->fd, ")\n");
3859

    
   
3859

   
3860
		ast_cli(a->fd, "  Status       : ");
3860
		ast_cli(a->fd, "  Status       : ");
3861
		peer_status(peer, status, sizeof(status));	
3861
		peer_status(peer, status, sizeof(status));	
3862
		ast_cli(a->fd, "%s\n",status);
3862
		ast_cli(a->fd, "%s\n",status);
3863
		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");
3863
		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");
3864
		ast_cli(a->fd, "\n");
3864
		ast_cli(a->fd, "\n");
3865
		peer_unref(peer);
3865
		peer_unref(peer);
3866
	} else {
3866
	} else {
3867
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3867
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
3868
		ast_cli(a->fd, "\n");
3868
		ast_cli(a->fd, "\n");
3869
	}
3869
	}
3870

    
   
3870

   
3871
	return CLI_SUCCESS;
3871
	return CLI_SUCCESS;
3872
}
3872
}
3873

    
   
3873

   
3874
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3874
static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
3875
{
3875
{
3876
	int which = 0;
3876
	int which = 0;
3877
	struct iax2_peer *peer;
3877
	struct iax2_peer *peer;
3878
	char *res = NULL;
3878
	char *res = NULL;
3879
	int wordlen = strlen(word);
3879
	int wordlen = strlen(word);
3880
	struct ao2_iterator i;
3880
	struct ao2_iterator i;
3881

    
   
3881

   
3882
	i = ao2_iterator_init(peers, 0);
3882
	i = ao2_iterator_init(peers, 0);
3883
	while ((peer = ao2_iterator_next(&i))) {
3883
	while ((peer = ao2_iterator_next(&i))) {
3884
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3884
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state
3885
			&& (!flags || ast_test_flag64(peer, flags))) {
3885
			&& (!flags || ast_test_flag64(peer, flags))) {
3886
			res = ast_strdup(peer->name);
3886
			res = ast_strdup(peer->name);
3887
			peer_unref(peer);
3887
			peer_unref(peer);
3888
			break;
3888
			break;
3889
		}
3889
		}
3890
		peer_unref(peer);
3890
		peer_unref(peer);
3891
	}
3891
	}
3892
	ao2_iterator_destroy(&i);
3892
	ao2_iterator_destroy(&i);
3893

    
   
3893

   
3894
	return res;
3894
	return res;
3895
}
3895
}
3896

    
   
3896

   
3897
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3897
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3898
{
3898
{
3899
	struct iax_frame *cur;
3899
	struct iax_frame *cur;
3900
	int cnt = 0, dead = 0, final = 0, i = 0;
3900
	int cnt = 0, dead = 0, final = 0, i = 0;
3901

    
   
3901

   
3902
	switch (cmd) {
3902
	switch (cmd) {
3903
	case CLI_INIT:
3903
	case CLI_INIT:
3904
		e->command = "iax2 show stats";
3904
		e->command = "iax2 show stats";
3905
		e->usage =
3905
		e->usage =
3906
			"Usage: iax2 show stats\n"
3906
			"Usage: iax2 show stats\n"
3907
			"       Display statistics on IAX channel driver.\n";
3907
			"       Display statistics on IAX channel driver.\n";
3908
		return NULL;
3908
		return NULL;
3909
	case CLI_GENERATE:
3909
	case CLI_GENERATE:
3910
		return NULL;
3910
		return NULL;
3911
	}
3911
	}
3912

    
   
3912

   
3913
	if (a->argc != 3)
3913
	if (a->argc != 3)
3914
		return CLI_SHOWUSAGE;
3914
		return CLI_SHOWUSAGE;
3915

    
   
3915

   
3916
	for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3916
	for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
3917
		ast_mutex_lock(&iaxsl[i]);
3917
		ast_mutex_lock(&iaxsl[i]);
3918
		AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3918
		AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
3919
			if (cur->retries < 0)
3919
			if (cur->retries < 0)
3920
				dead++;
3920
				dead++;
3921
			if (cur->final)
3921
			if (cur->final)
3922
				final++;
3922
				final++;
3923
			cnt++;
3923
			cnt++;
3924
		}
3924
		}
3925
		ast_mutex_unlock(&iaxsl[i]);
3925
		ast_mutex_unlock(&iaxsl[i]);
3926
	}
3926
	}
3927

    
   
3927

   
3928
	ast_cli(a->fd, "    IAX Statistics\n");
3928
	ast_cli(a->fd, "    IAX Statistics\n");
3929
	ast_cli(a->fd, "---------------------\n");
3929
	ast_cli(a->fd, "---------------------\n");
3930
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3930
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
3931
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3931
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
3932
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3932
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
3933
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3933
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
3934

    
   
3934

   
3935
	trunk_timed = trunk_untimed = 0;
3935
	trunk_timed = trunk_untimed = 0;
3936
	if (trunk_maxmtu > trunk_nmaxmtu)
3936
	if (trunk_maxmtu > trunk_nmaxmtu)
3937
		trunk_nmaxmtu = trunk_maxmtu;
3937
		trunk_nmaxmtu = trunk_maxmtu;
3938

    
   
3938

   
3939
	return CLI_SUCCESS;
3939
	return CLI_SUCCESS;
3940
}
3940
}
3941

    
   
3941

   
3942
/*! \brief Set trunk MTU from CLI */
3942
/*! \brief Set trunk MTU from CLI */
3943
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3943
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3944
{
3944
{
3945
	int mtuv;
3945
	int mtuv;
3946

    
   
3946

   
3947
	switch (cmd) {
3947
	switch (cmd) {
3948
	case CLI_INIT:
3948
	case CLI_INIT:
3949
		e->command = "iax2 set mtu";
3949
		e->command = "iax2 set mtu";
3950
		e->usage =
3950
		e->usage =
3951
			"Usage: iax2 set mtu <value>\n"
3951
			"Usage: iax2 set mtu <value>\n"
3952
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
3952
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
3953
			"       zero to disable. Disabling means that the operating system\n"
3953
			"       zero to disable. Disabling means that the operating system\n"
3954
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
3954
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
3955
			"       packet exceeds the UDP payload size. This is substantially\n"
3955
			"       packet exceeds the UDP payload size. This is substantially\n"
3956
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3956
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
3957
			"       greater for G.711 samples.\n";
3957
			"       greater for G.711 samples.\n";
3958
		return NULL;
3958
		return NULL;
3959
	case CLI_GENERATE:
3959
	case CLI_GENERATE:
3960
		return NULL;
3960
		return NULL;
3961
	}
3961
	}
3962

    
   
3962

   
3963
	if (a->argc != 4)
3963
	if (a->argc != 4)
3964
		return CLI_SHOWUSAGE; 
3964
		return CLI_SHOWUSAGE; 
3965
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3965
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
3966
		mtuv = MAX_TRUNK_MTU;
3966
		mtuv = MAX_TRUNK_MTU;
3967
	else
3967
	else
3968
		mtuv = atoi(a->argv[3]);
3968
		mtuv = atoi(a->argv[3]);
3969

    
   
3969

   
3970
	if (mtuv == 0) {
3970
	if (mtuv == 0) {
3971
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
3971
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
3972
		global_max_trunk_mtu = 0; 
3972
		global_max_trunk_mtu = 0; 
3973
		return CLI_SUCCESS; 
3973
		return CLI_SUCCESS; 
3974
	}
3974
	}
3975
	if (mtuv < 172 || mtuv > 4000) {
3975
	if (mtuv < 172 || mtuv > 4000) {
3976
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
3976
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
3977
		return CLI_SHOWUSAGE; 
3977
		return CLI_SHOWUSAGE; 
3978
	}
3978
	}
3979
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
3979
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
3980
	global_max_trunk_mtu = mtuv; 
3980
	global_max_trunk_mtu = mtuv; 
3981
	return CLI_SUCCESS;
3981
	return CLI_SUCCESS;
3982
}
3982
}
3983

    
   
3983

   
3984
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3984
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
3985
{
3985
{
3986
	struct iax2_dpcache *dp = NULL;
3986
	struct iax2_dpcache *dp = NULL;
3987
	char tmp[1024], *pc = NULL;
3987
	char tmp[1024], *pc = NULL;
3988
	int s, x, y;
3988
	int s, x, y;
3989
	struct timeval now = ast_tvnow();
3989
	struct timeval now = ast_tvnow();
3990

    
   
3990

   
3991
	switch (cmd) {
3991
	switch (cmd) {
3992
	case CLI_INIT:
3992
	case CLI_INIT:
3993
		e->command = "iax2 show cache";
3993
		e->command = "iax2 show cache";
3994
		e->usage =
3994
		e->usage =
3995
			"Usage: iax2 show cache\n"
3995
			"Usage: iax2 show cache\n"
3996
			"       Display currently cached IAX Dialplan results.\n";
3996
			"       Display currently cached IAX Dialplan results.\n";
3997
		return NULL;
3997
		return NULL;
3998
	case CLI_GENERATE:
3998
	case CLI_GENERATE:
3999
		return NULL;
3999
		return NULL;
4000
	}
4000
	}
4001

    
   
4001

   
4002
	AST_LIST_LOCK(&dpcache);
4002
	AST_LIST_LOCK(&dpcache);
4003

    
   
4003

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

    
   
4005

   
4006
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4006
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
4007
		s = dp->expiry.tv_sec - now.tv_sec;
4007
		s = dp->expiry.tv_sec - now.tv_sec;
4008
		tmp[0] = '\0';
4008
		tmp[0] = '\0';
4009
		if (dp->flags & CACHE_FLAG_EXISTS)
4009
		if (dp->flags & CACHE_FLAG_EXISTS)
4010
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4010
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
4011
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
4011
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
4012
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4012
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
4013
		if (dp->flags & CACHE_FLAG_CANEXIST)
4013
		if (dp->flags & CACHE_FLAG_CANEXIST)
4014
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4014
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
4015
		if (dp->flags & CACHE_FLAG_PENDING)
4015
		if (dp->flags & CACHE_FLAG_PENDING)
4016
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4016
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
4017
		if (dp->flags & CACHE_FLAG_TIMEOUT)
4017
		if (dp->flags & CACHE_FLAG_TIMEOUT)
4018
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4018
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
4019
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
4019
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
4020
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4020
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
4021
		if (dp->flags & CACHE_FLAG_MATCHMORE)
4021
		if (dp->flags & CACHE_FLAG_MATCHMORE)
4022
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4022
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
4023
		if (dp->flags & CACHE_FLAG_UNKNOWN)
4023
		if (dp->flags & CACHE_FLAG_UNKNOWN)
4024
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4024
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
4025
		/* Trim trailing pipe */
4025
		/* Trim trailing pipe */
4026
		if (!ast_strlen_zero(tmp)) {
4026
		if (!ast_strlen_zero(tmp)) {
4027
			tmp[strlen(tmp) - 1] = '\0';
4027
			tmp[strlen(tmp) - 1] = '\0';
4028
		} else {
4028
		} else {
4029
			ast_copy_string(tmp, "(none)", sizeof(tmp));
4029
			ast_copy_string(tmp, "(none)", sizeof(tmp));
4030
		}
4030
		}
4031
		y = 0;
4031
		y = 0;
4032
		pc = strchr(dp->peercontext, '@');
4032
		pc = strchr(dp->peercontext, '@');
4033
		if (!pc) {
4033
		if (!pc) {
4034
			pc = dp->peercontext;
4034
			pc = dp->peercontext;
4035
		} else {
4035
		} else {
4036
			pc++;
4036
			pc++;
4037
		}
4037
		}
4038
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4038
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
4039
			if (dp->waiters[x] > -1)
4039
			if (dp->waiters[x] > -1)
4040
				y++;
4040
				y++;
4041
		}
4041
		}
4042
		if (s > 0) {
4042
		if (s > 0) {
4043
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4043
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
4044
		} else {
4044
		} else {
4045
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4045
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
4046
		}
4046
		}
4047
	}
4047
	}
4048

    
   
4048

   
4049
	AST_LIST_UNLOCK(&dpcache);
4049
	AST_LIST_UNLOCK(&dpcache);
4050

    
   
4050

   
4051
	return CLI_SUCCESS;
4051
	return CLI_SUCCESS;
4052
}
4052
}
4053

    
   
4053

   
4054
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4054
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
4055

    
   
4055

   
4056
static void unwrap_timestamp(struct iax_frame *fr)
4056
static void unwrap_timestamp(struct iax_frame *fr)
4057
{
4057
{
4058
	/* Video mini frames only encode the lower 15 bits of the session
4058
	/* Video mini frames only encode the lower 15 bits of the session
4059
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4059
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
4060
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4060
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
4061
	const int lower_mask = (1 << ts_shift) - 1;
4061
	const int lower_mask = (1 << ts_shift) - 1;
4062
	const int upper_mask = ~lower_mask;
4062
	const int upper_mask = ~lower_mask;
4063
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
4063
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
4064

    
   
4064

   
4065
	if ( (fr->ts & upper_mask) == last_upper ) {
4065
	if ( (fr->ts & upper_mask) == last_upper ) {
4066
		const int x = fr->ts - iaxs[fr->callno]->last;
4066
		const int x = fr->ts - iaxs[fr->callno]->last;
4067
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
4067
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
4068

    
   
4068

   
4069
		if (x < -threshold) {
4069
		if (x < -threshold) {
4070
			/* Sudden big jump backwards in timestamp:
4070
			/* Sudden big jump backwards in timestamp:
4071
			   What likely happened here is that miniframe timestamp has circled but we haven't
4071
			   What likely happened here is that miniframe timestamp has circled but we haven't
4072
			   gotten the update from the main packet.  We'll just prete