Review Board 1.7.16


IAX2 Transfer Fix

Review Request #140 - Created Feb. 3, 2009 and submitted

David Vossel
1.6.0
0013468
Reviewers
asterisk-dev
russell
Asterisk
Fixes issue with IAX2 transfers not taking place.  As it was, a call that was being transfered would never be handed off correctly to the call ends because of how call numbers were stored in a hash table.  The hash table, "iax_peercallno_pvt", storing all the current call numbers did not take into account the complications associated with transferring a call, so a separate hash table was required.  This second hash table "iax_transfercallno_pvt" handles calls being transfered, once the call transfer is complete the call is removed from the transfer hash table and added to the peer hash table resuming normal operations. Addition functions were created to handle storing, removing, and comparing items in the iax_transfercallno_pvt table. 
this patch has been tested on both 1.6.0 and 1.4.  1.6.1 and trunk have issues of there own that must be fixed before this patch can be applied to them. 

Diff revision 3 (Latest)

1 2 3
1 2 3

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

    
   
18

   
19
/*! \file
19
/*! \file
20
 *
20
 *
21
 * \brief Implementation of Inter-Asterisk eXchange Version 2
21
 * \brief Implementation of Inter-Asterisk eXchange Version 2
22
 *
22
 *
23
 * \author Mark Spencer <markster@digium.com>
23
 * \author Mark Spencer <markster@digium.com>
24
 *
24
 *
25
 * \par See also
25
 * \par See also
26
 * \arg \ref Config_iax
26
 * \arg \ref Config_iax
27
 *
27
 *
28
 * \ingroup channel_drivers
28
 * \ingroup channel_drivers
29
 */
29
 */
30

    
   
30

   
31
/*** MODULEINFO
31
/*** MODULEINFO
32
	<use>dahdi</use>
32
	<use>dahdi</use>
33
	<use>crypto</use>
33
	<use>crypto</use>
34
 ***/
34
 ***/
35

    
   
35

   
36
#include "asterisk.h"
36
#include "asterisk.h"
37

    
   
37

   
38
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39

    
   
39

   
40
#include <sys/mman.h>
40
#include <sys/mman.h>
41
#include <dirent.h>
41
#include <dirent.h>
42
#include <sys/socket.h>
42
#include <sys/socket.h>
43
#include <netinet/in.h>
43
#include <netinet/in.h>
44
#include <arpa/inet.h>
44
#include <arpa/inet.h>
45
#include <netinet/in_systm.h>
45
#include <netinet/in_systm.h>
46
#include <netinet/ip.h>
46
#include <netinet/ip.h>
47
#include <sys/time.h>
47
#include <sys/time.h>
48
#include <sys/signal.h>
48
#include <sys/signal.h>
49
#include <signal.h>
49
#include <signal.h>
50
#include <strings.h>
50
#include <strings.h>
51
#include <netdb.h>
51
#include <netdb.h>
52
#include <fcntl.h>
52
#include <fcntl.h>
53
#include <sys/stat.h>
53
#include <sys/stat.h>
54
#include <regex.h>
54
#include <regex.h>
55
#include <sys/ioctl.h>
55
#include <sys/ioctl.h>
56
#if defined(HAVE_DAHDI)
56
#if defined(HAVE_DAHDI)
57
#include <dahdi/user.h>
57
#include <dahdi/user.h>
58
#endif
58
#endif
59

    
   
59

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

    
   
61

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

    
   
93

   
94
#include "iax2.h"
94
#include "iax2.h"
95
#include "iax2-parser.h"
95
#include "iax2-parser.h"
96
#include "iax2-provision.h"
96
#include "iax2-provision.h"
97
#include "jitterbuf.h"
97
#include "jitterbuf.h"
98

    
   
98

   
99
/* Define SCHED_MULTITHREADED to run the scheduler in a special
99
/* Define SCHED_MULTITHREADED to run the scheduler in a special
100
   multithreaded mode. */
100
   multithreaded mode. */
101
#define SCHED_MULTITHREADED
101
#define SCHED_MULTITHREADED
102

    
   
102

   
103
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
103
/* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
104
   thread is actually doing. */
104
   thread is actually doing. */
105
#define DEBUG_SCHED_MULTITHREAD
105
#define DEBUG_SCHED_MULTITHREAD
106

    
   
106

   
107

    
   
107

   
108
#ifdef SO_NO_CHECK
108
#ifdef SO_NO_CHECK
109
static int nochecksums = 0;
109
static int nochecksums = 0;
110
#endif
110
#endif
111

    
   
111

   
112

    
   
112

   
113
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
113
#define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
114
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
114
#define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
115

    
   
115

   
116
#define DEFAULT_THREAD_COUNT 10
116
#define DEFAULT_THREAD_COUNT 10
117
#define DEFAULT_MAX_THREAD_COUNT 100
117
#define DEFAULT_MAX_THREAD_COUNT 100
118
#define DEFAULT_RETRY_TIME 1000
118
#define DEFAULT_RETRY_TIME 1000
119
#define MEMORY_SIZE 100
119
#define MEMORY_SIZE 100
120
#define DEFAULT_DROP 3
120
#define DEFAULT_DROP 3
121

    
   
121

   
122
#define DEBUG_SUPPORT
122
#define DEBUG_SUPPORT
123

    
   
123

   
124
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
124
#define MIN_REUSE_TIME		60	/* Don't reuse a call number within 60 seconds */
125

    
   
125

   
126
/* Sample over last 100 units to determine historic jitter */
126
/* Sample over last 100 units to determine historic jitter */
127
#define GAMMA (0.01)
127
#define GAMMA (0.01)
128

    
   
128

   
129
static struct ast_codec_pref prefs;
129
static struct ast_codec_pref prefs;
130

    
   
130

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

    
   
132

   
133

    
   
133

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

    
   
137

   
138
static int global_max_trunk_mtu; 	/*!< Maximum MTU, 0 if not used */
138
static int global_max_trunk_mtu; 	/*!< Maximum MTU, 0 if not used */
139
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; 	/*!< Trunk MTU statistics */
139
static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; 	/*!< Trunk MTU statistics */
140

    
   
140

   
141

    
   
141

   
142
static char context[80] = "default";
142
static char context[80] = "default";
143

    
   
143

   
144
static char language[MAX_LANGUAGE] = "";
144
static char language[MAX_LANGUAGE] = "";
145
static char regcontext[AST_MAX_CONTEXT] = "";
145
static char regcontext[AST_MAX_CONTEXT] = "";
146

    
   
146

   
147
static int maxauthreq = 3;
147
static int maxauthreq = 3;
148
static int max_retries = 4;
148
static int max_retries = 4;
149
static int ping_time = 21;
149
static int ping_time = 21;
150
static int lagrq_time = 10;
150
static int lagrq_time = 10;
151
static int maxjitterbuffer=1000;
151
static int maxjitterbuffer=1000;
152
static int resyncthreshold=1000;
152
static int resyncthreshold=1000;
153
static int maxjitterinterps=10;
153
static int maxjitterinterps=10;
154
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
154
static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
155

    
   
155

   
156
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
156
#define MAX_TRUNKDATA           640 * 200       /*!< 40ms, uncompressed linear * 200 channels */
157

    
   
157

   
158
static int trunkfreq = 20;
158
static int trunkfreq = 20;
159
static int trunkmaxsize = MAX_TRUNKDATA;
159
static int trunkmaxsize = MAX_TRUNKDATA;
160

    
   
160

   
161
static int authdebug = 1;
161
static int authdebug = 1;
162
static int autokill = 0;
162
static int autokill = 0;
163
static int iaxcompat = 0;
163
static int iaxcompat = 0;
164
static int last_authmethod = 0;
164
static int last_authmethod = 0;
165

    
   
165

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

    
   
167

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

    
   
169

   
170
static unsigned int tos = 0;
170
static unsigned int tos = 0;
171

    
   
171

   
172
static unsigned int cos = 0;
172
static unsigned int cos = 0;
173

    
   
173

   
174
static int min_reg_expire;
174
static int min_reg_expire;
175
static int max_reg_expire;
175
static int max_reg_expire;
176

    
   
176

   
177
static int srvlookup = 0;
177
static int srvlookup = 0;
178

    
   
178

   
179
static int timingfd = -1;				/* Timing file descriptor */
179
static int timingfd = -1;				/* Timing file descriptor */
180

    
   
180

   
181
static struct ast_netsock_list *netsock;
181
static struct ast_netsock_list *netsock;
182
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
182
static struct ast_netsock_list *outsock;		/*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
183
static int defaultsockfd = -1;
183
static int defaultsockfd = -1;
184

    
   
184

   
185
int (*iax2_regfunk)(const char *username, int onoff) = NULL;
185
int (*iax2_regfunk)(const char *username, int onoff) = NULL;
186

    
   
186

   
187
/* Ethernet, etc */
187
/* Ethernet, etc */
188
#define IAX_CAPABILITY_FULLBANDWIDTH 	0xFFFF
188
#define IAX_CAPABILITY_FULLBANDWIDTH 	0xFFFF
189
/* T1, maybe ISDN */
189
/* T1, maybe ISDN */
190
#define IAX_CAPABILITY_MEDBANDWIDTH 	(IAX_CAPABILITY_FULLBANDWIDTH & 	\
190
#define IAX_CAPABILITY_MEDBANDWIDTH 	(IAX_CAPABILITY_FULLBANDWIDTH & 	\
191
					 ~AST_FORMAT_SLINEAR &			\
191
					 ~AST_FORMAT_SLINEAR &			\
192
					 ~AST_FORMAT_ULAW &			\
192
					 ~AST_FORMAT_ULAW &			\
193
					 ~AST_FORMAT_ALAW &			\
193
					 ~AST_FORMAT_ALAW &			\
194
					 ~AST_FORMAT_G722) 
194
					 ~AST_FORMAT_G722) 
195
/* A modem */
195
/* A modem */
196
#define IAX_CAPABILITY_LOWBANDWIDTH	(IAX_CAPABILITY_MEDBANDWIDTH & 		\
196
#define IAX_CAPABILITY_LOWBANDWIDTH	(IAX_CAPABILITY_MEDBANDWIDTH & 		\
197
					 ~AST_FORMAT_G726 &			\
197
					 ~AST_FORMAT_G726 &			\
198
					 ~AST_FORMAT_G726_AAL2 &		\
198
					 ~AST_FORMAT_G726_AAL2 &		\
199
					 ~AST_FORMAT_ADPCM)
199
					 ~AST_FORMAT_ADPCM)
200

    
   
200

   
201
#define IAX_CAPABILITY_LOWFREE		(IAX_CAPABILITY_LOWBANDWIDTH & 		\
201
#define IAX_CAPABILITY_LOWFREE		(IAX_CAPABILITY_LOWBANDWIDTH & 		\
202
					 ~AST_FORMAT_G723_1)
202
					 ~AST_FORMAT_G723_1)
203

    
   
203

   
204

    
   
204

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

    
   
208

   
209
static	struct io_context *io;
209
static	struct io_context *io;
210
static	struct sched_context *sched;
210
static	struct sched_context *sched;
211

    
   
211

   
212
static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
212
static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
213

    
   
213

   
214
static int iaxdebug = 0;
214
static int iaxdebug = 0;
215

    
   
215

   
216
static int iaxtrunkdebug = 0;
216
static int iaxtrunkdebug = 0;
217

    
   
217

   
218
static int test_losspct = 0;
218
static int test_losspct = 0;
219
#ifdef IAXTESTS
219
#ifdef IAXTESTS
220
static int test_late = 0;
220
static int test_late = 0;
221
static int test_resync = 0;
221
static int test_resync = 0;
222
static int test_jit = 0;
222
static int test_jit = 0;
223
static int test_jitpct = 0;
223
static int test_jitpct = 0;
224
#endif /* IAXTESTS */
224
#endif /* IAXTESTS */
225

    
   
225

   
226
static char accountcode[AST_MAX_ACCOUNT_CODE];
226
static char accountcode[AST_MAX_ACCOUNT_CODE];
227
static char mohinterpret[MAX_MUSICCLASS];
227
static char mohinterpret[MAX_MUSICCLASS];
228
static char mohsuggest[MAX_MUSICCLASS];
228
static char mohsuggest[MAX_MUSICCLASS];
229
static int amaflags = 0;
229
static int amaflags = 0;
230
static int adsi = 0;
230
static int adsi = 0;
231
static int delayreject = 0;
231
static int delayreject = 0;
232
static int iax2_encryption = 0;
232
static int iax2_encryption = 0;
233

    
   
233

   
234
static struct ast_flags globalflags = { 0 };
234
static struct ast_flags globalflags = { 0 };
235

    
   
235

   
236
static pthread_t netthreadid = AST_PTHREADT_NULL;
236
static pthread_t netthreadid = AST_PTHREADT_NULL;
237
static pthread_t schedthreadid = AST_PTHREADT_NULL;
237
static pthread_t schedthreadid = AST_PTHREADT_NULL;
238
AST_MUTEX_DEFINE_STATIC(sched_lock);
238
AST_MUTEX_DEFINE_STATIC(sched_lock);
239
static ast_cond_t sched_cond;
239
static ast_cond_t sched_cond;
240

    
   
240

   
241
enum iax2_state {
241
enum iax2_state {
242
	IAX_STATE_STARTED = 		(1 << 0),
242
	IAX_STATE_STARTED = 		(1 << 0),
243
	IAX_STATE_AUTHENTICATED = 	(1 << 1),
243
	IAX_STATE_AUTHENTICATED = 	(1 << 1),
244
	IAX_STATE_TBD = 		(1 << 2),
244
	IAX_STATE_TBD = 		(1 << 2),
245
	IAX_STATE_UNCHANGED = 		(1 << 3),
245
	IAX_STATE_UNCHANGED = 		(1 << 3),
246
};
246
};
247

    
   
247

   
248
struct iax2_context {
248
struct iax2_context {
249
	char context[AST_MAX_CONTEXT];
249
	char context[AST_MAX_CONTEXT];
250
	struct iax2_context *next;
250
	struct iax2_context *next;
251
};
251
};
252

    
   
252

   
253
enum iax2_flags {
253
enum iax2_flags {
254
	IAX_HASCALLERID = 	(1 << 0),	/*!< CallerID has been specified */
254
	IAX_HASCALLERID = 	(1 << 0),	/*!< CallerID has been specified */
255
	IAX_DELME =		(1 << 1),	/*!< Needs to be deleted */
255
	IAX_DELME =		(1 << 1),	/*!< Needs to be deleted */
256
	IAX_TEMPONLY =		(1 << 2),	/*!< Temporary (realtime) */
256
	IAX_TEMPONLY =		(1 << 2),	/*!< Temporary (realtime) */
257
	IAX_TRUNK =		(1 << 3),	/*!< Treat as a trunk */
257
	IAX_TRUNK =		(1 << 3),	/*!< Treat as a trunk */
258
	IAX_NOTRANSFER =	(1 << 4),	/*!< Don't native bridge */
258
	IAX_NOTRANSFER =	(1 << 4),	/*!< Don't native bridge */
259
	IAX_USEJITTERBUF =	(1 << 5),	/*!< Use jitter buffer */
259
	IAX_USEJITTERBUF =	(1 << 5),	/*!< Use jitter buffer */
260
	IAX_DYNAMIC =		(1 << 6),	/*!< dynamic peer */
260
	IAX_DYNAMIC =		(1 << 6),	/*!< dynamic peer */
261
	IAX_SENDANI = 		(1 << 7),	/*!< Send ANI along with CallerID */
261
	IAX_SENDANI = 		(1 << 7),	/*!< Send ANI along with CallerID */
262
        /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
262
        /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
263
	IAX_ALREADYGONE =	(1 << 9),	/*!< Already disconnected */
263
	IAX_ALREADYGONE =	(1 << 9),	/*!< Already disconnected */
264
	IAX_PROVISION =		(1 << 10),	/*!< This is a provisioning request */
264
	IAX_PROVISION =		(1 << 10),	/*!< This is a provisioning request */
265
	IAX_QUELCH = 		(1 << 11),	/*!< Whether or not we quelch audio */
265
	IAX_QUELCH = 		(1 << 11),	/*!< Whether or not we quelch audio */
266
	IAX_ENCRYPTED =		(1 << 12),	/*!< Whether we should assume encrypted tx/rx */
266
	IAX_ENCRYPTED =		(1 << 12),	/*!< Whether we should assume encrypted tx/rx */
267
	IAX_KEYPOPULATED = 	(1 << 13),	/*!< Whether we have a key populated */
267
	IAX_KEYPOPULATED = 	(1 << 13),	/*!< Whether we have a key populated */
268
	IAX_CODEC_USER_FIRST = 	(1 << 14),	/*!< are we willing to let the other guy choose the codec? */
268
	IAX_CODEC_USER_FIRST = 	(1 << 14),	/*!< are we willing to let the other guy choose the codec? */
269
	IAX_CODEC_NOPREFS =  	(1 << 15), 	/*!< Force old behaviour by turning off prefs */
269
	IAX_CODEC_NOPREFS =  	(1 << 15), 	/*!< Force old behaviour by turning off prefs */
270
	IAX_CODEC_NOCAP = 	(1 << 16),	/*!< only consider requested format and ignore capabilities*/
270
	IAX_CODEC_NOCAP = 	(1 << 16),	/*!< only consider requested format and ignore capabilities*/
271
	IAX_RTCACHEFRIENDS = 	(1 << 17), 	/*!< let realtime stay till your reload */
271
	IAX_RTCACHEFRIENDS = 	(1 << 17), 	/*!< let realtime stay till your reload */
272
	IAX_RTUPDATE = 		(1 << 18), 	/*!< Send a realtime update */
272
	IAX_RTUPDATE = 		(1 << 18), 	/*!< Send a realtime update */
273
	IAX_RTAUTOCLEAR = 	(1 << 19), 	/*!< erase me on expire */ 
273
	IAX_RTAUTOCLEAR = 	(1 << 19), 	/*!< erase me on expire */ 
274
	IAX_FORCEJITTERBUF =	(1 << 20),	/*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
274
	IAX_FORCEJITTERBUF =	(1 << 20),	/*!< Force jitterbuffer, even when bridged to a channel that can take jitter */ 
275
	IAX_RTIGNOREREGEXPIRE =	(1 << 21),	/*!< When using realtime, ignore registration expiration */
275
	IAX_RTIGNOREREGEXPIRE =	(1 << 21),	/*!< When using realtime, ignore registration expiration */
276
	IAX_TRUNKTIMESTAMPS =	(1 << 22),	/*!< Send trunk timestamps */
276
	IAX_TRUNKTIMESTAMPS =	(1 << 22),	/*!< Send trunk timestamps */
277
	IAX_TRANSFERMEDIA = 	(1 << 23),      /*!< When doing IAX2 transfers, transfer media only */
277
	IAX_TRANSFERMEDIA = 	(1 << 23),      /*!< When doing IAX2 transfers, transfer media only */
278
	IAX_MAXAUTHREQ =        (1 << 24),      /*!< Maximum outstanding AUTHREQ restriction is in place */
278
	IAX_MAXAUTHREQ =        (1 << 24),      /*!< Maximum outstanding AUTHREQ restriction is in place */
279
	IAX_DELAYPBXSTART =	(1 << 25),	/*!< Don't start a PBX on the channel until the peer sends us a
279
	IAX_DELAYPBXSTART =	(1 << 25),	/*!< Don't start a PBX on the channel until the peer sends us a
280
						     response, so that we've achieved a three-way handshake with
280
						     response, so that we've achieved a three-way handshake with
281
						     them before sending voice or anything else*/
281
						     them before sending voice or anything else*/
282
	IAX_ALLOWFWDOWNLOAD = (1 << 26),	/*!< Allow the FWDOWNL command? */
282
	IAX_ALLOWFWDOWNLOAD = (1 << 26),	/*!< Allow the FWDOWNL command? */
283
};
283
};
284

    
   
284

   
285
static int global_rtautoclear = 120;
285
static int global_rtautoclear = 120;
286

    
   
286

   
287
static int reload_config(void);
287
static int reload_config(void);
288

    
   
288

   
289
struct iax2_user {
289
struct iax2_user {
290
	AST_DECLARE_STRING_FIELDS(
290
	AST_DECLARE_STRING_FIELDS(
291
		AST_STRING_FIELD(name);
291
		AST_STRING_FIELD(name);
292
		AST_STRING_FIELD(secret);
292
		AST_STRING_FIELD(secret);
293
		AST_STRING_FIELD(dbsecret);
293
		AST_STRING_FIELD(dbsecret);
294
		AST_STRING_FIELD(accountcode);
294
		AST_STRING_FIELD(accountcode);
295
		AST_STRING_FIELD(mohinterpret);
295
		AST_STRING_FIELD(mohinterpret);
296
		AST_STRING_FIELD(mohsuggest);
296
		AST_STRING_FIELD(mohsuggest);
297
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
297
		AST_STRING_FIELD(inkeys);               /*!< Key(s) this user can use to authenticate to us */
298
		AST_STRING_FIELD(language);
298
		AST_STRING_FIELD(language);
299
		AST_STRING_FIELD(cid_num);
299
		AST_STRING_FIELD(cid_num);
300
		AST_STRING_FIELD(cid_name);
300
		AST_STRING_FIELD(cid_name);
301
	);
301
	);
302
	
302
	
303
	int authmethods;
303
	int authmethods;
304
	int encmethods;
304
	int encmethods;
305
	int amaflags;
305
	int amaflags;
306
	int adsi;
306
	int adsi;
307
	unsigned int flags;
307
	unsigned int flags;
308
	int capability;
308
	int capability;
309
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
309
	int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
310
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
310
	int curauthreq; /*!< Current number of outstanding AUTHREQs */
311
	struct ast_codec_pref prefs;
311
	struct ast_codec_pref prefs;
312
	struct ast_ha *ha;
312
	struct ast_ha *ha;
313
	struct iax2_context *contexts;
313
	struct iax2_context *contexts;
314
	struct ast_variable *vars;
314
	struct ast_variable *vars;
315
};
315
};
316

    
   
316

   
317
struct iax2_peer {
317
struct iax2_peer {
318
	AST_DECLARE_STRING_FIELDS(
318
	AST_DECLARE_STRING_FIELDS(
319
		AST_STRING_FIELD(name);
319
		AST_STRING_FIELD(name);
320
		AST_STRING_FIELD(username);
320
		AST_STRING_FIELD(username);
321
		AST_STRING_FIELD(secret);
321
		AST_STRING_FIELD(secret);
322
		AST_STRING_FIELD(dbsecret);
322
		AST_STRING_FIELD(dbsecret);
323
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
323
		AST_STRING_FIELD(outkey);	    /*!< What key we use to talk to this peer */
324

    
   
324

   
325
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
325
		AST_STRING_FIELD(regexten);     /*!< Extension to register (if regcontext is used) */
326
		AST_STRING_FIELD(context);      /*!< For transfers only */
326
		AST_STRING_FIELD(context);      /*!< For transfers only */
327
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
327
		AST_STRING_FIELD(peercontext);  /*!< Context to pass to peer */
328
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
328
		AST_STRING_FIELD(mailbox);	    /*!< Mailbox */
329
		AST_STRING_FIELD(mohinterpret);
329
		AST_STRING_FIELD(mohinterpret);
330
		AST_STRING_FIELD(mohsuggest);
330
		AST_STRING_FIELD(mohsuggest);
331
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
331
		AST_STRING_FIELD(inkeys);		/*!< Key(s) this peer can use to authenticate to us */
332
		/* Suggested caller id if registering */
332
		/* Suggested caller id if registering */
333
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
333
		AST_STRING_FIELD(cid_num);		/*!< Default context (for transfer really) */
334
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
334
		AST_STRING_FIELD(cid_name);		/*!< Default context (for transfer really) */
335
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
335
		AST_STRING_FIELD(zonetag);		/*!< Time Zone */
336
	);
336
	);
337
	struct ast_codec_pref prefs;
337
	struct ast_codec_pref prefs;
338
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
338
	struct ast_dnsmgr_entry *dnsmgr;		/*!< DNS refresh manager */
339
	struct sockaddr_in addr;
339
	struct sockaddr_in addr;
340
	int formats;
340
	int formats;
341
	int sockfd;					/*!< Socket to use for transmission */
341
	int sockfd;					/*!< Socket to use for transmission */
342
	struct in_addr mask;
342
	struct in_addr mask;
343
	int adsi;
343
	int adsi;
344
	unsigned int flags;
344
	unsigned int flags;
345

    
   
345

   
346
	/* Dynamic Registration fields */
346
	/* Dynamic Registration fields */
347
	struct sockaddr_in defaddr;			/*!< Default address if there is one */
347
	struct sockaddr_in defaddr;			/*!< Default address if there is one */
348
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
348
	int authmethods;				/*!< Authentication methods (IAX_AUTH_*) */
349
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
349
	int encmethods;					/*!< Encryption methods (IAX_ENCRYPT_*) */
350

    
   
350

   
351
	int expire;					/*!< Schedule entry for expiry */
351
	int expire;					/*!< Schedule entry for expiry */
352
	int expiry;					/*!< How soon to expire */
352
	int expiry;					/*!< How soon to expire */
353
	int capability;					/*!< Capability */
353
	int capability;					/*!< Capability */
354

    
   
354

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

    
   
360

   
361
	int pokefreqok;					/*!< How often to check if the host is up */
361
	int pokefreqok;					/*!< How often to check if the host is up */
362
	int pokefreqnotok;				/*!< How often to check when the host has been determined to be down */
362
	int pokefreqnotok;				/*!< How often to check when the host has been determined to be down */
363
	int historicms;					/*!< How long recent average responses took */
363
	int historicms;					/*!< How long recent average responses took */
364
	int smoothing;					/*!< Sample over how many units to determine historic ms */
364
	int smoothing;					/*!< Sample over how many units to determine historic ms */
365

    
   
365

   
366
	struct ast_event_sub *mwi_event_sub;
366
	struct ast_event_sub *mwi_event_sub;
367

    
   
367

   
368
	struct ast_ha *ha;
368
	struct ast_ha *ha;
369
};
369
};
370

    
   
370

   
371
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
371
#define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
372

    
   
372

   
373
struct iax2_trunk_peer {
373
struct iax2_trunk_peer {
374
	ast_mutex_t lock;
374
	ast_mutex_t lock;
375
	int sockfd;
375
	int sockfd;
376
	struct sockaddr_in addr;
376
	struct sockaddr_in addr;
377
	struct timeval txtrunktime;		/*!< Transmit trunktime */
377
	struct timeval txtrunktime;		/*!< Transmit trunktime */
378
	struct timeval rxtrunktime;		/*!< Receive trunktime */
378
	struct timeval rxtrunktime;		/*!< Receive trunktime */
379
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
379
	struct timeval lasttxtime;		/*!< Last transmitted trunktime */
380
	struct timeval trunkact;		/*!< Last trunk activity */
380
	struct timeval trunkact;		/*!< Last trunk activity */
381
	unsigned int lastsent;			/*!< Last sent time */
381
	unsigned int lastsent;			/*!< Last sent time */
382
	/* Trunk data and length */
382
	/* Trunk data and length */
383
	unsigned char *trunkdata;
383
	unsigned char *trunkdata;
384
	unsigned int trunkdatalen;
384
	unsigned int trunkdatalen;
385
	unsigned int trunkdataalloc;
385
	unsigned int trunkdataalloc;
386
	int trunkmaxmtu;
386
	int trunkmaxmtu;
387
	int trunkerror;
387
	int trunkerror;
388
	int calls;
388
	int calls;
389
	AST_LIST_ENTRY(iax2_trunk_peer) list;
389
	AST_LIST_ENTRY(iax2_trunk_peer) list;
390
};
390
};
391

    
   
391

   
392
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
392
static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
393

    
   
393

   
394
struct iax_firmware {
394
struct iax_firmware {
395
	AST_LIST_ENTRY(iax_firmware) list;
395
	AST_LIST_ENTRY(iax_firmware) list;
396
	int fd;
396
	int fd;
397
	int mmaplen;
397
	int mmaplen;
398
	int dead;
398
	int dead;
399
	struct ast_iax2_firmware_header *fwh;
399
	struct ast_iax2_firmware_header *fwh;
400
	unsigned char *buf;
400
	unsigned char *buf;
401
};
401
};
402

    
   
402

   
403
enum iax_reg_state {
403
enum iax_reg_state {
404
	REG_STATE_UNREGISTERED = 0,
404
	REG_STATE_UNREGISTERED = 0,
405
	REG_STATE_REGSENT,
405
	REG_STATE_REGSENT,
406
	REG_STATE_AUTHSENT,
406
	REG_STATE_AUTHSENT,
407
	REG_STATE_REGISTERED,
407
	REG_STATE_REGISTERED,
408
	REG_STATE_REJECTED,
408
	REG_STATE_REJECTED,
409
	REG_STATE_TIMEOUT,
409
	REG_STATE_TIMEOUT,
410
	REG_STATE_NOAUTH
410
	REG_STATE_NOAUTH
411
};
411
};
412

    
   
412

   
413
enum iax_transfer_state {
413
enum iax_transfer_state {
414
	TRANSFER_NONE = 0,
414
	TRANSFER_NONE = 0,
415
	TRANSFER_BEGIN,
415
	TRANSFER_BEGIN,
416
	TRANSFER_READY,
416
	TRANSFER_READY,
417
	TRANSFER_RELEASED,
417
	TRANSFER_RELEASED,
418
	TRANSFER_PASSTHROUGH,
418
	TRANSFER_PASSTHROUGH,
419
	TRANSFER_MBEGIN,
419
	TRANSFER_MBEGIN,
420
	TRANSFER_MREADY,
420
	TRANSFER_MREADY,
421
	TRANSFER_MRELEASED,
421
	TRANSFER_MRELEASED,
422
	TRANSFER_MPASSTHROUGH,
422
	TRANSFER_MPASSTHROUGH,
423
	TRANSFER_MEDIA,
423
	TRANSFER_MEDIA,
424
	TRANSFER_MEDIAPASS
424
	TRANSFER_MEDIAPASS
425
};
425
};
426

    
   
426

   
427
struct iax2_registry {
427
struct iax2_registry {
428
	struct sockaddr_in addr;		/*!< Who we connect to for registration purposes */
428
	struct sockaddr_in addr;		/*!< Who we connect to for registration purposes */
429
	char username[80];
429
	char username[80];
430
	char secret[80];			/*!< Password or key name in []'s */
430
	char secret[80];			/*!< Password or key name in []'s */
431
	int expire;				/*!< Sched ID of expiration */
431
	int expire;				/*!< Sched ID of expiration */
432
	int refresh;				/*!< How often to refresh */
432
	int refresh;				/*!< How often to refresh */
433
	enum iax_reg_state regstate;
433
	enum iax_reg_state regstate;
434
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
434
	int messages;				/*!< Message count, low 8 bits = new, high 8 bits = old */
435
	int callno;				/*!< Associated call number if applicable */
435
	int callno;				/*!< Associated call number if applicable */
436
	struct sockaddr_in us;			/*!< Who the server thinks we are */
436
	struct sockaddr_in us;			/*!< Who the server thinks we are */
437
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
437
	struct ast_dnsmgr_entry *dnsmgr;	/*!< DNS refresh manager */
438
	AST_LIST_ENTRY(iax2_registry) entry;
438
	AST_LIST_ENTRY(iax2_registry) entry;
439
};
439
};
440

    
   
440

   
441
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
441
static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
442

    
   
442

   
443
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
443
/* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
444
#define MIN_RETRY_TIME		100
444
#define MIN_RETRY_TIME		100
445
#define MAX_RETRY_TIME  	10000
445
#define MAX_RETRY_TIME  	10000
446

    
   
446

   
447
#define MAX_JITTER_BUFFER 	50
447
#define MAX_JITTER_BUFFER 	50
448
#define MIN_JITTER_BUFFER 	10
448
#define MIN_JITTER_BUFFER 	10
449

    
   
449

   
450
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
450
#define DEFAULT_TRUNKDATA	640 * 10	/*!< 40ms, uncompressed linear * 10 channels */
451

    
   
451

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

    
   
453

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

    
   
456

   
457
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
457
static int iaxthreadcount = DEFAULT_THREAD_COUNT;
458
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
458
static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
459
static int iaxdynamicthreadcount = 0;
459
static int iaxdynamicthreadcount = 0;
460
static int iaxdynamicthreadnum = 0;
460
static int iaxdynamicthreadnum = 0;
461
static int iaxactivethreadcount = 0;
461
static int iaxactivethreadcount = 0;
462

    
   
462

   
463
struct iax_rr {
463
struct iax_rr {
464
	int jitter;
464
	int jitter;
465
	int losspct;
465
	int losspct;
466
	int losscnt;
466
	int losscnt;
467
	int packets;
467
	int packets;
468
	int delay;
468
	int delay;
469
	int dropped;
469
	int dropped;
470
	int ooo;
470
	int ooo;
471
};
471
};
472

    
   
472

   
473
struct iax2_pvt_ref;
473
struct iax2_pvt_ref;
474

    
   
474

   
475
struct chan_iax2_pvt {
475
struct chan_iax2_pvt {
476
	/*! Socket to send/receive on for this call */
476
	/*! Socket to send/receive on for this call */
477
	int sockfd;
477
	int sockfd;
478
	/*! Last received voice format */
478
	/*! Last received voice format */
479
	int voiceformat;
479
	int voiceformat;
480
	/*! Last received video format */
480
	/*! Last received video format */
481
	int videoformat;
481
	int videoformat;
482
	/*! Last sent voice format */
482
	/*! Last sent voice format */
483
	int svoiceformat;
483
	int svoiceformat;
484
	/*! Last sent video format */
484
	/*! Last sent video format */
485
	int svideoformat;
485
	int svideoformat;
486
	/*! What we are capable of sending */
486
	/*! What we are capable of sending */
487
	int capability;
487
	int capability;
488
	/*! Last received timestamp */
488
	/*! Last received timestamp */
489
	unsigned int last;
489
	unsigned int last;
490
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
490
	/*! Last sent timestamp - never send the same timestamp twice in a single call */
491
	unsigned int lastsent;
491
	unsigned int lastsent;
492
	/*! Timestamp of the last video frame sent */
492
	/*! Timestamp of the last video frame sent */
493
	unsigned int lastvsent;
493
	unsigned int lastvsent;
494
	/*! Next outgoing timestamp if everything is good */
494
	/*! Next outgoing timestamp if everything is good */
495
	unsigned int nextpred;
495
	unsigned int nextpred;
496
	/*! True if the last voice we transmitted was not silence/CNG */
496
	/*! True if the last voice we transmitted was not silence/CNG */
497
	unsigned int notsilenttx:1;
497
	unsigned int notsilenttx:1;
498
	/*! Ping time */
498
	/*! Ping time */
499
	unsigned int pingtime;
499
	unsigned int pingtime;
500
	/*! Max time for initial response */
500
	/*! Max time for initial response */
501
	int maxtime;
501
	int maxtime;
502
	/*! Peer Address */
502
	/*! Peer Address */
503
	struct sockaddr_in addr;
503
	struct sockaddr_in addr;
504
	/*! Actual used codec preferences */
504
	/*! Actual used codec preferences */
505
	struct ast_codec_pref prefs;
505
	struct ast_codec_pref prefs;
506
	/*! Requested codec preferences */
506
	/*! Requested codec preferences */
507
	struct ast_codec_pref rprefs;
507
	struct ast_codec_pref rprefs;
508
	/*! Our call number */
508
	/*! Our call number */
509
	unsigned short callno;
509
	unsigned short callno;
510
	/*! Peer callno */
510
	/*! Peer callno */
511
	unsigned short peercallno;
511
	unsigned short peercallno;
512
	/*! Negotiated format, this is only used to remember what format was
512
	/*! Negotiated format, this is only used to remember what format was
513
	    chosen for an unauthenticated call so that the channel can get
513
	    chosen for an unauthenticated call so that the channel can get
514
	    created later using the right format */
514
	    created later using the right format */
515
	int chosenformat;
515
	int chosenformat;
516
	/*! Peer selected format */
516
	/*! Peer selected format */
517
	int peerformat;
517
	int peerformat;
518
	/*! Peer capability */
518
	/*! Peer capability */
519
	int peercapability;
519
	int peercapability;
520
	/*! timeval that we base our transmission on */
520
	/*! timeval that we base our transmission on */
521
	struct timeval offset;
521
	struct timeval offset;
522
	/*! timeval that we base our delivery on */
522
	/*! timeval that we base our delivery on */
523
	struct timeval rxcore;
523
	struct timeval rxcore;
524
	/*! The jitterbuffer */
524
	/*! The jitterbuffer */
525
	jitterbuf *jb;
525
	jitterbuf *jb;
526
	/*! active jb read scheduler id */
526
	/*! active jb read scheduler id */
527
	int jbid;                       
527
	int jbid;                       
528
	/*! LAG */
528
	/*! LAG */
529
	int lag;
529
	int lag;
530
	/*! Error, as discovered by the manager */
530
	/*! Error, as discovered by the manager */
531
	int error;
531
	int error;
532
	/*! Owner if we have one */
532
	/*! Owner if we have one */
533
	struct ast_channel *owner;
533
	struct ast_channel *owner;
534
	/*! What's our state? */
534
	/*! What's our state? */
535
	struct ast_flags state;
535
	struct ast_flags state;
536
	/*! Expiry (optional) */
536
	/*! Expiry (optional) */
537
	int expiry;
537
	int expiry;
538
	/*! Next outgoing sequence number */
538
	/*! Next outgoing sequence number */
539
	unsigned char oseqno;
539
	unsigned char oseqno;
540
	/*! Next sequence number they have not yet acknowledged */
540
	/*! Next sequence number they have not yet acknowledged */
541
	unsigned char rseqno;
541
	unsigned char rseqno;
542
	/*! Next incoming sequence number */
542
	/*! Next incoming sequence number */
543
	unsigned char iseqno;
543
	unsigned char iseqno;
544
	/*! Last incoming sequence number we have acknowledged */
544
	/*! Last incoming sequence number we have acknowledged */
545
	unsigned char aseqno;
545
	unsigned char aseqno;
546

    
   
546

   
547
	AST_DECLARE_STRING_FIELDS(
547
	AST_DECLARE_STRING_FIELDS(
548
		/*! Peer name */
548
		/*! Peer name */
549
		AST_STRING_FIELD(peer);
549
		AST_STRING_FIELD(peer);
550
		/*! Default Context */
550
		/*! Default Context */
551
		AST_STRING_FIELD(context);
551
		AST_STRING_FIELD(context);
552
		/*! Caller ID if available */
552
		/*! Caller ID if available */
553
		AST_STRING_FIELD(cid_num);
553
		AST_STRING_FIELD(cid_num);
554
		AST_STRING_FIELD(cid_name);
554
		AST_STRING_FIELD(cid_name);
555
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
555
		/*! Hidden Caller ID (i.e. ANI) if appropriate */
556
		AST_STRING_FIELD(ani);
556
		AST_STRING_FIELD(ani);
557
		/*! DNID */
557
		/*! DNID */
558
		AST_STRING_FIELD(dnid);
558
		AST_STRING_FIELD(dnid);
559
		/*! RDNIS */
559
		/*! RDNIS */
560
		AST_STRING_FIELD(rdnis);
560
		AST_STRING_FIELD(rdnis);
561
		/*! Requested Extension */
561
		/*! Requested Extension */
562
		AST_STRING_FIELD(exten);
562
		AST_STRING_FIELD(exten);
563
		/*! Expected Username */
563
		/*! Expected Username */
564
		AST_STRING_FIELD(username);
564
		AST_STRING_FIELD(username);
565
		/*! Expected Secret */
565
		/*! Expected Secret */
566
		AST_STRING_FIELD(secret);
566
		AST_STRING_FIELD(secret);
567
		/*! MD5 challenge */
567
		/*! MD5 challenge */
568
		AST_STRING_FIELD(challenge);
568
		AST_STRING_FIELD(challenge);
569
		/*! Public keys permitted keys for incoming authentication */
569
		/*! Public keys permitted keys for incoming authentication */
570
		AST_STRING_FIELD(inkeys);
570
		AST_STRING_FIELD(inkeys);
571
		/*! Private key for outgoing authentication */
571
		/*! Private key for outgoing authentication */
572
		AST_STRING_FIELD(outkey);
572
		AST_STRING_FIELD(outkey);
573
		/*! Preferred language */
573
		/*! Preferred language */
574
		AST_STRING_FIELD(language);
574
		AST_STRING_FIELD(language);
575
		/*! Hostname/peername for naming purposes */
575
		/*! Hostname/peername for naming purposes */
576
		AST_STRING_FIELD(host);
576
		AST_STRING_FIELD(host);
577

    
   
577

   
578
		AST_STRING_FIELD(dproot);
578
		AST_STRING_FIELD(dproot);
579
		AST_STRING_FIELD(accountcode);
579
		AST_STRING_FIELD(accountcode);
580
		AST_STRING_FIELD(mohinterpret);
580
		AST_STRING_FIELD(mohinterpret);
581
		AST_STRING_FIELD(mohsuggest);
581
		AST_STRING_FIELD(mohsuggest);
582
		/*! received OSP token */
582
		/*! received OSP token */
583
		AST_STRING_FIELD(osptoken);
583
		AST_STRING_FIELD(osptoken);
584
	);
584
	);
585
	
585
	
586
	/*! permitted authentication methods */
586
	/*! permitted authentication methods */
587
	int authmethods;
587
	int authmethods;
588
	/*! permitted encryption methods */
588
	/*! permitted encryption methods */
589
	int encmethods;
589
	int encmethods;
590
	/*! Encryption AES-128 Key */
590
	/*! Encryption AES-128 Key */
591
	ast_aes_encrypt_key ecx;
591
	ast_aes_encrypt_key ecx;
592
	/*! Decryption AES-128 Key */
592
	/*! Decryption AES-128 Key */
593
	ast_aes_decrypt_key dcx;
593
	ast_aes_decrypt_key dcx;
594
	/*! 32 bytes of semi-random data */
594
	/*! 32 bytes of semi-random data */
595
	unsigned char semirand[32];
595
	unsigned char semirand[32];
596
	/*! Associated registry */
596
	/*! Associated registry */
597
	struct iax2_registry *reg;
597
	struct iax2_registry *reg;
598
	/*! Associated peer for poking */
598
	/*! Associated peer for poking */
599
	struct iax2_peer *peerpoke;
599
	struct iax2_peer *peerpoke;
600
	/*! IAX_ flags */
600
	/*! IAX_ flags */
601
	unsigned int flags;
601
	unsigned int flags;
602
	int adsi;
602
	int adsi;
603

    
   
603

   
604
	/*! Transferring status */
604
	/*! Transferring status */
605
	enum iax_transfer_state transferring;
605
	enum iax_transfer_state transferring;
606
	/*! Transfer identifier */
606
	/*! Transfer identifier */
607
	int transferid;
607
	int transferid;
608
	/*! Who we are IAX transferring to */
608
	/*! Who we are IAX transferring to */
609
	struct sockaddr_in transfer;
609
	struct sockaddr_in transfer;
610
	/*! What's the new call number for the transfer */
610
	/*! What's the new call number for the transfer */
611
	unsigned short transfercallno;
611
	unsigned short transfercallno;
612
	/*! Transfer encrypt AES-128 Key */
612
	/*! Transfer encrypt AES-128 Key */
613
	ast_aes_encrypt_key tdcx;
613
	ast_aes_encrypt_key tdcx;
614

    
   
614

   
615
	/*! Status of knowledge of peer ADSI capability */
615
	/*! Status of knowledge of peer ADSI capability */
616
	int peeradsicpe;
616
	int peeradsicpe;
617

    
   
617

   
618
	/*! Who we are bridged to */
618
	/*! Who we are bridged to */
619
	unsigned short bridgecallno;
619
	unsigned short bridgecallno;
620
	
620
	
621
	int pingid;			/*!< Transmit PING request */
621
	int pingid;			/*!< Transmit PING request */
622
	int lagid;			/*!< Retransmit lag request */
622
	int lagid;			/*!< Retransmit lag request */
623
	int autoid;			/*!< Auto hangup for Dialplan requestor */
623
	int autoid;			/*!< Auto hangup for Dialplan requestor */
624
	int authid;			/*!< Authentication rejection ID */
624
	int authid;			/*!< Authentication rejection ID */
625
	int authfail;			/*!< Reason to report failure */
625
	int authfail;			/*!< Reason to report failure */
626
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
626
	int initid;			/*!< Initial peer auto-congest ID (based on qualified peers) */
627
	int calling_ton;
627
	int calling_ton;
628
	int calling_tns;
628
	int calling_tns;
629
	int calling_pres;
629
	int calling_pres;
630
	int amaflags;
630
	int amaflags;
631
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
631
	AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
632
	/*! variables inherited from the user definition */
632
	/*! variables inherited from the user definition */
633
	struct ast_variable *vars;
633
	struct ast_variable *vars;
634
	/*! variables transmitted in a NEW packet */
634
	/*! variables transmitted in a NEW packet */
635
	struct ast_variable *iaxvars;
635
	struct ast_variable *iaxvars;
636
	/*! last received remote rr */
636
	/*! last received remote rr */
637
	struct iax_rr remote_rr;
637
	struct iax_rr remote_rr;
638
	/*! Current base time: (just for stats) */
638
	/*! Current base time: (just for stats) */
639
	int min;
639
	int min;
640
	/*! Dropped frame count: (just for stats) */
640
	/*! Dropped frame count: (just for stats) */
641
	int frames_dropped;
641
	int frames_dropped;
642
	/*! received frame count: (just for stats) */
642
	/*! received frame count: (just for stats) */
643
	int frames_received;
643
	int frames_received;
644
};
644
};
645

    
   
645

   
646
/*!
646
/*!
647
 * \brief a list of frames that may need to be retransmitted
647
 * \brief a list of frames that may need to be retransmitted
648
 *
648
 *
649
 * \note The contents of this list do not need to be explicitly destroyed
649
 * \note The contents of this list do not need to be explicitly destroyed
650
 * on module unload.  This is because all active calls are destroyed, and
650
 * on module unload.  This is because all active calls are destroyed, and
651
 * all frames in this queue will get destroyed as a part of that process.
651
 * all frames in this queue will get destroyed as a part of that process.
652
 */
652
 */
653
static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
653
static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
654

    
   
654

   
655
/*!
655
/*!
656
 * This module will get much higher performance when doing a lot of
656
 * This module will get much higher performance when doing a lot of
657
 * user and peer lookups if the number of buckets is increased from 1.
657
 * user and peer lookups if the number of buckets is increased from 1.
658
 * However, to maintain old behavior for Asterisk 1.4, these are set to
658
 * However, to maintain old behavior for Asterisk 1.4, these are set to
659
 * 1 by default.  When using multiple buckets, search order through these
659
 * 1 by default.  When using multiple buckets, search order through these
660
 * containers is considered random, so you will not be able to depend on
660
 * containers is considered random, so you will not be able to depend on
661
 * the order the entires are specified in iax.conf for matching order. */
661
 * the order the entires are specified in iax.conf for matching order. */
662
#ifdef LOW_MEMORY
662
#ifdef LOW_MEMORY
663
#define MAX_PEER_BUCKETS 17
663
#define MAX_PEER_BUCKETS 17
664
#else
664
#else
665
#define MAX_PEER_BUCKETS 563
665
#define MAX_PEER_BUCKETS 563
666
#endif
666
#endif
667
static struct ao2_container *peers;
667
static struct ao2_container *peers;
668

    
   
668

   
669
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
669
#define MAX_USER_BUCKETS MAX_PEER_BUCKETS
670
static struct ao2_container *users;
670
static struct ao2_container *users;
671

    
   
671

   
672
static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
672
static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
673

    
   
673

   
674
enum {
674
enum {
675
	/*! Extension exists */
675
	/*! Extension exists */
676
	CACHE_FLAG_EXISTS      = (1 << 0),
676
	CACHE_FLAG_EXISTS      = (1 << 0),
677
	/*! Extension is nonexistent */
677
	/*! Extension is nonexistent */
678
	CACHE_FLAG_NONEXISTENT = (1 << 1),
678
	CACHE_FLAG_NONEXISTENT = (1 << 1),
679
	/*! Extension can exist */
679
	/*! Extension can exist */
680
	CACHE_FLAG_CANEXIST    = (1 << 2),
680
	CACHE_FLAG_CANEXIST    = (1 << 2),
681
	/*! Waiting to hear back response */
681
	/*! Waiting to hear back response */
682
	CACHE_FLAG_PENDING     = (1 << 3),
682
	CACHE_FLAG_PENDING     = (1 << 3),
683
	/*! Timed out */
683
	/*! Timed out */
684
	CACHE_FLAG_TIMEOUT     = (1 << 4),
684
	CACHE_FLAG_TIMEOUT     = (1 << 4),
685
	/*! Request transmitted */
685
	/*! Request transmitted */
686
	CACHE_FLAG_TRANSMITTED = (1 << 5),
686
	CACHE_FLAG_TRANSMITTED = (1 << 5),
687
	/*! Timeout */
687
	/*! Timeout */
688
	CACHE_FLAG_UNKNOWN     = (1 << 6),
688
	CACHE_FLAG_UNKNOWN     = (1 << 6),
689
	/*! Matchmore */
689
	/*! Matchmore */
690
	CACHE_FLAG_MATCHMORE   = (1 << 7),
690
	CACHE_FLAG_MATCHMORE   = (1 << 7),
691
};
691
};
692

    
   
692

   
693
struct iax2_dpcache {
693
struct iax2_dpcache {
694
	char peercontext[AST_MAX_CONTEXT];
694
	char peercontext[AST_MAX_CONTEXT];
695
	char exten[AST_MAX_EXTENSION];
695
	char exten[AST_MAX_EXTENSION];
696
	struct timeval orig;
696
	struct timeval orig;
697
	struct timeval expiry;
697
	struct timeval expiry;
698
	int flags;
698
	int flags;
699
	unsigned short callno;
699
	unsigned short callno;
700
	int waiters[256];
700
	int waiters[256];
701
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
701
	AST_LIST_ENTRY(iax2_dpcache) cache_list;
702
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
702
	AST_LIST_ENTRY(iax2_dpcache) peer_list;
703
};
703
};
704

    
   
704

   
705
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
705
static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
706

    
   
706

   
707
static void reg_source_db(struct iax2_peer *p);
707
static void reg_source_db(struct iax2_peer *p);
708
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
708
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
709

    
   
709

   
710
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
710
static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
711
static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
711
static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
712
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
712
static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
713

    
   
713

   
714
enum iax2_thread_iostate {
714
enum iax2_thread_iostate {
715
	IAX_IOSTATE_IDLE,
715
	IAX_IOSTATE_IDLE,
716
	IAX_IOSTATE_READY,
716
	IAX_IOSTATE_READY,
717
	IAX_IOSTATE_PROCESSING,
717
	IAX_IOSTATE_PROCESSING,
718
	IAX_IOSTATE_SCHEDREADY,
718
	IAX_IOSTATE_SCHEDREADY,
719
};
719
};
720

    
   
720

   
721
enum iax2_thread_type {
721
enum iax2_thread_type {
722
	IAX_THREAD_TYPE_POOL,
722
	IAX_THREAD_TYPE_POOL,
723
	IAX_THREAD_TYPE_DYNAMIC,
723
	IAX_THREAD_TYPE_DYNAMIC,
724
};
724
};
725

    
   
725

   
726
struct iax2_pkt_buf {
726
struct iax2_pkt_buf {
727
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
727
	AST_LIST_ENTRY(iax2_pkt_buf) entry;
728
	size_t len;
728
	size_t len;
729
	unsigned char buf[1];
729
	unsigned char buf[1];
730
};
730
};
731

    
   
731

   
732
struct iax2_thread {
732
struct iax2_thread {
733
	AST_LIST_ENTRY(iax2_thread) list;
733
	AST_LIST_ENTRY(iax2_thread) list;
734
	enum iax2_thread_type type;
734
	enum iax2_thread_type type;
735
	enum iax2_thread_iostate iostate;
735
	enum iax2_thread_iostate iostate;
736
#ifdef SCHED_MULTITHREADED
736
#ifdef SCHED_MULTITHREADED
737
	void (*schedfunc)(const void *);
737
	void (*schedfunc)(const void *);
738
	const void *scheddata;
738
	const void *scheddata;
739
#endif
739
#endif
740
#ifdef DEBUG_SCHED_MULTITHREAD
740
#ifdef DEBUG_SCHED_MULTITHREAD
741
	char curfunc[80];
741
	char curfunc[80];
742
#endif	
742
#endif	
743
	int actions;
743
	int actions;
744
	pthread_t threadid;
744
	pthread_t threadid;
745
	int threadnum;
745
	int threadnum;
746
	struct sockaddr_in iosin;
746
	struct sockaddr_in iosin;
747
	unsigned char readbuf[4096]; 
747
	unsigned char readbuf[4096]; 
748
	unsigned char *buf;
748
	unsigned char *buf;
749
	ssize_t buf_len;
749
	ssize_t buf_len;
750
	size_t buf_size;
750
	size_t buf_size;
751
	int iofd;
751
	int iofd;
752
	time_t checktime;
752
	time_t checktime;
753
	ast_mutex_t lock;
753
	ast_mutex_t lock;
754
	ast_cond_t cond;
754
	ast_cond_t cond;
755
	unsigned int ready_for_signal:1;
755
	unsigned int ready_for_signal:1;
756
	/*! if this thread is processing a full frame,
756
	/*! if this thread is processing a full frame,
757
	  some information about that frame will be stored
757
	  some information about that frame will be stored
758
	  here, so we can avoid dispatching any more full
758
	  here, so we can avoid dispatching any more full
759
	  frames for that callno to other threads */
759
	  frames for that callno to other threads */
760
	struct {
760
	struct {
761
		unsigned short callno;
761
		unsigned short callno;
762
		struct sockaddr_in sin;
762
		struct sockaddr_in sin;
763
		unsigned char type;
763
		unsigned char type;
764
		unsigned char csub;
764
		unsigned char csub;
765
	} ffinfo;
765
	} ffinfo;
766
	/*! Queued up full frames for processing.  If more full frames arrive for
766
	/*! Queued up full frames for processing.  If more full frames arrive for
767
	 *  a call which this thread is already processing a full frame for, they
767
	 *  a call which this thread is already processing a full frame for, they
768
	 *  are queued up here. */
768
	 *  are queued up here. */
769
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
769
	AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
770
};
770
};
771

    
   
771

   
772
/* Thread lists */
772
/* Thread lists */
773
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
773
static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
774
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
774
static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
775
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
775
static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
776

    
   
776

   
777
static void *iax2_process_thread(void *data);
777
static void *iax2_process_thread(void *data);
778
static void iax2_destroy(int callno);
778
static void iax2_destroy(int callno);
779

    
   
779

   
780
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
780
static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
781
{
781
{
782
	ast_mutex_lock(lock);
782
	ast_mutex_lock(lock);
783
	ast_cond_signal(cond);
783
	ast_cond_signal(cond);
784
	ast_mutex_unlock(lock);
784
	ast_mutex_unlock(lock);
785
}
785
}
786

    
   
786

   
787
static void iax_debug_output(const char *data)
787
static void iax_debug_output(const char *data)
788
{
788
{
789
	if (iaxdebug)
789
	if (iaxdebug)
790
		ast_verbose("%s", data);
790
		ast_verbose("%s", data);
791
}
791
}
792

    
   
792

   
793
static void iax_error_output(const char *data)
793
static void iax_error_output(const char *data)
794
{
794
{
795
	ast_log(LOG_WARNING, "%s", data);
795
	ast_log(LOG_WARNING, "%s", data);
796
}
796
}
797

    
   
797

   
798
static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
798
static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
799
{
799
{
800
	va_list args;
800
	va_list args;
801
	char buf[1024];
801
	char buf[1024];
802

    
   
802

   
803
	va_start(args, fmt);
803
	va_start(args, fmt);
804
	vsnprintf(buf, sizeof(buf), fmt, args);
804
	vsnprintf(buf, sizeof(buf), fmt, args);
805
	va_end(args);
805
	va_end(args);
806

    
   
806

   
807
	ast_log(LOG_ERROR, "%s", buf);
807
	ast_log(LOG_ERROR, "%s", buf);
808
}
808
}
809

    
   
809

   
810
static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
810
static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
811
{
811
{
812
	va_list args;
812
	va_list args;
813
	char buf[1024];
813
	char buf[1024];
814

    
   
814

   
815
	va_start(args, fmt);
815
	va_start(args, fmt);
816
	vsnprintf(buf, sizeof(buf), fmt, args);
816
	vsnprintf(buf, sizeof(buf), fmt, args);
817
	va_end(args);
817
	va_end(args);
818

    
   
818

   
819
	ast_log(LOG_WARNING, "%s", buf);
819
	ast_log(LOG_WARNING, "%s", buf);
820
}
820
}
821

    
   
821

   
822
static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
822
static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
823
{
823
{
824
	va_list args;
824
	va_list args;
825
	char buf[1024];
825
	char buf[1024];
826

    
   
826

   
827
	va_start(args, fmt);
827
	va_start(args, fmt);
828
	vsnprintf(buf, sizeof(buf), fmt, args);
828
	vsnprintf(buf, sizeof(buf), fmt, args);
829
	va_end(args);
829
	va_end(args);
830

    
   
830

   
831
	ast_verbose("%s", buf);
831
	ast_verbose("%s", buf);
832
}
832
}
833

    
   
833

   
834
/*!
834
/*!
835
 * \brief an array of iax2 pvt structures
835
 * \brief an array of iax2 pvt structures
836
 *
836
 *
837
 * The container for active chan_iax2_pvt structures is implemented as an
837
 * The container for active chan_iax2_pvt structures is implemented as an
838
 * array for extremely quick direct access to the correct pvt structure
838
 * array for extremely quick direct access to the correct pvt structure
839
 * based on the local call number.  The local call number is used as the
839
 * based on the local call number.  The local call number is used as the
840
 * index into the array where the associated pvt structure is stored.
840
 * index into the array where the associated pvt structure is stored.
841
 */
841
 */
842
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
842
static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
843

    
   
843

   
844
/*!
844
/*!
845
 * \brief Another container of iax2_pvt structures
845
 * \brief Another container of iax2_pvt structures
846
 *
846
 *
847
 * Active IAX2 pvt structs are also stored in this container, if they are a part
847
 * Active IAX2 pvt structs are also stored in this container, if they are a part
848
 * of an active call where we know the remote side's call number.  The reason
848
 * of an active call where we know the remote side's call number.  The reason
849
 * for this is that incoming media frames do not contain our call number.  So,
849
 * for this is that incoming media frames do not contain our call number.  So,
850
 * instead of having to iterate the entire iaxs array, we use this container to
850
 * instead of having to iterate the entire iaxs array, we use this container to
851
 * look up calls where the remote side is using a given call number.
851
 * look up calls where the remote side is using a given call number.
852
 */
852
 */
853
static struct ao2_container *iax_peercallno_pvts;
853
static struct ao2_container *iax_peercallno_pvts;
854

    
   
854

   
855
/*!
855
/*!
856
 * \brief chan_iax2_pvt structure locks
856
 * \brief chan_iax2_pvt structure locks
857
 *
857
 *
858
 * These locks are used when accessing a pvt structure in the iaxs array.
858
 * These locks are used when accessing a pvt structure in the iaxs array.
859
 * The index used here is the same as used in the iaxs array.  It is the
859
 * The index used here is the same as used in the iaxs array.  It is the
860
 * local call number for the associated pvt struct.
860
 * local call number for the associated pvt struct.
861
 */
861
 */
862
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
862
static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
863

    
   
863

   
864
/*!
864
/*!
865
 * \brief The last time a call number was used
865
 * \brief The last time a call number was used
866
 *
866
 *
867
 * It is important to know the last time that a call number was used locally so
867
 * It is important to know the last time that a call number was used locally so
868
 * that it is not used again too soon.  The reason for this is the same as the
868
 * that it is not used again too soon.  The reason for this is the same as the
869
 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
869
 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
870
 *
870
 *
871
 * For example, say that a call is up.  Then, the remote side sends a HANGUP,
871
 * For example, say that a call is up.  Then, the remote side sends a HANGUP,
872
 * which we respond to with an ACK.  However, there is no way to know whether
872
 * which we respond to with an ACK.  However, there is no way to know whether
873
 * the ACK made it there successfully.  If it were to get lost, the remote
873
 * the ACK made it there successfully.  If it were to get lost, the remote
874
 * side may retransmit the HANGUP.  If in the meantime, this call number has
874
 * side may retransmit the HANGUP.  If in the meantime, this call number has
875
 * been reused locally, given the right set of circumstances, this retransmitted
875
 * been reused locally, given the right set of circumstances, this retransmitted
876
 * HANGUP could potentially improperly hang up the new session.  So, to avoid
876
 * HANGUP could potentially improperly hang up the new session.  So, to avoid
877
 * this potential issue, we must wait a specified timeout period before reusing
877
 * this potential issue, we must wait a specified timeout period before reusing
878
 * a local call number.
878
 * a local call number.
879
 *
879
 *
880
 * The specified time that we must wait before reusing a local call number is
880
 * The specified time that we must wait before reusing a local call number is
881
 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
881
 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
882
 */
882
 */
883
static struct timeval lastused[ARRAY_LEN(iaxs)];
883
static struct timeval lastused[ARRAY_LEN(iaxs)];
884

    
   
884

   

    
   
885
/*!

    
   
886
 *  * \brief Another container of iax2_pvt structures

    
   
887
 *  

    
   
888
 *  Active IAX2 pvt stucts used during transfering a call are stored here.  

    
   
889
 */

    
   
890
static struct ao2_container *iax_transfercallno_pvts;

    
   
891

   
885
/* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
892
/* Flag to use with trunk calls, keeping these calls high up.  It halves our effective use
886
   but keeps the division between trunked and non-trunked better. */
893
   but keeps the division between trunked and non-trunked better. */
887
#define TRUNK_CALL_START	ARRAY_LEN(iaxs) / 2
894
#define TRUNK_CALL_START	ARRAY_LEN(iaxs) / 2
888

    
   
895

   
889
static int maxtrunkcall = TRUNK_CALL_START;
896
static int maxtrunkcall = TRUNK_CALL_START;
890
static int maxnontrunkcall = 1;
897
static int maxnontrunkcall = 1;
891

    
   
898

   
892
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);
899
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);
893
static int expire_registry(const void *data);
900
static int expire_registry(const void *data);
894
static int iax2_answer(struct ast_channel *c);
901
static int iax2_answer(struct ast_channel *c);
895
static int iax2_call(struct ast_channel *c, char *dest, int timeout);
902
static int iax2_call(struct ast_channel *c, char *dest, int timeout);
896
static int iax2_devicestate(void *data);
903
static int iax2_devicestate(void *data);
897
static int iax2_digit_begin(struct ast_channel *c, char digit);
904
static int iax2_digit_begin(struct ast_channel *c, char digit);
898
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
905
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
899
static int iax2_do_register(struct iax2_registry *reg);
906
static int iax2_do_register(struct iax2_registry *reg);
900
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
907
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
901
static int iax2_hangup(struct ast_channel *c);
908
static int iax2_hangup(struct ast_channel *c);
902
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
909
static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
903
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
910
static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
904
static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
911
static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
905
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
912
static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
906
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
913
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
907
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
914
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
908
static int iax2_sendtext(struct ast_channel *c, const char *text);
915
static int iax2_sendtext(struct ast_channel *c, const char *text);
909
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
916
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
910
static int iax2_transfer(struct ast_channel *c, const char *dest);
917
static int iax2_transfer(struct ast_channel *c, const char *dest);
911
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
918
static int iax2_write(struct ast_channel *c, struct ast_frame *f);
912
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
919
static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
913
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
920
static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
914
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
921
static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
915
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
922
static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
916
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
923
static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
917
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
924
static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
918
static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
925
static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
919
static struct ast_frame *iax2_read(struct ast_channel *c);
926
static struct ast_frame *iax2_read(struct ast_channel *c);
920
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
927
static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
921
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
928
static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
922
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
929
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
923
static void prune_peers(void);
930
static void prune_peers(void);
924
static void *iax2_dup_variable_datastore(void *);
931
static void *iax2_dup_variable_datastore(void *);
925
static void iax2_free_variable_datastore(void *);
932
static void iax2_free_variable_datastore(void *);
926

    
   
933

   
927
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
934
static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
928
static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
935
static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
929

    
   
936

   
930
static const struct ast_channel_tech iax2_tech = {
937
static const struct ast_channel_tech iax2_tech = {
931
	.type = "IAX2",
938
	.type = "IAX2",
932
	.description = tdesc,
939
	.description = tdesc,
933
	.capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
940
	.capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
934
	.properties = AST_CHAN_TP_WANTSJITTER,
941
	.properties = AST_CHAN_TP_WANTSJITTER,
935
	.requester = iax2_request,
942
	.requester = iax2_request,
936
	.devicestate = iax2_devicestate,
943
	.devicestate = iax2_devicestate,
937
	.send_digit_begin = iax2_digit_begin,
944
	.send_digit_begin = iax2_digit_begin,
938
	.send_digit_end = iax2_digit_end,
945
	.send_digit_end = iax2_digit_end,
939
	.send_text = iax2_sendtext,
946
	.send_text = iax2_sendtext,
940
	.send_image = iax2_sendimage,
947
	.send_image = iax2_sendimage,
941
	.send_html = iax2_sendhtml,
948
	.send_html = iax2_sendhtml,
942
	.call = iax2_call,
949
	.call = iax2_call,
943
	.hangup = iax2_hangup,
950
	.hangup = iax2_hangup,
944
	.answer = iax2_answer,
951
	.answer = iax2_answer,
945
	.read = iax2_read,
952
	.read = iax2_read,
946
	.write = iax2_write,
953
	.write = iax2_write,
947
	.write_video = iax2_write,
954
	.write_video = iax2_write,
948
	.indicate = iax2_indicate,
955
	.indicate = iax2_indicate,
949
	.setoption = iax2_setoption,
956
	.setoption = iax2_setoption,
950
	.bridge = iax2_bridge,
957
	.bridge = iax2_bridge,
951
	.transfer = iax2_transfer,
958
	.transfer = iax2_transfer,
952
	.fixup = iax2_fixup,
959
	.fixup = iax2_fixup,
953
	.func_channel_read = acf_channel_read,
960
	.func_channel_read = acf_channel_read,
954
	.func_channel_write = acf_channel_write,
961
	.func_channel_write = acf_channel_write,
955
};
962
};
956

    
   
963

   
957
static void mwi_event_cb(const struct ast_event *event, void *userdata)
964
static void mwi_event_cb(const struct ast_event *event, void *userdata)
958
{
965
{
959
	/* The MWI subscriptions exist just so the core knows we care about those
966
	/* The MWI subscriptions exist just so the core knows we care about those
960
	 * mailboxes.  However, we just grab the events out of the cache when it
967
	 * mailboxes.  However, we just grab the events out of the cache when it
961
	 * is time to send MWI, since it is only sent with a REGACK. */
968
	 * is time to send MWI, since it is only sent with a REGACK. */
962
}
969
}
963

    
   
970

   
964
/*! \brief Send manager event at call setup to link between Asterisk channel name
971
/*! \brief Send manager event at call setup to link between Asterisk channel name
965
	and IAX2 call identifiers */
972
	and IAX2 call identifiers */
966
static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
973
static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt) 
967
{
974
{
968
	manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
975
	manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
969
		"Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
976
		"Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
970
		pvt->owner ? pvt->owner->name : "",
977
		pvt->owner ? pvt->owner->name : "",
971
		pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
978
		pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
972
}
979
}
973

    
   
980

   
974

    
   
981

   
975
static struct ast_datastore_info iax2_variable_datastore_info = {
982
static struct ast_datastore_info iax2_variable_datastore_info = {
976
	.type = "IAX2_VARIABLE",
983
	.type = "IAX2_VARIABLE",
977
	.duplicate = iax2_dup_variable_datastore,
984
	.duplicate = iax2_dup_variable_datastore,
978
	.destroy = iax2_free_variable_datastore,
985
	.destroy = iax2_free_variable_datastore,
979
};
986
};
980

    
   
987

   
981
static void *iax2_dup_variable_datastore(void *old)
988
static void *iax2_dup_variable_datastore(void *old)
982
{
989
{
983
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
990
	AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
984
	struct ast_var_t *oldvar, *newvar;
991
	struct ast_var_t *oldvar, *newvar;
985

    
   
992

   
986
	newlist = ast_calloc(sizeof(*newlist), 1);
993
	newlist = ast_calloc(sizeof(*newlist), 1);
987
	if (!newlist) {
994
	if (!newlist) {
988
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
995
		ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
989
		return NULL;
996
		return NULL;
990
	}
997
	}
991

    
   
998

   
992
	AST_LIST_HEAD_INIT(newlist);
999
	AST_LIST_HEAD_INIT(newlist);
993
	AST_LIST_LOCK(oldlist);
1000
	AST_LIST_LOCK(oldlist);
994
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1001
	AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
995
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1002
		newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
996
		if (newvar)
1003
		if (newvar)
997
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1004
			AST_LIST_INSERT_TAIL(newlist, newvar, entries);
998
		else
1005
		else
999
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1006
			ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1000
	}
1007
	}
1001
	AST_LIST_UNLOCK(oldlist);
1008
	AST_LIST_UNLOCK(oldlist);
1002
	return newlist;
1009
	return newlist;
1003
}
1010
}
1004

    
   
1011

   
1005
static void iax2_free_variable_datastore(void *old)
1012
static void iax2_free_variable_datastore(void *old)
1006
{
1013
{
1007
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1014
	AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1008
	struct ast_var_t *oldvar;
1015
	struct ast_var_t *oldvar;
1009

    
   
1016

   
1010
	AST_LIST_LOCK(oldlist);
1017
	AST_LIST_LOCK(oldlist);
1011
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1018
	while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1012
		ast_free(oldvar);
1019
		ast_free(oldvar);
1013
	}
1020
	}
1014
	AST_LIST_UNLOCK(oldlist);
1021
	AST_LIST_UNLOCK(oldlist);
1015
	AST_LIST_HEAD_DESTROY(oldlist);
1022
	AST_LIST_HEAD_DESTROY(oldlist);
1016
	ast_free(oldlist);
1023
	ast_free(oldlist);
1017
}
1024
}
1018

    
   
1025

   
1019

    
   
1026

   
1020
/* WARNING: insert_idle_thread should only ever be called within the
1027
/* WARNING: insert_idle_thread should only ever be called within the
1021
 * context of an iax2_process_thread() thread.
1028
 * context of an iax2_process_thread() thread.
1022
 */
1029
 */
1023
static void insert_idle_thread(struct iax2_thread *thread)
1030
static void insert_idle_thread(struct iax2_thread *thread)
1024
{
1031
{
1025
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1032
	if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1026
		AST_LIST_LOCK(&dynamic_list);
1033
		AST_LIST_LOCK(&dynamic_list);
1027
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1034
		AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1028
		AST_LIST_UNLOCK(&dynamic_list);
1035
		AST_LIST_UNLOCK(&dynamic_list);
1029
	} else {
1036
	} else {
1030
		AST_LIST_LOCK(&idle_list);
1037
		AST_LIST_LOCK(&idle_list);
1031
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1038
		AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1032
		AST_LIST_UNLOCK(&idle_list);
1039
		AST_LIST_UNLOCK(&idle_list);
1033
	}
1040
	}
1034

    
   
1041

   
1035
	return;
1042
	return;
1036
}
1043
}
1037

    
   
1044

   
1038
static struct iax2_thread *find_idle_thread(void)
1045
static struct iax2_thread *find_idle_thread(void)
1039
{
1046
{
1040
	struct iax2_thread *thread = NULL;
1047
	struct iax2_thread *thread = NULL;
1041

    
   
1048

   
1042
	/* Pop the head of the idle list off */
1049
	/* Pop the head of the idle list off */
1043
	AST_LIST_LOCK(&idle_list);
1050
	AST_LIST_LOCK(&idle_list);
1044
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1051
	thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1045
	AST_LIST_UNLOCK(&idle_list);
1052
	AST_LIST_UNLOCK(&idle_list);
1046

    
   
1053

   
1047
	/* If we popped a thread off the idle list, just return it */
1054
	/* If we popped a thread off the idle list, just return it */
1048
	if (thread) {
1055
	if (thread) {
1049
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1056
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1050
		return thread;
1057
		return thread;
1051
	}
1058
	}
1052

    
   
1059

   
1053
	/* Pop the head of the dynamic list off */
1060
	/* Pop the head of the dynamic list off */
1054
	AST_LIST_LOCK(&dynamic_list);
1061
	AST_LIST_LOCK(&dynamic_list);
1055
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1062
	thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1056
	AST_LIST_UNLOCK(&dynamic_list);
1063
	AST_LIST_UNLOCK(&dynamic_list);
1057

    
   
1064

   
1058
	/* If we popped a thread off the dynamic list, just return it */
1065
	/* If we popped a thread off the dynamic list, just return it */
1059
	if (thread) {
1066
	if (thread) {
1060
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1067
		memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1061
		return thread;
1068
		return thread;
1062
	}
1069
	}
1063

    
   
1070

   
1064
	/* If we can't create a new dynamic thread for any reason, return no thread at all */
1071
	/* If we can't create a new dynamic thread for any reason, return no thread at all */
1065
	if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1072
	if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1066
		return NULL;
1073
		return NULL;
1067

    
   
1074

   
1068
	/* Set default values */
1075
	/* Set default values */
1069
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1076
	ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1070
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1077
	thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1071
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1078
	thread->type = IAX_THREAD_TYPE_DYNAMIC;
1072

    
   
1079

   
1073
	/* Initialize lock and condition */
1080
	/* Initialize lock and condition */
1074
	ast_mutex_init(&thread->lock);
1081
	ast_mutex_init(&thread->lock);
1075
	ast_cond_init(&thread->cond, NULL);
1082
	ast_cond_init(&thread->cond, NULL);
1076

    
   
1083

   
1077
	/* Create thread and send it on it's way */
1084
	/* Create thread and send it on it's way */
1078
	if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1085
	if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1079
		ast_cond_destroy(&thread->cond);
1086
		ast_cond_destroy(&thread->cond);
1080
		ast_mutex_destroy(&thread->lock);
1087
		ast_mutex_destroy(&thread->lock);
1081
		ast_free(thread);
1088
		ast_free(thread);
1082
		return NULL;
1089
		return NULL;
1083
	}
1090
	}
1084

    
   
1091

   
1085
	/* this thread is not processing a full frame (since it is idle),
1092
	/* this thread is not processing a full frame (since it is idle),
1086
	   so ensure that the field for the full frame call number is empty */
1093
	   so ensure that the field for the full frame call number is empty */
1087
	memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1094
	memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1088

    
   
1095

   
1089
	/* Wait for the thread to be ready before returning it to the caller */
1096
	/* Wait for the thread to be ready before returning it to the caller */
1090
	while (!thread->ready_for_signal)
1097
	while (!thread->ready_for_signal)
1091
		usleep(1);
1098
		usleep(1);
1092

    
   
1099

   
1093
	return thread;
1100
	return thread;
1094
}
1101
}
1095

    
   
1102

   
1096
#ifdef SCHED_MULTITHREADED
1103
#ifdef SCHED_MULTITHREADED
1097
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1104
static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1098
{
1105
{
1099
	struct iax2_thread *thread = NULL;
1106
	struct iax2_thread *thread = NULL;
1100
	static time_t lasterror;
1107
	static time_t lasterror;
1101
	static time_t t;
1108
	static time_t t;
1102

    
   
1109

   
1103
	thread = find_idle_thread();
1110
	thread = find_idle_thread();
1104

    
   
1111

   
1105
	if (thread != NULL) {
1112
	if (thread != NULL) {
1106
		thread->schedfunc = func;
1113
		thread->schedfunc = func;
1107
		thread->scheddata = data;
1114
		thread->scheddata = data;
1108
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1115
		thread->iostate = IAX_IOSTATE_SCHEDREADY;
1109
#ifdef DEBUG_SCHED_MULTITHREAD
1116
#ifdef DEBUG_SCHED_MULTITHREAD
1110
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1117
		ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1111
#endif
1118
#endif
1112
		signal_condition(&thread->lock, &thread->cond);
1119
		signal_condition(&thread->lock, &thread->cond);
1113
		return 0;
1120
		return 0;
1114
	}
1121
	}
1115
	time(&t);
1122
	time(&t);
1116
	if (t != lasterror) 
1123
	if (t != lasterror) 
1117
		ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1124
		ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1118
	lasterror = t;
1125
	lasterror = t;
1119

    
   
1126

   
1120
	return -1;
1127
	return -1;
1121
}
1128
}
1122
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1129
#define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1123
#endif
1130
#endif
1124

    
   
1131

   
1125
static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1132
static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1126
{
1133
{
1127
	AST_SCHED_REPLACE(id, con, when, callback, data);
1134
	AST_SCHED_REPLACE(id, con, when, callback, data);
1128
	signal_condition(&sched_lock, &sched_cond);
1135
	signal_condition(&sched_lock, &sched_cond);
1129

    
   
1136

   
1130
	return id;
1137
	return id;
1131
}
1138
}
1132

    
   
1139

   
1133
static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1140
static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1134
{
1141
{
1135
	int res;
1142
	int res;
1136

    
   
1143

   
1137
	res = ast_sched_add(con, when, callback, data);
1144
	res = ast_sched_add(con, when, callback, data);
1138
	signal_condition(&sched_lock, &sched_cond);
1145
	signal_condition(&sched_lock, &sched_cond);
1139

    
   
1146

   
1140
	return res;
1147
	return res;
1141
}
1148
}
1142

    
   
1149

   
1143
static int send_ping(const void *data);
1150
static int send_ping(const void *data);
1144

    
   
1151

   
1145
static void __send_ping(const void *data)
1152
static void __send_ping(const void *data)
1146
{
1153
{
1147
	int callno = (long) data;
1154
	int callno = (long) data;
1148

    
   
1155

   
1149
	ast_mutex_lock(&iaxsl[callno]);
1156
	ast_mutex_lock(&iaxsl[callno]);
1150

    
   
1157

   
1151
	if (iaxs[callno]) {
1158
	if (iaxs[callno]) {
1152
		if (iaxs[callno]->peercallno) {
1159
		if (iaxs[callno]->peercallno) {
1153
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1160
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1154
			iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1161
			iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1155
		} else {
1162
		} else {
1156
			/* I am the schedule, so I'm allowed to do this */
1163
			/* I am the schedule, so I'm allowed to do this */
1157
			iaxs[callno]->pingid = -1;
1164
			iaxs[callno]->pingid = -1;
1158
		}
1165
		}
1159
	} else if (option_debug > 0) {
1166
	} else if (option_debug > 0) {
1160
		ast_log(LOG_DEBUG, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno);
1167
		ast_log(LOG_DEBUG, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno);
1161
	}
1168
	}
1162

    
   
1169

   
1163
	ast_mutex_unlock(&iaxsl[callno]);
1170
	ast_mutex_unlock(&iaxsl[callno]);
1164
}
1171
}
1165

    
   
1172

   
1166
static int send_ping(const void *data)
1173
static int send_ping(const void *data)
1167
{
1174
{
1168
#ifdef SCHED_MULTITHREADED
1175
#ifdef SCHED_MULTITHREADED
1169
	if (schedule_action(__send_ping, data))
1176
	if (schedule_action(__send_ping, data))
1170
#endif		
1177
#endif		
1171
		__send_ping(data);
1178
		__send_ping(data);
1172

    
   
1179

   
1173
	return 0;
1180
	return 0;
1174
}
1181
}
1175

    
   
1182

   
1176
static int get_encrypt_methods(const char *s)
1183
static int get_encrypt_methods(const char *s)
1177
{
1184
{
1178
	int e;
1185
	int e;
1179
	if (!strcasecmp(s, "aes128"))
1186
	if (!strcasecmp(s, "aes128"))
1180
		e = IAX_ENCRYPT_AES128;
1187
		e = IAX_ENCRYPT_AES128;
1181
	else if (ast_true(s))
1188
	else if (ast_true(s))
1182
		e = IAX_ENCRYPT_AES128;
1189
		e = IAX_ENCRYPT_AES128;
1183
	else
1190
	else
1184
		e = 0;
1191
		e = 0;
1185
	return e;
1192
	return e;
1186
}
1193
}
1187

    
   
1194

   
1188
static int send_lagrq(const void *data);
1195
static int send_lagrq(const void *data);
1189

    
   
1196

   
1190
static void __send_lagrq(const void *data)
1197
static void __send_lagrq(const void *data)
1191
{
1198
{
1192
	int callno = (long) data;
1199
	int callno = (long) data;
1193

    
   
1200

   
1194
	ast_mutex_lock(&iaxsl[callno]);
1201
	ast_mutex_lock(&iaxsl[callno]);
1195

    
   
1202

   
1196
	if (iaxs[callno]) {
1203
	if (iaxs[callno]) {
1197
		if (iaxs[callno]->peercallno) {
1204
		if (iaxs[callno]->peercallno) {
1198
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1205
			send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1199
			iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1206
			iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1200
		} else {
1207
		} else {
1201
			/* I am the schedule, so I'm allowed to do this */
1208
			/* I am the schedule, so I'm allowed to do this */
1202
			iaxs[callno]->lagid = -1;
1209
			iaxs[callno]->lagid = -1;
1203
		}
1210
		}
1204
	} else {
1211
	} else {
1205
		ast_log(LOG_WARNING, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno);
1212
		ast_log(LOG_WARNING, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno);
1206
	}
1213
	}
1207

    
   
1214

   
1208
	ast_mutex_unlock(&iaxsl[callno]);
1215
	ast_mutex_unlock(&iaxsl[callno]);
1209
}
1216
}
1210

    
   
1217

   
1211
static int send_lagrq(const void *data)
1218
static int send_lagrq(const void *data)
1212
{
1219
{
1213
#ifdef SCHED_MULTITHREADED
1220
#ifdef SCHED_MULTITHREADED
1214
	if (schedule_action(__send_lagrq, data))
1221
	if (schedule_action(__send_lagrq, data))
1215
#endif		
1222
#endif		
1216
		__send_lagrq(data);
1223
		__send_lagrq(data);
1217
	
1224
	
1218
	return 0;
1225
	return 0;
1219
}
1226
}
1220

    
   
1227

   
1221
static unsigned char compress_subclass(int subclass)
1228
static unsigned char compress_subclass(int subclass)
1222
{
1229
{
1223
	int x;
1230
	int x;
1224
	int power=-1;
1231
	int power=-1;
1225
	/* If it's 128 or smaller, just return it */
1232
	/* If it's 128 or smaller, just return it */
1226
	if (subclass < IAX_FLAG_SC_LOG)
1233
	if (subclass < IAX_FLAG_SC_LOG)
1227
		return subclass;
1234
		return subclass;
1228
	/* Otherwise find its power */
1235
	/* Otherwise find its power */
1229
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1236
	for (x = 0; x < IAX_MAX_SHIFT; x++) {
1230
		if (subclass & (1 << x)) {
1237
		if (subclass & (1 << x)) {
1231
			if (power > -1) {
1238
			if (power > -1) {
1232
				ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1239
				ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1233
				return 0;
1240
				return 0;
1234
			} else
1241
			} else
1235
				power = x;
1242
				power = x;
1236
		}
1243
		}
1237
	}
1244
	}
1238
	return power | IAX_FLAG_SC_LOG;
1245
	return power | IAX_FLAG_SC_LOG;
1239
}
1246
}
1240

    
   
1247

   
1241
static int uncompress_subclass(unsigned char csub)
1248
static int uncompress_subclass(unsigned char csub)
1242
{
1249
{
1243
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1250
	/* If the SC_LOG flag is set, return 2^csub otherwise csub */
1244
	if (csub & IAX_FLAG_SC_LOG) {
1251
	if (csub & IAX_FLAG_SC_LOG) {
1245
		/* special case for 'compressed' -1 */
1252
		/* special case for 'compressed' -1 */
1246
		if (csub == 0xff)
1253
		if (csub == 0xff)
1247
			return -1;
1254
			return -1;
1248
		else
1255
		else
1249
			return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1256
			return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1250
	}
1257
	}
1251
	else
1258
	else
1252
		return csub;
1259
		return csub;
1253
}
1260
}
1254

    
   
1261

   
1255
/*!
1262
/*!
1256
 * \note The only member of the peer passed here guaranteed to be set is the name field
1263
 * \note The only member of the peer passed here guaranteed to be set is the name field
1257
 */
1264
 */
1258
static int peer_hash_cb(const void *obj, const int flags)
1265
static int peer_hash_cb(const void *obj, const int flags)
1259
{
1266
{
1260
	const struct iax2_peer *peer = obj;
1267
	const struct iax2_peer *peer = obj;
1261

    
   
1268

   
1262
	return ast_str_hash(peer->name);
1269
	return ast_str_hash(peer->name);
1263
}
1270
}
1264

    
   
1271

   
1265
/*!
1272
/*!
1266
 * \note The only member of the peer passed here guaranteed to be set is the name field
1273
 * \note The only member of the peer passed here guaranteed to be set is the name field
1267
 */
1274
 */
1268
static int peer_cmp_cb(void *obj, void *arg, int flags)
1275
static int peer_cmp_cb(void *obj, void *arg, int flags)
1269
{
1276
{
1270
	struct iax2_peer *peer = obj, *peer2 = arg;
1277
	struct iax2_peer *peer = obj, *peer2 = arg;
1271

    
   
1278

   
1272
	return !strcmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1279
	return !strcmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1273
}
1280
}
1274

    
   
1281

   
1275
/*!
1282
/*!
1276
 * \note The only member of the user passed here guaranteed to be set is the name field
1283
 * \note The only member of the user passed here guaranteed to be set is the name field
1277
 */
1284
 */
1278
static int user_hash_cb(const void *obj, const int flags)
1285
static int user_hash_cb(const void *obj, const int flags)
1279
{
1286
{
1280
	const struct iax2_user *user = obj;
1287
	const struct iax2_user *user = obj;
1281

    
   
1288

   
1282
	return ast_str_hash(user->name);
1289
	return ast_str_hash(user->name);
1283
}
1290
}
1284

    
   
1291

   
1285
/*!
1292
/*!
1286
 * \note The only member of the user passed here guaranteed to be set is the name field
1293
 * \note The only member of the user passed here guaranteed to be set is the name field
1287
 */
1294
 */
1288
static int user_cmp_cb(void *obj, void *arg, int flags)
1295
static int user_cmp_cb(void *obj, void *arg, int flags)
1289
{
1296
{
1290
	struct iax2_user *user = obj, *user2 = arg;
1297
	struct iax2_user *user = obj, *user2 = arg;
1291

    
   
1298

   
1292
	return !strcmp(user->name, user2->name) ? CMP_MATCH : 0;
1299
	return !strcmp(user->name, user2->name) ? CMP_MATCH : 0;
1293
}
1300
}
1294

    
   
1301

   
1295
/*!
1302
/*!
1296
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1303
 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1297
 *       so do not call it with a pvt lock held.
1304
 *       so do not call it with a pvt lock held.
1298
 */
1305
 */
1299
static struct iax2_peer *find_peer(const char *name, int realtime) 
1306
static struct iax2_peer *find_peer(const char *name, int realtime) 
1300
{
1307
{
1301
	struct iax2_peer *peer = NULL;
1308
	struct iax2_peer *peer = NULL;
1302
	struct iax2_peer tmp_peer = {
1309
	struct iax2_peer tmp_peer = {
1303
		.name = name,
1310
		.name = name,
1304
	};
1311
	};
1305

    
   
1312

   
1306
	peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1313
	peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1307

    
   
1314

   
1308
	/* Now go for realtime if applicable */
1315
	/* Now go for realtime if applicable */
1309
	if(!peer && realtime)
1316
	if(!peer && realtime)
1310
		peer = realtime_peer(name, NULL);
1317
		peer = realtime_peer(name, NULL);
1311

    
   
1318

   
1312
	return peer;
1319
	return peer;
1313
}
1320
}
1314

    
   
1321

   
1315
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1322
static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1316
{
1323
{
1317
	ao2_ref(peer, +1);
1324
	ao2_ref(peer, +1);
1318
	return peer;
1325
	return peer;
1319
}
1326
}
1320

    
   
1327

   
1321
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1328
static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1322
{
1329
{
1323
	ao2_ref(peer, -1);
1330
	ao2_ref(peer, -1);
1324
	return NULL;
1331
	return NULL;
1325
}
1332
}
1326

    
   
1333

   
1327
static inline struct iax2_user *user_ref(struct iax2_user *user)
1334
static inline struct iax2_user *user_ref(struct iax2_user *user)
1328
{
1335
{
1329
	ao2_ref(user, +1);
1336
	ao2_ref(user, +1);
1330
	return user;
1337
	return user;
1331
}
1338
}
1332

    
   
1339

   
1333
static inline struct iax2_user *user_unref(struct iax2_user *user)
1340
static inline struct iax2_user *user_unref(struct iax2_user *user)
1334
{
1341
{
1335
	ao2_ref(user, -1);
1342
	ao2_ref(user, -1);
1336
	return NULL;
1343
	return NULL;
1337
}
1344
}
1338

    
   
1345

   
1339
static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1346
static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1340
{
1347
{
1341
	struct iax2_peer *peer = NULL;
1348
	struct iax2_peer *peer = NULL;
1342
	int res = 0;
1349
	int res = 0;
1343
	struct ao2_iterator i;
1350
	struct ao2_iterator i;
1344

    
   
1351

   
1345
	i = ao2_iterator_init(peers, 0);
1352
	i = ao2_iterator_init(peers, 0);
1346
	while ((peer = ao2_iterator_next(&i))) {
1353
	while ((peer = ao2_iterator_next(&i))) {
1347
		if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1354
		if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1348
		    (peer->addr.sin_port == sin.sin_port)) {
1355
		    (peer->addr.sin_port == sin.sin_port)) {
1349
			ast_copy_string(host, peer->name, len);
1356
			ast_copy_string(host, peer->name, len);
1350
			peer_unref(peer);
1357
			peer_unref(peer);
1351
			res = 1;
1358
			res = 1;
1352
			break;
1359
			break;
1353
		}
1360
		}
1354
		peer_unref(peer);
1361
		peer_unref(peer);
1355
	}
1362
	}
1356

    
   
1363

   
1357
	if (!peer) {
1364
	if (!peer) {
1358
		peer = realtime_peer(NULL, &sin);
1365
		peer = realtime_peer(NULL, &sin);
1359
		if (peer) {
1366
		if (peer) {
1360
			ast_copy_string(host, peer->name, len);
1367
			ast_copy_string(host, peer->name, len);
1361
			peer_unref(peer);
1368
			peer_unref(peer);
1362
			res = 1;
1369
			res = 1;
1363
		}
1370
		}
1364
	}
1371
	}
1365

    
   
1372

   
1366
	return res;
1373
	return res;
1367
}
1374
}
1368

    
   
1375

   
1369
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1376
static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1370
{
1377
{
1371
	/* Decrement AUTHREQ count if needed */
1378
	/* Decrement AUTHREQ count if needed */
1372
	if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1379
	if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1373
		struct iax2_user *user;
1380
		struct iax2_user *user;
1374
		struct iax2_user tmp_user = {
1381
		struct iax2_user tmp_user = {
1375
			.name = pvt->username,
1382
			.name = pvt->username,
1376
		};
1383
		};
1377

    
   
1384

   
1378
		user = ao2_find(users, &tmp_user, OBJ_POINTER);
1385
		user = ao2_find(users, &tmp_user, OBJ_POINTER);
1379
		if (user) {
1386
		if (user) {
1380
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
1387
			ast_atomic_fetchadd_int(&user->curauthreq, -1);
1381
			user_unref(user);	
1388
			user_unref(user);	
1382
		}
1389
		}
1383

    
   
1390

   
1384
		ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1391
		ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1385
	}
1392
	}
1386
	/* No more pings or lagrq's */
1393
	/* No more pings or lagrq's */
1387
	AST_SCHED_DEL(sched, pvt->pingid);
1394
	AST_SCHED_DEL(sched, pvt->pingid);
1388
	AST_SCHED_DEL(sched, pvt->lagid);
1395
	AST_SCHED_DEL(sched, pvt->lagid);
1389
	AST_SCHED_DEL(sched, pvt->autoid);
1396
	AST_SCHED_DEL(sched, pvt->autoid);
1390
	AST_SCHED_DEL(sched, pvt->authid);
1397
	AST_SCHED_DEL(sched, pvt->authid);
1391
	AST_SCHED_DEL(sched, pvt->initid);
1398
	AST_SCHED_DEL(sched, pvt->initid);
1392
	AST_SCHED_DEL(sched, pvt->jbid);
1399
	AST_SCHED_DEL(sched, pvt->jbid);
1393
}
1400
}
1394

    
   
1401

   
1395
static void iax2_frame_free(struct iax_frame *fr)
1402
static void iax2_frame_free(struct iax_frame *fr)
1396
{
1403
{
1397
	AST_SCHED_DEL(sched, fr->retrans);
1404
	AST_SCHED_DEL(sched, fr->retrans);
1398
	iax_frame_free(fr);
1405
	iax_frame_free(fr);
1399
}
1406
}
1400

    
   
1407

   
1401
static int scheduled_destroy(const void *vid)
1408
static int scheduled_destroy(const void *vid)
1402
{
1409
{
1403
	short callno = PTR_TO_CALLNO(vid);
1410
	short callno = PTR_TO_CALLNO(vid);
1404
	ast_mutex_lock(&iaxsl[callno]);
1411
	ast_mutex_lock(&iaxsl[callno]);
1405
	if (iaxs[callno]) {
1412
	if (iaxs[callno]) {
1406
		if (option_debug) {
1413
		if (option_debug) {
1407
			ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1414
			ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
1408
		}
1415
		}
1409
		iax2_destroy(callno);
1416
		iax2_destroy(callno);
1410
	}
1417
	}
1411
	ast_mutex_unlock(&iaxsl[callno]);
1418
	ast_mutex_unlock(&iaxsl[callno]);
1412
	return 0;
1419
	return 0;
1413
}
1420
}
1414

    
   
1421

   
1415
static void pvt_destructor(void *obj)
1422
static void pvt_destructor(void *obj)
1416
{
1423
{
1417
	struct chan_iax2_pvt *pvt = obj;
1424
	struct chan_iax2_pvt *pvt = obj;
1418
	struct iax_frame *cur = NULL;
1425
	struct iax_frame *cur = NULL;
1419

    
   
1426

   
1420
	iax2_destroy_helper(pvt);
1427
	iax2_destroy_helper(pvt);
1421

    
   
1428

   
1422
	/* Already gone */
1429
	/* Already gone */
1423
	ast_set_flag(pvt, IAX_ALREADYGONE);	
1430
	ast_set_flag(pvt, IAX_ALREADYGONE);	
1424

    
   
1431

   
1425
	AST_LIST_LOCK(&frame_queue);
1432
	AST_LIST_LOCK(&frame_queue);
1426
	AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1433
	AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1427
		/* Cancel any pending transmissions */
1434
		/* Cancel any pending transmissions */
1428
		if (cur->callno == pvt->callno) { 
1435
		if (cur->callno == pvt->callno) { 
1429
			cur->retries = -1;
1436
			cur->retries = -1;
1430
		}
1437
		}
1431
	}
1438
	}
1432
	AST_LIST_UNLOCK(&frame_queue);
1439
	AST_LIST_UNLOCK(&frame_queue);
1433

    
   
1440

   
1434
	if (pvt->reg) {
1441
	if (pvt->reg) {
1435
		pvt->reg->callno = 0;
1442
		pvt->reg->callno = 0;
1436
	}
1443
	}
1437

    
   
1444

   
1438
	if (!pvt->owner) {
1445
	if (!pvt->owner) {
1439
		jb_frame frame;
1446
		jb_frame frame;
1440
		if (pvt->vars) {
1447
		if (pvt->vars) {
1441
		    ast_variables_destroy(pvt->vars);
1448
		    ast_variables_destroy(pvt->vars);
1442
		    pvt->vars = NULL;
1449
		    pvt->vars = NULL;
1443
		}
1450
		}
1444

    
   
1451

   
1445
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
1452
		while (jb_getall(pvt->jb, &frame) == JB_OK) {
1446
			iax2_frame_free(frame.data);
1453
			iax2_frame_free(frame.data);
1447
		}
1454
		}
1448

    
   
1455

   
1449
		jb_destroy(pvt->jb);
1456
		jb_destroy(pvt->jb);
1450
		ast_string_field_free_memory(pvt);
1457
		ast_string_field_free_memory(pvt);
1451
	}
1458
	}
1452
}
1459
}
1453

    
   
1460

   
1454
static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1461
static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1455
{
1462
{
1456
	struct chan_iax2_pvt *tmp;
1463
	struct chan_iax2_pvt *tmp;
1457
	jb_conf jbconf;
1464
	jb_conf jbconf;
1458

    
   
1465

   
1459
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1466
	if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1460
		return NULL;
1467
		return NULL;
1461
	}
1468
	}
1462

    
   
1469

   
1463
	if (ast_string_field_init(tmp, 32)) {
1470
	if (ast_string_field_init(tmp, 32)) {
1464
		ao2_ref(tmp, -1);
1471
		ao2_ref(tmp, -1);
1465
		tmp = NULL;
1472
		tmp = NULL;
1466
		return NULL;
1473
		return NULL;
1467
	}
1474
	}
1468
		
1475
		
1469
	tmp->prefs = prefs;
1476
	tmp->prefs = prefs;
1470
	tmp->pingid = -1;
1477
	tmp->pingid = -1;
1471
	tmp->lagid = -1;
1478
	tmp->lagid = -1;
1472
	tmp->autoid = -1;
1479
	tmp->autoid = -1;
1473
	tmp->authid = -1;
1480
	tmp->authid = -1;
1474
	tmp->initid = -1;
1481
	tmp->initid = -1;
1475

    
   
1482

   
1476
	ast_string_field_set(tmp,exten, "s");
1483
	ast_string_field_set(tmp,exten, "s");
1477
	ast_string_field_set(tmp,host, host);
1484
	ast_string_field_set(tmp,host, host);
1478

    
   
1485

   
1479
	tmp->jb = jb_new();
1486
	tmp->jb = jb_new();
1480
	tmp->jbid = -1;
1487
	tmp->jbid = -1;
1481
	jbconf.max_jitterbuf = maxjitterbuffer;
1488
	jbconf.max_jitterbuf = maxjitterbuffer;
1482
	jbconf.resync_threshold = resyncthreshold;
1489
	jbconf.resync_threshold = resyncthreshold;
1483
	jbconf.max_contig_interp = maxjitterinterps;
1490
	jbconf.max_contig_interp = maxjitterinterps;
1484
	jbconf.target_extra = jittertargetextra;
1491
	jbconf.target_extra = jittertargetextra;
1485
	jb_setconf(tmp->jb,&jbconf);
1492
	jb_setconf(tmp->jb,&jbconf);
1486

    
   
1493

   
1487
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1494
	AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1488

    
   
1495

   
1489
	return tmp;
1496
	return tmp;
1490
}
1497
}
1491

    
   
1498

   
1492
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1499
static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1493
{
1500
{
1494
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1501
	struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1495
	if (new) {
1502
	if (new) {
1496
		size_t afdatalen = new->afdatalen;
1503
		size_t afdatalen = new->afdatalen;
1497
		memcpy(new, fr, sizeof(*new));
1504
		memcpy(new, fr, sizeof(*new));
1498
		iax_frame_wrap(new, &fr->af);
1505
		iax_frame_wrap(new, &fr->af);
1499
		new->afdatalen = afdatalen;
1506
		new->afdatalen = afdatalen;
1500
		new->data = NULL;
1507
		new->data = NULL;
1501
		new->datalen = 0;
1508
		new->datalen = 0;
1502
		new->direction = DIRECTION_INGRESS;
1509
		new->direction = DIRECTION_INGRESS;
1503
		new->retrans = -1;
1510
		new->retrans = -1;
1504
	}
1511
	}
1505
	return new;
1512
	return new;
1506
}
1513
}
1507

    
   
1514

   
1508
#define NEW_PREVENT 	0
1515
#define NEW_PREVENT 	0
1509
#define NEW_ALLOW 	1
1516
#define NEW_ALLOW 	1
1510
#define NEW_FORCE 	2
1517
#define NEW_FORCE 	2
1511

    
   
1518

   
1512
static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1519
static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1513
{
1520
{
1514
	if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1521
	if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1515
		(cur->addr.sin_port == sin->sin_port)) {
1522
		(cur->addr.sin_port == sin->sin_port)) {
1516
		/* This is the main host */
1523
		/* This is the main host */
1517
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1524
		if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1518
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
1525
			 (check_dcallno ? dcallno == cur->callno : 1) ) {
1519
			/* That's us.  Be sure we keep track of the peer call number */
1526
			/* That's us.  Be sure we keep track of the peer call number */
1520
			return 1;
1527
			return 1;
1521
		}
1528
		}
1522
	}
1529
	}
1523
	if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1530
	if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1524
	    (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1531
	    (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1525
		/* We're transferring */
1532
		/* We're transferring */
1526
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1533
		if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1527
			return 1;
1534
			return 1;
1528
	}
1535
	}
1529
	return 0;
1536
	return 0;
1530
}
1537
}
1531

    
   
1538

   
1532
static void update_max_trunk(void)
1539
static void update_max_trunk(void)
1533
{
1540
{
1534
	int max = TRUNK_CALL_START;
1541
	int max = TRUNK_CALL_START;
1535
	int x;
1542
	int x;
1536

    
   
1543

   
1537
	/* XXX Prolly don't need locks here XXX */
1544
	/* XXX Prolly don't need locks here XXX */
1538
	for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1545
	for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1539
		if (iaxs[x]) {
1546
		if (iaxs[x]) {
1540
			max = x + 1;
1547
			max = x + 1;
1541
		}
1548
		}
1542
	}
1549
	}
1543

    
   
1550

   
1544
	maxtrunkcall = max;
1551
	maxtrunkcall = max;
1545
	if (iaxdebug)
1552
	if (iaxdebug)
1546
		ast_debug(1, "New max trunk callno is %d\n", max);
1553
		ast_debug(1, "New max trunk callno is %d\n", max);
1547
}
1554
}
1548

    
   
1555

   
1549
static void update_max_nontrunk(void)
1556
static void update_max_nontrunk(void)
1550
{
1557
{
1551
	int max = 1;
1558
	int max = 1;
1552
	int x;
1559
	int x;
1553
	/* XXX Prolly don't need locks here XXX */
1560
	/* XXX Prolly don't need locks here XXX */
1554
	for (x=1;x<TRUNK_CALL_START - 1; x++) {
1561
	for (x=1;x<TRUNK_CALL_START - 1; x++) {
1555
		if (iaxs[x])
1562
		if (iaxs[x])
1556
			max = x + 1;
1563
			max = x + 1;
1557
	}
1564
	}
1558
	maxnontrunkcall = max;
1565
	maxnontrunkcall = max;
1559
	if (iaxdebug)
1566
	if (iaxdebug)
1560
		ast_debug(1, "New max nontrunk callno is %d\n", max);
1567
		ast_debug(1, "New max nontrunk callno is %d\n", max);
1561
}
1568
}
1562

    
   
1569

   
1563
static int make_trunk(unsigned short callno, int locked)
1570
static int make_trunk(unsigned short callno, int locked)
1564
{
1571
{
1565
	int x;
1572
	int x;
1566
	int res= 0;
1573
	int res= 0;
1567
	struct timeval now = ast_tvnow();
1574
	struct timeval now = ast_tvnow();
1568
	if (iaxs[callno]->oseqno) {
1575
	if (iaxs[callno]->oseqno) {
1569
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1576
		ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1570
		return -1;
1577
		return -1;
1571
	}
1578
	}
1572
	if (callno & TRUNK_CALL_START) {
1579
	if (callno & TRUNK_CALL_START) {
1573
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1580
		ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1574
		return -1;
1581
		return -1;
1575
	}
1582
	}
1576
	for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1583
	for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1577
		ast_mutex_lock(&iaxsl[x]);
1584
		ast_mutex_lock(&iaxsl[x]);
1578
		if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1585
		if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1579
			/*!
1586
			/*!
1580
			 * \note We delete these before switching the slot, because if
1587
			 * \note We delete these before switching the slot, because if
1581
			 * they fire in the meantime, they will generate a warning.
1588
			 * they fire in the meantime, they will generate a warning.
1582
			 */
1589
			 */
1583
			AST_SCHED_DEL(sched, iaxs[callno]->pingid);
1590
			AST_SCHED_DEL(sched, iaxs[callno]->pingid);
1584
			AST_SCHED_DEL(sched, iaxs[callno]->lagid);
1591
			AST_SCHED_DEL(sched, iaxs[callno]->lagid);
1585
			iaxs[x] = iaxs[callno];
1592
			iaxs[x] = iaxs[callno];
1586
			iaxs[x]->callno = x;
1593
			iaxs[x]->callno = x;
1587
			iaxs[callno] = NULL;
1594
			iaxs[callno] = NULL;
1588
			/* Update the two timers that should have been started */
1595
			/* Update the two timers that should have been started */
1589
			iaxs[x]->pingid = iax2_sched_add(sched, 
1596
			iaxs[x]->pingid = iax2_sched_add(sched, 
1590
				ping_time * 1000, send_ping, (void *)(long)x);
1597
				ping_time * 1000, send_ping, (void *)(long)x);
1591
			iaxs[x]->lagid = iax2_sched_add(sched, 
1598
			iaxs[x]->lagid = iax2_sched_add(sched, 
1592
				lagrq_time * 1000, send_lagrq, (void *)(long)x);
1599
				lagrq_time * 1000, send_lagrq, (void *)(long)x);
1593
			if (locked)
1600
			if (locked)
1594
				ast_mutex_unlock(&iaxsl[callno]);
1601
				ast_mutex_unlock(&iaxsl[callno]);
1595
			res = x;
1602
			res = x;
1596
			if (!locked)
1603
			if (!locked)
1597
				ast_mutex_unlock(&iaxsl[x]);
1604
				ast_mutex_unlock(&iaxsl[x]);
1598
			break;
1605
			break;
1599
		}
1606
		}
1600
		ast_mutex_unlock(&iaxsl[x]);
1607
		ast_mutex_unlock(&iaxsl[x]);
1601
	}
1608
	}
1602
	if (x >= ARRAY_LEN(iaxs) - 1) {
1609
	if (x >= ARRAY_LEN(iaxs) - 1) {
1603
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1610
		ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1604
		return -1;
1611
		return -1;
1605
	}
1612
	}
1606
	ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1613
	ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1607
	/* We move this call from a non-trunked to a trunked call */
1614
	/* We move this call from a non-trunked to a trunked call */
1608
	update_max_trunk();
1615
	update_max_trunk();
1609
	update_max_nontrunk();
1616
	update_max_nontrunk();
1610
	return res;
1617
	return res;
1611
}
1618
}
1612

    
   
1619

   

    
   
1620
static void store_by_transfercallno(struct chan_iax2_pvt *pvt)

    
   
1621
{

    
   
1622
	if (!pvt->transfercallno) {

    
   
1623
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");

    
   
1624
		return;

    
   
1625
	}

    
   
1626

   

    
   
1627
	ao2_link(iax_transfercallno_pvts, pvt);

    
   
1628
}

    
   
1629

   

    
   
1630
static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)

    
   
1631
{

    
   
1632
	if (!pvt->transfercallno) {

    
   
1633
		ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");

    
   
1634
		return;

    
   
1635
	}

    
   
1636

   

    
   
1637
	ao2_unlink(iax_transfercallno_pvts, pvt);

    
   
1638
}
1613
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1639
static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1614
{
1640
{
1615
	if (!pvt->peercallno) {
1641
	if (!pvt->peercallno) {
1616
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1642
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1617
		return;
1643
		return;
1618
	}
1644
	}
1619

    
   
1645

   
1620
	ao2_link(iax_peercallno_pvts, pvt);
1646
	ao2_link(iax_peercallno_pvts, pvt);
1621
}
1647
}
1622

    
   
1648

   
1623
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1649
static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1624
{
1650
{
1625
	if (!pvt->peercallno) {
1651
	if (!pvt->peercallno) {
1626
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1652
		ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1627
		return;
1653
		return;
1628
	}
1654
	}
1629

    
   
1655

   
1630
	ao2_unlink(iax_peercallno_pvts, pvt);
1656
	ao2_unlink(iax_peercallno_pvts, pvt);
1631
}
1657
}
1632

    
   
1658

   
1633
/*
1659
/*
1634
 * \note Calling this function while holding another pvt lock can cause a deadlock.
1660
 * \note Calling this function while holding another pvt lock can cause a deadlock.
1635
 */
1661
 */
1636
static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1662
static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1637
{
1663
{
1638
	int res = 0;
1664
	int res = 0;
1639
	int x;
1665
	int x;
1640
	struct timeval now;
1666
	struct timeval now;
1641
	char host[80];
1667
	char host[80];
1642

    
   
1668

   
1643
	if (new <= NEW_ALLOW) {
1669
	if (new <= NEW_ALLOW) {
1644
		if (callno) {
1670
		if (callno) {
1645
			struct chan_iax2_pvt *pvt;
1671
			struct chan_iax2_pvt *pvt;
1646
			struct chan_iax2_pvt tmp_pvt = {
1672
			struct chan_iax2_pvt tmp_pvt = {
1647
				.callno = dcallno,
1673
				.callno = dcallno,
1648
				.peercallno = callno,
1674
				.peercallno = callno,

    
   
1675
				.transfercallno = callno,
1649
				/* hack!! */
1676
				/* hack!! */
1650
				.frames_received = check_dcallno,
1677
				.frames_received = check_dcallno,
1651
			};
1678
			};
1652

    
   
1679

   
1653
			memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1680
			memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1654

    
   
1681
			/* this works for finding normal call numbers not involving transfering */ 
1655
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1682
			if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1656
				if (return_locked) {
1683
				if (return_locked) {
1657
					ast_mutex_lock(&iaxsl[pvt->callno]);
1684
					ast_mutex_lock(&iaxsl[pvt->callno]);
1658
				}
1685
				}
1659
				res = pvt->callno;
1686
				res = pvt->callno;
1660
				ao2_ref(pvt, -1);
1687
				ao2_ref(pvt, -1);
1661
				pvt = NULL;
1688
				pvt = NULL;
1662
				return res;
1689
				return res;
1663
			}
1690
			}

    
   
1691
			/* this searches for transfer call numbers that might not get caught otherwise */

    
   
1692
			memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));

    
   
1693
			memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.addr));

    
   
1694
			if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {

    
   
1695
				if (return_locked) {

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

    
   
1697
				}

    
   
1698
				res = pvt->callno;

    
   
1699
				ao2_ref(pvt, -1);

    
   
1700
				pvt = NULL;

    
   
1701
				return res;

    
   
1702
			}
1664
		}
1703
		}
1665

    
   

   
1666
		/* This will occur on the first response to a message that we initiated,
1704
			/* This will occur on the first response to a message that we initiated,
1667
		 * such as a PING. */
1705
		 * such as a PING. */
1668
		if (dcallno) {
1706
		if (dcallno) {
1669
			ast_mutex_lock(&iaxsl[dcallno]);
1707
			ast_mutex_lock(&iaxsl[dcallno]);
1670
		}
1708
		}
1671
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1709
		if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1672
			iaxs[dcallno]->peercallno = callno;
1710
			iaxs[dcallno]->peercallno = callno;
1673
			res = dcallno;
1711
			res = dcallno;
1674
			store_by_peercallno(iaxs[dcallno]);
1712
			store_by_peercallno(iaxs[dcallno]);
1675
			if (!res || !return_locked) {
1713
			if (!res || !return_locked) {
1676
				ast_mutex_unlock(&iaxsl[dcallno]);
1714
				ast_mutex_unlock(&iaxsl[dcallno]);
1677
			}
1715
			}
1678
			return res;
1716
			return res;
1679
		}
1717
		}
1680
		if (dcallno) {
1718
		if (dcallno) {
1681
			ast_mutex_unlock(&iaxsl[dcallno]);
1719
			ast_mutex_unlock(&iaxsl[dcallno]);
1682
		}
1720
		}
1683

    
   

   
1684
#ifdef IAX_OLD_FIND
1721
#ifdef IAX_OLD_FIND
1685
		/* If we get here, we SHOULD NOT find a call structure for this
1722
		/* If we get here, we SHOULD NOT find a call structure for this
1686
		   callno; if we do, it means that there is a call structure that
1723
		   callno; if we do, it means that there is a call structure that
1687
		   has a peer callno but did NOT get entered into the hash table,
1724
		   has a peer callno but did NOT get entered into the hash table,
1688
		   which is bad.
1725
		   which is bad.
1689

    
   
1726

   
1690
		   If we find a call structure using this old, slow method, output a log
1727
		   If we find a call structure using this old, slow method, output a log
1691
		   message so we'll know about it. After a few months of leaving this in
1728
		   message so we'll know about it. After a few months of leaving this in
1692
		   place, if we don't hear about people seeing these messages, we can
1729
		   place, if we don't hear about people seeing these messages, we can
1693
		   remove this code for good.
1730
		   remove this code for good.
1694
		*/
1731
		*/
1695

    
   
1732

   
1696
		for (x = 1; !res && x < maxnontrunkcall; x++) {
1733
		for (x = 1; !res && x < maxnontrunkcall; x++) {
1697
			ast_mutex_lock(&iaxsl[x]);
1734
			ast_mutex_lock(&iaxsl[x]);
1698
			if (iaxs[x]) {
1735
			if (iaxs[x]) {
1699
				/* Look for an exact match */
1736
				/* Look for an exact match */
1700
				if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1737
				if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1701
					res = x;
1738
					res = x;
1702
				}
1739
				}
1703
			}
1740
			}
1704
			if (!res || !return_locked)
1741
			if (!res || !return_locked)
1705
				ast_mutex_unlock(&iaxsl[x]);
1742
				ast_mutex_unlock(&iaxsl[x]);
1706
		}
1743
		}
1707
		for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1744
		for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1708
			ast_mutex_lock(&iaxsl[x]);
1745
			ast_mutex_lock(&iaxsl[x]);
1709
			if (iaxs[x]) {
1746
			if (iaxs[x]) {
1710
				/* Look for an exact match */
1747
				/* Look for an exact match */
1711
				if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1748
				if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1712
					res = x;
1749
					res = x;
1713
				}
1750
				}
1714
			}
1751
			}
1715
			if (!res || !return_locked)
1752
			if (!res || !return_locked)
1716
				ast_mutex_unlock(&iaxsl[x]);
1753
				ast_mutex_unlock(&iaxsl[x]);
1717
		}
1754
		}
1718
#endif
1755
#endif
1719
	}
1756
	}
1720
	if (!res && (new >= NEW_ALLOW)) {
1757
	if (!res && (new >= NEW_ALLOW)) {
1721
		int start, found = 0;
1758
		int start, found = 0;
1722

    
   
1759

   
1723
		/* It may seem odd that we look through the peer list for a name for
1760
		/* It may seem odd that we look through the peer list for a name for
1724
		 * this *incoming* call.  Well, it is weird.  However, users don't
1761
		 * this *incoming* call.  Well, it is weird.  However, users don't
1725
		 * have an IP address/port number that we can match against.  So,
1762
		 * have an IP address/port number that we can match against.  So,
1726
		 * this is just checking for a peer that has that IP/port and
1763
		 * this is just checking for a peer that has that IP/port and
1727
		 * assuming that we have a user of the same name.  This isn't always
1764
		 * assuming that we have a user of the same name.  This isn't always
1728
		 * correct, but it will be changed if needed after authentication. */
1765
		 * correct, but it will be changed if needed after authentication. */
1729
		if (!iax2_getpeername(*sin, host, sizeof(host)))
1766
		if (!iax2_getpeername(*sin, host, sizeof(host)))
1730
			snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1767
			snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1731

    
   
1768

   
1732
		now = ast_tvnow();
1769
		now = ast_tvnow();
1733
		start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1770
		start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1734
		for (x = start; 1; x++) {
1771
		for (x = start; 1; x++) {
1735
			if (x == TRUNK_CALL_START) {
1772
			if (x == TRUNK_CALL_START) {
1736
				x = 1;
1773
				x = 1;
1737
				continue;
1774
				continue;
1738
			}
1775
			}
1739

    
   
1776

   
1740
			/* Find first unused call number that hasn't been used in a while */
1777
			/* Find first unused call number that hasn't been used in a while */
1741
			ast_mutex_lock(&iaxsl[x]);
1778
			ast_mutex_lock(&iaxsl[x]);
1742
			if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1779
			if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1743
				found = 1;
1780
				found = 1;
1744
				break;
1781
				break;
1745
			}
1782
			}
1746
			ast_mutex_unlock(&iaxsl[x]);
1783
			ast_mutex_unlock(&iaxsl[x]);
1747
			
1784
			
1748
			if (x == start - 1) {
1785
			if (x == start - 1) {
1749
				break;
1786
				break;
1750
			}
1787
			}
1751
		}
1788
		}
1752
		/* We've still got lock held if we found a spot */
1789
		/* We've still got lock held if we found a spot */
1753
		if (x == start - 1 && !found) {
1790
		if (x == start - 1 && !found) {
1754
			ast_log(LOG_WARNING, "No more space\n");
1791
			ast_log(LOG_WARNING, "No more space\n");
1755
			return 0;
1792
			return 0;
1756
		}
1793
		}
1757
		iaxs[x] = new_iax(sin, host);
1794
		iaxs[x] = new_iax(sin, host);
1758
		update_max_nontrunk();
1795
		update_max_nontrunk();
1759
		if (iaxs[x]) {
1796
		if (iaxs[x]) {
1760
			if (iaxdebug)
1797
			if (iaxdebug)
1761
				ast_debug(1, "Creating new call structure %d\n", x);
1798
				ast_debug(1, "Creating new call structure %d\n", x);
1762
			iaxs[x]->sockfd = sockfd;
1799
			iaxs[x]->sockfd = sockfd;
1763
			iaxs[x]->addr.sin_port = sin->sin_port;
1800
			iaxs[x]->addr.sin_port = sin->sin_port;
1764
			iaxs[x]->addr.sin_family = sin->sin_family;
1801
			iaxs[x]->addr.sin_family = sin->sin_family;
1765
			iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1802
			iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1766
			iaxs[x]->peercallno = callno;
1803
			iaxs[x]->peercallno = callno;
1767
			iaxs[x]->callno = x;
1804
			iaxs[x]->callno = x;
1768
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1805
			iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1769
			iaxs[x]->expiry = min_reg_expire;
1806
			iaxs[x]->expiry = min_reg_expire;
1770
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1807
			iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1771
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1808
			iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1772
			iaxs[x]->amaflags = amaflags;
1809
			iaxs[x]->amaflags = amaflags;
1773
			ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1810
			ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1774
			
1811
			
1775
			ast_string_field_set(iaxs[x], accountcode, accountcode);
1812
			ast_string_field_set(iaxs[x], accountcode, accountcode);
1776
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1813
			ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1777
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1814
			ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1778

    
   
1815

   
1779
			if (iaxs[x]->peercallno) {
1816
			if (iaxs[x]->peercallno) {
1780
				store_by_peercallno(iaxs[x]);
1817
				store_by_peercallno(iaxs[x]);
1781
			}
1818
			}
1782
		} else {
1819
		} else {
1783
			ast_log(LOG_WARNING, "Out of resources\n");
1820
			ast_log(LOG_WARNING, "Out of resources\n");
1784
			ast_mutex_unlock(&iaxsl[x]);
1821
			ast_mutex_unlock(&iaxsl[x]);
1785
			return 0;
1822
			return 0;
1786
		}
1823
		}
1787
		if (!return_locked)
1824
		if (!return_locked)
1788
			ast_mutex_unlock(&iaxsl[x]);
1825
			ast_mutex_unlock(&iaxsl[x]);
1789
		res = x;
1826
		res = x;
1790
	}
1827
	}
1791
	return res;
1828
	return res;
1792
}
1829
}
1793

    
   
1830

   
1794
static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1831
static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1795

    
   
1832

   
1796
	return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1833
	return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1797
}
1834
}
1798

    
   
1835

   
1799
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1836
static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1800

    
   
1837

   
1801
	return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1838
	return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1802
}
1839
}
1803

    
   
1840

   
1804
/*!
1841
/*!
1805
 * \brief Queue a frame to a call's owning asterisk channel
1842
 * \brief Queue a frame to a call's owning asterisk channel
1806
 *
1843
 *
1807
 * \pre This function assumes that iaxsl[callno] is locked when called.
1844
 * \pre This function assumes that iaxsl[callno] is locked when called.
1808
 *
1845
 *
1809
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1846
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1810
 * was valid before calling it, it may no longer be valid after calling it.
1847
 * was valid before calling it, it may no longer be valid after calling it.
1811
 * This function may unlock and lock the mutex associated with this callno,
1848
 * This function may unlock and lock the mutex associated with this callno,
1812
 * meaning that another thread may grab it and destroy the call.
1849
 * meaning that another thread may grab it and destroy the call.
1813
 */
1850
 */
1814
static int iax2_queue_frame(int callno, struct ast_frame *f)
1851
static int iax2_queue_frame(int callno, struct ast_frame *f)
1815
{
1852
{
1816
	for (;;) {
1853
	for (;;) {
1817
		if (iaxs[callno] && iaxs[callno]->owner) {
1854
		if (iaxs[callno] && iaxs[callno]->owner) {
1818
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1855
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1819
				/* Avoid deadlock by pausing and trying again */
1856
				/* Avoid deadlock by pausing and trying again */
1820
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1857
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1821
			} else {
1858
			} else {
1822
				ast_queue_frame(iaxs[callno]->owner, f);
1859
				ast_queue_frame(iaxs[callno]->owner, f);
1823
				ast_channel_unlock(iaxs[callno]->owner);
1860
				ast_channel_unlock(iaxs[callno]->owner);
1824
				break;
1861
				break;
1825
			}
1862
			}
1826
		} else
1863
		} else
1827
			break;
1864
			break;
1828
	}
1865
	}
1829
	return 0;
1866
	return 0;
1830
}
1867
}
1831

    
   
1868

   
1832
/*!
1869
/*!
1833
 * \brief Queue a hangup frame on the ast_channel owner
1870
 * \brief Queue a hangup frame on the ast_channel owner
1834
 *
1871
 *
1835
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1872
 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1836
 * is active for the given call number.
1873
 * is active for the given call number.
1837
 *
1874
 *
1838
 * \pre Assumes lock for callno is already held.
1875
 * \pre Assumes lock for callno is already held.
1839
 *
1876
 *
1840
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1877
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1841
 * was valid before calling it, it may no longer be valid after calling it.
1878
 * was valid before calling it, it may no longer be valid after calling it.
1842
 * This function may unlock and lock the mutex associated with this callno,
1879
 * This function may unlock and lock the mutex associated with this callno,
1843
 * meaning that another thread may grab it and destroy the call.
1880
 * meaning that another thread may grab it and destroy the call.
1844
 */
1881
 */
1845
static int iax2_queue_hangup(int callno)
1882
static int iax2_queue_hangup(int callno)
1846
{
1883
{
1847
	for (;;) {
1884
	for (;;) {
1848
		if (iaxs[callno] && iaxs[callno]->owner) {
1885
		if (iaxs[callno] && iaxs[callno]->owner) {
1849
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1886
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1850
				/* Avoid deadlock by pausing and trying again */
1887
				/* Avoid deadlock by pausing and trying again */
1851
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1888
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1852
			} else {
1889
			} else {
1853
				ast_queue_hangup(iaxs[callno]->owner);
1890
				ast_queue_hangup(iaxs[callno]->owner);
1854
				ast_channel_unlock(iaxs[callno]->owner);
1891
				ast_channel_unlock(iaxs[callno]->owner);
1855
				break;
1892
				break;
1856
			}
1893
			}
1857
		} else
1894
		} else
1858
			break;
1895
			break;
1859
	}
1896
	}
1860
	return 0;
1897
	return 0;
1861
}
1898
}
1862

    
   
1899

   
1863
/*!
1900
/*!
1864
 * \brief Queue a control frame on the ast_channel owner
1901
 * \brief Queue a control frame on the ast_channel owner
1865
 *
1902
 *
1866
 * This function queues a control frame on the owner of the IAX2 pvt struct that
1903
 * This function queues a control frame on the owner of the IAX2 pvt struct that
1867
 * is active for the given call number.
1904
 * is active for the given call number.
1868
 *
1905
 *
1869
 * \pre Assumes lock for callno is already held.
1906
 * \pre Assumes lock for callno is already held.
1870
 *
1907
 *
1871
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1908
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1872
 * was valid before calling it, it may no longer be valid after calling it.
1909
 * was valid before calling it, it may no longer be valid after calling it.
1873
 * This function may unlock and lock the mutex associated with this callno,
1910
 * This function may unlock and lock the mutex associated with this callno,
1874
 * meaning that another thread may grab it and destroy the call.
1911
 * meaning that another thread may grab it and destroy the call.
1875
 */
1912
 */
1876
static int iax2_queue_control_data(int callno, 
1913
static int iax2_queue_control_data(int callno, 
1877
	enum ast_control_frame_type control, const void *data, size_t datalen)
1914
	enum ast_control_frame_type control, const void *data, size_t datalen)
1878
{
1915
{
1879
	for (;;) {
1916
	for (;;) {
1880
		if (iaxs[callno] && iaxs[callno]->owner) {
1917
		if (iaxs[callno] && iaxs[callno]->owner) {
1881
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1918
			if (ast_channel_trylock(iaxs[callno]->owner)) {
1882
				/* Avoid deadlock by pausing and trying again */
1919
				/* Avoid deadlock by pausing and trying again */
1883
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1920
				DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1884
			} else {
1921
			} else {
1885
				ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1922
				ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1886
				ast_channel_unlock(iaxs[callno]->owner);
1923
				ast_channel_unlock(iaxs[callno]->owner);
1887
				break;
1924
				break;
1888
			}
1925
			}
1889
		} else
1926
		} else
1890
			break;
1927
			break;
1891
	}
1928
	}
1892
	return 0;
1929
	return 0;
1893
}
1930
}
1894
static void destroy_firmware(struct iax_firmware *cur)
1931
static void destroy_firmware(struct iax_firmware *cur)
1895
{
1932
{
1896
	/* Close firmware */
1933
	/* Close firmware */
1897
	if (cur->fwh) {
1934
	if (cur->fwh) {
1898
		munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1935
		munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1899
	}
1936
	}
1900
	close(cur->fd);
1937
	close(cur->fd);
1901
	ast_free(cur);
1938
	ast_free(cur);
1902
}
1939
}
1903

    
   
1940

   
1904
static int try_firmware(char *s)
1941
static int try_firmware(char *s)
1905
{
1942
{
1906
	struct stat stbuf;
1943
	struct stat stbuf;
1907
	struct iax_firmware *cur = NULL;
1944
	struct iax_firmware *cur = NULL;
1908
	int ifd, fd, res, len, chunk;
1945
	int ifd, fd, res, len, chunk;
1909
	struct ast_iax2_firmware_header *fwh, fwh2;
1946
	struct ast_iax2_firmware_header *fwh, fwh2;
1910
	struct MD5Context md5;
1947
	struct MD5Context md5;
1911
	unsigned char sum[16], buf[1024];
1948
	unsigned char sum[16], buf[1024];
1912
	char *s2, *last;
1949
	char *s2, *last;
1913

    
   
1950

   
1914
	if (!(s2 = alloca(strlen(s) + 100))) {
1951
	if (!(s2 = alloca(strlen(s) + 100))) {
1915
		ast_log(LOG_WARNING, "Alloca failed!\n");
1952
		ast_log(LOG_WARNING, "Alloca failed!\n");
1916
		return -1;
1953
		return -1;
1917
	}
1954
	}
1918

    
   
1955

   
1919
	last = strrchr(s, '/');
1956
	last = strrchr(s, '/');
1920
	if (last)
1957
	if (last)
1921
		last++;
1958
		last++;
1922
	else
1959
	else
1923
		last = s;
1960
		last = s;
1924

    
   
1961

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

    
   
1963

   
1927
	if ((res = stat(s, &stbuf) < 0)) {
1964
	if ((res = stat(s, &stbuf) < 0)) {
1928
		ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1965
		ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1929
		return -1;
1966
		return -1;
1930
	}
1967
	}
1931

    
   
1968

   
1932
	/* Make sure it's not a directory */
1969
	/* Make sure it's not a directory */
1933
	if (S_ISDIR(stbuf.st_mode))
1970
	if (S_ISDIR(stbuf.st_mode))
1934
		return -1;
1971
		return -1;
1935
	ifd = open(s, O_RDONLY);
1972
	ifd = open(s, O_RDONLY);
1936
	if (ifd < 0) {
1973
	if (ifd < 0) {
1937
		ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1974
		ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1938
		return -1;
1975
		return -1;
1939
	}
1976
	}
1940
	fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1977
	fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1941
	if (fd < 0) {
1978
	if (fd < 0) {
1942
		ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1979
		ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1943
		close(ifd);
1980
		close(ifd);
1944
		return -1;
1981
		return -1;
1945
	}
1982
	}
1946
	/* Unlink our newly created file */
1983
	/* Unlink our newly created file */
1947
	unlink(s2);
1984
	unlink(s2);
1948
	
1985
	
1949
	/* Now copy the firmware into it */
1986
	/* Now copy the firmware into it */
1950
	len = stbuf.st_size;
1987
	len = stbuf.st_size;
1951
	while(len) {
1988
	while(len) {
1952
		chunk = len;
1989
		chunk = len;
1953
		if (chunk > sizeof(buf))
1990
		if (chunk > sizeof(buf))
1954
			chunk = sizeof(buf);
1991
			chunk = sizeof(buf);
1955
		res = read(ifd, buf, chunk);
1992
		res = read(ifd, buf, chunk);
1956
		if (res != chunk) {
1993
		if (res != chunk) {
1957
			ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1994
			ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1958
			close(ifd);
1995
			close(ifd);
1959
			close(fd);
1996
			close(fd);
1960
			return -1;
1997
			return -1;
1961
		}
1998
		}
1962
		res = write(fd, buf, chunk);
1999
		res = write(fd, buf, chunk);
1963
		if (res != chunk) {
2000
		if (res != chunk) {
1964
			ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
2001
			ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1965
			close(ifd);
2002
			close(ifd);
1966
			close(fd);
2003
			close(fd);
1967
			return -1;
2004
			return -1;
1968
		}
2005
		}
1969
		len -= chunk;
2006
		len -= chunk;
1970
	}
2007
	}
1971
	close(ifd);
2008
	close(ifd);
1972
	/* Return to the beginning */
2009
	/* Return to the beginning */
1973
	lseek(fd, 0, SEEK_SET);
2010
	lseek(fd, 0, SEEK_SET);
1974
	if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
2011
	if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1975
		ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
2012
		ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1976
		close(fd);
2013
		close(fd);
1977
		return -1;
2014
		return -1;
1978
	}
2015
	}
1979
	if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2016
	if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1980
		ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2017
		ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1981
		close(fd);
2018
		close(fd);
1982
		return -1;
2019
		return -1;
1983
	}
2020
	}
1984
	if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2021
	if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1985
		ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2022
		ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1986
		close(fd);
2023
		close(fd);
1987
		return -1;
2024
		return -1;
1988
	}
2025
	}
1989
	if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2026
	if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1990
		ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2027
		ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1991
		close(fd);
2028
		close(fd);
1992
		return -1;
2029
		return -1;
1993
	}
2030
	}
1994
	fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
2031
	fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); 
1995
	if (fwh == (void *) -1) {
2032
	if (fwh == (void *) -1) {
1996
		ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
2033
		ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1997
		close(fd);
2034
		close(fd);
1998
		return -1;
2035
		return -1;
1999
	}
2036
	}
2000
	MD5Init(&md5);
2037
	MD5Init(&md5);
2001
	MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2038
	MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2002
	MD5Final(sum, &md5);
2039
	MD5Final(sum, &md5);
2003
	if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2040
	if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2004
		ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2041
		ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2005
		munmap((void*)fwh, stbuf.st_size);
2042
		munmap((void*)fwh, stbuf.st_size);
2006
		close(fd);
2043
		close(fd);
2007
		return -1;
2044
		return -1;
2008
	}
2045
	}
2009

    
   
2046

   
2010
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2047
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2011
		if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
2048
		if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
2012
			/* Found a candidate */
2049
			/* Found a candidate */
2013
			if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
2050
			if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
2014
				/* The version we have on loaded is older, load this one instead */
2051
				/* The version we have on loaded is older, load this one instead */
2015
				break;
2052
				break;
2016
			/* This version is no newer than what we have.  Don't worry about it.
2053
			/* This version is no newer than what we have.  Don't worry about it.
2017
			   We'll consider it a proper load anyhow though */
2054
			   We'll consider it a proper load anyhow though */
2018
			munmap((void*)fwh, stbuf.st_size);
2055
			munmap((void*)fwh, stbuf.st_size);
2019
			close(fd);
2056
			close(fd);
2020
			return 0;
2057
			return 0;
2021
		}
2058
		}
2022
	}
2059
	}
2023
	
2060
	
2024
	if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2061
	if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2025
		cur->fd = -1;
2062
		cur->fd = -1;
2026
		AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2063
		AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2027
	}
2064
	}
2028
	
2065
	
2029
	if (cur) {
2066
	if (cur) {
2030
		if (cur->fwh)
2067
		if (cur->fwh)
2031
			munmap((void*)cur->fwh, cur->mmaplen);
2068
			munmap((void*)cur->fwh, cur->mmaplen);
2032
		if (cur->fd > -1)
2069
		if (cur->fd > -1)
2033
			close(cur->fd);
2070
			close(cur->fd);
2034
		cur->fwh = fwh;
2071
		cur->fwh = fwh;
2035
		cur->fd = fd;
2072
		cur->fd = fd;
2036
		cur->mmaplen = stbuf.st_size;
2073
		cur->mmaplen = stbuf.st_size;
2037
		cur->dead = 0;
2074
		cur->dead = 0;
2038
	}
2075
	}
2039
	
2076
	
2040
	return 0;
2077
	return 0;
2041
}
2078
}
2042

    
   
2079

   
2043
static int iax_check_version(char *dev)
2080
static int iax_check_version(char *dev)
2044
{
2081
{
2045
	int res = 0;
2082
	int res = 0;
2046
	struct iax_firmware *cur = NULL;
2083
	struct iax_firmware *cur = NULL;
2047

    
   
2084

   
2048
	if (ast_strlen_zero(dev))
2085
	if (ast_strlen_zero(dev))
2049
		return 0;
2086
		return 0;
2050

    
   
2087

   
2051
	AST_LIST_LOCK(&firmwares);
2088
	AST_LIST_LOCK(&firmwares);
2052
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2089
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2053
		if (!strcmp(dev, (char *)cur->fwh->devname)) {
2090
		if (!strcmp(dev, (char *)cur->fwh->devname)) {
2054
			res = ntohs(cur->fwh->version);
2091
			res = ntohs(cur->fwh->version);
2055
			break;
2092
			break;
2056
		}
2093
		}
2057
	}
2094
	}
2058
	AST_LIST_UNLOCK(&firmwares);
2095
	AST_LIST_UNLOCK(&firmwares);
2059

    
   
2096

   
2060
	return res;
2097
	return res;
2061
}
2098
}
2062

    
   
2099

   
2063
static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2100
static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2064
{
2101
{
2065
	int res = -1;
2102
	int res = -1;
2066
	unsigned int bs = desc & 0xff;
2103
	unsigned int bs = desc & 0xff;
2067
	unsigned int start = (desc >> 8) & 0xffffff;
2104
	unsigned int start = (desc >> 8) & 0xffffff;
2068
	unsigned int bytes;
2105
	unsigned int bytes;
2069
	struct iax_firmware *cur;
2106
	struct iax_firmware *cur;
2070

    
   
2107

   
2071
	if (ast_strlen_zero((char *)dev) || !bs)
2108
	if (ast_strlen_zero((char *)dev) || !bs)
2072
		return -1;
2109
		return -1;
2073

    
   
2110

   
2074
	start *= bs;
2111
	start *= bs;
2075
	
2112
	
2076
	AST_LIST_LOCK(&firmwares);
2113
	AST_LIST_LOCK(&firmwares);
2077
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2114
	AST_LIST_TRAVERSE(&firmwares, cur, list) {
2078
		if (strcmp((char *)dev, (char *)cur->fwh->devname))
2115
		if (strcmp((char *)dev, (char *)cur->fwh->devname))
2079
			continue;
2116
			continue;
2080
		iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2117
		iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2081
		if (start < ntohl(cur->fwh->datalen)) {
2118
		if (start < ntohl(cur->fwh->datalen)) {
2082
			bytes = ntohl(cur->fwh->datalen) - start;
2119
			bytes = ntohl(cur->fwh->datalen) - start;
2083
			if (bytes > bs)
2120
			if (bytes > bs)
2084
				bytes = bs;
2121
				bytes = bs;
2085
			iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2122
			iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2086
		} else {
2123
		} else {
2087
			bytes = 0;
2124
			bytes = 0;
2088
			iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2125
			iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2089
		}
2126
		}
2090
		if (bytes == bs)
2127
		if (bytes == bs)
2091
			res = 0;
2128
			res = 0;
2092
		else
2129
		else
2093
			res = 1;
2130
			res = 1;
2094
		break;
2131
		break;
2095
	}
2132
	}
2096
	AST_LIST_UNLOCK(&firmwares);
2133
	AST_LIST_UNLOCK(&firmwares);
2097

    
   
2134

   
2098
	return res;
2135
	return res;
2099
}
2136
}
2100

    
   
2137

   
2101

    
   
2138

   
2102
static void reload_firmware(int unload)
2139
static void reload_firmware(int unload)
2103
{
2140
{
2104
	struct iax_firmware *cur = NULL;
2141
	struct iax_firmware *cur = NULL;
2105
	DIR *fwd;
2142
	DIR *fwd;
2106
	struct dirent *de;
2143
	struct dirent *de;
2107
	char dir[256], fn[256];
2144
	char dir[256], fn[256];
2108

    
   
2145

   
2109
	AST_LIST_LOCK(&firmwares);
2146
	AST_LIST_LOCK(&firmwares);
2110

    
   
2147

   
2111
	/* Mark all as dead */
2148
	/* Mark all as dead */
2112
	AST_LIST_TRAVERSE(&firmwares, cur, list)
2149
	AST_LIST_TRAVERSE(&firmwares, cur, list)
2113
		cur->dead = 1;
2150
		cur->dead = 1;
2114

    
   
2151

   
2115
	/* Now that we have marked them dead... load new ones */
2152
	/* Now that we have marked them dead... load new ones */
2116
	if (!unload) {
2153
	if (!unload) {
2117
		snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2154
		snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2118
		fwd = opendir(dir);
2155
		fwd = opendir(dir);
2119
		if (fwd) {
2156
		if (fwd) {
2120
			while((de = readdir(fwd))) {
2157
			while((de = readdir(fwd))) {
2121
				if (de->d_name[0] != '.') {
2158
				if (de->d_name[0] != '.') {
2122
					snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2159
					snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2123
					if (!try_firmware(fn)) {
2160
					if (!try_firmware(fn)) {
2124
						ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2161
						ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2125
					}
2162
					}
2126
				}
2163
				}
2127
			}
2164
			}
2128
			closedir(fwd);
2165
			closedir(fwd);
2129
		} else 
2166
		} else 
2130
			ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2167
			ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2131
	}
2168
	}
2132

    
   
2169

   
2133
	/* Clean up leftovers */
2170
	/* Clean up leftovers */
2134
	AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2171
	AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2135
		if (!cur->dead)
2172
		if (!cur->dead)
2136
			continue;
2173
			continue;
2137
		AST_LIST_REMOVE_CURRENT(list);
2174
		AST_LIST_REMOVE_CURRENT(list);
2138
		destroy_firmware(cur);
2175
		destroy_firmware(cur);
2139
	}
2176
	}
2140
	AST_LIST_TRAVERSE_SAFE_END;
2177
	AST_LIST_TRAVERSE_SAFE_END;
2141

    
   
2178

   
2142
	AST_LIST_UNLOCK(&firmwares);
2179
	AST_LIST_UNLOCK(&firmwares);
2143
}
2180
}
2144

    
   
2181

   
2145
/*!
2182
/*!
2146
 * \note This function assumes that iaxsl[callno] is locked when called.
2183
 * \note This function assumes that iaxsl[callno] is locked when called.
2147
 *
2184
 *
2148
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2185
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2149
 * was valid before calling it, it may no longer be valid after calling it.
2186
 * was valid before calling it, it may no longer be valid after calling it.
2150
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
2187
 * This function calls iax2_queue_frame(), which may unlock and lock the mutex 
2151
 * associated with this callno, meaning that another thread may grab it and destroy the call.
2188
 * associated with this callno, meaning that another thread may grab it and destroy the call.
2152
 */
2189
 */
2153
static int __do_deliver(void *data)
2190
static int __do_deliver(void *data)
2154
{
2191
{
2155
	/* Just deliver the packet by using queueing.  This is called by
2192
	/* Just deliver the packet by using queueing.  This is called by
2156
	  the IAX thread with the iaxsl lock held. */
2193
	  the IAX thread with the iaxsl lock held. */
2157
	struct iax_frame *fr = data;
2194
	struct iax_frame *fr = data;
2158
	fr->retrans = -1;
2195
	fr->retrans = -1;
2159
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2196
	ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2160
	if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2197
	if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2161
		iax2_queue_frame(fr->callno, &fr->af);
2198
		iax2_queue_frame(fr->callno, &fr->af);
2162
	/* Free our iax frame */
2199
	/* Free our iax frame */
2163
	iax2_frame_free(fr);
2200
	iax2_frame_free(fr);
2164
	/* And don't run again */
2201
	/* And don't run again */
2165
	return 0;
2202
	return 0;
2166
}
2203
}
2167

    
   
2204

   
2168
static int handle_error(void)
2205
static int handle_error(void)
2169
{
2206
{
2170
	/* XXX Ideally we should figure out why an error occurred and then abort those
2207
	/* XXX Ideally we should figure out why an error occurred and then abort those
2171
	   rather than continuing to try.  Unfortunately, the published interface does
2208
	   rather than continuing to try.  Unfortunately, the published interface does
2172
	   not seem to work XXX */
2209
	   not seem to work XXX */
2173
#if 0
2210
#if 0
2174
	struct sockaddr_in *sin;
2211
	struct sockaddr_in *sin;
2175
	int res;
2212
	int res;
2176
	struct msghdr m;
2213
	struct msghdr m;
2177
	struct sock_extended_err e;
2214
	struct sock_extended_err e;
2178
	m.msg_name = NULL;
2215
	m.msg_name = NULL;
2179
	m.msg_namelen = 0;
2216
	m.msg_namelen = 0;
2180
	m.msg_iov = NULL;
2217
	m.msg_iov = NULL;
2181
	m.msg_control = &e;
2218
	m.msg_control = &e;
2182
	m.msg_controllen = sizeof(e);
2219
	m.msg_controllen = sizeof(e);
2183
	m.msg_flags = 0;
2220
	m.msg_flags = 0;
2184
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2221
	res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2185
	if (res < 0)
2222
	if (res < 0)
2186
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2223
		ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2187
	else {
2224
	else {
2188
		if (m.msg_controllen) {
2225
		if (m.msg_controllen) {
2189
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2226
			sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2190
			if (sin) 
2227
			if (sin) 
2191
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2228
				ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2192
			else
2229
			else
2193
				ast_log(LOG_WARNING, "No address detected??\n");
2230
				ast_log(LOG_WARNING, "No address detected??\n");
2194
		} else {
2231
		} else {
2195
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2232
			ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2196
		}
2233
		}
2197
	}
2234
	}
2198
#endif
2235
#endif
2199
	return 0;
2236
	return 0;
2200
}
2237
}
2201

    
   
2238

   
2202
static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2239
static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2203
{
2240
{
2204
	int res;
2241
	int res;
2205
	res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2242
	res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2206
					sizeof(*sin));
2243
					sizeof(*sin));
2207
	if (res < 0) {
2244
	if (res < 0) {
2208
		ast_debug(1, "Received error: %s\n", strerror(errno));
2245
		ast_debug(1, "Received error: %s\n", strerror(errno));
2209
		handle_error();
2246
		handle_error();
2210
	} else
2247
	} else
2211
		res = 0;
2248
		res = 0;
2212
	return res;
2249
	return res;
2213
}
2250
}
2214

    
   
2251

   
2215
static int send_packet(struct iax_frame *f)
2252
static int send_packet(struct iax_frame *f)
2216
{
2253
{
2217
	int res;
2254
	int res;
2218
	int callno = f->callno;
2255
	int callno = f->callno;
2219

    
   
2256

   
2220
	/* Don't send if there was an error, but return error instead */
2257
	/* Don't send if there was an error, but return error instead */
2221
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
2258
	if (!callno || !iaxs[callno] || iaxs[callno]->error)
2222
	    return -1;
2259
	    return -1;
2223
	
2260
	
2224
	/* Called with iaxsl held */
2261
	/* Called with iaxsl held */
2225
	if (iaxdebug)
2262
	if (iaxdebug)
2226
		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));
2263
		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));
2227
	if (f->transfer) {
2264
	if (f->transfer) {
2228
		if (iaxdebug)
2265
		if (iaxdebug)
2229
			iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2266
			iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2230
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
2267
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
2231
					sizeof(iaxs[callno]->transfer));
2268
					sizeof(iaxs[callno]->transfer));
2232
	} else {
2269
	} else {
2233
		if (iaxdebug)
2270
		if (iaxdebug)
2234
			iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2271
			iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2235
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
2272
		res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
2236
					sizeof(iaxs[callno]->addr));
2273
					sizeof(iaxs[callno]->addr));
2237
	}
2274
	}
2238
	if (res < 0) {
2275
	if (res < 0) {
2239
		if (iaxdebug)
2276
		if (iaxdebug)
2240
			ast_debug(1, "Received error: %s\n", strerror(errno));
2277
			ast_debug(1, "Received error: %s\n", strerror(errno));
2241
		handle_error();
2278
		handle_error();
2242
	} else
2279
	} else
2243
		res = 0;
2280
		res = 0;
2244
	return res;
2281
	return res;
2245
}
2282
}
2246

    
   
2283

   
2247
/*!
2284
/*!
2248
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2285
 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2249
 *       for the given call number may disappear during its execution.
2286
 *       for the given call number may disappear during its execution.
2250
 */
2287
 */
2251
static int iax2_predestroy(int callno)
2288
static int iax2_predestroy(int callno)
2252
{
2289
{
2253
	struct ast_channel *c = NULL;
2290
	struct ast_channel *c = NULL;
2254
	struct chan_iax2_pvt *pvt = iaxs[callno];
2291
	struct chan_iax2_pvt *pvt = iaxs[callno];
2255

    
   
2292

   
2256
	if (!pvt)
2293
	if (!pvt)
2257
		return -1;
2294
		return -1;
2258

    
   
2295

   
2259
	if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2296
	if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2260
		iax2_destroy_helper(pvt);
2297
		iax2_destroy_helper(pvt);
2261
		ast_set_flag(pvt, IAX_ALREADYGONE);	
2298
		ast_set_flag(pvt, IAX_ALREADYGONE);	
2262
	}
2299
	}
2263

    
   
2300

   
2264
	if ((c = pvt->owner)) {
2301
	if ((c = pvt->owner)) {
2265
		c->tech_pvt = NULL;
2302
		c->tech_pvt = NULL;
2266
		iax2_queue_hangup(callno);
2303
		iax2_queue_hangup(callno);
2267
		pvt->owner = NULL;
2304
		pvt->owner = NULL;
2268
		ast_module_unref(ast_module_info->self);
2305
		ast_module_unref(ast_module_info->self);
2269
	}
2306
	}
2270

    
   
2307

   
2271
	return 0;
2308
	return 0;
2272
}
2309
}
2273

    
   
2310

   
2274
static void iax2_destroy(int callno)
2311
static void iax2_destroy(int callno)
2275
{
2312
{
2276
	struct chan_iax2_pvt *pvt = NULL;
2313
	struct chan_iax2_pvt *pvt = NULL;
2277
	struct ast_channel *owner = NULL;
2314
	struct ast_channel *owner = NULL;
2278

    
   
2315

   
2279
retry:
2316
retry:
2280
	pvt = iaxs[callno];
2317
	pvt = iaxs[callno];
2281
	lastused[callno] = ast_tvnow();
2318
	lastused[callno] = ast_tvnow();
2282
	
2319
	
2283
	owner = pvt ? pvt->owner : NULL;
2320
	owner = pvt ? pvt->owner : NULL;
2284

    
   
2321

   
2285
	if (owner) {
2322
	if (owner) {
2286
		if (ast_channel_trylock(owner)) {
2323
		if (ast_channel_trylock(owner)) {
2287
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
2324
			ast_debug(3, "Avoiding IAX destroy deadlock\n");
2288
			ast_mutex_unlock(&iaxsl[callno]);
2325
			ast_mutex_unlock(&iaxsl[callno]);
2289
			usleep(1);
2326
			usleep(1);
2290
			ast_mutex_lock(&iaxsl[callno]);
2327
			ast_mutex_lock(&iaxsl[callno]);
2291
			goto retry;
2328
			goto retry;
2292
		}
2329
		}
2293
	}
2330
	}
2294

    
   
2331

   
2295
	if (!owner) {
2332
	if (!owner) {
2296
		iaxs[callno] = NULL;
2333
		iaxs[callno] = NULL;
2297
	}
2334
	}
2298

    
   
2335

   
2299
	if (pvt) {
2336
	if (pvt) {
2300
		if (!owner) {
2337
		if (!owner) {
2301
			pvt->owner = NULL;
2338
			pvt->owner = NULL;
2302
		} else {
2339
		} else {
2303
			/* If there's an owner, prod it to give up */
2340
			/* If there's an owner, prod it to give up */
2304
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2341
			/* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2305
			 * because we already hold the owner channel lock. */
2342
			 * because we already hold the owner channel lock. */
2306
			ast_queue_hangup(owner);
2343
			ast_queue_hangup(owner);
2307
		}
2344
		}
2308

    
   
2345

   
2309
		if (pvt->peercallno) {
2346
		if (pvt->peercallno) {
2310
			remove_by_peercallno(pvt);
2347
			remove_by_peercallno(pvt);
2311
		}
2348
		}
2312

    
   
2349

   

    
   
2350
		if(pvt->transfercallno) {

    
   
2351
			remove_by_transfercallno(pvt);

    
   
2352
		}

    
   
2353

   
2313
		if (!owner) {
2354
		if (!owner) {
2314
			ao2_ref(pvt, -1);
2355
			ao2_ref(pvt, -1);
2315
			pvt = NULL;
2356
			pvt = NULL;
2316
		}
2357
		}
2317
	}
2358
	}
2318

    
   
2359

   
2319
	if (owner) {
2360
	if (owner) {
2320
		ast_channel_unlock(owner);
2361
		ast_channel_unlock(owner);
2321
	}
2362
	}
2322

    
   
2363

   
2323
	if (callno & 0x4000) {
2364
	if (callno & 0x4000) {
2324
		update_max_trunk();
2365
		update_max_trunk();
2325
	}
2366
	}
2326
}
2367
}
2327

    
   
2368

   
2328
static int update_packet(struct iax_frame *f)
2369
static int update_packet(struct iax_frame *f)
2329
{
2370
{
2330
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2371
	/* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2331
	struct ast_iax2_full_hdr *fh = f->data;
2372
	struct ast_iax2_full_hdr *fh = f->data;
2332
	/* Mark this as a retransmission */
2373
	/* Mark this as a retransmission */
2333
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2374
	fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2334
	/* Update iseqno */
2375
	/* Update iseqno */
2335
	f->iseqno = iaxs[f->callno]->iseqno;
2376
	f->iseqno = iaxs[f->callno]->iseqno;
2336
	fh->iseqno = f->iseqno;
2377
	fh->iseqno = f->iseqno;
2337
	return 0;
2378
	return 0;
2338
}
2379
}
2339

    
   
2380

   
2340
static int attempt_transmit(const void *data);
2381
static int attempt_transmit(const void *data);
2341
static void __attempt_transmit(const void *data)
2382
static void __attempt_transmit(const void *data)
2342
{
2383
{
2343
	/* Attempt to transmit the frame to the remote peer...
2384
	/* Attempt to transmit the frame to the remote peer...
2344
	   Called without iaxsl held. */
2385
	   Called without iaxsl held. */
2345
	struct iax_frame *f = (struct iax_frame *)data;
2386
	struct iax_frame *f = (struct iax_frame *)data;
2346
	int freeme = 0;
2387
	int freeme = 0;
2347
	int callno = f->callno;
2388
	int callno = f->callno;
2348
	/* Make sure this call is still active */
2389
	/* Make sure this call is still active */
2349
	if (callno) 
2390
	if (callno) 
2350
		ast_mutex_lock(&iaxsl[callno]);
2391
		ast_mutex_lock(&iaxsl[callno]);
2351
	if (callno && iaxs[callno]) {
2392
	if (callno && iaxs[callno]) {
2352
		if ((f->retries < 0) /* Already ACK'd */ ||
2393
		if ((f->retries < 0) /* Already ACK'd */ ||
2353
		    (f->retries >= max_retries) /* Too many attempts */) {
2394
		    (f->retries >= max_retries) /* Too many attempts */) {
2354
				/* Record an error if we've transmitted too many times */
2395
				/* Record an error if we've transmitted too many times */
2355
				if (f->retries >= max_retries) {
2396
				if (f->retries >= max_retries) {
2356
					if (f->transfer) {
2397
					if (f->transfer) {
2357
						/* Transfer timeout */
2398
						/* Transfer timeout */
2358
						send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2399
						send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2359
					} else if (f->final) {
2400
					} else if (f->final) {
2360
						if (f->final) 
2401
						if (f->final) 
2361
							iax2_destroy(callno);
2402
							iax2_destroy(callno);
2362
					} else {
2403
					} else {
2363
						if (iaxs[callno]->owner)
2404
						if (iaxs[callno]->owner)
2364
							ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2405
							ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2365
						iaxs[callno]->error = ETIMEDOUT;
2406
						iaxs[callno]->error = ETIMEDOUT;
2366
						if (iaxs[callno]->owner) {
2407
						if (iaxs[callno]->owner) {
2367
							struct ast_frame fr = { 0, };
2408
							struct ast_frame fr = { 0, };
2368
							/* Hangup the fd */
2409
							/* Hangup the fd */
2369
							fr.frametype = AST_FRAME_CONTROL;
2410
							fr.frametype = AST_FRAME_CONTROL;
2370
							fr.subclass = AST_CONTROL_HANGUP;
2411
							fr.subclass = AST_CONTROL_HANGUP;
2371
							iax2_queue_frame(callno, &fr); /* XXX */
2412
							iax2_queue_frame(callno, &fr); /* XXX */
2372
							/* Remember, owner could disappear */
2413
							/* Remember, owner could disappear */
2373
							if (iaxs[callno] && iaxs[callno]->owner)
2414
							if (iaxs[callno] && iaxs[callno]->owner)
2374
								iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2415
								iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2375
						} else {
2416
						} else {
2376
							if (iaxs[callno]->reg) {
2417
							if (iaxs[callno]->reg) {
2377
								memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2418
								memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2378
								iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2419
								iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2379
								iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2420
								iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2380
							}
2421
							}
2381
							iax2_destroy(callno);
2422
							iax2_destroy(callno);
2382
						}
2423
						}
2383
					}
2424
					}
2384

    
   
2425

   
2385
				}
2426
				}
2386
				freeme = 1;
2427
				freeme = 1;
2387
		} else {
2428
		} else {
2388
			/* Update it if it needs it */
2429
			/* Update it if it needs it */
2389
			update_packet(f);
2430
			update_packet(f);
2390
			/* Attempt transmission */
2431
			/* Attempt transmission */
2391
			send_packet(f);
2432
			send_packet(f);
2392
			f->retries++;
2433
			f->retries++;
2393
			/* Try again later after 10 times as long */
2434
			/* Try again later after 10 times as long */
2394
			f->retrytime *= 10;
2435
			f->retrytime *= 10;
2395
			if (f->retrytime > MAX_RETRY_TIME)
2436
			if (f->retrytime > MAX_RETRY_TIME)
2396
				f->retrytime = MAX_RETRY_TIME;
2437
				f->retrytime = MAX_RETRY_TIME;
2397
			/* Transfer messages max out at one second */
2438
			/* Transfer messages max out at one second */
2398
			if (f->transfer && (f->retrytime > 1000))
2439
			if (f->transfer && (f->retrytime > 1000))
2399
				f->retrytime = 1000;
2440
				f->retrytime = 1000;
2400
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2441
			f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2401
		}
2442
		}
2402
	} else {
2443
	} else {
2403
		/* Make sure it gets freed */
2444
		/* Make sure it gets freed */
2404
		f->retries = -1;
2445
		f->retries = -1;
2405
		freeme = 1;
2446
		freeme = 1;
2406
	}
2447
	}
2407
	if (callno)
2448
	if (callno)
2408
		ast_mutex_unlock(&iaxsl[callno]);
2449
		ast_mutex_unlock(&iaxsl[callno]);
2409
	/* Do not try again */
2450
	/* Do not try again */
2410
	if (freeme) {
2451
	if (freeme) {
2411
		/* Don't attempt delivery, just remove it from the queue */
2452
		/* Don't attempt delivery, just remove it from the queue */
2412
		AST_LIST_LOCK(&frame_queue);
2453
		AST_LIST_LOCK(&frame_queue);
2413
		AST_LIST_REMOVE(&frame_queue, f, list);
2454
		AST_LIST_REMOVE(&frame_queue, f, list);
2414
		AST_LIST_UNLOCK(&frame_queue);
2455
		AST_LIST_UNLOCK(&frame_queue);
2415
		f->retrans = -1;
2456
		f->retrans = -1;
2416
		/* Free the IAX frame */
2457
		/* Free the IAX frame */
2417
		iax2_frame_free(f);
2458
		iax2_frame_free(f);
2418
	}
2459
	}
2419
}
2460
}
2420

    
   
2461

   
2421
static int attempt_transmit(const void *data)
2462
static int attempt_transmit(const void *data)
2422
{
2463
{
2423
#ifdef SCHED_MULTITHREADED
2464
#ifdef SCHED_MULTITHREADED
2424
	if (schedule_action(__attempt_transmit, data))
2465
	if (schedule_action(__attempt_transmit, data))
2425
#endif		
2466
#endif		
2426
		__attempt_transmit(data);
2467
		__attempt_transmit(data);
2427
	return 0;
2468
	return 0;
2428
}
2469
}
2429

    
   
2470

   
2430
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2471
static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2431
{
2472
{
2432
	struct iax2_peer *peer;
2473
	struct iax2_peer *peer;
2433

    
   
2474

   
2434
	switch (cmd) {
2475
	switch (cmd) {
2435
	case CLI_INIT:
2476
	case CLI_INIT:
2436
		e->command = "iax2 prune realtime";
2477
		e->command = "iax2 prune realtime";
2437
		e->usage =
2478
		e->usage =
2438
			"Usage: iax2 prune realtime [<peername>|all]\n"
2479
			"Usage: iax2 prune realtime [<peername>|all]\n"
2439
			"       Prunes object(s) from the cache\n";
2480
			"       Prunes object(s) from the cache\n";
2440
		return NULL;
2481
		return NULL;
2441
	case CLI_GENERATE:
2482
	case CLI_GENERATE:
2442
		return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2483
		return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2443
	}
2484
	}
2444

    
   
2485

   
2445
	if (a->argc != 4)
2486
	if (a->argc != 4)
2446
        return CLI_SHOWUSAGE;
2487
        return CLI_SHOWUSAGE;
2447
	if (!strcmp(a->argv[3], "all")) {
2488
	if (!strcmp(a->argv[3], "all")) {
2448
		reload_config();
2489
		reload_config();
2449
		ast_cli(a->fd, "Cache flushed successfully.\n");
2490
		ast_cli(a->fd, "Cache flushed successfully.\n");
2450
	} else if ((peer = find_peer(a->argv[3], 0))) {
2491
	} else if ((peer = find_peer(a->argv[3], 0))) {
2451
		if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2492
		if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2452
			ast_set_flag(peer, IAX_RTAUTOCLEAR);
2493
			ast_set_flag(peer, IAX_RTAUTOCLEAR);
2453
			expire_registry(peer_ref(peer));
2494
			expire_registry(peer_ref(peer));
2454
			ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2495
			ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2455
		} else {
2496
		} else {
2456
			ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2497
			ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2457
		}
2498
		}
2458
		peer_unref(peer);
2499
		peer_unref(peer);
2459
	} else {
2500
	} else {
2460
		ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2501
		ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2461
	}
2502
	}
2462
	
2503
	
2463
	return CLI_SUCCESS;
2504
	return CLI_SUCCESS;
2464
}
2505
}
2465

    
   
2506

   
2466
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2507
static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2467
{
2508
{
2468
	switch (cmd) {
2509
	switch (cmd) {
2469
	case CLI_INIT:
2510
	case CLI_INIT:
2470
		e->command = "iax2 test losspct";
2511
		e->command = "iax2 test losspct";
2471
		e->usage =
2512
		e->usage =
2472
			"Usage: iax2 test losspct <percentage>\n"
2513
			"Usage: iax2 test losspct <percentage>\n"
2473
			"       For testing, throws away <percentage> percent of incoming packets\n";
2514
			"       For testing, throws away <percentage> percent of incoming packets\n";
2474
		return NULL;
2515
		return NULL;
2475
	case CLI_GENERATE:
2516
	case CLI_GENERATE:
2476
		return NULL;
2517
		return NULL;
2477
	}
2518
	}
2478
	if (a->argc != 4)
2519
	if (a->argc != 4)
2479
		return CLI_SHOWUSAGE;
2520
		return CLI_SHOWUSAGE;
2480

    
   
2521

   
2481
	test_losspct = atoi(a->argv[3]);
2522
	test_losspct = atoi(a->argv[3]);
2482

    
   
2523

   
2483
	return CLI_SUCCESS;
2524
	return CLI_SUCCESS;
2484
}
2525
}
2485

    
   
2526

   
2486
#ifdef IAXTESTS
2527
#ifdef IAXTESTS
2487
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2528
static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2488
{
2529
{
2489
	switch (cmd) {
2530
	switch (cmd) {
2490
	case CLI_INIT:
2531
	case CLI_INIT:
2491
		e->command = "iax2 test late";
2532
		e->command = "iax2 test late";
2492
		e->usage =
2533
		e->usage =
2493
			"Usage: iax2 test late <ms>\n"
2534
			"Usage: iax2 test late <ms>\n"
2494
			"       For testing, count the next frame as <ms> ms late\n";
2535
			"       For testing, count the next frame as <ms> ms late\n";
2495
		return NULL;
2536
		return NULL;
2496
	case CLI_GENERATE:
2537
	case CLI_GENERATE:
2497
		return NULL;
2538
		return NULL;
2498
	}
2539
	}
2499

    
   
2540

   
2500
	if (a->argc != 4)
2541
	if (a->argc != 4)
2501
		return CLI_SHOWUSAGE;
2542
		return CLI_SHOWUSAGE;
2502

    
   
2543

   
2503
	test_late = atoi(a->argv[3]);
2544
	test_late = atoi(a->argv[3]);
2504

    
   
2545

   
2505
	return CLI_SUCCESS;
2546
	return CLI_SUCCESS;
2506
}
2547
}
2507

    
   
2548

   
2508
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2549
static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2509
{
2550
{
2510
	switch (cmd) {
2551
	switch (cmd) {
2511
	case CLI_INIT:
2552
	case CLI_INIT:
2512
		e->command = "iax2 test resync";
2553
		e->command = "iax2 test resync";
2513
		e->usage =
2554
		e->usage =
2514
			"Usage: iax2 test resync <ms>\n"
2555
			"Usage: iax2 test resync <ms>\n"
2515
			"       For testing, adjust all future frames by <ms> ms\n";
2556
			"       For testing, adjust all future frames by <ms> ms\n";
2516
		return NULL;
2557
		return NULL;
2517
	case CLI_GENERATE:
2558
	case CLI_GENERATE:
2518
		return NULL;
2559
		return NULL;
2519
	}
2560
	}
2520

    
   
2561

   
2521
	if (a->argc != 4)
2562
	if (a->argc != 4)
2522
		return CLI_SHOWUSAGE;
2563
		return CLI_SHOWUSAGE;
2523

    
   
2564

   
2524
	test_resync = atoi(a->argv[3]);
2565
	test_resync = atoi(a->argv[3]);
2525

    
   
2566

   
2526
	return CLI_SUCCESS;
2567
	return CLI_SUCCESS;
2527
}
2568
}
2528

    
   
2569

   
2529
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2570
static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2530
{
2571
{
2531
	switch (cmd) {
2572
	switch (cmd) {
2532
	case CLI_INIT:
2573
	case CLI_INIT:
2533
		e->command = "iax2 test jitter";
2574
		e->command = "iax2 test jitter";
2534
		e->usage =
2575
		e->usage =
2535
			"Usage: iax2 test jitter <ms> <pct>\n"
2576
			"Usage: iax2 test jitter <ms> <pct>\n"
2536
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2577
			"       For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2537
			"       percentage of packets. If <pct> is not specified, adds\n"
2578
			"       percentage of packets. If <pct> is not specified, adds\n"
2538
			"       jitter to all packets.\n";
2579
			"       jitter to all packets.\n";
2539
		return NULL;
2580
		return NULL;
2540
	case CLI_GENERATE:
2581
	case CLI_GENERATE:
2541
		return NULL;
2582
		return NULL;
2542
	}
2583
	}
2543

    
   
2584

   
2544
	if (a->argc < 4 || a->argc > 5)
2585
	if (a->argc < 4 || a->argc > 5)
2545
		return CLI_SHOWUSAGE;
2586
		return CLI_SHOWUSAGE;
2546

    
   
2587

   
2547
	test_jit = atoi(a->argv[3]);
2588
	test_jit = atoi(a->argv[3]);
2548
	if (a->argc == 5)
2589
	if (a->argc == 5)
2549
		test_jitpct = atoi(a->argv[4]);
2590
		test_jitpct = atoi(a->argv[4]);
2550

    
   
2591

   
2551
	return CLI_SUCCESS;
2592
	return CLI_SUCCESS;
2552
}
2593
}
2553
#endif /* IAXTESTS */
2594
#endif /* IAXTESTS */
2554

    
   
2595

   
2555
/*! \brief  peer_status: Report Peer status in character string */
2596
/*! \brief  peer_status: Report Peer status in character string */
2556
/* 	returns 1 if peer is online, -1 if unmonitored */
2597
/* 	returns 1 if peer is online, -1 if unmonitored */
2557
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2598
static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2558
{
2599
{
2559
	int res = 0;
2600
	int res = 0;
2560
	if (peer->maxms) {
2601
	if (peer->maxms) {
2561
		if (peer->lastms < 0) {
2602
		if (peer->lastms < 0) {
2562
			ast_copy_string(status, "UNREACHABLE", statuslen);
2603
			ast_copy_string(status, "UNREACHABLE", statuslen);
2563
		} else if (peer->lastms > peer->maxms) {
2604
		} else if (peer->lastms > peer->maxms) {
2564
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2605
			snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2565
			res = 1;
2606
			res = 1;
2566
		} else if (peer->lastms) {
2607
		} else if (peer->lastms) {
2567
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2608
			snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2568
			res = 1;
2609
			res = 1;
2569
		} else {
2610
		} else {
2570
			ast_copy_string(status, "UNKNOWN", statuslen);
2611
			ast_copy_string(status, "UNKNOWN", statuslen);
2571
		}
2612
		}
2572
	} else { 
2613
	} else { 
2573
		ast_copy_string(status, "Unmonitored", statuslen);
2614
		ast_copy_string(status, "Unmonitored", statuslen);
2574
		res = -1;
2615
		res = -1;
2575
	}
2616
	}
2576
	return res;
2617
	return res;
2577
}
2618
}
2578

    
   
2619

   
2579
/*! \brief Show one peer in detail */
2620
/*! \brief Show one peer in detail */
2580
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2621
static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2581
{
2622
{
2582
	char status[30];
2623
	char status[30];
2583
	char cbuf[256];
2624
	char cbuf[256];
2584
	struct iax2_peer *peer;
2625
	struct iax2_peer *peer;
2585
	char codec_buf[512];
2626
	char codec_buf[512];
2586
	int x = 0, codec = 0, load_realtime = 0;
2627
	int x = 0, codec = 0, load_realtime = 0;
2587

    
   
2628

   
2588
	switch (cmd) {
2629
	switch (cmd) {
2589
	case CLI_INIT:
2630
	case CLI_INIT:
2590
		e->command = "iax2 show peer";
2631
		e->command = "iax2 show peer";
2591
		e->usage =
2632
		e->usage =
2592
			"Usage: iax2 show peer <name>\n"
2633
			"Usage: iax2 show peer <name>\n"
2593
			"       Display details on specific IAX peer\n";
2634
			"       Display details on specific IAX peer\n";
2594
		return NULL;
2635
		return NULL;
2595
	case CLI_GENERATE:
2636
	case CLI_GENERATE:
2596
		return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2637
		return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2597
	}
2638
	}
2598

    
   
2639

   
2599
	if (a->argc < 4)
2640
	if (a->argc < 4)
2600
		return CLI_SHOWUSAGE;
2641
		return CLI_SHOWUSAGE;
2601

    
   
2642

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

    
   
2644

   
2604
	peer = find_peer(a->argv[3], load_realtime);
2645
	peer = find_peer(a->argv[3], load_realtime);
2605
	if (peer) {
2646
	if (peer) {
2606
		ast_cli(a->fd, "\n\n");
2647
		ast_cli(a->fd, "\n\n");
2607
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
2648
		ast_cli(a->fd, "  * Name       : %s\n", peer->name);
2608
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2649
		ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2609
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
2650
		ast_cli(a->fd, "  Context      : %s\n", peer->context);
2610
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
2651
		ast_cli(a->fd, "  Mailbox      : %s\n", peer->mailbox);
2611
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2652
		ast_cli(a->fd, "  Dynamic      : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2612
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2653
		ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2613
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
2654
		ast_cli(a->fd, "  Expire       : %d\n", peer->expire);
2614
		ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
2655
		ast_cli(a->fd, "  ACL          : %s\n", (peer->ha ? "Yes" : "No"));
2615
		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));
2656
		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));
2616
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2657
		ast_cli(a->fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2617
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
2658
		ast_cli(a->fd, "  Username     : %s\n", peer->username);
2618
		ast_cli(a->fd, "  Codecs       : ");
2659
		ast_cli(a->fd, "  Codecs       : ");
2619
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2660
		ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2620
		ast_cli(a->fd, "%s\n", codec_buf);
2661
		ast_cli(a->fd, "%s\n", codec_buf);
2621

    
   
2662

   
2622
		ast_cli(a->fd, "  Codec Order  : (");
2663
		ast_cli(a->fd, "  Codec Order  : (");
2623
		for(x = 0; x < 32 ; x++) {
2664
		for(x = 0; x < 32 ; x++) {
2624
			codec = ast_codec_pref_index(&peer->prefs,x);
2665
			codec = ast_codec_pref_index(&peer->prefs,x);
2625
			if(!codec)
2666
			if(!codec)
2626
				break;
2667
				break;
2627
			ast_cli(a->fd, "%s", ast_getformatname(codec));
2668
			ast_cli(a->fd, "%s", ast_getformatname(codec));
2628
			if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2669
			if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2629
				ast_cli(a->fd, "|");
2670
				ast_cli(a->fd, "|");
2630
		}
2671
		}
2631

    
   
2672

   
2632
		if (!x)
2673
		if (!x)
2633
			ast_cli(a->fd, "none");
2674
			ast_cli(a->fd, "none");
2634
		ast_cli(a->fd, ")\n");
2675
		ast_cli(a->fd, ")\n");
2635

    
   
2676

   
2636
		ast_cli(a->fd, "  Status       : ");
2677
		ast_cli(a->fd, "  Status       : ");
2637
		peer_status(peer, status, sizeof(status));	
2678
		peer_status(peer, status, sizeof(status));	
2638
		ast_cli(a->fd, "%s\n",status);
2679
		ast_cli(a->fd, "%s\n",status);
2639
		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");
2680
		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");
2640
		ast_cli(a->fd, "\n");
2681
		ast_cli(a->fd, "\n");
2641
		peer_unref(peer);
2682
		peer_unref(peer);
2642
	} else {
2683
	} else {
2643
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2684
		ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2644
		ast_cli(a->fd, "\n");
2685
		ast_cli(a->fd, "\n");
2645
	}
2686
	}
2646

    
   
2687

   
2647
	return CLI_SUCCESS;
2688
	return CLI_SUCCESS;
2648
}
2689
}
2649

    
   
2690

   
2650
static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2691
static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2651
{
2692
{
2652
	int which = 0;
2693
	int which = 0;
2653
	struct iax2_peer *peer;
2694
	struct iax2_peer *peer;
2654
	char *res = NULL;
2695
	char *res = NULL;
2655
	int wordlen = strlen(word);
2696
	int wordlen = strlen(word);
2656
	struct ao2_iterator i;
2697
	struct ao2_iterator i;
2657

    
   
2698

   
2658
	/* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2699
	/* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2659
	if (pos != 3)
2700
	if (pos != 3)
2660
		return NULL;
2701
		return NULL;
2661

    
   
2702

   
2662
	i = ao2_iterator_init(peers, 0);
2703
	i = ao2_iterator_init(peers, 0);
2663
	while ((peer = ao2_iterator_next(&i))) {
2704
	while ((peer = ao2_iterator_next(&i))) {
2664
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2705
		if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2665
			res = ast_strdup(peer->name);
2706
			res = ast_strdup(peer->name);
2666
			peer_unref(peer);
2707
			peer_unref(peer);
2667
			break;
2708
			break;
2668
		}
2709
		}
2669
		peer_unref(peer);
2710
		peer_unref(peer);
2670
	}
2711
	}
2671

    
   
2712

   
2672
	return res;
2713
	return res;
2673
}
2714
}
2674

    
   
2715

   
2675
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2716
static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2676
{
2717
{
2677
	struct iax_frame *cur;
2718
	struct iax_frame *cur;
2678
	int cnt = 0, dead = 0, final = 0;
2719
	int cnt = 0, dead = 0, final = 0;
2679

    
   
2720

   
2680
	switch (cmd) {
2721
	switch (cmd) {
2681
	case CLI_INIT:
2722
	case CLI_INIT:
2682
		e->command = "iax2 show stats";
2723
		e->command = "iax2 show stats";
2683
		e->usage =
2724
		e->usage =
2684
			"Usage: iax2 show stats\n"
2725
			"Usage: iax2 show stats\n"
2685
			"       Display statistics on IAX channel driver.\n";
2726
			"       Display statistics on IAX channel driver.\n";
2686
		return NULL;
2727
		return NULL;
2687
	case CLI_GENERATE:
2728
	case CLI_GENERATE:
2688
		return NULL;
2729
		return NULL;
2689
	}
2730
	}
2690

    
   
2731

   
2691
	if (a->argc != 3)
2732
	if (a->argc != 3)
2692
		return CLI_SHOWUSAGE;
2733
		return CLI_SHOWUSAGE;
2693

    
   
2734

   
2694
	AST_LIST_LOCK(&frame_queue);
2735
	AST_LIST_LOCK(&frame_queue);
2695
	AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2736
	AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2696
		if (cur->retries < 0)
2737
		if (cur->retries < 0)
2697
			dead++;
2738
			dead++;
2698
		if (cur->final)
2739
		if (cur->final)
2699
			final++;
2740
			final++;
2700
		cnt++;
2741
		cnt++;
2701
	}
2742
	}
2702
	AST_LIST_UNLOCK(&frame_queue);
2743
	AST_LIST_UNLOCK(&frame_queue);
2703

    
   
2744

   
2704
	ast_cli(a->fd, "    IAX Statistics\n");
2745
	ast_cli(a->fd, "    IAX Statistics\n");
2705
	ast_cli(a->fd, "---------------------\n");
2746
	ast_cli(a->fd, "---------------------\n");
2706
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2747
	ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2707
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2748
	ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2708
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2749
		trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2709
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2750
	ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2710

    
   
2751

   
2711
	trunk_timed = trunk_untimed = 0;
2752
	trunk_timed = trunk_untimed = 0;
2712
	if (trunk_maxmtu > trunk_nmaxmtu)
2753
	if (trunk_maxmtu > trunk_nmaxmtu)
2713
		trunk_nmaxmtu = trunk_maxmtu;
2754
		trunk_nmaxmtu = trunk_maxmtu;
2714

    
   
2755

   
2715
	return CLI_SUCCESS;
2756
	return CLI_SUCCESS;
2716
}
2757
}
2717

    
   
2758

   
2718
/*! \brief Set trunk MTU from CLI */
2759
/*! \brief Set trunk MTU from CLI */
2719
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2760
static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2720
{
2761
{
2721
	int mtuv;
2762
	int mtuv;
2722

    
   
2763

   
2723
	switch (cmd) {
2764
	switch (cmd) {
2724
	case CLI_INIT:
2765
	case CLI_INIT:
2725
		e->command = "iax2 set mtu";
2766
		e->command = "iax2 set mtu";
2726
		e->usage =
2767
		e->usage =
2727
			"Usage: iax2 set mtu <value>\n"
2768
			"Usage: iax2 set mtu <value>\n"
2728
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
2769
			"       Set the system-wide IAX IP mtu to <value> bytes net or\n"
2729
			"       zero to disable. Disabling means that the operating system\n"
2770
			"       zero to disable. Disabling means that the operating system\n"
2730
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
2771
			"       must handle fragmentation of UDP packets when the IAX2 trunk\n"
2731
			"       packet exceeds the UDP payload size. This is substantially\n"
2772
			"       packet exceeds the UDP payload size. This is substantially\n"
2732
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2773
			"       below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2733
			"       greater for G.711 samples.\n";
2774
			"       greater for G.711 samples.\n";
2734
		return NULL;
2775
		return NULL;
2735
	case CLI_GENERATE:
2776
	case CLI_GENERATE:
2736
		return NULL;
2777
		return NULL;
2737
	}
2778
	}
2738

    
   
2779

   
2739
	if (a->argc != 4)
2780
	if (a->argc != 4)
2740
		return CLI_SHOWUSAGE; 
2781
		return CLI_SHOWUSAGE; 
2741
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2782
	if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2742
		mtuv = MAX_TRUNK_MTU;
2783
		mtuv = MAX_TRUNK_MTU;
2743
	else
2784
	else
2744
		mtuv = atoi(a->argv[3]);
2785
		mtuv = atoi(a->argv[3]);
2745

    
   
2786

   
2746
	if (mtuv == 0) {
2787
	if (mtuv == 0) {
2747
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
2788
		ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu); 
2748
		global_max_trunk_mtu = 0; 
2789
		global_max_trunk_mtu = 0; 
2749
		return CLI_SUCCESS; 
2790
		return CLI_SUCCESS; 
2750
	}
2791
	}
2751
	if (mtuv < 172 || mtuv > 4000) {
2792
	if (mtuv < 172 || mtuv > 4000) {
2752
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
2793
		ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n"); 
2753
		return CLI_SHOWUSAGE; 
2794
		return CLI_SHOWUSAGE; 
2754
	}
2795
	}
2755
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
2796
	ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv); 
2756
	global_max_trunk_mtu = mtuv; 
2797
	global_max_trunk_mtu = mtuv; 
2757
	return CLI_SUCCESS;
2798
	return CLI_SUCCESS;
2758
}
2799
}
2759

    
   
2800

   
2760
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2801
static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2761
{
2802
{
2762
	struct iax2_dpcache *dp = NULL;
2803
	struct iax2_dpcache *dp = NULL;
2763
	char tmp[1024], *pc = NULL;
2804
	char tmp[1024], *pc = NULL;
2764
	int s, x, y;
2805
	int s, x, y;
2765
	struct timeval tv = ast_tvnow();
2806
	struct timeval tv = ast_tvnow();
2766

    
   
2807

   
2767
	switch (cmd) {
2808
	switch (cmd) {
2768
	case CLI_INIT:
2809
	case CLI_INIT:
2769
		e->command = "iax2 show cache";
2810
		e->command = "iax2 show cache";
2770
		e->usage =
2811
		e->usage =
2771
			"Usage: iax2 show cache\n"
2812
			"Usage: iax2 show cache\n"
2772
			"       Display currently cached IAX Dialplan results.\n";
2813
			"       Display currently cached IAX Dialplan results.\n";
2773
		return NULL;
2814
		return NULL;
2774
	case CLI_GENERATE:
2815
	case CLI_GENERATE:
2775
		return NULL;
2816
		return NULL;
2776
	}
2817
	}
2777

    
   
2818

   
2778
	AST_LIST_LOCK(&dpcache);
2819
	AST_LIST_LOCK(&dpcache);
2779

    
   
2820

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

    
   
2822

   
2782
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2823
	AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2783
		s = dp->expiry.tv_sec - tv.tv_sec;
2824
		s = dp->expiry.tv_sec - tv.tv_sec;
2784
		tmp[0] = '\0';
2825
		tmp[0] = '\0';
2785
		if (dp->flags & CACHE_FLAG_EXISTS)
2826
		if (dp->flags & CACHE_FLAG_EXISTS)
2786
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2827
			strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2787
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
2828
		if (dp->flags & CACHE_FLAG_NONEXISTENT)
2788
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2829
			strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2789
		if (dp->flags & CACHE_FLAG_CANEXIST)
2830
		if (dp->flags & CACHE_FLAG_CANEXIST)
2790
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2831
			strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2791
		if (dp->flags & CACHE_FLAG_PENDING)
2832
		if (dp->flags & CACHE_FLAG_PENDING)
2792
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2833
			strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2793
		if (dp->flags & CACHE_FLAG_TIMEOUT)
2834
		if (dp->flags & CACHE_FLAG_TIMEOUT)
2794
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2835
			strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2795
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
2836
		if (dp->flags & CACHE_FLAG_TRANSMITTED)
2796
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2837
			strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2797
		if (dp->flags & CACHE_FLAG_MATCHMORE)
2838
		if (dp->flags & CACHE_FLAG_MATCHMORE)
2798
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2839
			strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2799
		if (dp->flags & CACHE_FLAG_UNKNOWN)
2840
		if (dp->flags & CACHE_FLAG_UNKNOWN)
2800
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2841
			strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2801
		/* Trim trailing pipe */
2842
		/* Trim trailing pipe */
2802
		if (!ast_strlen_zero(tmp)) {
2843
		if (!ast_strlen_zero(tmp)) {
2803
			tmp[strlen(tmp) - 1] = '\0';
2844
			tmp[strlen(tmp) - 1] = '\0';
2804
		} else {
2845
		} else {
2805
			ast_copy_string(tmp, "(none)", sizeof(tmp));
2846
			ast_copy_string(tmp, "(none)", sizeof(tmp));
2806
		}
2847
		}
2807
		y = 0;
2848
		y = 0;
2808
		pc = strchr(dp->peercontext, '@');
2849
		pc = strchr(dp->peercontext, '@');
2809
		if (!pc) {
2850
		if (!pc) {
2810
			pc = dp->peercontext;
2851
			pc = dp->peercontext;
2811
		} else {
2852
		} else {
2812
			pc++;
2853
			pc++;
2813
		}
2854
		}
2814
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
2855
		for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
2815
			if (dp->waiters[x] > -1)
2856
			if (dp->waiters[x] > -1)
2816
				y++;
2857
				y++;
2817
		}
2858
		}
2818
		if (s > 0) {
2859
		if (s > 0) {
2819
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2860
			ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2820
		} else {
2861
		} else {
2821
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2862
			ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2822
		}
2863
		}
2823
	}
2864
	}
2824

    
   
2865

   
2825
	AST_LIST_LOCK(&dpcache);
2866
	AST_LIST_LOCK(&dpcache);
2826

    
   
2867

   
2827
	return CLI_SUCCESS;
2868
	return CLI_SUCCESS;
2828
}
2869
}
2829

    
   
2870

   
2830
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2871
static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2831

    
   
2872

   
2832
static void unwrap_timestamp(struct iax_frame *fr)
2873
static void unwrap_timestamp(struct iax_frame *fr)
2833
{
2874
{
2834
	/* Video mini frames only encode the lower 15 bits of the session
2875
	/* Video mini frames only encode the lower 15 bits of the session
2835
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
2876
	 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
2836
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
2877
	const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
2837
	const int lower_mask = (1 << ts_shift) - 1;
2878
	const int lower_mask = (1 << ts_shift) - 1;
2838
	const int upper_mask = ~lower_mask;
2879
	const int upper_mask = ~lower_mask;
2839
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
2880
	const int last_upper = iaxs[fr->callno]->last & upper_mask;
2840

    
   
2881

   
2841
	if ( (fr->ts & upper_mask) == last_upper ) {
2882
	if ( (fr->ts & upper_mask) == last_upper ) {
2842
		const int x = fr->ts - iaxs[fr->callno]->last;
2883
		const int x = fr->ts - iaxs[fr->callno]->last;
2843
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
2884
		const int threshold = (ts_shift == 15) ? 25000 : 50000;
2844

    
   
2885

   
2845
		if (x < -threshold) {
2886
		if (x < -threshold) {
2846
			/* Sudden big jump backwards in timestamp:
2887
			/* Sudden big jump backwards in timestamp:
2847
			   What likely happened here is that miniframe timestamp has circled but we haven't
2888
			   What likely happened here is that miniframe timestamp has circled but we haven't
2848
			   gotten the update from the main packet.  We'll just pretend that we did, and
2889
			   gotten the update from the main packet.  We'll just pretend that we did, and
2849
			   update the timestamp appropriately. */
2890
			   update the timestamp appropriately. */
2850
			fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
2891
			fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
2851
			if (iaxdebug)
2892
			if (iaxdebug)
2852
				ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2893
				ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2853
		} else if (x > threshold) {
2894
		} else if (x > threshold) {
2854
			/* Sudden apparent big jump forwards in timestamp:
2895
			/* Sudden apparent big jump forwards in timestamp:
2855
			   What's likely happened is this is an old miniframe belonging to the previous
2896
			   What's likely happened is this is an old miniframe belonging to the previous
2856
			   top 15 or 16-bit timestamp that has turned up out of order.
2897
			   top 15 or 16-bit timestamp that has turned up out of order.
2857
			   Adjust the timestamp appropriately. */
2898
			   Adjust the timestamp appropriately. */
2858
			fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
2899
			fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
2859
			if (iaxdebug)
2900
			if (iaxdebug)
2860
				ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2901
				ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2861
		}
2902
		}
2862
	}
2903
	}
2863
}
2904
}
2864

    
   
2905

   
2865
static int get_from_jb(const void *p);
2906
static int get_from_jb(const void *p);
2866

    
   
2907

   
2867
static void update_jbsched(struct chan_iax2_pvt *pvt)
2908
static void update_jbsched(struct chan_iax2_pvt *pvt)
2868
{
2909
{
2869
	int when;
2910
	int when;
2870
	
2911
	
2871
	when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2912
	when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2872
	
2913
	
2873
	when = jb_next(pvt->jb) - when;
2914
	when = jb_next(pvt->jb) - when;
2874

    
   
2915

   
2875
	if (when <= 0) {
2916
	if (when <= 0) {
2876
		/* XXX should really just empty until when > 0.. */
2917
		/* XXX should really just empty until when > 0.. */
2877
		when = 1;
2918
		when = 1;
2878
	}
2919
	}
2879
	
2920
	
2880
	pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
2921
	pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb, 
2881
		CALLNO_TO_PTR(pvt->callno));
2922
		CALLNO_TO_PTR(pvt->callno));
2882
}
2923
}
2883

    
   
2924

   
2884
static void __get_from_jb(const void *p) 
2925
static void __get_from_jb(const void *p) 
2885
{
2926
{
2886
	int callno = PTR_TO_CALLNO(p);
2927
	int callno = PTR_TO_CALLNO(p);
2887
	struct chan_iax2_pvt *pvt = NULL;
2928
	struct chan_iax2_pvt *pvt = NULL;
2888
	struct iax_frame *fr;
2929
	struct iax_frame *fr;
2889
	jb_frame frame;
2930
	jb_frame frame;
2890
	int ret;
2931
	int ret;
2891
	long now;
2932
	long now;
2892
	long next;
2933
	long next;
2893
	struct timeval tv = ast_tvnow();
2934
	struct timeval tv = ast_tvnow();
2894
	
2935
	
2895
	/* Make sure we have a valid private structure before going on */
2936
	/* Make sure we have a valid private structure before going on */
2896
	ast_mutex_lock(&iaxsl[callno]);
2937
	ast_mutex_lock(&iaxsl[callno]);
2897
	pvt = iaxs[callno];
2938
	pvt = iaxs[callno];
2898
	if (!pvt) {
2939
	if (!pvt) {
2899
		/* No go! */
2940
		/* No go! */
2900
		ast_mutex_unlock(&iaxsl[callno]);
2941
		ast_mutex_unlock(&iaxsl[callno]);
2901
		return;
2942
		return;
2902
	}
2943
	}
2903

    
   
2944

   
2904
	pvt->jbid = -1;
2945
	pvt->jbid = -1;
2905
	
2946
	
2906
	/* round up a millisecond since ast_sched_runq does; */
2947
	/* round up a millisecond since ast_sched_runq does; */
2907
	/* prevents us from spinning while waiting for our now */
2948
	/* prevents us from spinning while waiting for our now */
2908
	/* to catch up with runq's now */
2949
	/* to catch up with runq's now */
2909
	tv.tv_usec += 1000;
2950
	tv.tv_usec += 1000;
2910
	
2951
	
2911
	now = ast_tvdiff_ms(tv, pvt->rxcore);
2952
	now = ast_tvdiff_ms(tv, pvt->rxcore);
2912
	
2953
	
2913
	if(now >= (next = jb_next(pvt->jb))) {
2954
	if(now >= (next = jb_next(pvt->jb))) {
2914
		ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2955
		ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2915
		switch(ret) {
2956
		switch(ret) {
2916
		case JB_OK:
2957
		case JB_OK:
2917
			fr = frame.data;
2958
			fr = frame.data;
2918
			__do_deliver(fr);
2959
			__do_deliver(fr);
2919
			/* __do_deliver() can cause the call to disappear */
2960
			/* __do_deliver() can cause the call to disappear */
2920
			pvt = iaxs[callno];
2961
			pvt = iaxs[callno];
2921
			break;
2962
			break;
2922
		case JB_INTERP:
2963
		case JB_INTERP:
2923
		{
2964
		{
2924
			struct ast_frame af = { 0, };
2965
			struct ast_frame af = { 0, };
2925
			
2966
			
2926
			/* create an interpolation frame */
2967
			/* create an interpolation frame */
2927
			af.frametype = AST_FRAME_VOICE;
2968
			af.frametype = AST_FRAME_VOICE;
2928
			af.subclass = pvt->voiceformat;
2969
			af.subclass = pvt->voiceformat;
2929
			af.samples  = frame.ms * 8;
2970
			af.samples  = frame.ms * 8;
2930
			af.src  = "IAX2 JB interpolation";
2971
			af.src  = "IAX2 JB interpolation";
2931
			af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2972
			af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2932
			af.offset = AST_FRIENDLY_OFFSET;
2973
			af.offset = AST_FRIENDLY_OFFSET;
2933
			
2974
			
2934
			/* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2975
			/* queue the frame:  For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2935
			 * which we'd need to malloc, and then it would free it.  That seems like a drag */
2976
			 * which we'd need to malloc, and then it would free it.  That seems like a drag */
2936
			if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2977
			if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2937
				iax2_queue_frame(callno, &af);
2978
				iax2_queue_frame(callno, &af);
2938
				/* iax2_queue_frame() could cause the call to disappear */
2979
				/* iax2_queue_frame() could cause the call to disappear */
2939
				pvt = iaxs[callno];
2980
				pvt = iaxs[callno];
2940
			}
2981
			}
2941
		}
2982
		}
2942
			break;
2983
			break;
2943
		case JB_DROP:
2984
		case JB_DROP:
2944
			iax2_frame_free(frame.data);
2985
			iax2_frame_free(frame.data);
2945
			break;
2986
			break;
2946
		case JB_NOFRAME:
2987
		case JB_NOFRAME:
2947
		case JB_EMPTY:
2988
		case JB_EMPTY:
2948
			/* do nothing */
2989
			/* do nothing */
2949
			break;
2990
			break;
2950
		default:
2991
		default:
2951
			/* shouldn't happen */
2992
			/* shouldn't happen */
2952
			break;
2993
			break;
2953
		}
2994
		}
2954
	}
2995
	}
2955
	if (pvt)
2996
	if (pvt)
2956
		update_jbsched(pvt);
2997
		update_jbsched(pvt);
2957
	ast_mutex_unlock(&iaxsl[callno]);
2998
	ast_mutex_unlock(&iaxsl[callno]);
2958
}
2999
}
2959

    
   
3000

   
2960
static int get_from_jb(const void *data)
3001
static int get_from_jb(const void *data)
2961
{
3002
{
2962
#ifdef SCHED_MULTITHREADED
3003
#ifdef SCHED_MULTITHREADED
2963
	if (schedule_action(__get_from_jb, data))
3004
	if (schedule_action(__get_from_jb, data))
2964
#endif		
3005
#endif		
2965
		__get_from_jb(data);
3006
		__get_from_jb(data);
2966
	return 0;
3007
	return 0;
2967
}
3008
}
2968

    
   
3009

   
2969
/*!
3010
/*!
2970
 * \note This function assumes fr->callno is locked
3011
 * \note This function assumes fr->callno is locked
2971
 *
3012
 *
2972
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3013
 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2973
 * was valid before calling it, it may no longer be valid after calling it.
3014
 * was valid before calling it, it may no longer be valid after calling it.
2974
 */
3015
 */
2975
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
3016
static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2976
{
3017
{
2977
	int type, len;
3018
	int type, len;
2978
	int ret;
3019
	int ret;
2979
	int needfree = 0;
3020
	int needfree = 0;
2980
	struct ast_channel *owner = NULL;
3021
	struct ast_channel *owner = NULL;
2981
	struct ast_channel *bridge = NULL;
3022
	struct ast_channel *bridge = NULL;
2982
	
3023
	
2983
	/* Attempt to recover wrapped timestamps */
3024
	/* Attempt to recover wrapped timestamps */
2984
	unwrap_timestamp(fr);
3025
	unwrap_timestamp(fr);
2985

    
   
3026

   
2986
	/* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
3027
	/* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2987
	if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
3028
	if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2988
		fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
3029
		fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2989
	else {
3030
	else {
2990
#if 0
3031
#if 0
2991
		ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
3032
		ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2992
#endif
3033
#endif
2993
		fr->af.delivery = ast_tv(0,0);
3034
		fr->af.delivery = ast_tv(0,0);
2994
	}
3035
	}
2995

    
   
3036

   
2996
	type = JB_TYPE_CONTROL;
3037
	type = JB_TYPE_CONTROL;
2997
	len = 0;
3038
	len = 0;
2998

    
   
3039

   
2999
	if(fr->af.frametype == AST_FRAME_VOICE) {
3040
	if(fr->af.frametype == AST_FRAME_VOICE) {
3000
		type = JB_TYPE_VOICE;
3041
		type = JB_TYPE_VOICE;
3001
		len = ast_codec_get_samples(&fr->af) / 8;
3042
		len = ast_codec_get_samples(&fr->af) / 8;
3002
	} else if(fr->af.frametype == AST_FRAME_CNG) {
3043
	} else if(fr->af.frametype == AST_FRAME_CNG) {
3003
		type = JB_TYPE_SILENCE;
3044
		type = JB_TYPE_SILENCE;
3004
	}
3045
	}
3005

    
   
3046

   
3006
	if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
3047
	if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
3007
		if (tsout)
3048
		if (tsout)
3008
			*tsout = fr->ts;
3049
			*tsout = fr->ts;
3009
		__do_deliver(fr);
3050
		__do_deliver(fr);
3010
		return -1;
3051
		return -1;
3011
	}
3052
	}
3012

    
   
3053

   
3013
	if ((owner = iaxs[fr->callno]->owner))
3054
	if ((owner = iaxs[fr->callno]->owner))
3014
		bridge = ast_bridged_channel(owner);
3055
		bridge = ast_bridged_channel(owner);
3015

    
   
3056

   
3016
	/* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
3057
	/* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
3017
	 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
3058
	 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
3018
	if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
3059
	if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
3019
		jb_frame frame;
3060
		jb_frame frame;
3020

    
   
3061

   
3021
		/* deliver any frames in the jb */
3062
		/* deliver any frames in the jb */
3022
		while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
3063
		while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
3023
			__do_deliver(frame.data);
3064
			__do_deliver(frame.data);
3024
			/* __do_deliver() can make the call disappear */
3065
			/* __do_deliver() can make the call disappear */
3025
			if (!iaxs[fr->callno])
3066
			if (!iaxs[fr->callno])
3026
				return -1;
3067
				return -1;
3027
		}
3068
		}
3028

    
   
3069

   
3029
		jb_reset(iaxs[fr->callno]->jb);
3070
		jb_reset(iaxs[fr->callno]->jb);
3030

    
   
3071

   
3031
		AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
3072
		AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
3032

    
   
3073

   
3033
		/* deliver this frame now */
3074
		/* deliver this frame now */
3034
		if (tsout)
3075
		if (tsout)
3035
			*tsout = fr->ts;
3076
			*tsout = fr->ts;
3036
		__do_deliver(fr);
3077
		__do_deliver(fr);
3037
		return -1;
3078
		return -1;
3038
	}
3079
	}
3039

    
   
3080

   
3040
	/* insert into jitterbuffer */
3081
	/* insert into jitterbuffer */
3041
	/* TODO: Perhaps we could act immediately if it's not droppable and late */
3082
	/* TODO: Perhaps we could act immediately if it's not droppable and late */
3042
	ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
3083
	ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
3043
			calc_rxstamp(iaxs[fr->callno],fr->ts));
3084
			calc_rxstamp(iaxs[fr->callno],fr->ts));
3044
	if (ret == JB_DROP) {
3085
	if (ret == JB_DROP) {
3045
		needfree++;
3086
		needfree++;
3046
	} else if (ret == JB_SCHED) {
3087
	} else if (ret == JB_SCHED) {
3047
		update_jbsched(iaxs[fr->callno]);
3088
		update_jbsched(iaxs[fr->callno]);
3048
	}
3089
	}
3049
	if (tsout)
3090
	if (tsout)
3050
		*tsout = fr->ts;
3091
		*tsout = fr->ts;
3051
	if (needfree) {
3092
	if (needfree) {
3052
		/* Free our iax frame */
3093
		/* Free our iax frame */
3053
		iax2_frame_free(fr);
3094
		iax2_frame_free(fr);
3054
		return -1;
3095
		return -1;
3055
	}
3096
	}
3056
	return 0;
3097
	return 0;
3057
}
3098
}
3058

    
   
3099

   
3059
static int iax2_transmit(struct iax_frame *fr)
3100
static int iax2_transmit(struct iax_frame *fr)
3060
{
3101
{
3061
	/* Lock the queue and place this packet at the end */
3102
	/* Lock the queue and place this packet at the end */
3062
	/* By setting this to 0, the network thread will send it for us, and
3103
	/* By setting this to 0, the network thread will send it for us, and
3063
	   queue retransmission if necessary */
3104
	   queue retransmission if necessary */
3064
	fr->sentyet = 0;
3105
	fr->sentyet = 0;
3065
	AST_LIST_LOCK(&frame_queue);
3106
	AST_LIST_LOCK(&frame_queue);
3066
	AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
3107
	AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
3067
	AST_LIST_UNLOCK(&frame_queue);
3108
	AST_LIST_UNLOCK(&frame_queue);
3068
	/* Wake up the network and scheduler thread */
3109
	/* Wake up the network and scheduler thread */
3069
	if (netthreadid != AST_PTHREADT_NULL)
3110
	if (netthreadid != AST_PTHREADT_NULL)
3070
		pthread_kill(netthreadid, SIGURG);
3111
		pthread_kill(netthreadid, SIGURG);
3071
	signal_condition(&sched_lock, &sched_cond);
3112
	signal_condition(&sched_lock, &sched_cond);
3072
	return 0;
3113
	return 0;
3073
}
3114
}
3074

    
   
3115

   
3075

    
   
3116

   
3076

    
   
3117

   
3077
static int iax2_digit_begin(struct ast_channel *c, char digit)
3118
static int iax2_digit_begin(struct ast_channel *c, char digit)
3078
{
3119
{
3079
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
3120
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
3080
}
3121
}
3081

    
   
3122

   
3082
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
3123
static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
3083
{
3124
{
3084
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
3125
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
3085
}
3126
}
3086

    
   
3127

   
3087
static int iax2_sendtext(struct ast_channel *c, const char *text)
3128
static int iax2_sendtext(struct ast_channel *c, const char *text)
3088
{
3129
{
3089
	
3130
	
3090
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
3131
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
3091
		0, 0, (unsigned char *)text, strlen(text) + 1, -1);
3132
		0, 0, (unsigned char *)text, strlen(text) + 1, -1);
3092
}
3133
}
3093

    
   
3134

   
3094
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
3135
static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
3095
{
3136
{
3096
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
3137
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
3097
}
3138
}
3098

    
   
3139

   
3099
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
3140
static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
3100
{
3141
{
3101
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
3142
	return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
3102
}
3143
}
3103

    
   
3144

   
3104
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
3145
static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
3105
{
3146
{
3106
	unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
3147
	unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
3107
	ast_mutex_lock(&iaxsl[callno]);
3148
	ast_mutex_lock(&iaxsl[callno]);
3108
	if (iaxs[callno])
3149
	if (iaxs[callno])
3109
		iaxs[callno]->owner = newchan;
3150
		iaxs[callno]->owner = newchan;
3110
	else
3151
	else
3111
		ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
3152
		ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
3112
	ast_mutex_unlock(&iaxsl[callno]);
3153
	ast_mutex_unlock(&iaxsl[callno]);
3113
	return 0;
3154
	return 0;
3114
}
3155
}
3115

    
   
3156

   
3116
/*!
3157
/*!
3117
 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3158
 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3118
 *       so do not call this with a pvt lock held.
3159
 *       so do not call this with a pvt lock held.
3119
 */
3160
 */
3120
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
3161
static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
3121
{
3162
{
3122
	struct ast_variable *var = NULL;
3163
	struct ast_variable *var = NULL;
3123
	struct ast_variable *tmp;
3164
	struct ast_variable *tmp;
3124
	struct iax2_peer *peer=NULL;
3165
	struct iax2_peer *peer=NULL;
3125
	time_t regseconds = 0, nowtime;
3166
	time_t regseconds = 0, nowtime;
3126
	int dynamic=0;
3167
	int dynamic=0;
3127

    
   
3168

   
3128
	if (peername) {
3169
	if (peername) {
3129
		var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
3170
		var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
3130
		if (!var && sin)
3171
		if (!var && sin)
3131
			var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3172
			var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3132
	} else if (sin) {
3173
	} else if (sin) {
3133
		char porta[25];
3174
		char porta[25];
3134
		sprintf(porta, "%d", ntohs(sin->sin_port));
3175
		sprintf(porta, "%d", ntohs(sin->sin_port));
3135
		var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3176
		var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3136
		if (var) {
3177
		if (var) {
3137
			/* We'll need the peer name in order to build the structure! */
3178
			/* We'll need the peer name in order to build the structure! */
3138
			for (tmp = var; tmp; tmp = tmp->next) {
3179
			for (tmp = var; tmp; tmp = tmp->next) {
3139
				if (!strcasecmp(tmp->name, "name"))
3180
				if (!strcasecmp(tmp->name, "name"))
3140
					peername = tmp->value;
3181
					peername = tmp->value;
3141
			}
3182
			}
3142
		}
3183
		}
3143
	}
3184
	}
3144
	if (!var && peername) { /* Last ditch effort */
3185
	if (!var && peername) { /* Last ditch effort */
3145
		var = ast_load_realtime("iaxpeers", "name", peername, NULL);
3186
		var = ast_load_realtime("iaxpeers", "name", peername, NULL);
3146
		/*!\note
3187
		/*!\note
3147
		 * If this one loaded something, then we need to ensure that the host
3188
		 * If this one loaded something, then we need to ensure that the host
3148
		 * field matched.  The only reason why we can't have this as a criteria
3189
		 * field matched.  The only reason why we can't have this as a criteria
3149
		 * is because we only have the IP address and the host field might be
3190
		 * is because we only have the IP address and the host field might be
3150
		 * set as a name (and the reverse PTR might not match).
3191
		 * set as a name (and the reverse PTR might not match).
3151
		 */
3192
		 */
3152
		if (var && sin) {
3193
		if (var && sin) {
3153
			for (tmp = var; tmp; tmp = tmp->next) {
3194
			for (tmp = var; tmp; tmp = tmp->next) {
3154
				if (!strcasecmp(tmp->name, "host")) {
3195
				if (!strcasecmp(tmp->name, "host")) {
3155
					struct ast_hostent ahp;
3196
					struct ast_hostent ahp;
3156
					struct hostent *hp;
3197
					struct hostent *hp;
3157
					if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3198
					if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3158
						/* No match */
3199
						/* No match */
3159
						ast_variables_destroy(var);
3200
						ast_variables_destroy(var);
3160
						var = NULL;
3201
						var = NULL;
3161
					}
3202
					}
3162
					break;
3203
					break;
3163
				}
3204
				}
3164
			}
3205
			}
3165
		}
3206
		}
3166
	}
3207
	}
3167
	if (!var)
3208
	if (!var)
3168
		return NULL;
3209
		return NULL;
3169

    
   
3210

   
3170
	peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
3211
	peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
3171
	
3212
	
3172
	if (!peer) {
3213
	if (!peer) {
3173
		ast_variables_destroy(var);
3214
		ast_variables_destroy(var);
3174
		return NULL;
3215
		return NULL;
3175
	}
3216
	}
3176

    
   
3217

   
3177
	for (tmp = var; tmp; tmp = tmp->next) {
3218
	for (tmp = var; tmp; tmp = tmp->next) {
3178
		/* Make sure it's not a user only... */
3219
		/* Make sure it's not a user only... */
3179
		if (!strcasecmp(tmp->name, "type")) {
3220
		if (!strcasecmp(tmp->name, "type")) {
3180
			if (strcasecmp(tmp->value, "friend") &&
3221
			if (strcasecmp(tmp->value, "friend") &&
3181
			    strcasecmp(tmp->value, "peer")) {
3222
			    strcasecmp(tmp->value, "peer")) {
3182
				/* Whoops, we weren't supposed to exist! */
3223
				/* Whoops, we weren't supposed to exist! */
3183
				peer = peer_unref(peer);
3224
				peer = peer_unref(peer);
3184
				break;
3225
				break;
3185
			} 
3226
			} 
3186
		} else if (!strcasecmp(tmp->name, "regseconds")) {
3227
		} else if (!strcasecmp(tmp->name, "regseconds")) {
3187
			ast_get_time_t(tmp->value, &regseconds, 0, NULL);
3228
			ast_get_time_t(tmp->value, &regseconds, 0, NULL);
3188
		} else if (!strcasecmp(tmp->name, "ipaddr")) {
3229
		} else if (!strcasecmp(tmp->name, "ipaddr")) {
3189
			inet_aton(tmp->value, &(peer->addr.sin_addr));
3230
			inet_aton(tmp->value, &(peer->addr.sin_addr));
3190
		} else if (!strcasecmp(tmp->name, "port")) {
3231
		} else if (!strcasecmp(tmp->name, "port")) {
3191
			peer->addr.sin_port = htons(atoi(tmp->value));
3232
			peer->addr.sin_port = htons(atoi(tmp->value));
3192
		} else if (!strcasecmp(tmp->name, "host")) {
3233
		} else if (!strcasecmp(tmp->name, "host")) {
3193
			if (!strcasecmp(tmp->value, "dynamic"))
3234
			if (!strcasecmp(tmp->value, "dynamic"))
3194
				dynamic = 1;
3235
				dynamic = 1;
3195
		}
3236
		}
3196
	}
3237
	}
3197

    
   
3238

   
3198
	ast_variables_destroy(var);
3239
	ast_variables_destroy(var);
3199

    
   
3240

   
3200
	if (!peer)
3241
	if (!peer)
3201
		return NULL;
3242
		return NULL;
3202

    
   
3243

   
3203
	if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3244
	if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3204
		ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3245
		ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3205
		if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3246
		if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3206
 			if (peer->expire > -1) {
3247
 			if (peer->expire > -1) {
3207
 				if (!ast_sched_del(sched, peer->expire)) {
3248
 				if (!ast_sched_del(sched, peer->expire)) {
3208
 					peer->expire = -1;
3249
 					peer->expire = -1;
3209
 					peer_unref(peer);
3250
 					peer_unref(peer);
3210
 				}
3251
 				}
3211
 			}
3252
 			}
3212
 			peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3253
 			peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3213
 			if (peer->expire == -1)
3254
 			if (peer->expire == -1)
3214
 				peer_unref(peer);
3255
 				peer_unref(peer);
3215
		}
3256
		}
3216
		ao2_link(peers, peer);
3257
		ao2_link(peers, peer);
3217
		if (ast_test_flag(peer, IAX_DYNAMIC))
3258
		if (ast_test_flag(peer, IAX_DYNAMIC))
3218
			reg_source_db(peer);
3259
			reg_source_db(peer);
3219
	} else {
3260
	} else {
3220
		ast_set_flag(peer, IAX_TEMPONLY);	
3261
		ast_set_flag(peer, IAX_TEMPONLY);	
3221
	}
3262
	}
3222

    
   
3263

   
3223
	if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3264
	if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3224
		time(&nowtime);
3265
		time(&nowtime);
3225
		if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3266
		if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3226
			memset(&peer->addr, 0, sizeof(peer->addr));
3267
			memset(&peer->addr, 0, sizeof(peer->addr));
3227
			realtime_update_peer(peer->name, &peer->addr, 0);
3268
			realtime_update_peer(peer->name, &peer->addr, 0);
3228
			ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3269
			ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3229
				peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3270
				peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3230
		}
3271
		}
3231
		else {
3272
		else {
3232
			ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3273
			ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3233
				peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3274
				peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3234
		}
3275
		}
3235
	}
3276
	}
3236

    
   
3277

   
3237
	return peer;
3278
	return peer;
3238
}
3279
}
3239

    
   
3280

   
3240
static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
3281
static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
3241
{
3282
{
3242
	struct ast_variable *var;
3283
	struct ast_variable *var;
3243
	struct ast_variable *tmp;
3284
	struct ast_variable *tmp;
3244
	struct iax2_user *user=NULL;
3285
	struct iax2_user *user=NULL;
3245

    
   
3286

   
3246
	var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
3287
	var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
3247
	if (!var)
3288
	if (!var)
3248
		var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3289
		var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
3249
	if (!var && sin) {
3290
	if (!var && sin) {
3250
		char porta[6];
3291
		char porta[6];
3251
		snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
3292
		snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
3252
		var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3293
		var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3253
		if (!var)
3294
		if (!var)
3254
			var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3295
			var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3255
	}
3296
	}
3256
	if (!var) { /* Last ditch effort */
3297
	if (!var) { /* Last ditch effort */
3257
		var = ast_load_realtime("iaxusers", "name", username, NULL);
3298
		var = ast_load_realtime("iaxusers", "name", username, NULL);
3258
		/*!\note
3299
		/*!\note
3259
		 * If this one loaded something, then we need to ensure that the host
3300
		 * If this one loaded something, then we need to ensure that the host
3260
		 * field matched.  The only reason why we can't have this as a criteria
3301
		 * field matched.  The only reason why we can't have this as a criteria
3261
		 * is because we only have the IP address and the host field might be
3302
		 * is because we only have the IP address and the host field might be
3262
		 * set as a name (and the reverse PTR might not match).
3303
		 * set as a name (and the reverse PTR might not match).
3263
		 */
3304
		 */
3264
		if (var) {
3305
		if (var) {
3265
			for (tmp = var; tmp; tmp = tmp->next) {
3306
			for (tmp = var; tmp; tmp = tmp->next) {
3266
				if (!strcasecmp(tmp->name, "host")) {
3307
				if (!strcasecmp(tmp->name, "host")) {
3267
					struct ast_hostent ahp;
3308
					struct ast_hostent ahp;
3268
					struct hostent *hp;
3309
					struct hostent *hp;
3269
					if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3310
					if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3270
						/* No match */
3311
						/* No match */
3271
						ast_variables_destroy(var);
3312
						ast_variables_destroy(var);
3272
						var = NULL;
3313
						var = NULL;
3273
					}
3314
					}
3274
					break;
3315
					break;
3275
				}
3316
				}
3276
			}
3317
			}
3277
		}
3318
		}
3278
	}
3319
	}
3279
	if (!var)
3320
	if (!var)
3280
		return NULL;
3321
		return NULL;
3281

    
   
3322

   
3282
	tmp = var;
3323
	tmp = var;
3283
	while(tmp) {
3324
	while(tmp) {
3284
		/* Make sure it's not a peer only... */
3325
		/* Make sure it's not a peer only... */
3285
		if (!strcasecmp(tmp->name, "type")) {
3326
		if (!strcasecmp(tmp->name, "type")) {
3286
			if (strcasecmp(tmp->value, "friend") &&
3327
			if (strcasecmp(tmp->value, "friend") &&
3287
			    strcasecmp(tmp->value, "user")) {
3328
			    strcasecmp(tmp->value, "user")) {
3288
				return NULL;
3329
				return NULL;
3289
			} 
3330
			} 
3290
		}
3331
		}
3291
		tmp = tmp->next;
3332
		tmp = tmp->next;
3292
	}
3333
	}
3293

    
   
3334

   
3294
	user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3335
	user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3295

    
   
3336

   
3296
	ast_variables_destroy(var);
3337
	ast_variables_destroy(var);
3297

    
   
3338

   
3298
	if (!user)
3339
	if (!user)
3299
		return NULL;
3340
		return NULL;
3300

    
   
3341

   
3301
	if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3342
	if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3302
		ast_set_flag(user, IAX_RTCACHEFRIENDS);
3343
		ast_set_flag(user, IAX_RTCACHEFRIENDS);
3303
		ao2_link(users, user);
3344
		ao2_link(users, user);
3304
	} else {
3345
	} else {
3305
		ast_set_flag(user, IAX_TEMPONLY);	
3346
		ast_set_flag(user, IAX_TEMPONLY);	
3306
	}
3347
	}
3307

    
   
3348

   
3308
	return user;
3349
	return user;
3309
}
3350
}
3310

    
   
3351

   
3311
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3352
static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3312
{
3353
{
3313
	char port[10];
3354
	char port[10];
3314
	char regseconds[20];
3355
	char regseconds[20];
3315
	
3356
	
3316
	snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3357
	snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3317
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3358
	snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3318
	ast_update_realtime("iaxpeers", "name", peername, 
3359
	ast_update_realtime("iaxpeers", "name", peername, 
3319
		"ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
3360
		"ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port, 
3320
		"regseconds", regseconds, NULL);
3361
		"regseconds", regseconds, NULL);
3321
}
3362
}
3322

    
   
3363

   
3323
struct create_addr_info {
3364
struct create_addr_info {
3324
	int capability;
3365
	int capability;
3325
	unsigned int flags;
3366
	unsigned int flags;
3326
	int maxtime;
3367
	int maxtime;
3327
	int encmethods;
3368
	int encmethods;
3328
	int found;
3369
	int found;
3329
	int sockfd;
3370
	int sockfd;
3330
	int adsi;
3371
	int adsi;
3331
	char username[80];
3372
	char username[80];
3332
	char secret[80];
3373
	char secret[80];
3333
	char outkey[80];
3374
	char outkey[80];
3334
	char timezone[80];
3375
	char timezone[80];
3335
	char prefs[32];
3376
	char prefs[32];
3336
	char context[AST_MAX_CONTEXT];
3377
	char context[AST_MAX_CONTEXT];
3337
	char peercontext[AST_MAX_CONTEXT];
3378
	char peercontext[AST_MAX_CONTEXT];
3338
	char mohinterpret[MAX_MUSICCLASS];
3379
	char mohinterpret[MAX_MUSICCLASS];
3339
	char mohsuggest[MAX_MUSICCLASS];
3380
	char mohsuggest[MAX_MUSICCLASS];
3340
};
3381
};
3341

    
   
3382

   
3342
static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
3383
static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
3343
{
3384
{
3344
	struct iax2_peer *peer;
3385
	struct iax2_peer *peer;
3345
	int res = -1;
3386
	int res = -1;
3346
	struct ast_codec_pref ourprefs;
3387
	struct ast_codec_pref ourprefs;
3347

    
   
3388

   
3348
	ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3389
	ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3349
	cai->sockfd = defaultsockfd;
3390
	cai->sockfd = defaultsockfd;
3350
	cai->maxtime = 0;
3391
	cai->maxtime = 0;
3351
	sin->sin_family = AF_INET;
3392
	sin->sin_family = AF_INET;
3352

    
   
3393

   
3353
	if (!(peer = find_peer(peername, 1))) {
3394
	if (!(peer = find_peer(peername, 1))) {
3354
		cai->found = 0;
3395
		cai->found = 0;
3355
		if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
3396
		if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
3356
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
3397
			ast_log(LOG_WARNING, "No such host: %s\n", peername);
3357
			return -1;
3398
			return -1;
3358
		}
3399
		}
3359
		sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3400
		sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3360
		/* use global iax prefs for unknown peer/user */
3401
		/* use global iax prefs for unknown peer/user */
3361
		/* But move the calling channel's native codec to the top of the preference list */
3402
		/* But move the calling channel's native codec to the top of the preference list */
3362
		memcpy(&ourprefs, &prefs, sizeof(ourprefs));
3403
		memcpy(&ourprefs, &prefs, sizeof(ourprefs));
3363
		if (c)
3404
		if (c)
3364
			ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3405
			ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3365
		ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3406
		ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3366
		return 0;
3407
		return 0;
3367
	}
3408
	}
3368

    
   
3409

   
3369
	cai->found = 1;
3410
	cai->found = 1;
3370
	
3411
	
3371
	/* if the peer has no address (current or default), return failure */
3412
	/* if the peer has no address (current or default), return failure */
3372
	if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3413
	if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3373
		goto return_unref;
3414
		goto return_unref;
3374

    
   
3415

   
3375
	/* if the peer is being monitored and is currently unreachable, return failure */
3416
	/* if the peer is being monitored and is currently unreachable, return failure */
3376
	if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3417
	if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3377
		goto return_unref;
3418
		goto return_unref;
3378

    
   
3419

   
3379
	ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
3420
	ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
3380
	cai->maxtime = peer->maxms;
3421
	cai->maxtime = peer->maxms;
3381
	cai->capability = peer->capability;
3422
	cai->capability = peer->capability;
3382
	cai->encmethods = peer->encmethods;
3423
	cai->encmethods = peer->encmethods;
3383
	cai->sockfd = peer->sockfd;
3424
	cai->sockfd = peer->sockfd;
3384
	cai->adsi = peer->adsi;
3425
	cai->adsi = peer->adsi;
3385
	memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
3426
	memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
3386
	/* Move the calling channel's native codec to the top of the preference list */
3427
	/* Move the calling channel's native codec to the top of the preference list */
3387
	if (c) {
3428
	if (c) {
3388
		ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
3429
		ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
3389
		ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3430
		ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3390
	}
3431
	}
3391
	ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3432
	ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3392
	ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3433
	ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3393
	ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3434
	ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3394
	ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3435
	ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3395
	ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3436
	ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3396
	ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3437
	ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3397
	ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3438
	ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3398
	ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3439
	ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3399
	if (ast_strlen_zero(peer->dbsecret)) {
3440
	if (ast_strlen_zero(peer->dbsecret)) {
3400
		ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3441
		ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3401
	} else {
3442
	} else {
3402
		char *family;
3443
		char *family;
3403
		char *key = NULL;
3444
		char *key = NULL;
3404

    
   
3445

   
3405
		family = ast_strdupa(peer->dbsecret);
3446
		family = ast_strdupa(peer->dbsecret);
3406
		key = strchr(family, '/');
3447
		key = strchr(family, '/');
3407
		if (key)
3448
		if (key)
3408
			*key++ = '\0';
3449
			*key++ = '\0';
3409
		if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3450
		if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3410
			ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3451
			ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3411
			goto return_unref;
3452
			goto return_unref;
3412
		}
3453
		}
3413
	}
3454
	}
3414

    
   
3455

   
3415
	if (peer->addr.sin_addr.s_addr) {
3456
	if (peer->addr.sin_addr.s_addr) {
3416
		sin->sin_addr = peer->addr.sin_addr;
3457
		sin->sin_addr = peer->addr.sin_addr;
3417
		sin->sin_port = peer->addr.sin_port;
3458
		sin->sin_port = peer->addr.sin_port;
3418
	} else {
3459
	} else {
3419
		sin->sin_addr = peer->defaddr.sin_addr;
3460
		sin->sin_addr = peer->defaddr.sin_addr;
3420
		sin->sin_port = peer->defaddr.sin_port;
3461
		sin->sin_port = peer->defaddr.sin_port;
3421
	}
3462
	}
3422

    
   
3463

   
3423
	res = 0;
3464
	res = 0;
3424

    
   
3465

   
3425
return_unref:
3466
return_unref:
3426
	peer_unref(peer);
3467
	peer_unref(peer);
3427

    
   
3468

   
3428
	return res;
3469
	return res;
3429
}
3470
}
3430

    
   
3471

   
3431
static void __auto_congest(const void *nothing)
3472
static void __auto_congest(const void *nothing)
3432
{
3473
{
3433
	int callno = PTR_TO_CALLNO(nothing);
3474
	int callno = PTR_TO_CALLNO(nothing);
3434
	struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3475
	struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3435
	ast_mutex_lock(&iaxsl[callno]);
3476
	ast_mutex_lock(&iaxsl[callno]);
3436
	if (iaxs[callno]) {
3477
	if (iaxs[callno]) {
3437
		iaxs[callno]->initid = -1;
3478
		iaxs[callno]->initid = -1;
3438
		iax2_queue_frame(callno, &f);
3479
		iax2_queue_frame(callno, &f);
3439
		ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3480
		ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3440
	}
3481
	}
3441
	ast_mutex_unlock(&iaxsl[callno]);
3482
	ast_mutex_unlock(&iaxsl[callno]);
3442
}
3483
}
3443

    
   
3484

   
3444
static int auto_congest(const void *data)
3485
static int auto_congest(const void *data)
3445
{
3486
{
3446
#ifdef SCHED_MULTITHREADED
3487
#ifdef SCHED_MULTITHREADED
3447
	if (schedule_action(__auto_congest, data))
3488
	if (schedule_action(__auto_congest, data))
3448
#endif		
3489
#endif		
3449
		__auto_congest(data);
3490
		__auto_congest(data);
3450
	return 0;
3491
	return 0;
3451
}
3492
}
3452

    
   
3493

   
3453
static unsigned int iax2_datetime(const char *tz)
3494
static unsigned int iax2_datetime(const char *tz)
3454
{
3495
{
3455
	struct timeval t = ast_tvnow();
3496
	struct timeval t = ast_tvnow();
3456
	struct ast_tm tm;
3497
	struct ast_tm tm;
3457
	unsigned int tmp;
3498
	unsigned int tmp;
3458
	ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
3499
	ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
3459
	tmp  = (tm.tm_sec >> 1) & 0x1f;			/* 5 bits of seconds */
3500
	tmp  = (tm.tm_sec >> 1) & 0x1f;			/* 5 bits of seconds */
3460
	tmp |= (tm.tm_min & 0x3f) << 5;			/* 6 bits of minutes */
3501
	tmp |= (tm.tm_min & 0x3f) << 5;			/* 6 bits of minutes */
3461
	tmp |= (tm.tm_hour & 0x1f) << 11;		/* 5 bits of hours */
3502
	tmp |= (tm.tm_hour & 0x1f) << 11;		/* 5 bits of hours */
3462
	tmp |= (tm.tm_mday & 0x1f) << 16;		/* 5 bits of day of month */
3503
	tmp |= (tm.tm_mday & 0x1f) << 16;		/* 5 bits of day of month */
3463
	tmp |= ((tm.tm_mon + 1) & 0xf) << 21;		/* 4 bits of month */
3504
	tmp |= ((tm.tm_mon + 1) & 0xf) << 21;		/* 4 bits of month */
3464
	tmp |= ((tm.tm_year - 100) & 0x7f) << 25;	/* 7 bits of year */
3505
	tmp |= ((tm.tm_year - 100) & 0x7f) << 25;	/* 7 bits of year */
3465
	return tmp;
3506
	return tmp;
3466
}
3507
}
3467

    
   
3508

   
3468
struct parsed_dial_string {
3509
struct parsed_dial_string {
3469
	char *username;
3510
	char *username;
3470
	char *password;
3511
	char *password;
3471
	char *key;
3512
	char *key;
3472
	char *peer;
3513
	char *peer;
3473
	char *port;
3514
	char *port;
3474
	char *exten;
3515
	char *exten;
3475
	char *context;
3516
	char *context;
3476
	char *options;
3517
	char *options;
3477
};
3518
};
3478

    
   
3519

   
3479
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int command, int ts, unsigned char seqno)
3520
static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int command, int ts, unsigned char seqno)
3480
{
3521
{
3481
	struct ast_iax2_full_hdr f = { .scallno = htons(0x8000 | callno), .dcallno = htons(dcallno),
3522
	struct ast_iax2_full_hdr f = { .scallno = htons(0x8000 | callno), .dcallno = htons(dcallno),
3482
		.ts = htonl(ts), .iseqno = seqno, .oseqno = 0, .type = AST_FRAME_IAX,
3523
		.ts = htonl(ts), .iseqno = seqno, .oseqno = 0, .type = AST_FRAME_IAX,
3483
		.csub = compress_subclass(command) };
3524
		.csub = compress_subclass(command) };
3484

    
   
3525

   
3485
	return sendto(defaultsockfd, &f, sizeof(f), 0, (struct sockaddr *)sin, sizeof(*sin));
3526
	return sendto(defaultsockfd, &f, sizeof(f), 0, (struct sockaddr *)sin, sizeof(*sin));
3486
}
3527
}
3487

    
   
3528

   
3488
/*!
3529
/*!
3489
 * \brief Parses an IAX dial string into its component parts.
3530
 * \brief Parses an IAX dial string into its component parts.
3490
 * \param data the string to be parsed
3531
 * \param data the string to be parsed
3491
 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3532
 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3492
 * \return nothing
3533
 * \return nothing
3493
 *
3534
 *
3494
 * This function parses the string and fills the structure
3535
 * This function parses the string and fills the structure
3495
 * with pointers to its component parts. The input string
3536
 * with pointers to its component parts. The input string
3496
 * will be modified.
3537
 * will be modified.
3497
 *
3538
 *
3498
 * \note This function supports both plaintext passwords and RSA
3539
 * \note This function supports both plaintext passwords and RSA
3499
 * key names; if the password string is formatted as '[keyname]',
3540
 * key names; if the password string is formatted as '[keyname]',
3500
 * then the keyname will be placed into the key field, and the
3541
 * then the keyname will be placed into the key field, and the
3501
 * password field will be set to NULL.
3542
 * password field will be set to NULL.
3502
 *
3543
 *
3503
 * \note The dial string format is:
3544
 * \note The dial string format is:
3504
 *       [username[:password]@]peer[:port][/exten[@@context]][/options]
3545
 *       [username[:password]@]peer[:port][/exten[@@context]][/options]
3505
 */
3546
 */
3506
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3547
static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3507
{
3548
{
3508
	if (ast_strlen_zero(data))
3549
	if (ast_strlen_zero(data))
3509
		return;
3550
		return;
3510

    
   
3551

   
3511
	pds->peer = strsep(&data, "/");
3552
	pds->peer = strsep(&data, "/");
3512
	pds->exten = strsep(&data, "/");
3553
	pds->exten = strsep(&data, "/");
3513
	pds->options = data;
3554
	pds->options = data;
3514

    
   
3555

   
3515
	if (pds->exten) {
3556
	if (pds->exten) {
3516
		data = pds->exten;
3557
		data = pds->exten;
3517
		pds->exten = strsep(&data, "@");
3558
		pds->exten = strsep(&data, "@");
3518
		pds->context = data;
3559
		pds->context = data;
3519
	}
3560
	}
3520

    
   
3561

   
3521
	if (strchr(pds->peer, '@')) {
3562
	if (strchr(pds->peer, '@')) {
3522
		data = pds->peer;
3563
		data = pds->peer;
3523
		pds->username = strsep(&data, "@");
3564
		pds->username = strsep(&data, "@");
3524
		pds->peer = data;
3565
		pds->peer = data;
3525
	}
3566
	}
3526

    
   
3567

   
3527
	if (pds->username) {
3568
	if (pds->username) {
3528
		data = pds->username;
3569
		data = pds->username;
3529
		pds->username = strsep(&data, ":");
3570
		pds->username = strsep(&data, ":");
3530
		pds->password = data;
3571
		pds->password = data;
3531
	}
3572
	}
3532

    
   
3573

   
3533
	data = pds->peer;
3574
	data = pds->peer;
3534
	pds->peer = strsep(&data, ":");
3575
	pds->peer = strsep(&data, ":");
3535
	pds->port = data;
3576
	pds->port = data;
3536

    
   
3577

   
3537
	/* check for a key name wrapped in [] in the secret position, if found,
3578
	/* check for a key name wrapped in [] in the secret position, if found,
3538
	   move it to the key field instead
3579
	   move it to the key field instead
3539
	*/
3580
	*/
3540
	if (pds->password && (pds->password[0] == '[')) {
3581
	if (pds->password && (pds->password[0] == '[')) {
3541
		pds->key = ast_strip_quoted(pds->password, "[", "]");
3582
		pds->key = ast_strip_quoted(pds->password, "[", "]");
3542
		pds->password = NULL;
3583
		pds->password = NULL;
3543
	}
3584
	}
3544
}
3585
}
3545

    
   
3586

   
3546
static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3587
static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3547
{
3588
{
3548
	struct sockaddr_in sin;
3589
	struct sockaddr_in sin;
3549
	char *l=NULL, *n=NULL, *tmpstr;
3590
	char *l=NULL, *n=NULL, *tmpstr;
3550
	struct iax_ie_data ied;
3591
	struct iax_ie_data ied;
3551
	char *defaultrdest = "s";
3592
	char *defaultrdest = "s";
3552
	unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3593
	unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3553
	struct parsed_dial_string pds;
3594
	struct parsed_dial_string pds;
3554
	struct create_addr_info cai;
3595
	struct create_addr_info cai;
3555
	struct ast_var_t *var;
3596
	struct ast_var_t *var;
3556
	struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3597
	struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3557
	const char* osp_token_ptr;
3598
	const char* osp_token_ptr;
3558
	unsigned int osp_token_length;
3599
	unsigned int osp_token_length;
3559
	unsigned char osp_block_index;
3600
	unsigned char osp_block_index;
3560
	unsigned int osp_block_length;
3601
	unsigned int osp_block_length;
3561
	unsigned char osp_buffer[256];
3602
	unsigned char osp_buffer[256];
3562

    
   
3603

   
3563
	if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3604
	if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3564
		ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3605
		ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3565
		return -1;
3606
		return -1;
3566
	}
3607
	}
3567

    
   
3608

   
3568
	memset(&cai, 0, sizeof(cai));
3609
	memset(&cai, 0, sizeof(cai));
3569
	cai.encmethods = iax2_encryption;
3610
	cai.encmethods = iax2_encryption;
3570

    
   
3611

   
3571
	memset(&pds, 0, sizeof(pds));
3612
	memset(&pds, 0, sizeof(pds));
3572
	tmpstr = ast_strdupa(dest);
3613
	tmpstr = ast_strdupa(dest);
3573
	parse_dial_string(tmpstr, &pds);
3614
	parse_dial_string(tmpstr, &pds);
3574

    
   
3615

   
3575
	if (ast_strlen_zero(pds.peer)) {
3616
	if (ast_strlen_zero(pds.peer)) {
3576
		ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3617
		ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3577
		return -1;
3618
		return -1;
3578
	}
3619
	}
3579

    
   
3620

   
3580
	if (!pds.exten) {
3621
	if (!pds.exten) {
3581
		pds.exten = defaultrdest;
3622
		pds.exten = defaultrdest;
3582
	}
3623
	}
3583

    
   
3624

   
3584
	if (create_addr(pds.peer, c, &sin, &cai)) {
3625
	if (create_addr(pds.peer, c, &sin, &cai)) {
3585
		ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3626
		ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3586
		return -1;
3627
		return -1;
3587
	}
3628
	}
3588

    
   
3629

   
3589
	if (!pds.username && !ast_strlen_zero(cai.username))
3630
	if (!pds.username && !ast_strlen_zero(cai.username))
3590
		pds.username = cai.username;
3631
		pds.username = cai.username;
3591
	if (!pds.password && !ast_strlen_zero(cai.secret))
3632
	if (!pds.password && !ast_strlen_zero(cai.secret))
3592
		pds.password = cai.secret;
3633
		pds.password = cai.secret;
3593
	if (!pds.key && !ast_strlen_zero(cai.outkey))
3634
	if (!pds.key && !ast_strlen_zero(cai.outkey))
3594
		pds.key = cai.outkey;
3635
		pds.key = cai.outkey;
3595
	if (!pds.context && !ast_strlen_zero(cai.peercontext))
3636
	if (!pds.context && !ast_strlen_zero(cai.peercontext))
3596
		pds.context = cai.peercontext;
3637
		pds.context = cai.peercontext;
3597

    
   
3638

   
3598
	/* Keep track of the context for outgoing calls too */
3639
	/* Keep track of the context for outgoing calls too */
3599
	ast_copy_string(c->context, cai.context, sizeof(c->context));
3640
	ast_copy_string(c->context, cai.context, sizeof(c->context));
3600

    
   
3641

   
3601
	if (pds.port)
3642
	if (pds.port)
3602
		sin.sin_port = htons(atoi(pds.port));
3643
		sin.sin_port = htons(atoi(pds.port));
3603

    
   
3644

   
3604
	l = c->cid.cid_num;
3645
	l = c->cid.cid_num;
3605
	n = c->cid.cid_name;
3646
	n = c->cid.cid_name;
3606

    
   
3647

   
3607
	/* Now build request */	
3648
	/* Now build request */	
3608
	memset(&ied, 0, sizeof(ied));
3649
	memset(&ied, 0, sizeof(ied));
3609

    
   
3650

   
3610
	/* On new call, first IE MUST be IAX version of caller */
3651
	/* On new call, first IE MUST be IAX version of caller */
3611
	iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3652
	iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3612
	iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3653
	iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3613
	if (pds.options && strchr(pds.options, 'a')) {
3654
	if (pds.options && strchr(pds.options, 'a')) {
3614
		/* Request auto answer */
3655
		/* Request auto answer */
3615
		iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3656
		iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3616
	}
3657
	}
3617

    
   
3658

   
3618
	iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3659
	iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3619

    
   
3660

   
3620
	if (l) {
3661
	if (l) {
3621
		iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3662
		iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3622
		iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3663
		iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3623
	} else {
3664
	} else {
3624
		if (n)
3665
		if (n)
3625
			iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3666
			iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3626
		else
3667
		else
3627
			iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3668
			iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3628
	}
3669
	}
3629

    
   
3670

   
3630
	iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3671
	iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3631
	iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3672
	iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3632

    
   
3673

   
3633
	if (n)
3674
	if (n)
3634
		iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3675
		iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3635
	if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3676
	if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3636
		iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3677
		iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3637

    
   
3678

   
3638
	if (!ast_strlen_zero(c->language))
3679
	if (!ast_strlen_zero(c->language))
3639
		iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3680
		iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3640
	if (!ast_strlen_zero(c->cid.cid_dnid))
3681
	if (!ast_strlen_zero(c->cid.cid_dnid))
3641
		iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3682
		iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3642
	if (!ast_strlen_zero(c->cid.cid_rdnis))
3683
	if (!ast_strlen_zero(c->cid.cid_rdnis))
3643
		iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3684
		iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3644

    
   
3685

   
3645
	if (pds.context)
3686
	if (pds.context)
3646
		iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3687
		iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3647

    
   
3688

   
3648
	if (pds.username)
3689
	if (pds.username)
3649
		iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3690
		iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3650

    
   
3691

   
3651
	if (cai.encmethods)
3692
	if (cai.encmethods)
3652
		iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3693
		iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3653

    
   
3694

   
3654
	ast_mutex_lock(&iaxsl[callno]);
3695
	ast_mutex_lock(&iaxsl[callno]);
3655

    
   
3696

   
3656
	if (!ast_strlen_zero(c->context))
3697
	if (!ast_strlen_zero(c->context))
3657
		ast_string_field_set(iaxs[callno], context, c->context);
3698
		ast_string_field_set(iaxs[callno], context, c->context);
3658

    
   
3699

   
3659
	if (pds.username)
3700
	if (pds.username)
3660
		ast_string_field_set(iaxs[callno], username, pds.username);
3701
		ast_string_field_set(iaxs[callno], username, pds.username);
3661

    
   
3702

   
3662
	iaxs[callno]->encmethods = cai.encmethods;
3703
	iaxs[callno]->encmethods = cai.encmethods;
3663

    
   
3704

   
3664
	iaxs[callno]->adsi = cai.adsi;
3705
	iaxs[callno]->adsi = cai.adsi;
3665
	
3706
	
3666
	ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3707
	ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3667
	ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3708
	ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3668

    
   
3709

   
3669
	if (pds.key)
3710
	if (pds.key)
3670
		ast_string_field_set(iaxs[callno], outkey, pds.key);
3711
		ast_string_field_set(iaxs[callno], outkey, pds.key);
3671
	if (pds.password)
3712
	if (pds.password)
3672
		ast_string_field_set(iaxs[callno], secret, pds.password);
3713
		ast_string_field_set(iaxs[callno], secret, pds.password);
3673

    
   
3714

   
3674
	iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3715
	iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3675
	iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3716
	iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3676
	iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3717
	iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3677
	iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3718
	iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3678

    
   
3719

   
3679
	if (iaxs[callno]->maxtime) {
3720
	if (iaxs[callno]->maxtime) {
3680
		/* Initialize pingtime and auto-congest time */
3721
		/* Initialize pingtime and auto-congest time */
3681
		iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3722
		iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3682
		iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3723
		iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3683
	} else if (autokill) {
3724
	} else if (autokill) {
3684
		iaxs[callno]->pingtime = autokill / 2;
3725
		iaxs[callno]->pingtime = autokill / 2;
3685
		iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3726
		iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3686
	}
3727
	}
3687

    
   
3728

   
3688
	/* Check if there is an OSP token set by IAXCHANINFO function */
3729
	/* Check if there is an OSP token set by IAXCHANINFO function */
3689
	osp_token_ptr = iaxs[callno]->osptoken;
3730
	osp_token_ptr = iaxs[callno]->osptoken;
3690
	if (!ast_strlen_zero(osp_token_ptr)) {
3731
	if (!ast_strlen_zero(osp_token_ptr)) {
3691
		if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3732
		if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3692
			osp_block_index = 0;
3733
			osp_block_index = 0;
3693
			while (osp_token_length > 0) {
3734
			while (osp_token_length > 0) {
3694
				osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3735
				osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3695
				osp_buffer[0] = osp_block_index;
3736
				osp_buffer[0] = osp_block_index;
3696
				memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3737
				memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3697
				iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3738
				iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3698
				osp_block_index++;
3739
				osp_block_index++;
3699
				osp_token_ptr += osp_block_length;
3740
				osp_token_ptr += osp_block_length;
3700
				osp_token_length -= osp_block_length;
3741
				osp_token_length -= osp_block_length;
3701
			} 
3742
			} 
3702
		} else
3743
		} else
3703
			ast_log(LOG_WARNING, "OSP token is too long\n");
3744
			ast_log(LOG_WARNING, "OSP token is too long\n");
3704
	} else if (iaxdebug)
3745
	} else if (iaxdebug)
3705
		ast_debug(1, "OSP token is undefined\n");
3746
		ast_debug(1, "OSP token is undefined\n");
3706

    
   
3747

   
3707
	/* send the command using the appropriate socket for this peer */
3748
	/* send the command using the appropriate socket for this peer */
3708
	iaxs[callno]->sockfd = cai.sockfd;
3749
	iaxs[callno]->sockfd = cai.sockfd;
3709

    
   
3750

   
3710
	/* Add remote vars */
3751
	/* Add remote vars */
3711
	if (variablestore) {
3752
	if (variablestore) {
3712
		AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
3753
		AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
3713
		ast_debug(1, "Found an IAX variable store on this channel\n");
3754
		ast_debug(1, "Found an IAX variable store on this channel\n");
3714
		AST_LIST_LOCK(variablelist);
3755
		AST_LIST_LOCK(variablelist);
3715
		AST_LIST_TRAVERSE(variablelist, var, entries) {
3756
		AST_LIST_TRAVERSE(variablelist, var, entries) {
3716
			char tmp[256];
3757
			char tmp[256];
3717
			int i;
3758
			int i;
3718
			ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
3759
			ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
3719
			/* Automatically divide the value up into sized chunks */
3760
			/* Automatically divide the value up into sized chunks */
3720
			for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
3761
			for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
3721
				snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
3762
				snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
3722
				iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3763
				iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3723
			}
3764
			}
3724
		}
3765
		}
3725
		AST_LIST_UNLOCK(variablelist);
3766
		AST_LIST_UNLOCK(variablelist);
3726
	}
3767
	}
3727

    
   
3768

   
3728
	/* Transmit the string in a "NEW" request */
3769
	/* Transmit the string in a "NEW" request */
3729
	send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3770
	send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3730

    
   
3771

   
3731
	ast_mutex_unlock(&iaxsl[callno]);
3772
	ast_mutex_unlock(&iaxsl[callno]);
3732
	ast_setstate(c, AST_STATE_RINGING);
3773
	ast_setstate(c, AST_STATE_RINGING);
3733

    
   
3774

   
3734
	return 0;
3775
	return 0;
3735
}
3776
}
3736

    
   
3777

   
3737
static int iax2_hangup(struct ast_channel *c) 
3778
static int iax2_hangup(struct ast_channel *c) 
3738
{
3779
{
3739
	unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3780
	unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3740
 	struct iax_ie_data ied;
3781
 	struct iax_ie_data ied;
3741
	int alreadygone;
3782
	int alreadygone;
3742
 	memset(&ied, 0, sizeof(ied));
3783
 	memset(&ied, 0, sizeof(ied));
3743
	ast_mutex_lock(&iaxsl[callno]);
3784
	ast_mutex_lock(&iaxsl[callno]);
3744
	if (callno && iaxs[callno]) {
3785
	if (callno && iaxs[callno]) {
3745
		ast_debug(1, "We're hanging up %s now...\n", c->name);
3786
		ast_debug(1, "We're hanging up %s now...\n", c->name);
3746
		alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3787
		alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3747
		/* Send the hangup unless we have had a transmission error or are already gone */
3788
		/* Send the hangup unless we have had a transmission error or are already gone */
3748
 		iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3789
 		iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3749
		if (!iaxs[callno]->error && !alreadygone) {
3790
		if (!iaxs[callno]->error && !alreadygone) {
3750
 			if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
3791
 			if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
3751
				ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
3792
				ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
3752
			}
3793
			}
3753
			if (!iaxs[callno]) {
3794
			if (!iaxs[callno]) {
3754
				ast_mutex_unlock(&iaxsl[callno]);
3795
				ast_mutex_unlock(&iaxsl[callno]);
3755
				return 0;
3796
				return 0;
3756
			}
3797
			}
3757
		}
3798
		}
3758
		/* Explicitly predestroy it */
3799
		/* Explicitly predestroy it */
3759
		iax2_predestroy(callno);
3800
		iax2_predestroy(callno);
3760
		/* If we were already gone to begin with, destroy us now */
3801
		/* If we were already gone to begin with, destroy us now */
3761
		if (iaxs[callno] && alreadygone) {
3802
		if (iaxs[callno] && alreadygone) {
3762
			ast_debug(1, "Really destroying %s now...\n", c->name);
3803
			ast_debug(1, "Really destroying %s now...\n", c->name);
3763
			iax2_destroy(callno);
3804
			iax2_destroy(callno);
3764
		} else if (iaxs[callno]) {
3805
		} else if (iaxs[callno]) {
3765
			if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
3806
			if (ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
3766
				ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
3807
				ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!!  Destroying immediately.\n", callno);
3767
				iax2_destroy(callno);
3808
				iax2_destroy(callno);
3768
			}
3809
			}
3769
		}
3810
		}
3770
	} else if (c->tech_pvt) {
3811
	} else if (c->tech_pvt) {
3771
		/* If this call no longer exists, but the channel still
3812
		/* If this call no longer exists, but the channel still
3772
		 * references it we need to set the channel's tech_pvt to null
3813
		 * references it we need to set the channel's tech_pvt to null
3773
		 * to avoid ast_channel_free() trying to free it.
3814
		 * to avoid ast_channel_free() trying to free it.
3774
		 */
3815
		 */
3775
		c->tech_pvt = NULL;
3816
		c->tech_pvt = NULL;
3776
	}
3817
	}
3777
	ast_mutex_unlock(&iaxsl[callno]);
3818
	ast_mutex_unlock(&iaxsl[callno]);
3778
	ast_verb(3, "Hungup '%s'\n", c->name);
3819
	ast_verb(3, "Hungup '%s'\n", c->name);
3779
	return 0;
3820
	return 0;
3780
}
3821
}
3781

    
   
3822

   
3782
/*!
3823
/*!
3783
 * \note expects the pvt to be locked
3824
 * \note expects the pvt to be locked
3784
 */
3825
 */
3785
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
3826
static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
3786
{
3827
{
3787
	unsigned short callno = pvt->callno;
3828
	unsigned short callno = pvt->callno;
3788

    
   
3829

   
3789
	if (!pvt->peercallno) {
3830
	if (!pvt->peercallno) {
3790
		/* We don't know the remote side's call number, yet.  :( */
3831
		/* We don't know the remote side's call number, yet.  :( */
3791
		int count = 10;
3832
		int count = 10;
3792
		while (count-- && pvt && !pvt->peercallno) {
3833
		while (count-- && pvt && !pvt->peercallno) {
3793
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3834
			DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3794
			pvt = iaxs[callno];
3835
			pvt = iaxs[callno];
3795
		}
3836
		}
3796
		if (!pvt->peercallno) {
3837
		if (!pvt->peercallno) {
3797
			return -1;
3838
			return -1;
3798
		}
3839
		}
3799
	}
3840
	}
3800

    
   
3841

   
3801
	return 0;
3842
	return 0;
3802
}
3843
}
3803

    
   
3844

   
3804
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3845
static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3805
{
3846
{
3806
	struct ast_option_header *h;
3847
	struct ast_option_header *h;
3807
	int res;
3848
	int res;
3808

    
   
3849

   
3809
	switch (option) {
3850
	switch (option) {
3810
	case AST_OPTION_TXGAIN:
3851
	case AST_OPTION_TXGAIN:
3811
	case AST_OPTION_RXGAIN:
3852
	case AST_OPTION_RXGAIN:
3812
		/* these two cannot be sent, because they require a result */
3853
		/* these two cannot be sent, because they require a result */
3813
		errno = ENOSYS;
3854
		errno = ENOSYS;
3814
		return -1;
3855
		return -1;
3815
	default:
3856
	default:
3816
	{
3857
	{
3817
		unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3858
		unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3818
		struct chan_iax2_pvt *pvt;
3859
		struct chan_iax2_pvt *pvt;
3819

    
   
3860

   
3820
		ast_mutex_lock(&iaxsl[callno]);
3861
		ast_mutex_lock(&iaxsl[callno]);
3821
		pvt = iaxs[callno];
3862
		pvt = iaxs[callno];
3822

    
   
3863

   
3823
		if (wait_for_peercallno(pvt)) {
3864
		if (wait_for_peercallno(pvt)) {
3824
			ast_mutex_unlock(&iaxsl[callno]);
3865
			ast_mutex_unlock(&iaxsl[callno]);
3825
			return -1;
3866
			return -1;
3826
		}
3867
		}
3827

    
   
3868

   
3828
		ast_mutex_unlock(&iaxsl[callno]);
3869
		ast_mutex_unlock(&iaxsl[callno]);
3829

    
   
3870

   
3830
		if (!(h = ast_malloc(datalen + sizeof(*h)))) {
3871
		if (!(h = ast_malloc(datalen + sizeof(*h)))) {
3831
			return -1;
3872
			return -1;
3832
		}
3873
		}
3833

    
   
3874

   
3834
		h->flag = AST_OPTION_FLAG_REQUEST;
3875
		h->flag = AST_OPTION_FLAG_REQUEST;
3835
		h->option = htons(option);
3876
		h->option = htons(option);
3836
		memcpy(h->data, data, datalen);
3877
		memcpy(h->data, data, datalen);
3837
		res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3878
		res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3838
					  AST_CONTROL_OPTION, 0, (unsigned char *) h,
3879
					  AST_CONTROL_OPTION, 0, (unsigned char *) h,
3839
					  datalen + sizeof(*h), -1);
3880
					  datalen + sizeof(*h), -1);
3840
		ast_free(h);
3881
		ast_free(h);
3841
		return res;
3882
		return res;
3842
	}
3883
	}
3843
	}
3884
	}
3844
}
3885
}
3845

    
   
3886

   
3846
static struct ast_frame *iax2_read(struct ast_channel *c) 
3887
static struct ast_frame *iax2_read(struct ast_channel *c) 
3847
{
3888
{
3848
	ast_log(LOG_NOTICE, "I should never be called!\n");
3889
	ast_log(LOG_NOTICE, "I should never be called!\n");
3849
	return &ast_null_frame;
3890
	return &ast_null_frame;
3850
}
3891
}
3851

    
   
3892

   
3852
static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3893
static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3853
{
3894
{
3854
	int res;
3895
	int res;
3855
	struct iax_ie_data ied0;
3896
	struct iax_ie_data ied0;
3856
	struct iax_ie_data ied1;
3897
	struct iax_ie_data ied1;
3857
	unsigned int transferid = (unsigned int)ast_random();
3898
	unsigned int transferid = (unsigned int)ast_random();
3858
	memset(&ied0, 0, sizeof(ied0));
3899
	memset(&ied0, 0, sizeof(ied0));
3859
	iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3900
	iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3860
	iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3901
	iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3861
	iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3902
	iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3862

    
   
3903

   
3863
	memset(&ied1, 0, sizeof(ied1));
3904
	memset(&ied1, 0, sizeof(ied1));
3864
	iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3905
	iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3865
	iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3906
	iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3866
	iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3907
	iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3867
	
3908
	
3868
	res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3909
	res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3869
	if (res)
3910
	if (res)
3870
		return -1;
3911
		return -1;
3871
	res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3912
	res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3872
	if (res)
3913
	if (res)
3873
		return -1;
3914
		return -1;
3874
	iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3915
	iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3875
	iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3916
	iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3876
	return 0;
3917
	return 0;
3877
}
3918
}
3878

    
   
3919

   
3879
static void lock_both(unsigned short callno0, unsigned short callno1)
3920
static void lock_both(unsigned short callno0, unsigned short callno1)
3880
{
3921
{
3881
	ast_mutex_lock(&iaxsl[callno0]);
3922
	ast_mutex_lock(&iaxsl[callno0]);
3882
	while (ast_mutex_trylock(&iaxsl[callno1])) {
3923
	while (ast_mutex_trylock(&iaxsl[callno1])) {
3883
		DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
3924
		DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
3884
	}
3925
	}
3885
}
3926
}
3886

    
   
3927

   
3887
static void unlock_both(unsigned short callno0, unsigned short callno1)
3928
static void unlock_both(unsigned short callno0, unsigned short callno1)
3888
{
3929
{
3889
	ast_mutex_unlock(&iaxsl[callno1]);
3930
	ast_mutex_unlock(&iaxsl[callno1]);
3890
	ast_mutex_unlock(&iaxsl[callno0]);
3931
	ast_mutex_unlock(&iaxsl[callno0]);
3891
}
3932
}
3892

    
   
3933

   
3893
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)
3934
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)
3894
{
3935
{
3895
	struct ast_channel *cs[3];
3936
	struct ast_channel *cs[3];
3896
	struct ast_channel *who, *other;
3937
	struct ast_channel *who, *other;
3897
	int to = -1;
3938
	int to = -1;
3898
	int res = -1;
3939
	int res = -1;
3899
	int transferstarted=0;
3940
	int transferstarted=0;
3900
	struct ast_frame *f;
3941
	struct ast_frame *f;
3901
	unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3942
	unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3902
	unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3943
	unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3903
	struct timeval waittimer = {0, 0}, tv;
3944
	struct timeval waittimer = {0, 0}, tv;
3904

    
   
3945

   
3905
	/* We currently do not support native bridging if a timeoutms value has been provided */
3946
	/* We currently do not support native bridging if a timeoutms value has been provided */
3906
	if (timeoutms > 0) {
3947
	if (timeoutms > 0) {
3907
		return AST_BRIDGE_FAILED;
3948
		return AST_BRIDGE_FAILED;
3908
	}
3949
	}
3909

    
   
3950

   
3910
	timeoutms = 0;
3951
	timeoutms = 0;
3911

    
   
3952

   
3912
	lock_both(callno0, callno1);
3953
	lock_both(callno0, callno1);
3913
	if (!iaxs[callno0] || !iaxs[callno1]) {
3954
	if (!iaxs[callno0] || !iaxs[callno1]) {
3914
		unlock_both(callno0, callno1);
3955
		unlock_both(callno0, callno1);
3915
		return AST_BRIDGE_FAILED;
3956
		return AST_BRIDGE_FAILED;
3916
	}
3957
	}
3917
	/* Put them in native bridge mode */
3958
	/* Put them in native bridge mode */
3918
	if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3959
	if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3919
		iaxs[callno0]->bridgecallno = callno1;
3960
		iaxs[callno0]->bridgecallno = callno1;
3920
		iaxs[callno1]->bridgecallno = callno0;
3961
		iaxs[callno1]->bridgecallno = callno0;
3921
	}
3962
	}
3922
	/* If the bridge got retried, don't queue up more packets - the transfer request will be retransmitted as necessary */
3963
	/* If the bridge got retried, don't queue up more packets - the transfer request will be retransmitted as necessary */
3923
	if (iaxs[callno0]->transferring && iaxs[callno1]->transferring) {
3964
	if (iaxs[callno0]->transferring && iaxs[callno1]->transferring) {
3924
		transferstarted = 1;
3965
		transferstarted = 1;
3925
	}
3966
	}
3926
	unlock_both(callno0, callno1);
3967
	unlock_both(callno0, callno1);
3927

    
   
3968

   
3928
	/* If not, try to bridge until we can execute a transfer, if we can */
3969
	/* If not, try to bridge until we can execute a transfer, if we can */
3929
	cs[0] = c0;
3970
<