use the ARRAY_LEN macro for indexing through the iaxs/iaxsl arrays so that the size...
[asterisk-bristuff.git] / channels / chan_iax2.c
blobdeec4c0695e0899b3350d71c9f639382258198cc
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*! \file
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
25 * \par See also
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
31 /*** MODULEINFO
32 <use>zaptel</use>
33 <depend>res_features</depend>
34 ***/
36 #include "asterisk.h"
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <sys/types.h>
43 #include <sys/mman.h>
44 #include <dirent.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <sys/time.h>
51 #include <sys/signal.h>
52 #include <signal.h>
53 #include <string.h>
54 #include <strings.h>
55 #include <errno.h>
56 #include <unistd.h>
57 #include <netdb.h>
58 #include <fcntl.h>
59 #include <sys/stat.h>
60 #include <regex.h>
62 #ifdef HAVE_ZAPTEL
63 #include <sys/ioctl.h>
64 #include <zaptel/zaptel.h>
65 #endif
67 #include "asterisk/lock.h"
68 #include "asterisk/frame.h"
69 #include "asterisk/channel.h"
70 #include "asterisk/logger.h"
71 #include "asterisk/module.h"
72 #include "asterisk/pbx.h"
73 #include "asterisk/sched.h"
74 #include "asterisk/io.h"
75 #include "asterisk/config.h"
76 #include "asterisk/options.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/cdr.h"
81 #include "asterisk/crypto.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/app.h"
86 #include "asterisk/astdb.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/features.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/causes.h"
91 #include "asterisk/localtime.h"
92 #include "asterisk/aes.h"
93 #include "asterisk/dnsmgr.h"
94 #include "asterisk/devicestate.h"
95 #include "asterisk/netsock.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/linkedlists.h"
98 #include "asterisk/astobj2.h"
100 #include "iax2.h"
101 #include "iax2-parser.h"
102 #include "iax2-provision.h"
103 #include "jitterbuf.h"
105 /* Define SCHED_MULTITHREADED to run the scheduler in a special
106 multithreaded mode. */
107 #define SCHED_MULTITHREADED
109 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
110 thread is actually doing. */
111 #define DEBUG_SCHED_MULTITHREAD
113 #ifndef IPTOS_MINCOST
114 #define IPTOS_MINCOST 0x02
115 #endif
117 #ifdef SO_NO_CHECK
118 static int nochecksums = 0;
119 #endif
122 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
123 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
125 #define DEFAULT_THREAD_COUNT 10
126 #define DEFAULT_MAX_THREAD_COUNT 100
127 #define DEFAULT_RETRY_TIME 1000
128 #define MEMORY_SIZE 100
129 #define DEFAULT_DROP 3
131 #define DEBUG_SUPPORT
133 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
135 /* Sample over last 100 units to determine historic jitter */
136 #define GAMMA (0.01)
138 static struct ast_codec_pref prefs;
140 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
142 static char context[80] = "default";
144 static char language[MAX_LANGUAGE] = "";
145 static char regcontext[AST_MAX_CONTEXT] = "";
147 static int maxauthreq = 3;
148 static int max_retries = 4;
149 static int ping_time = 21;
150 static int lagrq_time = 10;
151 static int maxjitterbuffer=1000;
152 static int resyncthreshold=1000;
153 static int maxjitterinterps=10;
154 static int trunkfreq = 20;
155 static int authdebug = 1;
156 static int autokill = 0;
157 static int iaxcompat = 0;
159 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
161 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
163 static unsigned int tos = 0;
165 static int min_reg_expire;
166 static int max_reg_expire;
168 static int timingfd = -1; /* Timing file descriptor */
170 static struct ast_netsock_list *netsock;
171 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
172 static int defaultsockfd = -1;
174 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
176 /* Ethernet, etc */
177 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
178 /* T1, maybe ISDN */
179 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
180 ~AST_FORMAT_SLINEAR & \
181 ~AST_FORMAT_ULAW & \
182 ~AST_FORMAT_ALAW & \
183 ~AST_FORMAT_G722)
184 /* A modem */
185 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
186 ~AST_FORMAT_G726 & \
187 ~AST_FORMAT_G726_AAL2 & \
188 ~AST_FORMAT_ADPCM)
190 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
191 ~AST_FORMAT_G723_1)
194 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
195 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
196 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
198 static struct io_context *io;
199 static struct sched_context *sched;
201 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
203 static int iaxdebug = 0;
205 static int iaxtrunkdebug = 0;
207 static int test_losspct = 0;
208 #ifdef IAXTESTS
209 static int test_late = 0;
210 static int test_resync = 0;
211 static int test_jit = 0;
212 static int test_jitpct = 0;
213 #endif /* IAXTESTS */
215 static char accountcode[AST_MAX_ACCOUNT_CODE];
216 static char mohinterpret[MAX_MUSICCLASS];
217 static char mohsuggest[MAX_MUSICCLASS];
218 static int amaflags = 0;
219 static int adsi = 0;
220 static int delayreject = 0;
221 static int iax2_encryption = 0;
223 static struct ast_flags globalflags = { 0 };
225 static pthread_t netthreadid = AST_PTHREADT_NULL;
226 static pthread_t schedthreadid = AST_PTHREADT_NULL;
227 AST_MUTEX_DEFINE_STATIC(sched_lock);
228 static ast_cond_t sched_cond;
230 enum {
231 IAX_STATE_STARTED = (1 << 0),
232 IAX_STATE_AUTHENTICATED = (1 << 1),
233 IAX_STATE_TBD = (1 << 2),
234 IAX_STATE_UNCHANGED = (1 << 3),
235 } iax2_state;
237 struct iax2_context {
238 char context[AST_MAX_CONTEXT];
239 struct iax2_context *next;
242 enum {
243 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
244 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
245 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
246 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
247 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
248 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
249 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
250 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
251 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
252 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
253 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
254 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
255 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
256 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
257 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
258 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
259 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
260 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
261 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
262 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
263 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
264 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
265 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
266 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
267 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
268 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
269 response, so that we've achieved a three-way handshake with
270 them before sending voice or anything else*/
271 } iax2_flags;
273 static int global_rtautoclear = 120;
275 static int reload_config(void);
276 static int iax2_reload(int fd, int argc, char *argv[]);
279 struct iax2_user {
280 AST_DECLARE_STRING_FIELDS(
281 AST_STRING_FIELD(name);
282 AST_STRING_FIELD(secret);
283 AST_STRING_FIELD(dbsecret);
284 AST_STRING_FIELD(accountcode);
285 AST_STRING_FIELD(mohinterpret);
286 AST_STRING_FIELD(mohsuggest);
287 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
288 AST_STRING_FIELD(language);
289 AST_STRING_FIELD(cid_num);
290 AST_STRING_FIELD(cid_name);
293 int authmethods;
294 int encmethods;
295 int amaflags;
296 int adsi;
297 unsigned int flags;
298 int capability;
299 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
300 int curauthreq; /*!< Current number of outstanding AUTHREQs */
301 struct ast_codec_pref prefs;
302 struct ast_ha *ha;
303 struct iax2_context *contexts;
304 struct ast_variable *vars;
307 struct iax2_peer {
308 AST_DECLARE_STRING_FIELDS(
309 AST_STRING_FIELD(name);
310 AST_STRING_FIELD(username);
311 AST_STRING_FIELD(secret);
312 AST_STRING_FIELD(dbsecret);
313 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
315 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
316 AST_STRING_FIELD(context); /*!< For transfers only */
317 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
318 AST_STRING_FIELD(mailbox); /*!< Mailbox */
319 AST_STRING_FIELD(mohinterpret);
320 AST_STRING_FIELD(mohsuggest);
321 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
322 /* Suggested caller id if registering */
323 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
324 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
325 AST_STRING_FIELD(zonetag); /*!< Time Zone */
327 struct ast_codec_pref prefs;
328 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
329 struct sockaddr_in addr;
330 int formats;
331 int sockfd; /*!< Socket to use for transmission */
332 struct in_addr mask;
333 int adsi;
334 unsigned int flags;
336 /* Dynamic Registration fields */
337 struct sockaddr_in defaddr; /*!< Default address if there is one */
338 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
339 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
341 int expire; /*!< Schedule entry for expiry */
342 int expiry; /*!< How soon to expire */
343 int capability; /*!< Capability */
345 /* Qualification */
346 int callno; /*!< Call number of POKE request */
347 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
348 int lastms; /*!< How long last response took (in ms), or -1 for no response */
349 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
351 int pokefreqok; /*!< How often to check if the host is up */
352 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
353 int historicms; /*!< How long recent average responses took */
354 int smoothing; /*!< Sample over how many units to determine historic ms */
356 struct ast_ha *ha;
359 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
361 static struct iax2_trunk_peer {
362 ast_mutex_t lock;
363 int sockfd;
364 struct sockaddr_in addr;
365 struct timeval txtrunktime; /*!< Transmit trunktime */
366 struct timeval rxtrunktime; /*!< Receive trunktime */
367 struct timeval lasttxtime; /*!< Last transmitted trunktime */
368 struct timeval trunkact; /*!< Last trunk activity */
369 unsigned int lastsent; /*!< Last sent time */
370 /* Trunk data and length */
371 unsigned char *trunkdata;
372 unsigned int trunkdatalen;
373 unsigned int trunkdataalloc;
374 struct iax2_trunk_peer *next;
375 int trunkerror;
376 int calls;
377 } *tpeers = NULL;
379 AST_MUTEX_DEFINE_STATIC(tpeerlock);
381 struct iax_firmware {
382 struct iax_firmware *next;
383 int fd;
384 int mmaplen;
385 int dead;
386 struct ast_iax2_firmware_header *fwh;
387 unsigned char *buf;
390 enum iax_reg_state {
391 REG_STATE_UNREGISTERED = 0,
392 REG_STATE_REGSENT,
393 REG_STATE_AUTHSENT,
394 REG_STATE_REGISTERED,
395 REG_STATE_REJECTED,
396 REG_STATE_TIMEOUT,
397 REG_STATE_NOAUTH
400 enum iax_transfer_state {
401 TRANSFER_NONE = 0,
402 TRANSFER_BEGIN,
403 TRANSFER_READY,
404 TRANSFER_RELEASED,
405 TRANSFER_PASSTHROUGH,
406 TRANSFER_MBEGIN,
407 TRANSFER_MREADY,
408 TRANSFER_MRELEASED,
409 TRANSFER_MPASSTHROUGH,
410 TRANSFER_MEDIA,
411 TRANSFER_MEDIAPASS
414 struct iax2_registry {
415 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
416 char username[80];
417 char secret[80]; /*!< Password or key name in []'s */
418 char random[80];
419 int expire; /*!< Sched ID of expiration */
420 int refresh; /*!< How often to refresh */
421 enum iax_reg_state regstate;
422 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
423 int callno; /*!< Associated call number if applicable */
424 struct sockaddr_in us; /*!< Who the server thinks we are */
425 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
426 AST_LIST_ENTRY(iax2_registry) entry;
429 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
431 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
432 #define MIN_RETRY_TIME 100
433 #define MAX_RETRY_TIME 10000
435 #define MAX_JITTER_BUFFER 50
436 #define MIN_JITTER_BUFFER 10
438 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
439 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
441 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
443 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
444 #define TS_GAP_FOR_JB_RESYNC 5000
446 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
447 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
448 static int iaxdynamicthreadcount = 0;
449 static int iaxactivethreadcount = 0;
451 struct iax_rr {
452 int jitter;
453 int losspct;
454 int losscnt;
455 int packets;
456 int delay;
457 int dropped;
458 int ooo;
461 struct chan_iax2_pvt {
462 /*! Socket to send/receive on for this call */
463 int sockfd;
464 /*! Last received voice format */
465 int voiceformat;
466 /*! Last received video format */
467 int videoformat;
468 /*! Last sent voice format */
469 int svoiceformat;
470 /*! Last sent video format */
471 int svideoformat;
472 /*! What we are capable of sending */
473 int capability;
474 /*! Last received timestamp */
475 unsigned int last;
476 /*! Last sent timestamp - never send the same timestamp twice in a single call */
477 unsigned int lastsent;
478 /*! Timestamp of the last video frame sent */
479 unsigned int lastvsent;
480 /*! Next outgoing timestamp if everything is good */
481 unsigned int nextpred;
482 /*! True if the last voice we transmitted was not silence/CNG */
483 int notsilenttx;
484 /*! Ping time */
485 unsigned int pingtime;
486 /*! Max time for initial response */
487 int maxtime;
488 /*! Peer Address */
489 struct sockaddr_in addr;
490 /*! Actual used codec preferences */
491 struct ast_codec_pref prefs;
492 /*! Requested codec preferences */
493 struct ast_codec_pref rprefs;
494 /*! Our call number */
495 unsigned short callno;
496 /*! Peer callno */
497 unsigned short peercallno;
498 /*! Negotiated format, this is only used to remember what format was
499 chosen for an unauthenticated call so that the channel can get
500 created later using the right format */
501 int chosenformat;
502 /*! Peer selected format */
503 int peerformat;
504 /*! Peer capability */
505 int peercapability;
506 /*! timeval that we base our transmission on */
507 struct timeval offset;
508 /*! timeval that we base our delivery on */
509 struct timeval rxcore;
510 /*! The jitterbuffer */
511 jitterbuf *jb;
512 /*! active jb read scheduler id */
513 int jbid;
514 /*! LAG */
515 int lag;
516 /*! Error, as discovered by the manager */
517 int error;
518 /*! Owner if we have one */
519 struct ast_channel *owner;
520 /*! What's our state? */
521 struct ast_flags state;
522 /*! Expiry (optional) */
523 int expiry;
524 /*! Next outgoing sequence number */
525 unsigned char oseqno;
526 /*! Next sequence number they have not yet acknowledged */
527 unsigned char rseqno;
528 /*! Next incoming sequence number */
529 unsigned char iseqno;
530 /*! Last incoming sequence number we have acknowledged */
531 unsigned char aseqno;
533 AST_DECLARE_STRING_FIELDS(
534 /*! Peer name */
535 AST_STRING_FIELD(peer);
536 /*! Default Context */
537 AST_STRING_FIELD(context);
538 /*! Caller ID if available */
539 AST_STRING_FIELD(cid_num);
540 AST_STRING_FIELD(cid_name);
541 /*! Hidden Caller ID (i.e. ANI) if appropriate */
542 AST_STRING_FIELD(ani);
543 /*! DNID */
544 AST_STRING_FIELD(dnid);
545 /*! RDNIS */
546 AST_STRING_FIELD(rdnis);
547 /*! Requested Extension */
548 AST_STRING_FIELD(exten);
549 /*! Expected Username */
550 AST_STRING_FIELD(username);
551 /*! Expected Secret */
552 AST_STRING_FIELD(secret);
553 /*! MD5 challenge */
554 AST_STRING_FIELD(challenge);
555 /*! Public keys permitted keys for incoming authentication */
556 AST_STRING_FIELD(inkeys);
557 /*! Private key for outgoing authentication */
558 AST_STRING_FIELD(outkey);
559 /*! Preferred language */
560 AST_STRING_FIELD(language);
561 /*! Hostname/peername for naming purposes */
562 AST_STRING_FIELD(host);
564 AST_STRING_FIELD(dproot);
565 AST_STRING_FIELD(accountcode);
566 AST_STRING_FIELD(mohinterpret);
567 AST_STRING_FIELD(mohsuggest);
570 /*! permitted authentication methods */
571 int authmethods;
572 /*! permitted encryption methods */
573 int encmethods;
574 /*! Encryption AES-128 Key */
575 aes_encrypt_ctx ecx;
576 /*! Decryption AES-128 Key */
577 aes_decrypt_ctx dcx;
578 /*! 32 bytes of semi-random data */
579 unsigned char semirand[32];
580 /*! Associated registry */
581 struct iax2_registry *reg;
582 /*! Associated peer for poking */
583 struct iax2_peer *peerpoke;
584 /*! IAX_ flags */
585 unsigned int flags;
586 int adsi;
588 /*! Transferring status */
589 enum iax_transfer_state transferring;
590 /*! Transfer identifier */
591 int transferid;
592 /*! Who we are IAX transfering to */
593 struct sockaddr_in transfer;
594 /*! What's the new call number for the transfer */
595 unsigned short transfercallno;
596 /*! Transfer decrypt AES-128 Key */
597 aes_encrypt_ctx tdcx;
599 /*! Status of knowledge of peer ADSI capability */
600 int peeradsicpe;
602 /*! Who we are bridged to */
603 unsigned short bridgecallno;
605 int pingid; /*!< Transmit PING request */
606 int lagid; /*!< Retransmit lag request */
607 int autoid; /*!< Auto hangup for Dialplan requestor */
608 int authid; /*!< Authentication rejection ID */
609 int authfail; /*!< Reason to report failure */
610 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
611 int calling_ton;
612 int calling_tns;
613 int calling_pres;
614 int amaflags;
615 struct iax2_dpcache *dpentries;
616 struct ast_variable *vars;
617 /*! last received remote rr */
618 struct iax_rr remote_rr;
619 /*! Current base time: (just for stats) */
620 int min;
621 /*! Dropped frame count: (just for stats) */
622 int frames_dropped;
623 /*! received frame count: (just for stats) */
624 int frames_received;
627 static struct ast_iax2_queue {
628 AST_LIST_HEAD(, iax_frame) queue;
629 int count;
630 } iaxq;
633 * This module will get much higher performance when doing a lot of
634 * user and peer lookups if the number of buckets is increased from 1.
635 * However, to maintain old behavior for Asterisk 1.4, these are set to
636 * 1 by default. When using multiple buckets, search order through these
637 * containers is considered random, so you will not be able to depend on
638 * the order the entires are specified in iax.conf for matching order. */
639 #ifdef LOW_MEMORY
640 #define MAX_PEER_BUCKETS 1
641 /* #define MAX_PEER_BUCKETS 17 */
642 #else
643 #define MAX_PEER_BUCKETS 1
644 /* #define MAX_PEER_BUCKETS 563 */
645 #endif
646 static struct ao2_container *peers;
648 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
649 static struct ao2_container *users;
651 static struct ast_firmware_list {
652 struct iax_firmware *wares;
653 ast_mutex_t lock;
654 } waresl;
656 /*! Extension exists */
657 #define CACHE_FLAG_EXISTS (1 << 0)
658 /*! Extension is nonexistent */
659 #define CACHE_FLAG_NONEXISTENT (1 << 1)
660 /*! Extension can exist */
661 #define CACHE_FLAG_CANEXIST (1 << 2)
662 /*! Waiting to hear back response */
663 #define CACHE_FLAG_PENDING (1 << 3)
664 /*! Timed out */
665 #define CACHE_FLAG_TIMEOUT (1 << 4)
666 /*! Request transmitted */
667 #define CACHE_FLAG_TRANSMITTED (1 << 5)
668 /*! Timeout */
669 #define CACHE_FLAG_UNKNOWN (1 << 6)
670 /*! Matchmore */
671 #define CACHE_FLAG_MATCHMORE (1 << 7)
673 static struct iax2_dpcache {
674 char peercontext[AST_MAX_CONTEXT];
675 char exten[AST_MAX_EXTENSION];
676 struct timeval orig;
677 struct timeval expiry;
678 int flags;
679 unsigned short callno;
680 int waiters[256];
681 struct iax2_dpcache *next;
682 struct iax2_dpcache *peer; /*!< For linking in peers */
683 } *dpcache;
685 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
687 static void reg_source_db(struct iax2_peer *p);
688 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
690 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
692 #define IAX_IOSTATE_IDLE 0
693 #define IAX_IOSTATE_READY 1
694 #define IAX_IOSTATE_PROCESSING 2
695 #define IAX_IOSTATE_SCHEDREADY 3
697 #define IAX_TYPE_POOL 1
698 #define IAX_TYPE_DYNAMIC 2
700 struct iax2_pkt_buf {
701 AST_LIST_ENTRY(iax2_pkt_buf) entry;
702 size_t len;
703 unsigned char buf[1];
706 struct iax2_thread {
707 AST_LIST_ENTRY(iax2_thread) list;
708 int type;
709 int iostate;
710 #ifdef SCHED_MULTITHREADED
711 void (*schedfunc)(const void *);
712 const void *scheddata;
713 #endif
714 #ifdef DEBUG_SCHED_MULTITHREAD
715 char curfunc[80];
716 #endif
717 int actions;
718 pthread_t threadid;
719 int threadnum;
720 struct sockaddr_in iosin;
721 unsigned char readbuf[4096];
722 unsigned char *buf;
723 ssize_t buf_len;
724 size_t buf_size;
725 int iofd;
726 time_t checktime;
727 ast_mutex_t lock;
728 ast_cond_t cond;
729 unsigned int ready_for_signal:1;
730 /*! if this thread is processing a full frame,
731 some information about that frame will be stored
732 here, so we can avoid dispatching any more full
733 frames for that callno to other threads */
734 struct {
735 unsigned short callno;
736 struct sockaddr_in sin;
737 unsigned char type;
738 unsigned char csub;
739 } ffinfo;
740 /*! Queued up full frames for processing. If more full frames arrive for
741 * a call which this thread is already processing a full frame for, they
742 * are queued up here. */
743 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
746 /* Thread lists */
747 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
748 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
749 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
751 static void *iax2_process_thread(void *data);
753 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
755 ast_mutex_lock(lock);
756 ast_cond_signal(cond);
757 ast_mutex_unlock(lock);
760 static void iax_debug_output(const char *data)
762 if (iaxdebug)
763 ast_verbose("%s", data);
766 static void iax_error_output(const char *data)
768 ast_log(LOG_WARNING, "%s", data);
771 static void jb_error_output(const char *fmt, ...)
773 va_list args;
774 char buf[1024];
776 va_start(args, fmt);
777 vsnprintf(buf, 1024, fmt, args);
778 va_end(args);
780 ast_log(LOG_ERROR, buf);
783 static void jb_warning_output(const char *fmt, ...)
785 va_list args;
786 char buf[1024];
788 va_start(args, fmt);
789 vsnprintf(buf, 1024, fmt, args);
790 va_end(args);
792 ast_log(LOG_WARNING, buf);
795 static void jb_debug_output(const char *fmt, ...)
797 va_list args;
798 char buf[1024];
800 va_start(args, fmt);
801 vsnprintf(buf, 1024, fmt, args);
802 va_end(args);
804 ast_verbose(buf);
807 /* XXX We probably should use a mutex when working with this XXX */
808 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
809 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
810 static struct timeval lastused[ARRAY_LEN(iaxs)];
812 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
813 but keeps the division between trunked and non-trunked better. */
814 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
816 static int maxtrunkcall = TRUNK_CALL_START;
817 static int maxnontrunkcall = 1;
819 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);
820 static int expire_registry(const void *data);
821 static int iax2_answer(struct ast_channel *c);
822 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
823 static int iax2_devicestate(void *data);
824 static int iax2_digit_begin(struct ast_channel *c, char digit);
825 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
826 static int iax2_do_register(struct iax2_registry *reg);
827 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
828 static int iax2_hangup(struct ast_channel *c);
829 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
830 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
831 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
832 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
833 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
834 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
835 static int iax2_sendtext(struct ast_channel *c, const char *text);
836 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
837 static int iax2_transfer(struct ast_channel *c, const char *dest);
838 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
839 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
840 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
841 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
842 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
843 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
844 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
845 static struct ast_frame *iax2_read(struct ast_channel *c);
846 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
847 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
848 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
849 static void prune_peers(void);
851 static const struct ast_channel_tech iax2_tech = {
852 .type = "IAX2",
853 .description = tdesc,
854 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
855 .properties = AST_CHAN_TP_WANTSJITTER,
856 .requester = iax2_request,
857 .devicestate = iax2_devicestate,
858 .send_digit_begin = iax2_digit_begin,
859 .send_digit_end = iax2_digit_end,
860 .send_text = iax2_sendtext,
861 .send_image = iax2_sendimage,
862 .send_html = iax2_sendhtml,
863 .call = iax2_call,
864 .hangup = iax2_hangup,
865 .answer = iax2_answer,
866 .read = iax2_read,
867 .write = iax2_write,
868 .write_video = iax2_write,
869 .indicate = iax2_indicate,
870 .setoption = iax2_setoption,
871 .bridge = iax2_bridge,
872 .transfer = iax2_transfer,
873 .fixup = iax2_fixup,
876 /* WARNING: insert_idle_thread should only ever be called within the
877 * context of an iax2_process_thread() thread.
879 static void insert_idle_thread(struct iax2_thread *thread)
881 if (thread->type == IAX_TYPE_DYNAMIC) {
882 AST_LIST_LOCK(&dynamic_list);
883 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
884 AST_LIST_UNLOCK(&dynamic_list);
885 } else {
886 AST_LIST_LOCK(&idle_list);
887 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
888 AST_LIST_UNLOCK(&idle_list);
891 return;
894 static struct iax2_thread *find_idle_thread(void)
896 pthread_attr_t attr;
897 struct iax2_thread *thread = NULL;
899 /* Pop the head of the list off */
900 AST_LIST_LOCK(&idle_list);
901 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
902 AST_LIST_UNLOCK(&idle_list);
904 /* If no idle thread is available from the regular list, try dynamic */
905 if (thread == NULL) {
906 AST_LIST_LOCK(&dynamic_list);
907 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
908 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
909 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
910 /* We need to MAKE a thread! */
911 if ((thread = ast_calloc(1, sizeof(*thread)))) {
912 thread->threadnum = iaxdynamicthreadcount;
913 thread->type = IAX_TYPE_DYNAMIC;
914 ast_mutex_init(&thread->lock);
915 ast_cond_init(&thread->cond, NULL);
916 pthread_attr_init(&attr);
917 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
918 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
919 free(thread);
920 thread = NULL;
921 } else {
922 /* All went well and the thread is up, so increment our count */
923 iaxdynamicthreadcount++;
925 /* Wait for the thread to be ready before returning it to the caller */
926 while (!thread->ready_for_signal)
927 usleep(1);
931 AST_LIST_UNLOCK(&dynamic_list);
934 /* this thread is not processing a full frame (since it is idle),
935 so ensure that the field for the full frame call number is empty */
936 if (thread)
937 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
939 return thread;
942 #ifdef SCHED_MULTITHREADED
943 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
945 struct iax2_thread *thread = NULL;
946 static time_t lasterror;
947 static time_t t;
949 thread = find_idle_thread();
951 if (thread != NULL) {
952 thread->schedfunc = func;
953 thread->scheddata = data;
954 thread->iostate = IAX_IOSTATE_SCHEDREADY;
955 #ifdef DEBUG_SCHED_MULTITHREAD
956 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
957 #endif
958 signal_condition(&thread->lock, &thread->cond);
959 return 0;
961 time(&t);
962 if (t != lasterror && option_debug)
963 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for scheduling!\n");
964 lasterror = t;
966 return -1;
968 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
969 #endif
971 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
973 int res;
975 res = ast_sched_add(con, when, callback, data);
976 signal_condition(&sched_lock, &sched_cond);
978 return res;
981 static int send_ping(const void *data);
983 static void __send_ping(const void *data)
985 int callno = (long)data;
986 ast_mutex_lock(&iaxsl[callno]);
987 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
988 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
989 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
991 ast_mutex_unlock(&iaxsl[callno]);
994 static int send_ping(const void *data)
996 #ifdef SCHED_MULTITHREADED
997 if (schedule_action(__send_ping, data))
998 #endif
999 __send_ping(data);
1000 return 0;
1003 static int get_encrypt_methods(const char *s)
1005 int e;
1006 if (!strcasecmp(s, "aes128"))
1007 e = IAX_ENCRYPT_AES128;
1008 else if (ast_true(s))
1009 e = IAX_ENCRYPT_AES128;
1010 else
1011 e = 0;
1012 return e;
1015 static int send_lagrq(const void *data);
1017 static void __send_lagrq(const void *data)
1019 int callno = (long)data;
1020 /* Ping only if it's real not if it's bridged */
1021 ast_mutex_lock(&iaxsl[callno]);
1022 if (iaxs[callno] && iaxs[callno]->lagid > -1) {
1023 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1024 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1026 ast_mutex_unlock(&iaxsl[callno]);
1029 static int send_lagrq(const void *data)
1031 #ifdef SCHED_MULTITHREADED
1032 if (schedule_action(__send_lagrq, data))
1033 #endif
1034 __send_lagrq(data);
1035 return 0;
1038 static unsigned char compress_subclass(int subclass)
1040 int x;
1041 int power=-1;
1042 /* If it's 128 or smaller, just return it */
1043 if (subclass < IAX_FLAG_SC_LOG)
1044 return subclass;
1045 /* Otherwise find its power */
1046 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1047 if (subclass & (1 << x)) {
1048 if (power > -1) {
1049 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1050 return 0;
1051 } else
1052 power = x;
1055 return power | IAX_FLAG_SC_LOG;
1058 static int uncompress_subclass(unsigned char csub)
1060 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1061 if (csub & IAX_FLAG_SC_LOG) {
1062 /* special case for 'compressed' -1 */
1063 if (csub == 0xff)
1064 return -1;
1065 else
1066 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1068 else
1069 return csub;
1073 * \note The only member of the peer passed here guaranteed to be set is the name field
1075 static int peer_hash_cb(const void *obj, const int flags)
1077 const struct iax2_peer *peer = obj;
1079 return ast_str_hash(peer->name);
1083 * \note The only member of the peer passed here guaranteed to be set is the name field
1085 static int peer_cmp_cb(void *obj, void *arg, int flags)
1087 struct iax2_peer *peer = obj, *peer2 = arg;
1089 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1093 * \note The only member of the user passed here guaranteed to be set is the name field
1095 static int user_hash_cb(const void *obj, const int flags)
1097 const struct iax2_user *user = obj;
1099 return ast_str_hash(user->name);
1103 * \note The only member of the user passed here guaranteed to be set is the name field
1105 static int user_cmp_cb(void *obj, void *arg, int flags)
1107 struct iax2_user *user = obj, *user2 = arg;
1109 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1113 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1114 * so do not call it with a pvt lock held.
1116 static struct iax2_peer *find_peer(const char *name, int realtime)
1118 struct iax2_peer *peer = NULL;
1119 struct iax2_peer tmp_peer = {
1120 .name = name,
1123 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1125 /* Now go for realtime if applicable */
1126 if(!peer && realtime)
1127 peer = realtime_peer(name, NULL);
1129 return peer;
1132 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1134 ao2_ref(peer, +1);
1135 return peer;
1138 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1140 ao2_ref(peer, -1);
1141 return NULL;
1144 static inline struct iax2_user *user_ref(struct iax2_user *user)
1146 ao2_ref(user, +1);
1147 return user;
1150 static inline struct iax2_user *user_unref(struct iax2_user *user)
1152 ao2_ref(user, -1);
1153 return NULL;
1156 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1158 struct iax2_peer *peer = NULL;
1159 int res = 0;
1160 struct ao2_iterator i;
1162 i = ao2_iterator_init(peers, 0);
1163 while ((peer = ao2_iterator_next(&i))) {
1164 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1165 (peer->addr.sin_port == sin.sin_port)) {
1166 ast_copy_string(host, peer->name, len);
1167 peer_unref(peer);
1168 res = 1;
1169 break;
1171 peer_unref(peer);
1174 if (!peer) {
1175 peer = realtime_peer(NULL, &sin);
1176 if (peer) {
1177 ast_copy_string(host, peer->name, len);
1178 peer_unref(peer);
1179 res = 1;
1183 return res;
1186 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1188 struct chan_iax2_pvt *tmp;
1189 jb_conf jbconf;
1191 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1192 return NULL;
1194 if (ast_string_field_init(tmp, 32)) {
1195 free(tmp);
1196 tmp = NULL;
1197 return NULL;
1200 tmp->prefs = prefs;
1201 tmp->callno = 0;
1202 tmp->peercallno = 0;
1203 tmp->transfercallno = 0;
1204 tmp->bridgecallno = 0;
1205 tmp->pingid = -1;
1206 tmp->lagid = -1;
1207 tmp->autoid = -1;
1208 tmp->authid = -1;
1209 tmp->initid = -1;
1211 ast_string_field_set(tmp,exten, "s");
1212 ast_string_field_set(tmp,host, host);
1214 tmp->jb = jb_new();
1215 tmp->jbid = -1;
1216 jbconf.max_jitterbuf = maxjitterbuffer;
1217 jbconf.resync_threshold = resyncthreshold;
1218 jbconf.max_contig_interp = maxjitterinterps;
1219 jb_setconf(tmp->jb,&jbconf);
1221 return tmp;
1224 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1226 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1227 if (new) {
1228 size_t afdatalen = new->afdatalen;
1229 memcpy(new, fr, sizeof(*new));
1230 iax_frame_wrap(new, &fr->af);
1231 new->afdatalen = afdatalen;
1232 new->data = NULL;
1233 new->datalen = 0;
1234 new->direction = DIRECTION_INGRESS;
1235 new->retrans = -1;
1237 return new;
1240 #define NEW_PREVENT 0
1241 #define NEW_ALLOW 1
1242 #define NEW_FORCE 2
1244 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur, int full_frame)
1246 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1247 (cur->addr.sin_port == sin->sin_port)) {
1248 /* This is the main host */
1249 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1250 (full_frame ? dcallno == cur->callno : 1) ) {
1251 /* That's us. Be sure we keep track of the peer call number */
1252 return 1;
1255 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1256 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1257 /* We're transferring */
1258 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1259 return 1;
1261 return 0;
1264 static void update_max_trunk(void)
1266 int max = TRUNK_CALL_START;
1267 int x;
1269 /* XXX Prolly don't need locks here XXX */
1270 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1271 if (iaxs[x]) {
1272 max = x + 1;
1276 maxtrunkcall = max;
1277 if (option_debug && iaxdebug)
1278 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1281 static void update_max_nontrunk(void)
1283 int max = 1;
1284 int x;
1285 /* XXX Prolly don't need locks here XXX */
1286 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1287 if (iaxs[x])
1288 max = x + 1;
1290 maxnontrunkcall = max;
1291 if (option_debug && iaxdebug)
1292 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1295 static int make_trunk(unsigned short callno, int locked)
1297 int x;
1298 int res= 0;
1299 struct timeval now;
1300 if (iaxs[callno]->oseqno) {
1301 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1302 return -1;
1304 if (callno & TRUNK_CALL_START) {
1305 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1306 return -1;
1308 gettimeofday(&now, NULL);
1309 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1310 ast_mutex_lock(&iaxsl[x]);
1311 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1312 iaxs[x] = iaxs[callno];
1313 iaxs[x]->callno = x;
1314 iaxs[callno] = NULL;
1315 /* Update the two timers that should have been started */
1316 AST_SCHED_DEL(sched, iaxs[x]->pingid);
1317 AST_SCHED_DEL(sched, iaxs[x]->lagid);
1318 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1319 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1320 if (locked)
1321 ast_mutex_unlock(&iaxsl[callno]);
1322 res = x;
1323 if (!locked)
1324 ast_mutex_unlock(&iaxsl[x]);
1325 break;
1327 ast_mutex_unlock(&iaxsl[x]);
1329 if (x >= ARRAY_LEN(iaxs) - 1) {
1330 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1331 return -1;
1333 if (option_debug)
1334 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1335 /* We move this call from a non-trunked to a trunked call */
1336 update_max_trunk();
1337 update_max_nontrunk();
1338 return res;
1342 * \note Calling this function while holding another pvt lock can cause a deadlock.
1344 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int full_frame)
1346 int res = 0;
1347 int x;
1348 struct timeval now;
1349 char host[80];
1351 if (new <= NEW_ALLOW) {
1352 /* Look for an existing connection first */
1353 for (x = 1; !res && x < maxnontrunkcall; x++) {
1354 ast_mutex_lock(&iaxsl[x]);
1355 if (iaxs[x]) {
1356 /* Look for an exact match */
1357 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1358 res = x;
1361 if (!res || !return_locked)
1362 ast_mutex_unlock(&iaxsl[x]);
1364 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1365 ast_mutex_lock(&iaxsl[x]);
1366 if (iaxs[x]) {
1367 /* Look for an exact match */
1368 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1369 res = x;
1372 if (!res || !return_locked)
1373 ast_mutex_unlock(&iaxsl[x]);
1376 if (!res && (new >= NEW_ALLOW)) {
1377 int start, found = 0;
1379 /* It may seem odd that we look through the peer list for a name for
1380 * this *incoming* call. Well, it is weird. However, users don't
1381 * have an IP address/port number that we can match against. So,
1382 * this is just checking for a peer that has that IP/port and
1383 * assuming that we have a user of the same name. This isn't always
1384 * correct, but it will be changed if needed after authentication. */
1385 if (!iax2_getpeername(*sin, host, sizeof(host)))
1386 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1388 now = ast_tvnow();
1389 start = 1 + (ast_random() % (TRUNK_CALL_START - 1));
1390 for (x = start; 1; x++) {
1391 if (x == TRUNK_CALL_START) {
1392 x = 0;
1393 continue;
1396 /* Find first unused call number that hasn't been used in a while */
1397 ast_mutex_lock(&iaxsl[x]);
1398 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1399 found = 1;
1400 break;
1402 ast_mutex_unlock(&iaxsl[x]);
1404 if (x == start - 1) {
1405 break;
1408 /* We've still got lock held if we found a spot */
1409 if (x == start - 1 && !found) {
1410 ast_log(LOG_WARNING, "No more space\n");
1411 return 0;
1413 iaxs[x] = new_iax(sin, host);
1414 update_max_nontrunk();
1415 if (iaxs[x]) {
1416 if (option_debug && iaxdebug)
1417 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1418 iaxs[x]->sockfd = sockfd;
1419 iaxs[x]->addr.sin_port = sin->sin_port;
1420 iaxs[x]->addr.sin_family = sin->sin_family;
1421 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1422 iaxs[x]->peercallno = callno;
1423 iaxs[x]->callno = x;
1424 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1425 iaxs[x]->expiry = min_reg_expire;
1426 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1427 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1428 iaxs[x]->amaflags = amaflags;
1429 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1431 ast_string_field_set(iaxs[x], accountcode, accountcode);
1432 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1433 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1434 } else {
1435 ast_log(LOG_WARNING, "Out of resources\n");
1436 ast_mutex_unlock(&iaxsl[x]);
1437 return 0;
1439 if (!return_locked)
1440 ast_mutex_unlock(&iaxsl[x]);
1441 res = x;
1443 return res;
1446 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1448 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1451 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1453 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1456 static void iax2_frame_free(struct iax_frame *fr)
1458 AST_SCHED_DEL(sched, fr->retrans);
1459 iax_frame_free(fr);
1463 * \brief Queue a frame to a call's owning asterisk channel
1465 * \pre This function assumes that iaxsl[callno] is locked when called.
1467 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1468 * was valid before calling it, it may no longer be valid after calling it.
1469 * This function may unlock and lock the mutex associated with this callno,
1470 * meaning that another thread may grab it and destroy the call.
1472 static int iax2_queue_frame(int callno, struct ast_frame *f)
1474 for (;;) {
1475 if (iaxs[callno] && iaxs[callno]->owner) {
1476 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1477 /* Avoid deadlock by pausing and trying again */
1478 ast_mutex_unlock(&iaxsl[callno]);
1479 usleep(1);
1480 ast_mutex_lock(&iaxsl[callno]);
1481 } else {
1482 ast_queue_frame(iaxs[callno]->owner, f);
1483 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1484 break;
1486 } else
1487 break;
1489 return 0;
1493 * \brief Queue a hangup frame on the ast_channel owner
1495 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1496 * is active for the given call number.
1498 * \pre Assumes lock for callno is already held.
1500 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1501 * was valid before calling it, it may no longer be valid after calling it.
1502 * This function may unlock and lock the mutex associated with this callno,
1503 * meaning that another thread may grab it and destroy the call.
1505 static int iax2_queue_hangup(int callno)
1507 for (;;) {
1508 if (iaxs[callno] && iaxs[callno]->owner) {
1509 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1510 /* Avoid deadlock by pausing and trying again */
1511 ast_mutex_unlock(&iaxsl[callno]);
1512 usleep(1);
1513 ast_mutex_lock(&iaxsl[callno]);
1514 } else {
1515 ast_queue_hangup(iaxs[callno]->owner);
1516 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1517 break;
1519 } else
1520 break;
1522 return 0;
1526 * \brief Queue a control frame on the ast_channel owner
1528 * This function queues a control frame on the owner of the IAX2 pvt struct that
1529 * is active for the given call number.
1531 * \pre Assumes lock for callno is already held.
1533 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1534 * was valid before calling it, it may no longer be valid after calling it.
1535 * This function may unlock and lock the mutex associated with this callno,
1536 * meaning that another thread may grab it and destroy the call.
1538 static int iax2_queue_control_data(int callno,
1539 enum ast_control_frame_type control, const void *data, size_t datalen)
1541 for (;;) {
1542 if (iaxs[callno] && iaxs[callno]->owner) {
1543 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1544 /* Avoid deadlock by pausing and trying again */
1545 ast_mutex_unlock(&iaxsl[callno]);
1546 usleep(1);
1547 ast_mutex_lock(&iaxsl[callno]);
1548 } else {
1549 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1550 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1551 break;
1553 } else
1554 break;
1556 return 0;
1558 static void destroy_firmware(struct iax_firmware *cur)
1560 /* Close firmware */
1561 if (cur->fwh) {
1562 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1564 close(cur->fd);
1565 free(cur);
1568 static int try_firmware(char *s)
1570 struct stat stbuf;
1571 struct iax_firmware *cur;
1572 int ifd;
1573 int fd;
1574 int res;
1576 struct ast_iax2_firmware_header *fwh, fwh2;
1577 struct MD5Context md5;
1578 unsigned char sum[16];
1579 unsigned char buf[1024];
1580 int len, chunk;
1581 char *s2;
1582 char *last;
1583 s2 = alloca(strlen(s) + 100);
1584 if (!s2) {
1585 ast_log(LOG_WARNING, "Alloca failed!\n");
1586 return -1;
1588 last = strrchr(s, '/');
1589 if (last)
1590 last++;
1591 else
1592 last = s;
1593 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1594 res = stat(s, &stbuf);
1595 if (res < 0) {
1596 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1597 return -1;
1599 /* Make sure it's not a directory */
1600 if (S_ISDIR(stbuf.st_mode))
1601 return -1;
1602 ifd = open(s, O_RDONLY);
1603 if (ifd < 0) {
1604 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1605 return -1;
1607 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
1608 if (fd < 0) {
1609 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1610 close(ifd);
1611 return -1;
1613 /* Unlink our newly created file */
1614 unlink(s2);
1616 /* Now copy the firmware into it */
1617 len = stbuf.st_size;
1618 while(len) {
1619 chunk = len;
1620 if (chunk > sizeof(buf))
1621 chunk = sizeof(buf);
1622 res = read(ifd, buf, chunk);
1623 if (res != chunk) {
1624 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1625 close(ifd);
1626 close(fd);
1627 return -1;
1629 res = write(fd, buf, chunk);
1630 if (res != chunk) {
1631 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1632 close(ifd);
1633 close(fd);
1634 return -1;
1636 len -= chunk;
1638 close(ifd);
1639 /* Return to the beginning */
1640 lseek(fd, 0, SEEK_SET);
1641 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1642 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1643 close(fd);
1644 return -1;
1646 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1647 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1648 close(fd);
1649 return -1;
1651 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1652 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1653 close(fd);
1654 return -1;
1656 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1657 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1658 close(fd);
1659 return -1;
1661 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1662 if (fwh == (void *) -1) {
1663 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1664 close(fd);
1665 return -1;
1667 MD5Init(&md5);
1668 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1669 MD5Final(sum, &md5);
1670 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1671 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1672 munmap((void*)fwh, stbuf.st_size);
1673 close(fd);
1674 return -1;
1676 cur = waresl.wares;
1677 while(cur) {
1678 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1679 /* Found a candidate */
1680 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1681 /* The version we have on loaded is older, load this one instead */
1682 break;
1683 /* This version is no newer than what we have. Don't worry about it.
1684 We'll consider it a proper load anyhow though */
1685 munmap((void*)fwh, stbuf.st_size);
1686 close(fd);
1687 return 0;
1689 cur = cur->next;
1691 if (!cur) {
1692 /* Allocate a new one and link it */
1693 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1694 cur->fd = -1;
1695 cur->next = waresl.wares;
1696 waresl.wares = cur;
1699 if (cur) {
1700 if (cur->fwh) {
1701 munmap((void*)cur->fwh, cur->mmaplen);
1703 if (cur->fd > -1)
1704 close(cur->fd);
1705 cur->fwh = fwh;
1706 cur->fd = fd;
1707 cur->mmaplen = stbuf.st_size;
1708 cur->dead = 0;
1710 return 0;
1713 static int iax_check_version(char *dev)
1715 int res = 0;
1716 struct iax_firmware *cur;
1717 if (!ast_strlen_zero(dev)) {
1718 ast_mutex_lock(&waresl.lock);
1719 cur = waresl.wares;
1720 while(cur) {
1721 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1722 res = ntohs(cur->fwh->version);
1723 break;
1725 cur = cur->next;
1727 ast_mutex_unlock(&waresl.lock);
1729 return res;
1732 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1734 int res = -1;
1735 unsigned int bs = desc & 0xff;
1736 unsigned int start = (desc >> 8) & 0xffffff;
1737 unsigned int bytes;
1738 struct iax_firmware *cur;
1739 if (!ast_strlen_zero((char *)dev) && bs) {
1740 start *= bs;
1741 ast_mutex_lock(&waresl.lock);
1742 cur = waresl.wares;
1743 while(cur) {
1744 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1745 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1746 if (start < ntohl(cur->fwh->datalen)) {
1747 bytes = ntohl(cur->fwh->datalen) - start;
1748 if (bytes > bs)
1749 bytes = bs;
1750 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1751 } else {
1752 bytes = 0;
1753 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1755 if (bytes == bs)
1756 res = 0;
1757 else
1758 res = 1;
1759 break;
1761 cur = cur->next;
1763 ast_mutex_unlock(&waresl.lock);
1765 return res;
1769 static void reload_firmware(int unload)
1771 struct iax_firmware *cur, *curl, *curp;
1772 DIR *fwd;
1773 struct dirent *de;
1774 char dir[256];
1775 char fn[256];
1776 /* Mark all as dead */
1777 ast_mutex_lock(&waresl.lock);
1778 cur = waresl.wares;
1779 while(cur) {
1780 cur->dead = 1;
1781 cur = cur->next;
1784 /* Now that we've freed them, load the new ones */
1785 if (!unload) {
1786 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1787 fwd = opendir(dir);
1788 if (fwd) {
1789 while((de = readdir(fwd))) {
1790 if (de->d_name[0] != '.') {
1791 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1792 if (!try_firmware(fn)) {
1793 if (option_verbose > 1)
1794 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1798 closedir(fwd);
1799 } else
1800 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1803 /* Clean up leftovers */
1804 cur = waresl.wares;
1805 curp = NULL;
1806 while(cur) {
1807 curl = cur;
1808 cur = cur->next;
1809 if (curl->dead) {
1810 if (curp) {
1811 curp->next = cur;
1812 } else {
1813 waresl.wares = cur;
1815 destroy_firmware(curl);
1816 } else {
1817 curp = cur;
1820 ast_mutex_unlock(&waresl.lock);
1824 * \note This function assumes that iaxsl[callno] is locked when called.
1826 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1827 * was valid before calling it, it may no longer be valid after calling it.
1828 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1829 * associated with this callno, meaning that another thread may grab it and destroy the call.
1831 static int __do_deliver(void *data)
1833 /* Just deliver the packet by using queueing. This is called by
1834 the IAX thread with the iaxsl lock held. */
1835 struct iax_frame *fr = data;
1836 fr->retrans = -1;
1837 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
1838 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1839 iax2_queue_frame(fr->callno, &fr->af);
1840 /* Free our iax frame */
1841 iax2_frame_free(fr);
1842 /* And don't run again */
1843 return 0;
1846 static int handle_error(void)
1848 /* XXX Ideally we should figure out why an error occured and then abort those
1849 rather than continuing to try. Unfortunately, the published interface does
1850 not seem to work XXX */
1851 #if 0
1852 struct sockaddr_in *sin;
1853 int res;
1854 struct msghdr m;
1855 struct sock_extended_err e;
1856 m.msg_name = NULL;
1857 m.msg_namelen = 0;
1858 m.msg_iov = NULL;
1859 m.msg_control = &e;
1860 m.msg_controllen = sizeof(e);
1861 m.msg_flags = 0;
1862 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1863 if (res < 0)
1864 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1865 else {
1866 if (m.msg_controllen) {
1867 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1868 if (sin)
1869 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1870 else
1871 ast_log(LOG_WARNING, "No address detected??\n");
1872 } else {
1873 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1876 #endif
1877 return 0;
1880 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1882 int res;
1883 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1884 sizeof(*sin));
1885 if (res < 0) {
1886 if (option_debug)
1887 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1888 handle_error();
1889 } else
1890 res = 0;
1891 return res;
1894 static int send_packet(struct iax_frame *f)
1896 int res;
1897 int callno = f->callno;
1899 /* Don't send if there was an error, but return error instead */
1900 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1901 return -1;
1903 /* Called with iaxsl held */
1904 if (option_debug > 2 && iaxdebug)
1905 ast_log(LOG_DEBUG, "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));
1906 if (f->transfer) {
1907 if (iaxdebug)
1908 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1909 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1910 sizeof(iaxs[callno]->transfer));
1911 } else {
1912 if (iaxdebug)
1913 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1914 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1915 sizeof(iaxs[callno]->addr));
1917 if (res < 0) {
1918 if (option_debug && iaxdebug)
1919 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1920 handle_error();
1921 } else
1922 res = 0;
1923 return res;
1926 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1928 /* Decrement AUTHREQ count if needed */
1929 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1930 struct iax2_user *user;
1931 struct iax2_user tmp_user = {
1932 .name = pvt->username,
1935 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1936 if (user) {
1937 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1938 user_unref(user);
1941 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1943 /* No more pings or lagrq's */
1944 AST_SCHED_DEL(sched, pvt->pingid);
1945 AST_SCHED_DEL(sched, pvt->lagid);
1946 AST_SCHED_DEL(sched, pvt->autoid);
1947 AST_SCHED_DEL(sched, pvt->authid);
1948 AST_SCHED_DEL(sched, pvt->initid);
1949 AST_SCHED_DEL(sched, pvt->jbid);
1953 * \note Since this function calls iax2_queue_hangup(), the pvt struct
1954 * for the given call number may disappear during its execution.
1956 static int iax2_predestroy(int callno)
1958 struct ast_channel *c;
1959 struct chan_iax2_pvt *pvt = iaxs[callno];
1961 if (!pvt)
1962 return -1;
1963 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1964 iax2_destroy_helper(pvt);
1965 ast_set_flag(pvt, IAX_ALREADYGONE);
1967 c = pvt->owner;
1968 if (c) {
1969 c->tech_pvt = NULL;
1970 iax2_queue_hangup(callno);
1971 pvt->owner = NULL;
1972 ast_module_unref(ast_module_info->self);
1974 return 0;
1977 static void iax2_destroy(int callno)
1979 struct chan_iax2_pvt *pvt;
1980 struct iax_frame *cur;
1981 struct ast_channel *owner;
1983 retry:
1984 pvt = iaxs[callno];
1985 gettimeofday(&lastused[callno], NULL);
1987 owner = pvt ? pvt->owner : NULL;
1989 if (owner) {
1990 if (ast_mutex_trylock(&owner->lock)) {
1991 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1992 ast_mutex_unlock(&iaxsl[callno]);
1993 usleep(1);
1994 ast_mutex_lock(&iaxsl[callno]);
1995 goto retry;
1998 if (!owner)
1999 iaxs[callno] = NULL;
2000 if (pvt) {
2001 if (!owner)
2002 pvt->owner = NULL;
2003 iax2_destroy_helper(pvt);
2005 /* Already gone */
2006 ast_set_flag(pvt, IAX_ALREADYGONE);
2008 if (owner) {
2009 /* If there's an owner, prod it to give up */
2010 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2011 * because we already hold the owner channel lock. */
2012 ast_queue_hangup(owner);
2015 AST_LIST_LOCK(&iaxq.queue);
2016 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2017 /* Cancel any pending transmissions */
2018 if (cur->callno == pvt->callno)
2019 cur->retries = -1;
2021 AST_LIST_UNLOCK(&iaxq.queue);
2023 if (pvt->reg)
2024 pvt->reg->callno = 0;
2025 if (!owner) {
2026 jb_frame frame;
2027 if (pvt->vars) {
2028 ast_variables_destroy(pvt->vars);
2029 pvt->vars = NULL;
2032 while (jb_getall(pvt->jb, &frame) == JB_OK)
2033 iax2_frame_free(frame.data);
2034 jb_destroy(pvt->jb);
2035 /* gotta free up the stringfields */
2036 ast_string_field_free_memory(pvt);
2037 free(pvt);
2040 if (owner) {
2041 ast_mutex_unlock(&owner->lock);
2043 if (callno & 0x4000)
2044 update_max_trunk();
2047 static int update_packet(struct iax_frame *f)
2049 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2050 struct ast_iax2_full_hdr *fh = f->data;
2051 /* Mark this as a retransmission */
2052 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2053 /* Update iseqno */
2054 f->iseqno = iaxs[f->callno]->iseqno;
2055 fh->iseqno = f->iseqno;
2056 return 0;
2059 static int attempt_transmit(const void *data);
2060 static void __attempt_transmit(const void *data)
2062 /* Attempt to transmit the frame to the remote peer...
2063 Called without iaxsl held. */
2064 struct iax_frame *f = (struct iax_frame *)data;
2065 int freeme=0;
2066 int callno = f->callno;
2067 /* Make sure this call is still active */
2068 if (callno)
2069 ast_mutex_lock(&iaxsl[callno]);
2070 if (callno && iaxs[callno]) {
2071 if ((f->retries < 0) /* Already ACK'd */ ||
2072 (f->retries >= max_retries) /* Too many attempts */) {
2073 /* Record an error if we've transmitted too many times */
2074 if (f->retries >= max_retries) {
2075 if (f->transfer) {
2076 /* Transfer timeout */
2077 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2078 } else if (f->final) {
2079 if (f->final)
2080 iax2_destroy(callno);
2081 } else {
2082 if (iaxs[callno]->owner)
2083 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);
2084 iaxs[callno]->error = ETIMEDOUT;
2085 if (iaxs[callno]->owner) {
2086 struct ast_frame fr = { 0, };
2087 /* Hangup the fd */
2088 fr.frametype = AST_FRAME_CONTROL;
2089 fr.subclass = AST_CONTROL_HANGUP;
2090 iax2_queue_frame(callno, &fr); // XXX
2091 /* Remember, owner could disappear */
2092 if (iaxs[callno] && iaxs[callno]->owner)
2093 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2094 } else {
2095 if (iaxs[callno]->reg) {
2096 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2097 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2098 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2100 iax2_destroy(callno);
2105 freeme++;
2106 } else {
2107 /* Update it if it needs it */
2108 update_packet(f);
2109 /* Attempt transmission */
2110 send_packet(f);
2111 f->retries++;
2112 /* Try again later after 10 times as long */
2113 f->retrytime *= 10;
2114 if (f->retrytime > MAX_RETRY_TIME)
2115 f->retrytime = MAX_RETRY_TIME;
2116 /* Transfer messages max out at one second */
2117 if (f->transfer && (f->retrytime > 1000))
2118 f->retrytime = 1000;
2119 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2121 } else {
2122 /* Make sure it gets freed */
2123 f->retries = -1;
2124 freeme++;
2126 if (callno)
2127 ast_mutex_unlock(&iaxsl[callno]);
2128 /* Do not try again */
2129 if (freeme) {
2130 /* Don't attempt delivery, just remove it from the queue */
2131 AST_LIST_LOCK(&iaxq.queue);
2132 AST_LIST_REMOVE(&iaxq.queue, f, list);
2133 iaxq.count--;
2134 AST_LIST_UNLOCK(&iaxq.queue);
2135 f->retrans = -1;
2136 /* Free the IAX frame */
2137 iax2_frame_free(f);
2141 static int attempt_transmit(const void *data)
2143 #ifdef SCHED_MULTITHREADED
2144 if (schedule_action(__attempt_transmit, data))
2145 #endif
2146 __attempt_transmit(data);
2147 return 0;
2150 static int iax2_prune_realtime(int fd, int argc, char *argv[])
2152 struct iax2_peer *peer;
2154 if (argc != 4)
2155 return RESULT_SHOWUSAGE;
2156 if (!strcmp(argv[3],"all")) {
2157 reload_config();
2158 ast_cli(fd, "OK cache is flushed.\n");
2159 } else if ((peer = find_peer(argv[3], 0))) {
2160 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2161 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2162 expire_registry(peer_ref(peer));
2163 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
2164 } else {
2165 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2167 peer_unref(peer);
2168 } else {
2169 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
2172 return RESULT_SUCCESS;
2175 static int iax2_test_losspct(int fd, int argc, char *argv[])
2177 if (argc != 4)
2178 return RESULT_SHOWUSAGE;
2180 test_losspct = atoi(argv[3]);
2182 return RESULT_SUCCESS;
2185 #ifdef IAXTESTS
2186 static int iax2_test_late(int fd, int argc, char *argv[])
2188 if (argc != 4)
2189 return RESULT_SHOWUSAGE;
2191 test_late = atoi(argv[3]);
2193 return RESULT_SUCCESS;
2196 static int iax2_test_resync(int fd, int argc, char *argv[])
2198 if (argc != 4)
2199 return RESULT_SHOWUSAGE;
2201 test_resync = atoi(argv[3]);
2203 return RESULT_SUCCESS;
2206 static int iax2_test_jitter(int fd, int argc, char *argv[])
2208 if (argc < 4 || argc > 5)
2209 return RESULT_SHOWUSAGE;
2211 test_jit = atoi(argv[3]);
2212 if (argc == 5)
2213 test_jitpct = atoi(argv[4]);
2215 return RESULT_SUCCESS;
2217 #endif /* IAXTESTS */
2219 /*! \brief peer_status: Report Peer status in character string */
2220 /* returns 1 if peer is online, -1 if unmonitored */
2221 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2223 int res = 0;
2224 if (peer->maxms) {
2225 if (peer->lastms < 0) {
2226 ast_copy_string(status, "UNREACHABLE", statuslen);
2227 } else if (peer->lastms > peer->maxms) {
2228 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2229 res = 1;
2230 } else if (peer->lastms) {
2231 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2232 res = 1;
2233 } else {
2234 ast_copy_string(status, "UNKNOWN", statuslen);
2236 } else {
2237 ast_copy_string(status, "Unmonitored", statuslen);
2238 res = -1;
2240 return res;
2243 /*! \brief Show one peer in detail */
2244 static int iax2_show_peer(int fd, int argc, char *argv[])
2246 char status[30];
2247 char cbuf[256];
2248 struct iax2_peer *peer;
2249 char codec_buf[512];
2250 int x = 0, codec = 0, load_realtime = 0;
2252 if (argc < 4)
2253 return RESULT_SHOWUSAGE;
2255 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2257 peer = find_peer(argv[3], load_realtime);
2258 if (peer) {
2259 ast_cli(fd,"\n\n");
2260 ast_cli(fd, " * Name : %s\n", peer->name);
2261 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2262 ast_cli(fd, " Context : %s\n", peer->context);
2263 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2264 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2265 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2266 ast_cli(fd, " Expire : %d\n", peer->expire);
2267 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2268 ast_cli(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));
2269 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2270 ast_cli(fd, " Username : %s\n", peer->username);
2271 ast_cli(fd, " Codecs : ");
2272 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2273 ast_cli(fd, "%s\n", codec_buf);
2275 ast_cli(fd, " Codec Order : (");
2276 for(x = 0; x < 32 ; x++) {
2277 codec = ast_codec_pref_index(&peer->prefs,x);
2278 if(!codec)
2279 break;
2280 ast_cli(fd, "%s", ast_getformatname(codec));
2281 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2282 ast_cli(fd, "|");
2285 if (!x)
2286 ast_cli(fd, "none");
2287 ast_cli(fd, ")\n");
2289 ast_cli(fd, " Status : ");
2290 peer_status(peer, status, sizeof(status));
2291 ast_cli(fd, "%s\n",status);
2292 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2293 ast_cli(fd,"\n");
2294 peer_unref(peer);
2295 } else {
2296 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2297 ast_cli(fd,"\n");
2300 return RESULT_SUCCESS;
2303 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2305 int which = 0;
2306 struct iax2_peer *peer;
2307 char *res = NULL;
2308 int wordlen = strlen(word);
2309 struct ao2_iterator i;
2311 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2312 if (pos != 3)
2313 return NULL;
2315 i = ao2_iterator_init(peers, 0);
2316 while ((peer = ao2_iterator_next(&i))) {
2317 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2318 res = ast_strdup(peer->name);
2319 peer_unref(peer);
2320 break;
2322 peer_unref(peer);
2325 return res;
2328 static int iax2_show_stats(int fd, int argc, char *argv[])
2330 struct iax_frame *cur;
2331 int cnt = 0, dead=0, final=0;
2333 if (argc != 3)
2334 return RESULT_SHOWUSAGE;
2336 AST_LIST_LOCK(&iaxq.queue);
2337 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2338 if (cur->retries < 0)
2339 dead++;
2340 if (cur->final)
2341 final++;
2342 cnt++;
2344 AST_LIST_UNLOCK(&iaxq.queue);
2346 ast_cli(fd, " IAX Statistics\n");
2347 ast_cli(fd, "---------------------\n");
2348 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2349 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2351 return RESULT_SUCCESS;
2354 static int iax2_show_cache(int fd, int argc, char *argv[])
2356 struct iax2_dpcache *dp;
2357 char tmp[1024], *pc;
2358 int s;
2359 int x,y;
2360 struct timeval tv;
2361 gettimeofday(&tv, NULL);
2362 ast_mutex_lock(&dpcache_lock);
2363 dp = dpcache;
2364 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2365 while(dp) {
2366 s = dp->expiry.tv_sec - tv.tv_sec;
2367 tmp[0] = '\0';
2368 if (dp->flags & CACHE_FLAG_EXISTS)
2369 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2370 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2371 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2372 if (dp->flags & CACHE_FLAG_CANEXIST)
2373 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2374 if (dp->flags & CACHE_FLAG_PENDING)
2375 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2376 if (dp->flags & CACHE_FLAG_TIMEOUT)
2377 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2378 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2379 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2380 if (dp->flags & CACHE_FLAG_MATCHMORE)
2381 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2382 if (dp->flags & CACHE_FLAG_UNKNOWN)
2383 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2384 /* Trim trailing pipe */
2385 if (!ast_strlen_zero(tmp))
2386 tmp[strlen(tmp) - 1] = '\0';
2387 else
2388 ast_copy_string(tmp, "(none)", sizeof(tmp));
2389 y=0;
2390 pc = strchr(dp->peercontext, '@');
2391 if (!pc)
2392 pc = dp->peercontext;
2393 else
2394 pc++;
2395 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2396 if (dp->waiters[x] > -1)
2397 y++;
2398 if (s > 0)
2399 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2400 else
2401 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2402 dp = dp->next;
2404 ast_mutex_unlock(&dpcache_lock);
2405 return RESULT_SUCCESS;
2408 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2410 static void unwrap_timestamp(struct iax_frame *fr)
2412 int x;
2414 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2415 x = fr->ts - iaxs[fr->callno]->last;
2416 if (x < -50000) {
2417 /* Sudden big jump backwards in timestamp:
2418 What likely happened here is that miniframe timestamp has circled but we haven't
2419 gotten the update from the main packet. We'll just pretend that we did, and
2420 update the timestamp appropriately. */
2421 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2422 if (option_debug && iaxdebug)
2423 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2425 if (x > 50000) {
2426 /* Sudden apparent big jump forwards in timestamp:
2427 What's likely happened is this is an old miniframe belonging to the previous
2428 top-16-bit timestamp that has turned up out of order.
2429 Adjust the timestamp appropriately. */
2430 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2431 if (option_debug && iaxdebug)
2432 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2437 static int get_from_jb(const void *p);
2439 static void update_jbsched(struct chan_iax2_pvt *pvt)
2441 int when;
2443 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2445 when = jb_next(pvt->jb) - when;
2447 AST_SCHED_DEL(sched, pvt->jbid);
2449 if(when <= 0) {
2450 /* XXX should really just empty until when > 0.. */
2451 when = 1;
2454 pvt->jbid = iax2_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2457 static void __get_from_jb(const void *p)
2459 int callno = PTR_TO_CALLNO(p);
2460 struct chan_iax2_pvt *pvt = NULL;
2461 struct iax_frame *fr;
2462 jb_frame frame;
2463 int ret;
2464 long now;
2465 long next;
2466 struct timeval tv;
2468 /* Make sure we have a valid private structure before going on */
2469 ast_mutex_lock(&iaxsl[callno]);
2470 pvt = iaxs[callno];
2471 if (!pvt) {
2472 /* No go! */
2473 ast_mutex_unlock(&iaxsl[callno]);
2474 return;
2477 pvt->jbid = -1;
2479 gettimeofday(&tv,NULL);
2480 /* round up a millisecond since ast_sched_runq does; */
2481 /* prevents us from spinning while waiting for our now */
2482 /* to catch up with runq's now */
2483 tv.tv_usec += 1000;
2485 now = ast_tvdiff_ms(tv, pvt->rxcore);
2487 if(now >= (next = jb_next(pvt->jb))) {
2488 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2489 switch(ret) {
2490 case JB_OK:
2491 fr = frame.data;
2492 __do_deliver(fr);
2493 /* __do_deliver() can cause the call to disappear */
2494 pvt = iaxs[callno];
2495 break;
2496 case JB_INTERP:
2498 struct ast_frame af = { 0, };
2500 /* create an interpolation frame */
2501 af.frametype = AST_FRAME_VOICE;
2502 af.subclass = pvt->voiceformat;
2503 af.samples = frame.ms * 8;
2504 af.src = "IAX2 JB interpolation";
2505 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2506 af.offset = AST_FRIENDLY_OFFSET;
2508 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2509 * which we'd need to malloc, and then it would free it. That seems like a drag */
2510 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2511 iax2_queue_frame(callno, &af);
2512 /* iax2_queue_frame() could cause the call to disappear */
2513 pvt = iaxs[callno];
2516 break;
2517 case JB_DROP:
2518 iax2_frame_free(frame.data);
2519 break;
2520 case JB_NOFRAME:
2521 case JB_EMPTY:
2522 /* do nothing */
2523 break;
2524 default:
2525 /* shouldn't happen */
2526 break;
2529 if (pvt)
2530 update_jbsched(pvt);
2531 ast_mutex_unlock(&iaxsl[callno]);
2534 static int get_from_jb(const void *data)
2536 #ifdef SCHED_MULTITHREADED
2537 if (schedule_action(__get_from_jb, data))
2538 #endif
2539 __get_from_jb(data);
2540 return 0;
2544 * \note This function assumes fr->callno is locked
2546 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2547 * was valid before calling it, it may no longer be valid after calling it.
2549 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2551 int type, len;
2552 int ret;
2553 int needfree = 0;
2554 struct ast_channel *owner = NULL;
2555 struct ast_channel *bridge = NULL;
2557 /* Attempt to recover wrapped timestamps */
2558 unwrap_timestamp(fr);
2560 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2561 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2562 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2563 else {
2564 #if 0
2565 if (option_debug)
2566 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2567 #endif
2568 fr->af.delivery = ast_tv(0,0);
2571 type = JB_TYPE_CONTROL;
2572 len = 0;
2574 if(fr->af.frametype == AST_FRAME_VOICE) {
2575 type = JB_TYPE_VOICE;
2576 len = ast_codec_get_samples(&fr->af) / 8;
2577 } else if(fr->af.frametype == AST_FRAME_CNG) {
2578 type = JB_TYPE_SILENCE;
2581 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2582 if (tsout)
2583 *tsout = fr->ts;
2584 __do_deliver(fr);
2585 return -1;
2588 if ((owner = iaxs[fr->callno]->owner))
2589 bridge = ast_bridged_channel(owner);
2591 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2592 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2593 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
2594 jb_frame frame;
2596 /* deliver any frames in the jb */
2597 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2598 __do_deliver(frame.data);
2599 /* __do_deliver() can make the call disappear */
2600 if (!iaxs[fr->callno])
2601 return -1;
2604 jb_reset(iaxs[fr->callno]->jb);
2606 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
2608 /* deliver this frame now */
2609 if (tsout)
2610 *tsout = fr->ts;
2611 __do_deliver(fr);
2612 return -1;
2615 /* insert into jitterbuffer */
2616 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2617 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2618 calc_rxstamp(iaxs[fr->callno],fr->ts));
2619 if (ret == JB_DROP) {
2620 needfree++;
2621 } else if (ret == JB_SCHED) {
2622 update_jbsched(iaxs[fr->callno]);
2624 if (tsout)
2625 *tsout = fr->ts;
2626 if (needfree) {
2627 /* Free our iax frame */
2628 iax2_frame_free(fr);
2629 return -1;
2631 return 0;
2634 static int iax2_transmit(struct iax_frame *fr)
2636 /* Lock the queue and place this packet at the end */
2637 /* By setting this to 0, the network thread will send it for us, and
2638 queue retransmission if necessary */
2639 fr->sentyet = 0;
2640 AST_LIST_LOCK(&iaxq.queue);
2641 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2642 iaxq.count++;
2643 AST_LIST_UNLOCK(&iaxq.queue);
2644 /* Wake up the network and scheduler thread */
2645 if (netthreadid != AST_PTHREADT_NULL)
2646 pthread_kill(netthreadid, SIGURG);
2647 signal_condition(&sched_lock, &sched_cond);
2648 return 0;
2653 static int iax2_digit_begin(struct ast_channel *c, char digit)
2655 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2658 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2660 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2663 static int iax2_sendtext(struct ast_channel *c, const char *text)
2666 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2667 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2670 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2672 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2675 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2677 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2680 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2682 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2683 ast_mutex_lock(&iaxsl[callno]);
2684 if (iaxs[callno])
2685 iaxs[callno]->owner = newchan;
2686 else
2687 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2688 ast_mutex_unlock(&iaxsl[callno]);
2689 return 0;
2693 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2694 * so do not call this with a pvt lock held.
2696 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2698 struct ast_variable *var = NULL;
2699 struct ast_variable *tmp;
2700 struct iax2_peer *peer=NULL;
2701 time_t regseconds = 0, nowtime;
2702 int dynamic=0;
2704 if (peername) {
2705 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
2706 if (!var && sin)
2707 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2708 } else if (sin) {
2709 char porta[25];
2710 sprintf(porta, "%d", ntohs(sin->sin_port));
2711 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2712 if (var) {
2713 /* We'll need the peer name in order to build the structure! */
2714 for (tmp = var; tmp; tmp = tmp->next) {
2715 if (!strcasecmp(tmp->name, "name"))
2716 peername = tmp->value;
2720 if (!var && peername) { /* Last ditch effort */
2721 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2722 /*!\note
2723 * If this one loaded something, then we need to ensure that the host
2724 * field matched. The only reason why we can't have this as a criteria
2725 * is because we only have the IP address and the host field might be
2726 * set as a name (and the reverse PTR might not match).
2728 if (var && sin) {
2729 for (tmp = var; tmp; tmp = tmp->next) {
2730 if (!strcasecmp(tmp->name, "host")) {
2731 struct ast_hostent ahp;
2732 struct hostent *hp;
2733 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2734 /* No match */
2735 ast_variables_destroy(var);
2736 var = NULL;
2738 break;
2743 if (!var)
2744 return NULL;
2746 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2748 if (!peer) {
2749 ast_variables_destroy(var);
2750 return NULL;
2753 for (tmp = var; tmp; tmp = tmp->next) {
2754 /* Make sure it's not a user only... */
2755 if (!strcasecmp(tmp->name, "type")) {
2756 if (strcasecmp(tmp->value, "friend") &&
2757 strcasecmp(tmp->value, "peer")) {
2758 /* Whoops, we weren't supposed to exist! */
2759 peer = peer_unref(peer);
2760 break;
2762 } else if (!strcasecmp(tmp->name, "regseconds")) {
2763 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2764 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2765 inet_aton(tmp->value, &(peer->addr.sin_addr));
2766 } else if (!strcasecmp(tmp->name, "port")) {
2767 peer->addr.sin_port = htons(atoi(tmp->value));
2768 } else if (!strcasecmp(tmp->name, "host")) {
2769 if (!strcasecmp(tmp->value, "dynamic"))
2770 dynamic = 1;
2774 ast_variables_destroy(var);
2776 if (!peer)
2777 return NULL;
2779 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2780 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2781 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2782 if (peer->expire > -1) {
2783 if (!ast_sched_del(sched, peer->expire)) {
2784 peer->expire = -1;
2785 peer_unref(peer);
2788 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
2789 if (peer->expire == -1)
2790 peer_unref(peer);
2792 ao2_link(peers, peer);
2793 if (ast_test_flag(peer, IAX_DYNAMIC))
2794 reg_source_db(peer);
2795 } else {
2796 ast_set_flag(peer, IAX_TEMPONLY);
2799 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2800 time(&nowtime);
2801 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2802 memset(&peer->addr, 0, sizeof(peer->addr));
2803 realtime_update_peer(peer->name, &peer->addr, 0);
2804 if (option_debug)
2805 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2806 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2808 else {
2809 if (option_debug)
2810 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2811 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2815 return peer;
2818 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
2820 struct ast_variable *var;
2821 struct ast_variable *tmp;
2822 struct iax2_user *user=NULL;
2824 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
2825 if (!var)
2826 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2827 if (!var && sin) {
2828 char porta[6];
2829 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
2830 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2831 if (!var)
2832 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2834 if (!var) { /* Last ditch effort */
2835 var = ast_load_realtime("iaxusers", "name", username, NULL);
2836 /*!\note
2837 * If this one loaded something, then we need to ensure that the host
2838 * field matched. The only reason why we can't have this as a criteria
2839 * is because we only have the IP address and the host field might be
2840 * set as a name (and the reverse PTR might not match).
2842 if (var) {
2843 for (tmp = var; tmp; tmp = tmp->next) {
2844 if (!strcasecmp(tmp->name, "host")) {
2845 struct ast_hostent ahp;
2846 struct hostent *hp;
2847 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2848 /* No match */
2849 ast_variables_destroy(var);
2850 var = NULL;
2852 break;
2857 if (!var)
2858 return NULL;
2860 tmp = var;
2861 while(tmp) {
2862 /* Make sure it's not a peer only... */
2863 if (!strcasecmp(tmp->name, "type")) {
2864 if (strcasecmp(tmp->value, "friend") &&
2865 strcasecmp(tmp->value, "user")) {
2866 return NULL;
2869 tmp = tmp->next;
2872 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2874 ast_variables_destroy(var);
2876 if (!user)
2877 return NULL;
2879 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2880 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2881 ao2_link(users, user);
2882 } else {
2883 ast_set_flag(user, IAX_TEMPONLY);
2886 return user;
2889 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2891 char port[10];
2892 char regseconds[20];
2894 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2895 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2896 ast_update_realtime("iaxpeers", "name", peername,
2897 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2898 "regseconds", regseconds, NULL);
2901 struct create_addr_info {
2902 int capability;
2903 unsigned int flags;
2904 int maxtime;
2905 int encmethods;
2906 int found;
2907 int sockfd;
2908 int adsi;
2909 char username[80];
2910 char secret[80];
2911 char outkey[80];
2912 char timezone[80];
2913 char prefs[32];
2914 char context[AST_MAX_CONTEXT];
2915 char peercontext[AST_MAX_CONTEXT];
2916 char mohinterpret[MAX_MUSICCLASS];
2917 char mohsuggest[MAX_MUSICCLASS];
2920 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
2922 struct ast_hostent ahp;
2923 struct hostent *hp;
2924 struct iax2_peer *peer;
2925 int res = -1;
2926 struct ast_codec_pref ourprefs;
2928 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2929 cai->sockfd = defaultsockfd;
2930 cai->maxtime = 0;
2931 sin->sin_family = AF_INET;
2933 if (!(peer = find_peer(peername, 1))) {
2934 cai->found = 0;
2936 hp = ast_gethostbyname(peername, &ahp);
2937 if (hp) {
2938 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2939 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2940 /* use global iax prefs for unknown peer/user */
2941 /* But move the calling channel's native codec to the top of the preference list */
2942 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
2943 if (c)
2944 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
2945 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
2946 return 0;
2947 } else {
2948 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2949 return -1;
2953 cai->found = 1;
2955 /* if the peer has no address (current or default), return failure */
2956 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
2957 goto return_unref;
2959 /* if the peer is being monitored and is currently unreachable, return failure */
2960 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
2961 goto return_unref;
2963 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2964 cai->maxtime = peer->maxms;
2965 cai->capability = peer->capability;
2966 cai->encmethods = peer->encmethods;
2967 cai->sockfd = peer->sockfd;
2968 cai->adsi = peer->adsi;
2969 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
2970 /* Move the calling channel's native codec to the top of the preference list */
2971 if (c) {
2972 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
2973 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
2975 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
2976 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2977 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2978 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2979 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2980 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2981 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2982 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2983 if (ast_strlen_zero(peer->dbsecret)) {
2984 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2985 } else {
2986 char *family;
2987 char *key = NULL;
2989 family = ast_strdupa(peer->dbsecret);
2990 key = strchr(family, '/');
2991 if (key)
2992 *key++ = '\0';
2993 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2994 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2995 goto return_unref;
2999 if (peer->addr.sin_addr.s_addr) {
3000 sin->sin_addr = peer->addr.sin_addr;
3001 sin->sin_port = peer->addr.sin_port;
3002 } else {
3003 sin->sin_addr = peer->defaddr.sin_addr;
3004 sin->sin_port = peer->defaddr.sin_port;
3007 res = 0;
3009 return_unref:
3010 peer_unref(peer);
3012 return res;
3015 static void __auto_congest(const void *nothing)
3017 int callno = PTR_TO_CALLNO(nothing);
3018 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3019 ast_mutex_lock(&iaxsl[callno]);
3020 if (iaxs[callno]) {
3021 iaxs[callno]->initid = -1;
3022 iax2_queue_frame(callno, &f);
3023 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3025 ast_mutex_unlock(&iaxsl[callno]);
3028 static int auto_congest(const void *data)
3030 #ifdef SCHED_MULTITHREADED
3031 if (schedule_action(__auto_congest, data))
3032 #endif
3033 __auto_congest(data);
3034 return 0;
3037 static unsigned int iax2_datetime(const char *tz)
3039 time_t t;
3040 struct tm tm;
3041 unsigned int tmp;
3042 time(&t);
3043 if (!ast_strlen_zero(tz))
3044 ast_localtime(&t, &tm, tz);
3045 else
3046 ast_localtime(&t, &tm, NULL);
3047 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3048 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3049 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3050 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3051 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3052 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3053 return tmp;
3056 struct parsed_dial_string {
3057 char *username;
3058 char *password;
3059 char *key;
3060 char *peer;
3061 char *port;
3062 char *exten;
3063 char *context;
3064 char *options;
3068 * \brief Parses an IAX dial string into its component parts.
3069 * \param data the string to be parsed
3070 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3071 * \return nothing
3073 * This function parses the string and fills the structure
3074 * with pointers to its component parts. The input string
3075 * will be modified.
3077 * \note This function supports both plaintext passwords and RSA
3078 * key names; if the password string is formatted as '[keyname]',
3079 * then the keyname will be placed into the key field, and the
3080 * password field will be set to NULL.
3082 * \note The dial string format is:
3083 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3085 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3087 if (ast_strlen_zero(data))
3088 return;
3090 pds->peer = strsep(&data, "/");
3091 pds->exten = strsep(&data, "/");
3092 pds->options = data;
3094 if (pds->exten) {
3095 data = pds->exten;
3096 pds->exten = strsep(&data, "@");
3097 pds->context = data;
3100 if (strchr(pds->peer, '@')) {
3101 data = pds->peer;
3102 pds->username = strsep(&data, "@");
3103 pds->peer = data;
3106 if (pds->username) {
3107 data = pds->username;
3108 pds->username = strsep(&data, ":");
3109 pds->password = data;
3112 data = pds->peer;
3113 pds->peer = strsep(&data, ":");
3114 pds->port = data;
3116 /* check for a key name wrapped in [] in the secret position, if found,
3117 move it to the key field instead
3119 if (pds->password && (pds->password[0] == '[')) {
3120 pds->key = ast_strip_quoted(pds->password, "[", "]");
3121 pds->password = NULL;
3125 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3127 struct sockaddr_in sin;
3128 char *l=NULL, *n=NULL, *tmpstr;
3129 struct iax_ie_data ied;
3130 char *defaultrdest = "s";
3131 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3132 struct parsed_dial_string pds;
3133 struct create_addr_info cai;
3135 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3136 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3137 return -1;
3140 memset(&cai, 0, sizeof(cai));
3141 cai.encmethods = iax2_encryption;
3143 memset(&pds, 0, sizeof(pds));
3144 tmpstr = ast_strdupa(dest);
3145 parse_dial_string(tmpstr, &pds);
3147 if (ast_strlen_zero(pds.peer)) {
3148 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3149 return -1;
3152 if (!pds.exten) {
3153 if (!ast_strlen_zero(c->exten))
3154 pds.exten = c->exten;
3155 else
3156 pds.exten = defaultrdest;
3159 if (create_addr(pds.peer, c, &sin, &cai)) {
3160 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3161 return -1;
3164 if (!pds.username && !ast_strlen_zero(cai.username))
3165 pds.username = cai.username;
3166 if (!pds.password && !ast_strlen_zero(cai.secret))
3167 pds.password = cai.secret;
3168 if (!pds.key && !ast_strlen_zero(cai.outkey))
3169 pds.key = cai.outkey;
3170 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3171 pds.context = cai.peercontext;
3173 /* Keep track of the context for outgoing calls too */
3174 ast_copy_string(c->context, cai.context, sizeof(c->context));
3176 if (pds.port)
3177 sin.sin_port = htons(atoi(pds.port));
3179 l = c->cid.cid_num;
3180 n = c->cid.cid_name;
3182 /* Now build request */
3183 memset(&ied, 0, sizeof(ied));
3185 /* On new call, first IE MUST be IAX version of caller */
3186 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3187 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3188 if (pds.options && strchr(pds.options, 'a')) {
3189 /* Request auto answer */
3190 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3193 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3195 if (l) {
3196 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3197 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3198 } else {
3199 if (n)
3200 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3201 else
3202 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3205 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3206 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3208 if (n)
3209 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3210 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3211 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3213 if (!ast_strlen_zero(c->language))
3214 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3215 if (!ast_strlen_zero(c->cid.cid_dnid))
3216 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3217 if (!ast_strlen_zero(c->cid.cid_rdnis))
3218 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3220 if (pds.context)
3221 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3223 if (pds.username)
3224 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3226 if (cai.encmethods)
3227 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3229 ast_mutex_lock(&iaxsl[callno]);
3231 if (!ast_strlen_zero(c->context))
3232 ast_string_field_set(iaxs[callno], context, c->context);
3234 if (pds.username)
3235 ast_string_field_set(iaxs[callno], username, pds.username);
3237 iaxs[callno]->encmethods = cai.encmethods;
3239 iaxs[callno]->adsi = cai.adsi;
3241 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3242 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3244 if (pds.key)
3245 ast_string_field_set(iaxs[callno], outkey, pds.key);
3246 if (pds.password)
3247 ast_string_field_set(iaxs[callno], secret, pds.password);
3249 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3250 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3251 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3252 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3254 if (iaxs[callno]->maxtime) {
3255 /* Initialize pingtime and auto-congest time */
3256 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3257 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3258 } else if (autokill) {
3259 iaxs[callno]->pingtime = autokill / 2;
3260 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3263 /* send the command using the appropriate socket for this peer */
3264 iaxs[callno]->sockfd = cai.sockfd;
3266 /* Transmit the string in a "NEW" request */
3267 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3269 ast_mutex_unlock(&iaxsl[callno]);
3270 ast_setstate(c, AST_STATE_RINGING);
3272 return 0;
3275 static int iax2_hangup(struct ast_channel *c)
3277 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3278 int alreadygone;
3279 struct iax_ie_data ied;
3280 memset(&ied, 0, sizeof(ied));
3281 ast_mutex_lock(&iaxsl[callno]);
3282 if (callno && iaxs[callno]) {
3283 if (option_debug)
3284 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3285 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3286 /* Send the hangup unless we have had a transmission error or are already gone */
3287 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3288 if (!iaxs[callno]->error && !alreadygone) {
3289 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3290 if (!iaxs[callno]) {
3291 ast_mutex_unlock(&iaxsl[callno]);
3292 return 0;
3295 /* Explicitly predestroy it */
3296 iax2_predestroy(callno);
3297 /* If we were already gone to begin with, destroy us now */
3298 if (alreadygone && iaxs[callno]) {
3299 if (option_debug)
3300 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3301 iax2_destroy(callno);
3304 ast_mutex_unlock(&iaxsl[callno]);
3305 if (option_verbose > 2)
3306 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3307 return 0;
3310 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3312 struct ast_option_header *h;
3313 int res;
3315 switch (option) {
3316 case AST_OPTION_TXGAIN:
3317 case AST_OPTION_RXGAIN:
3318 /* these two cannot be sent, because they require a result */
3319 errno = ENOSYS;
3320 return -1;
3321 default:
3322 if (!(h = ast_malloc(datalen + sizeof(*h))))
3323 return -1;
3325 h->flag = AST_OPTION_FLAG_REQUEST;
3326 h->option = htons(option);
3327 memcpy(h->data, data, datalen);
3328 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3329 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3330 datalen + sizeof(*h), -1);
3331 free(h);
3332 return res;
3336 static struct ast_frame *iax2_read(struct ast_channel *c)
3338 ast_log(LOG_NOTICE, "I should never be called!\n");
3339 return &ast_null_frame;
3342 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3344 int res;
3345 struct iax_ie_data ied0;
3346 struct iax_ie_data ied1;
3347 unsigned int transferid = (unsigned int)ast_random();
3348 memset(&ied0, 0, sizeof(ied0));
3349 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3350 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3351 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3353 memset(&ied1, 0, sizeof(ied1));
3354 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3355 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3356 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3358 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3359 if (res)
3360 return -1;
3361 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3362 if (res)
3363 return -1;
3364 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3365 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3366 return 0;
3369 static void lock_both(unsigned short callno0, unsigned short callno1)
3371 ast_mutex_lock(&iaxsl[callno0]);
3372 while (ast_mutex_trylock(&iaxsl[callno1])) {
3373 ast_mutex_unlock(&iaxsl[callno0]);
3374 usleep(10);
3375 ast_mutex_lock(&iaxsl[callno0]);
3379 static void unlock_both(unsigned short callno0, unsigned short callno1)
3381 ast_mutex_unlock(&iaxsl[callno1]);
3382 ast_mutex_unlock(&iaxsl[callno0]);
3385 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)
3387 struct ast_channel *cs[3];
3388 struct ast_channel *who, *other;
3389 int to = -1;
3390 int res = -1;
3391 int transferstarted=0;
3392 struct ast_frame *f;
3393 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3394 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3395 struct timeval waittimer = {0, 0}, tv;
3397 lock_both(callno0, callno1);
3398 if (!iaxs[callno0] || !iaxs[callno1]) {
3399 unlock_both(callno0, callno1);
3400 return AST_BRIDGE_FAILED;
3402 /* Put them in native bridge mode */
3403 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3404 iaxs[callno0]->bridgecallno = callno1;
3405 iaxs[callno1]->bridgecallno = callno0;
3407 unlock_both(callno0, callno1);
3409 /* If not, try to bridge until we can execute a transfer, if we can */
3410 cs[0] = c0;
3411 cs[1] = c1;
3412 for (/* ever */;;) {
3413 /* Check in case we got masqueraded into */
3414 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3415 if (option_verbose > 2)
3416 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3417 /* Remove from native mode */
3418 if (c0->tech == &iax2_tech) {
3419 ast_mutex_lock(&iaxsl[callno0]);
3420 iaxs[callno0]->bridgecallno = 0;
3421 ast_mutex_unlock(&iaxsl[callno0]);
3423 if (c1->tech == &iax2_tech) {
3424 ast_mutex_lock(&iaxsl[callno1]);
3425 iaxs[callno1]->bridgecallno = 0;
3426 ast_mutex_unlock(&iaxsl[callno1]);
3428 return AST_BRIDGE_FAILED_NOWARN;
3430 if (c0->nativeformats != c1->nativeformats) {
3431 if (option_verbose > 2) {
3432 char buf0[255];
3433 char buf1[255];
3434 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3435 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3436 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3438 /* Remove from native mode */
3439 lock_both(callno0, callno1);
3440 if (iaxs[callno0])
3441 iaxs[callno0]->bridgecallno = 0;
3442 if (iaxs[callno1])
3443 iaxs[callno1]->bridgecallno = 0;
3444 unlock_both(callno0, callno1);
3445 return AST_BRIDGE_FAILED_NOWARN;
3447 /* check if transfered and if we really want native bridging */
3448 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3449 /* Try the transfer */
3450 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3451 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3452 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3453 transferstarted = 1;
3455 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3456 /* Call has been transferred. We're no longer involved */
3457 gettimeofday(&tv, NULL);
3458 if (ast_tvzero(waittimer)) {
3459 waittimer = tv;
3460 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3461 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3462 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3463 *fo = NULL;
3464 *rc = c0;
3465 res = AST_BRIDGE_COMPLETE;
3466 break;
3469 to = 1000;
3470 who = ast_waitfor_n(cs, 2, &to);
3471 if (timeoutms > -1) {
3472 timeoutms -= (1000 - to);
3473 if (timeoutms < 0)
3474 timeoutms = 0;
3476 if (!who) {
3477 if (!timeoutms) {
3478 res = AST_BRIDGE_RETRY;
3479 break;
3481 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3482 res = AST_BRIDGE_FAILED;
3483 break;
3485 continue;
3487 f = ast_read(who);
3488 if (!f) {
3489 *fo = NULL;
3490 *rc = who;
3491 res = AST_BRIDGE_COMPLETE;
3492 break;
3494 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3495 *fo = f;
3496 *rc = who;
3497 res = AST_BRIDGE_COMPLETE;
3498 break;
3500 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3501 if ((f->frametype == AST_FRAME_VOICE) ||
3502 (f->frametype == AST_FRAME_TEXT) ||
3503 (f->frametype == AST_FRAME_VIDEO) ||
3504 (f->frametype == AST_FRAME_IMAGE) ||
3505 (f->frametype == AST_FRAME_DTMF)) {
3506 /* monitored dtmf take out of the bridge.
3507 * check if we monitor the specific source.
3509 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3510 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3511 *rc = who;
3512 *fo = f;
3513 res = AST_BRIDGE_COMPLETE;
3514 /* Remove from native mode */
3515 break;
3517 /* everything else goes to the other side */
3518 ast_write(other, f);
3520 ast_frfree(f);
3521 /* Swap who gets priority */
3522 cs[2] = cs[0];
3523 cs[0] = cs[1];
3524 cs[1] = cs[2];
3526 lock_both(callno0, callno1);
3527 if(iaxs[callno0])
3528 iaxs[callno0]->bridgecallno = 0;
3529 if(iaxs[callno1])
3530 iaxs[callno1]->bridgecallno = 0;
3531 unlock_both(callno0, callno1);
3532 return res;
3535 static int iax2_answer(struct ast_channel *c)
3537 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3538 if (option_debug)
3539 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3540 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3543 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
3545 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3546 struct chan_iax2_pvt *pvt;
3547 int res = 0;
3549 if (option_debug && iaxdebug)
3550 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3552 ast_mutex_lock(&iaxsl[callno]);
3553 pvt = iaxs[callno];
3555 switch (condition) {
3556 case AST_CONTROL_HOLD:
3557 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3558 ast_moh_start(c, data, pvt->mohinterpret);
3559 goto done;
3561 break;
3562 case AST_CONTROL_UNHOLD:
3563 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3564 ast_moh_stop(c);
3565 goto done;
3569 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3571 done:
3572 ast_mutex_unlock(&iaxsl[callno]);
3574 return res;
3577 static int iax2_transfer(struct ast_channel *c, const char *dest)
3579 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3580 struct iax_ie_data ied;
3581 char tmp[256], *context;
3582 ast_copy_string(tmp, dest, sizeof(tmp));
3583 context = strchr(tmp, '@');
3584 if (context) {
3585 *context = '\0';
3586 context++;
3588 memset(&ied, 0, sizeof(ied));
3589 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3590 if (context)
3591 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3592 if (option_debug)
3593 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3594 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3597 static int iax2_getpeertrunk(struct sockaddr_in sin)
3599 struct iax2_peer *peer;
3600 int res = 0;
3601 struct ao2_iterator i;
3603 i = ao2_iterator_init(peers, 0);
3604 while ((peer = ao2_iterator_next(&i))) {
3605 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3606 (peer->addr.sin_port == sin.sin_port)) {
3607 res = ast_test_flag(peer, IAX_TRUNK);
3608 peer_unref(peer);
3609 break;
3611 peer_unref(peer);
3614 return res;
3617 /*! \brief Create new call, interface with the PBX core */
3618 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3620 struct ast_channel *tmp;
3621 struct chan_iax2_pvt *i;
3622 struct ast_variable *v = NULL;
3624 if (!(i = iaxs[callno])) {
3625 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
3626 return NULL;
3629 /* Don't hold call lock */
3630 ast_mutex_unlock(&iaxsl[callno]);
3631 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
3632 ast_mutex_lock(&iaxsl[callno]);
3633 if (!iaxs[callno]) {
3634 if (tmp) {
3635 ast_channel_free(tmp);
3637 ast_mutex_unlock(&iaxsl[callno]);
3638 return NULL;
3641 if (!tmp)
3642 return NULL;
3643 tmp->tech = &iax2_tech;
3644 /* We can support any format by default, until we get restricted */
3645 tmp->nativeformats = capability;
3646 tmp->readformat = ast_best_codec(capability);
3647 tmp->writeformat = ast_best_codec(capability);
3648 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3650 /* Don't use ast_set_callerid() here because it will
3651 * generate a NewCallerID event before the NewChannel event */
3652 if (!ast_strlen_zero(i->ani))
3653 tmp->cid.cid_ani = ast_strdup(i->ani);
3654 else
3655 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3656 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3657 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3658 tmp->cid.cid_pres = i->calling_pres;
3659 tmp->cid.cid_ton = i->calling_ton;
3660 tmp->cid.cid_tns = i->calling_tns;
3661 if (!ast_strlen_zero(i->language))
3662 ast_string_field_set(tmp, language, i->language);
3663 if (!ast_strlen_zero(i->accountcode))
3664 ast_string_field_set(tmp, accountcode, i->accountcode);
3665 if (i->amaflags)
3666 tmp->amaflags = i->amaflags;
3667 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3668 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3669 if (i->adsi)
3670 tmp->adsicpe = i->peeradsicpe;
3671 else
3672 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3673 i->owner = tmp;
3674 i->capability = capability;
3676 for (v = i->vars ; v ; v = v->next)
3677 pbx_builtin_setvar_helper(tmp, v->name, v->value);
3679 if (state != AST_STATE_DOWN) {
3680 if (ast_pbx_start(tmp)) {
3681 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3682 ast_hangup(tmp);
3683 i->owner = NULL;
3684 return NULL;
3688 ast_module_ref(ast_module_info->self);
3690 return tmp;
3693 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3695 unsigned long int mssincetx; /* unsigned to handle overflows */
3696 long int ms, pred;
3698 tpeer->trunkact = *tv;
3699 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3700 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3701 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3702 tpeer->txtrunktime = *tv;
3703 tpeer->lastsent = 999999;
3705 /* Update last transmit time now */
3706 tpeer->lasttxtime = *tv;
3708 /* Calculate ms offset */
3709 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3710 /* Predict from last value */
3711 pred = tpeer->lastsent + sampms;
3712 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3713 ms = pred;
3715 /* We never send the same timestamp twice, so fudge a little if we must */
3716 if (ms == tpeer->lastsent)
3717 ms = tpeer->lastsent + 1;
3718 tpeer->lastsent = ms;
3719 return ms;
3722 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3724 long ms; /* NOT unsigned */
3725 if (ast_tvzero(iaxs[callno]->rxcore)) {
3726 /* Initialize rxcore time if appropriate */
3727 gettimeofday(&iaxs[callno]->rxcore, NULL);
3728 /* Round to nearest 20ms so traces look pretty */
3729 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3731 /* Calculate difference between trunk and channel */
3732 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3733 /* Return as the sum of trunk time and the difference between trunk and real time */
3734 return ms + ts;
3737 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3739 int ms;
3740 int voice = 0;
3741 int genuine = 0;
3742 int adjust;
3743 struct timeval *delivery = NULL;
3746 /* What sort of frame do we have?: voice is self-explanatory
3747 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3748 non-genuine frames are CONTROL frames [ringing etc], DTMF
3749 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3750 the others need a timestamp slaved to the voice frames so that they go in sequence
3752 if (f) {
3753 if (f->frametype == AST_FRAME_VOICE) {
3754 voice = 1;
3755 delivery = &f->delivery;
3756 } else if (f->frametype == AST_FRAME_IAX) {
3757 genuine = 1;
3758 } else if (f->frametype == AST_FRAME_CNG) {
3759 p->notsilenttx = 0;
3762 if (ast_tvzero(p->offset)) {
3763 gettimeofday(&p->offset, NULL);
3764 /* Round to nearest 20ms for nice looking traces */
3765 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3767 /* If the timestamp is specified, just send it as is */
3768 if (ts)
3769 return ts;
3770 /* If we have a time that the frame arrived, always use it to make our timestamp */
3771 if (delivery && !ast_tvzero(*delivery)) {
3772 ms = ast_tvdiff_ms(*delivery, p->offset);
3773 if (option_debug > 2 && iaxdebug)
3774 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3775 } else {
3776 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3777 if (ms < 0)
3778 ms = 0;
3779 if (voice) {
3780 /* On a voice frame, use predicted values if appropriate */
3781 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3782 /* Adjust our txcore, keeping voice and non-voice synchronized */
3783 /* AN EXPLANATION:
3784 When we send voice, we usually send "calculated" timestamps worked out
3785 on the basis of the number of samples sent. When we send other frames,
3786 we usually send timestamps worked out from the real clock.
3787 The problem is that they can tend to drift out of step because the
3788 source channel's clock and our clock may not be exactly at the same rate.
3789 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3790 for this call. Moving it adjusts timestamps for non-voice frames.
3791 We make the adjustment in the style of a moving average. Each time we
3792 adjust p->offset by 10% of the difference between our clock-derived
3793 timestamp and the predicted timestamp. That's why you see "10000"
3794 below even though IAX2 timestamps are in milliseconds.
3795 The use of a moving average avoids offset moving too radically.
3796 Generally, "adjust" roams back and forth around 0, with offset hardly
3797 changing at all. But if a consistent different starts to develop it
3798 will be eliminated over the course of 10 frames (200-300msecs)
3800 adjust = (ms - p->nextpred);
3801 if (adjust < 0)
3802 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3803 else if (adjust > 0)
3804 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3806 if (!p->nextpred) {
3807 p->nextpred = ms; /*f->samples / 8;*/
3808 if (p->nextpred <= p->lastsent)
3809 p->nextpred = p->lastsent + 3;
3811 ms = p->nextpred;
3812 } else {
3813 /* in this case, just use the actual
3814 * time, since we're either way off
3815 * (shouldn't happen), or we're ending a
3816 * silent period -- and seed the next
3817 * predicted time. Also, round ms to the
3818 * next multiple of frame size (so our
3819 * silent periods are multiples of
3820 * frame size too) */
3822 if (option_debug && iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3823 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3824 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3826 if (f->samples >= 8) /* check to make sure we dont core dump */
3828 int diff = ms % (f->samples / 8);
3829 if (diff)
3830 ms += f->samples/8 - diff;
3833 p->nextpred = ms;
3834 p->notsilenttx = 1;
3836 } else if ( f->frametype == AST_FRAME_VIDEO ) {
3838 * IAX2 draft 03 says that timestamps MUST be in order.
3839 * It does not say anything about several frames having the same timestamp
3840 * When transporting video, we can have a frame that spans multiple iax packets
3841 * (so called slices), so it would make sense to use the same timestamp for all of
3842 * them
3843 * We do want to make sure that frames don't go backwards though
3845 if ( (unsigned int)ms < p->lastsent )
3846 ms = p->lastsent;
3847 } else {
3848 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3849 it's a genuine frame */
3850 if (genuine) {
3851 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3852 if (ms <= p->lastsent)
3853 ms = p->lastsent + 3;
3854 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3855 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3856 ms = p->lastsent + 3;
3860 p->lastsent = ms;
3861 if (voice)
3862 p->nextpred = p->nextpred + f->samples / 8;
3863 return ms;
3866 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3868 /* Returns where in "receive time" we are. That is, how many ms
3869 since we received (or would have received) the frame with timestamp 0 */
3870 int ms;
3871 #ifdef IAXTESTS
3872 int jit;
3873 #endif /* IAXTESTS */
3874 /* Setup rxcore if necessary */
3875 if (ast_tvzero(p->rxcore)) {
3876 p->rxcore = ast_tvnow();
3877 if (option_debug && iaxdebug)
3878 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3879 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3880 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3881 #if 1
3882 if (option_debug && iaxdebug)
3883 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3884 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3885 #endif
3888 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3889 #ifdef IAXTESTS
3890 if (test_jit) {
3891 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3892 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3893 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3894 jit = -jit;
3895 ms += jit;
3898 if (test_late) {
3899 ms += test_late;
3900 test_late = 0;
3902 #endif /* IAXTESTS */
3903 return ms;
3906 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3908 struct iax2_trunk_peer *tpeer;
3910 /* Finds and locks trunk peer */
3911 ast_mutex_lock(&tpeerlock);
3912 for (tpeer = tpeers; tpeer; tpeer = tpeer->next) {
3913 /* We don't lock here because tpeer->addr *never* changes */
3914 if (!inaddrcmp(&tpeer->addr, sin)) {
3915 ast_mutex_lock(&tpeer->lock);
3916 break;
3919 if (!tpeer) {
3920 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
3921 ast_mutex_init(&tpeer->lock);
3922 tpeer->lastsent = 9999;
3923 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3924 tpeer->trunkact = ast_tvnow();
3925 ast_mutex_lock(&tpeer->lock);
3926 tpeer->next = tpeers;
3927 tpeer->sockfd = fd;
3928 tpeers = tpeer;
3929 #ifdef SO_NO_CHECK
3930 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3931 #endif
3932 if (option_debug)
3933 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3936 ast_mutex_unlock(&tpeerlock);
3937 return tpeer;
3940 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
3942 struct ast_frame *f;
3943 struct iax2_trunk_peer *tpeer;
3944 void *tmp, *ptr;
3945 struct ast_iax2_meta_trunk_entry *met;
3946 struct ast_iax2_meta_trunk_mini *mtm;
3948 f = &fr->af;
3949 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
3950 if (tpeer) {
3951 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
3952 /* Need to reallocate space */
3953 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
3954 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
3955 ast_mutex_unlock(&tpeer->lock);
3956 return -1;
3959 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
3960 tpeer->trunkdata = tmp;
3961 if (option_debug)
3962 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
3963 } else {
3964 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3965 ast_mutex_unlock(&tpeer->lock);
3966 return -1;
3970 /* Append to meta frame */
3971 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
3972 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
3973 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
3974 mtm->len = htons(f->datalen);
3975 mtm->mini.callno = htons(pvt->callno);
3976 mtm->mini.ts = htons(0xffff & fr->ts);
3977 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
3978 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
3979 } else {
3980 met = (struct ast_iax2_meta_trunk_entry *)ptr;
3981 /* Store call number and length in meta header */
3982 met->callno = htons(pvt->callno);
3983 met->len = htons(f->datalen);
3984 /* Advance pointers/decrease length past trunk entry header */
3985 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
3986 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
3988 /* Copy actual trunk data */
3989 memcpy(ptr, f->data, f->datalen);
3990 tpeer->trunkdatalen += f->datalen;
3992 tpeer->calls++;
3993 ast_mutex_unlock(&tpeer->lock);
3995 return 0;
3998 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
4000 aes_encrypt_key128(digest, ecx);
4001 aes_decrypt_key128(digest, dcx);
4004 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
4006 #if 0
4007 /* Debug with "fake encryption" */
4008 int x;
4009 if (len % 16)
4010 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4011 for (x=0;x<len;x++)
4012 dst[x] = src[x] ^ 0xff;
4013 #else
4014 unsigned char lastblock[16] = { 0 };
4015 int x;
4016 while(len > 0) {
4017 aes_decrypt(src, dst, dcx);
4018 for (x=0;x<16;x++)
4019 dst[x] ^= lastblock[x];
4020 memcpy(lastblock, src, sizeof(lastblock));
4021 dst += 16;
4022 src += 16;
4023 len -= 16;
4025 #endif
4028 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
4030 #if 0
4031 /* Debug with "fake encryption" */
4032 int x;
4033 if (len % 16)
4034 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4035 for (x=0;x<len;x++)
4036 dst[x] = src[x] ^ 0xff;
4037 #else
4038 unsigned char curblock[16] = { 0 };
4039 int x;
4040 while(len > 0) {
4041 for (x=0;x<16;x++)
4042 curblock[x] ^= src[x];
4043 aes_encrypt(curblock, dst, ecx);
4044 memcpy(curblock, dst, sizeof(curblock));
4045 dst += 16;
4046 src += 16;
4047 len -= 16;
4049 #endif
4052 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4054 int padding;
4055 unsigned char *workspace;
4057 workspace = alloca(*datalen);
4058 memset(f, 0, sizeof(*f));
4059 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4060 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4061 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
4062 return -1;
4063 /* Decrypt */
4064 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
4066 padding = 16 + (workspace[15] & 0xf);
4067 if (option_debug && iaxdebug)
4068 ast_log(LOG_DEBUG, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
4069 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
4070 return -1;
4072 *datalen -= padding;
4073 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4074 f->frametype = fh->type;
4075 if (f->frametype == AST_FRAME_VIDEO) {
4076 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
4077 } else {
4078 f->subclass = uncompress_subclass(fh->csub);
4080 } else {
4081 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4082 if (option_debug && iaxdebug)
4083 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
4084 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
4085 return -1;
4086 /* Decrypt */
4087 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
4088 padding = 16 + (workspace[15] & 0x0f);
4089 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
4090 return -1;
4091 *datalen -= padding;
4092 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4094 return 0;
4097 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4099 int padding;
4100 unsigned char *workspace;
4101 workspace = alloca(*datalen + 32);
4102 if (!workspace)
4103 return -1;
4104 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4105 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4106 if (option_debug && iaxdebug)
4107 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
4108 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
4109 padding = 16 + (padding & 0xf);
4110 memcpy(workspace, poo, padding);
4111 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4112 workspace[15] &= 0xf0;
4113 workspace[15] |= (padding & 0xf);
4114 if (option_debug && iaxdebug)
4115 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
4116 *datalen += padding;
4117 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
4118 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
4119 memcpy(poo, workspace + *datalen - 32, 32);
4120 } else {
4121 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4122 if (option_debug && iaxdebug)
4123 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
4124 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
4125 padding = 16 + (padding & 0xf);
4126 memcpy(workspace, poo, padding);
4127 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4128 workspace[15] &= 0xf0;
4129 workspace[15] |= (padding & 0x0f);
4130 *datalen += padding;
4131 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
4132 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
4133 memcpy(poo, workspace + *datalen - 32, 32);
4135 return 0;
4138 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4140 int res=-1;
4141 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
4142 /* Search for possible keys, given secrets */
4143 struct MD5Context md5;
4144 unsigned char digest[16];
4145 char *tmppw, *stringp;
4147 tmppw = ast_strdupa(iaxs[callno]->secret);
4148 stringp = tmppw;
4149 while ((tmppw = strsep(&stringp, ";"))) {
4150 MD5Init(&md5);
4151 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
4152 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
4153 MD5Final(digest, &md5);
4154 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
4155 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4156 if (!res) {
4157 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4158 break;
4161 } else
4162 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4163 return res;
4166 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
4168 /* Queue a packet for delivery on a given private structure. Use "ts" for
4169 timestamp, or calculate if ts is 0. Send immediately without retransmission
4170 or delayed, with retransmission */
4171 struct ast_iax2_full_hdr *fh;
4172 struct ast_iax2_mini_hdr *mh;
4173 struct ast_iax2_video_hdr *vh;
4174 struct {
4175 struct iax_frame fr2;
4176 unsigned char buffer[4096];
4177 } frb;
4178 struct iax_frame *fr;
4179 int res;
4180 int sendmini=0;
4181 unsigned int lastsent;
4182 unsigned int fts;
4184 frb.fr2.afdatalen = sizeof(frb.buffer);
4186 if (!pvt) {
4187 ast_log(LOG_WARNING, "No private structure for packet?\n");
4188 return -1;
4191 lastsent = pvt->lastsent;
4193 /* Calculate actual timestamp */
4194 fts = calc_timestamp(pvt, ts, f);
4196 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4197 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4198 * increment the "predicted timestamps" for voice, if we're predecting */
4199 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
4200 return 0;
4203 if ((ast_test_flag(pvt, IAX_TRUNK) ||
4204 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
4205 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
4206 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4207 (f->frametype == AST_FRAME_VOICE)
4208 /* is a voice frame */ &&
4209 (f->subclass == pvt->svoiceformat)
4210 /* is the same type */ ) {
4211 /* Force immediate rather than delayed transmission */
4212 now = 1;
4213 /* Mark that mini-style frame is appropriate */
4214 sendmini = 1;
4216 if ( f->frametype == AST_FRAME_VIDEO ) {
4218 * If the lower 15 bits of the timestamp roll over, or if
4219 * the video format changed then send a full frame.
4220 * Otherwise send a mini video frame
4222 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
4223 ((f->subclass & ~0x1) == pvt->svideoformat)
4225 now = 1;
4226 sendmini = 1;
4227 } else {
4228 now = 0;
4229 sendmini = 0;
4231 pvt->lastvsent = fts;
4233 /* Allocate an iax_frame */
4234 if (now) {
4235 fr = &frb.fr2;
4236 } else
4237 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
4238 if (!fr) {
4239 ast_log(LOG_WARNING, "Out of memory\n");
4240 return -1;
4242 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4243 iax_frame_wrap(fr, f);
4245 fr->ts = fts;
4246 fr->callno = pvt->callno;
4247 fr->transfer = transfer;
4248 fr->final = final;
4249 if (!sendmini) {
4250 /* We need a full frame */
4251 if (seqno > -1)
4252 fr->oseqno = seqno;
4253 else
4254 fr->oseqno = pvt->oseqno++;
4255 fr->iseqno = pvt->iseqno;
4256 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
4257 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
4258 fh->ts = htonl(fr->ts);
4259 fh->oseqno = fr->oseqno;
4260 if (transfer) {
4261 fh->iseqno = 0;
4262 } else
4263 fh->iseqno = fr->iseqno;
4264 /* Keep track of the last thing we've acknowledged */
4265 if (!transfer)
4266 pvt->aseqno = fr->iseqno;
4267 fh->type = fr->af.frametype & 0xFF;
4268 if (fr->af.frametype == AST_FRAME_VIDEO)
4269 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
4270 else
4271 fh->csub = compress_subclass(fr->af.subclass);
4272 if (transfer) {
4273 fr->dcallno = pvt->transfercallno;
4274 } else
4275 fr->dcallno = pvt->peercallno;
4276 fh->dcallno = htons(fr->dcallno);
4277 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4278 fr->data = fh;
4279 fr->retries = 0;
4280 /* Retry after 2x the ping time has passed */
4281 fr->retrytime = pvt->pingtime * 2;
4282 if (fr->retrytime < MIN_RETRY_TIME)
4283 fr->retrytime = MIN_RETRY_TIME;
4284 if (fr->retrytime > MAX_RETRY_TIME)
4285 fr->retrytime = MAX_RETRY_TIME;
4286 /* Acks' don't get retried */
4287 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
4288 fr->retries = -1;
4289 else if (f->frametype == AST_FRAME_VOICE)
4290 pvt->svoiceformat = f->subclass;
4291 else if (f->frametype == AST_FRAME_VIDEO)
4292 pvt->svideoformat = f->subclass & ~0x1;
4293 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4294 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4295 if (iaxdebug) {
4296 if (fr->transfer)
4297 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4298 else
4299 iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4301 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
4302 } else
4303 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4306 if (now) {
4307 res = send_packet(fr);
4308 } else
4309 res = iax2_transmit(fr);
4310 } else {
4311 if (ast_test_flag(pvt, IAX_TRUNK)) {
4312 iax2_trunk_queue(pvt, fr);
4313 res = 0;
4314 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4315 /* Video frame have no sequence number */
4316 fr->oseqno = -1;
4317 fr->iseqno = -1;
4318 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
4319 vh->zeros = 0;
4320 vh->callno = htons(0x8000 | fr->callno);
4321 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
4322 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
4323 fr->data = vh;
4324 fr->retries = -1;
4325 res = send_packet(fr);
4326 } else {
4327 /* Mini-frames have no sequence number */
4328 fr->oseqno = -1;
4329 fr->iseqno = -1;
4330 /* Mini frame will do */
4331 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
4332 mh->callno = htons(fr->callno);
4333 mh->ts = htons(fr->ts & 0xFFFF);
4334 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
4335 fr->data = mh;
4336 fr->retries = -1;
4337 if (pvt->transferring == TRANSFER_MEDIAPASS)
4338 fr->transfer = 1;
4339 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4340 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4341 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
4342 } else
4343 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4345 res = send_packet(fr);
4348 return res;
4351 static int iax2_show_users(int fd, int argc, char *argv[])
4353 regex_t regexbuf;
4354 int havepattern = 0;
4356 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4357 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4359 struct iax2_user *user = NULL;
4360 char auth[90];
4361 char *pstr = "";
4362 struct ao2_iterator i;
4364 switch (argc) {
4365 case 5:
4366 if (!strcasecmp(argv[3], "like")) {
4367 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4368 return RESULT_SHOWUSAGE;
4369 havepattern = 1;
4370 } else
4371 return RESULT_SHOWUSAGE;
4372 case 3:
4373 break;
4374 default:
4375 return RESULT_SHOWUSAGE;
4378 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4379 i = ao2_iterator_init(users, 0);
4380 for (user = ao2_iterator_next(&i); user;
4381 user_unref(user), user = ao2_iterator_next(&i)) {
4382 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
4383 continue;
4385 if (!ast_strlen_zero(user->secret)) {
4386 ast_copy_string(auth,user->secret,sizeof(auth));
4387 } else if (!ast_strlen_zero(user->inkeys)) {
4388 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
4389 } else
4390 ast_copy_string(auth, "-no secret-", sizeof(auth));
4392 if(ast_test_flag(user,IAX_CODEC_NOCAP))
4393 pstr = "REQ Only";
4394 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
4395 pstr = "Disabled";
4396 else
4397 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
4399 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
4400 user->contexts ? user->contexts->context : context,
4401 user->ha ? "Yes" : "No", pstr);
4404 if (havepattern)
4405 regfree(&regexbuf);
4407 return RESULT_SUCCESS;
4408 #undef FORMAT
4409 #undef FORMAT2
4412 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
4414 regex_t regexbuf;
4415 int havepattern = 0;
4416 int total_peers = 0;
4417 int online_peers = 0;
4418 int offline_peers = 0;
4419 int unmonitored_peers = 0;
4420 struct ao2_iterator i;
4422 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4423 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4425 struct iax2_peer *peer = NULL;
4426 char name[256];
4427 int registeredonly=0;
4428 char *term = manager ? "\r\n" : "\n";
4430 switch (argc) {
4431 case 6:
4432 if (!strcasecmp(argv[3], "registered"))
4433 registeredonly = 1;
4434 else
4435 return RESULT_SHOWUSAGE;
4436 if (!strcasecmp(argv[4], "like")) {
4437 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
4438 return RESULT_SHOWUSAGE;
4439 havepattern = 1;
4440 } else
4441 return RESULT_SHOWUSAGE;
4442 break;
4443 case 5:
4444 if (!strcasecmp(argv[3], "like")) {
4445 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4446 return RESULT_SHOWUSAGE;
4447 havepattern = 1;
4448 } else
4449 return RESULT_SHOWUSAGE;
4450 break;
4451 case 4:
4452 if (!strcasecmp(argv[3], "registered"))
4453 registeredonly = 1;
4454 else
4455 return RESULT_SHOWUSAGE;
4456 break;
4457 case 3:
4458 break;
4459 default:
4460 return RESULT_SHOWUSAGE;
4464 if (s)
4465 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4466 else
4467 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4469 i = ao2_iterator_init(peers, 0);
4470 for (peer = ao2_iterator_next(&i); peer;
4471 peer_unref(peer), peer = ao2_iterator_next(&i)) {
4472 char nm[20];
4473 char status[20];
4474 char srch[2000];
4475 int retstatus;
4477 if (registeredonly && !peer->addr.sin_addr.s_addr)
4478 continue;
4479 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
4480 continue;
4482 if (!ast_strlen_zero(peer->username))
4483 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
4484 else
4485 ast_copy_string(name, peer->name, sizeof(name));
4487 retstatus = peer_status(peer, status, sizeof(status));
4488 if (retstatus > 0)
4489 online_peers++;
4490 else if (!retstatus)
4491 offline_peers++;
4492 else
4493 unmonitored_peers++;
4495 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
4497 snprintf(srch, sizeof(srch), FORMAT, name,
4498 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4499 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4501 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4502 peer->encmethods ? "(E)" : " ", status, term);
4504 if (s)
4505 astman_append(s, FORMAT, name,
4506 peer->addr.sin_addr.s_addr ? ast_inet_ntoa( peer->addr.sin_addr) : "(Unspecified)",
4507 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4509 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4510 peer->encmethods ? "(E)" : " ", status, term);
4511 else
4512 ast_cli(fd, FORMAT, name,
4513 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4514 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4516 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4517 peer->encmethods ? "(E)" : " ", status, term);
4518 total_peers++;
4521 if (s)
4522 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4523 else
4524 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4526 if (havepattern)
4527 regfree(&regexbuf);
4529 return RESULT_SUCCESS;
4530 #undef FORMAT
4531 #undef FORMAT2
4534 static int iax2_show_threads(int fd, int argc, char *argv[])
4536 struct iax2_thread *thread = NULL;
4537 time_t t;
4538 int threadcount = 0, dynamiccount = 0;
4539 char type;
4541 if (argc != 3)
4542 return RESULT_SHOWUSAGE;
4544 ast_cli(fd, "IAX2 Thread Information\n");
4545 time(&t);
4546 ast_cli(fd, "Idle Threads:\n");
4547 AST_LIST_LOCK(&idle_list);
4548 AST_LIST_TRAVERSE(&idle_list, thread, list) {
4549 #ifdef DEBUG_SCHED_MULTITHREAD
4550 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4551 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4552 #else
4553 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4554 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4555 #endif
4556 threadcount++;
4558 AST_LIST_UNLOCK(&idle_list);
4559 ast_cli(fd, "Active Threads:\n");
4560 AST_LIST_LOCK(&active_list);
4561 AST_LIST_TRAVERSE(&active_list, thread, list) {
4562 if (thread->type == IAX_TYPE_DYNAMIC)
4563 type = 'D';
4564 else
4565 type = 'P';
4566 #ifdef DEBUG_SCHED_MULTITHREAD
4567 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4568 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4569 #else
4570 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4571 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4572 #endif
4573 threadcount++;
4575 AST_LIST_UNLOCK(&active_list);
4576 ast_cli(fd, "Dynamic Threads:\n");
4577 AST_LIST_LOCK(&dynamic_list);
4578 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
4579 #ifdef DEBUG_SCHED_MULTITHREAD
4580 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4581 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4582 #else
4583 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4584 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4585 #endif
4586 dynamiccount++;
4588 AST_LIST_UNLOCK(&dynamic_list);
4589 ast_cli(fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
4590 return RESULT_SUCCESS;
4593 static int iax2_show_peers(int fd, int argc, char *argv[])
4595 return __iax2_show_peers(0, fd, NULL, argc, argv);
4597 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
4599 ast_cli_netstats(s, -1, 0);
4600 astman_append(s, "\r\n");
4601 return RESULT_SUCCESS;
4604 static int iax2_show_firmware(int fd, int argc, char *argv[])
4606 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4607 #if !defined(__FreeBSD__)
4608 #define FORMAT "%-15.15s %-15d %-15d\n"
4609 #else /* __FreeBSD__ */
4610 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4611 #endif /* __FreeBSD__ */
4612 struct iax_firmware *cur;
4613 if ((argc != 3) && (argc != 4))
4614 return RESULT_SHOWUSAGE;
4615 ast_mutex_lock(&waresl.lock);
4617 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
4618 for (cur = waresl.wares;cur;cur = cur->next) {
4619 if ((argc == 3) || (!strcasecmp(argv[3], (char *)cur->fwh->devname)))
4620 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
4621 (int)ntohl(cur->fwh->datalen));
4623 ast_mutex_unlock(&waresl.lock);
4624 return RESULT_SUCCESS;
4625 #undef FORMAT
4626 #undef FORMAT2
4629 /* JDG: callback to display iax peers in manager */
4630 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
4632 char *a[] = { "iax2", "show", "users" };
4633 int ret;
4634 const char *id = astman_get_header(m,"ActionID");
4636 if (!ast_strlen_zero(id))
4637 astman_append(s, "ActionID: %s\r\n",id);
4638 ret = __iax2_show_peers(1, -1, s, 3, a );
4639 astman_append(s, "\r\n\r\n" );
4640 return ret;
4641 } /* /JDG */
4643 static char *regstate2str(int regstate)
4645 switch(regstate) {
4646 case REG_STATE_UNREGISTERED:
4647 return "Unregistered";
4648 case REG_STATE_REGSENT:
4649 return "Request Sent";
4650 case REG_STATE_AUTHSENT:
4651 return "Auth. Sent";
4652 case REG_STATE_REGISTERED:
4653 return "Registered";
4654 case REG_STATE_REJECTED:
4655 return "Rejected";
4656 case REG_STATE_TIMEOUT:
4657 return "Timeout";
4658 case REG_STATE_NOAUTH:
4659 return "No Authentication";
4660 default:
4661 return "Unknown";
4665 static int iax2_show_registry(int fd, int argc, char *argv[])
4667 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4668 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4669 struct iax2_registry *reg = NULL;
4671 char host[80];
4672 char perceived[80];
4673 if (argc != 3)
4674 return RESULT_SHOWUSAGE;
4675 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4676 AST_LIST_LOCK(&registrations);
4677 AST_LIST_TRAVERSE(&registrations, reg, entry) {
4678 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
4679 if (reg->us.sin_addr.s_addr)
4680 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
4681 else
4682 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
4683 ast_cli(fd, FORMAT, host,
4684 (reg->dnsmgr) ? "Y" : "N",
4685 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
4687 AST_LIST_UNLOCK(&registrations);
4688 return RESULT_SUCCESS;
4689 #undef FORMAT
4690 #undef FORMAT2
4693 static int iax2_show_channels(int fd, int argc, char *argv[])
4695 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4696 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
4697 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4698 int x;
4699 int numchans = 0;
4701 if (argc != 3)
4702 return RESULT_SHOWUSAGE;
4703 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4704 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4705 ast_mutex_lock(&iaxsl[x]);
4706 if (iaxs[x]) {
4707 int lag, jitter, localdelay;
4708 jb_info jbinfo;
4710 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4711 jb_getinfo(iaxs[x]->jb, &jbinfo);
4712 jitter = jbinfo.jitter;
4713 localdelay = jbinfo.current - jbinfo.min;
4714 } else {
4715 jitter = -1;
4716 localdelay = 0;
4718 lag = iaxs[x]->remote_rr.delay;
4719 ast_cli(fd, FORMAT,
4720 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4721 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
4722 S_OR(iaxs[x]->username, "(None)"),
4723 iaxs[x]->callno, iaxs[x]->peercallno,
4724 iaxs[x]->oseqno, iaxs[x]->iseqno,
4725 lag,
4726 jitter,
4727 localdelay,
4728 ast_getformatname(iaxs[x]->voiceformat) );
4729 numchans++;
4731 ast_mutex_unlock(&iaxsl[x]);
4733 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4734 return RESULT_SUCCESS;
4735 #undef FORMAT
4736 #undef FORMAT2
4737 #undef FORMATB
4740 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
4742 int x;
4743 int numchans = 0;
4744 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4745 ast_mutex_lock(&iaxsl[x]);
4746 if (iaxs[x]) {
4747 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
4748 char *fmt;
4749 jb_info jbinfo;
4751 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4752 jb_getinfo(iaxs[x]->jb, &jbinfo);
4753 localjitter = jbinfo.jitter;
4754 localdelay = jbinfo.current - jbinfo.min;
4755 locallost = jbinfo.frames_lost;
4756 locallosspct = jbinfo.losspct/1000;
4757 localdropped = jbinfo.frames_dropped;
4758 localooo = jbinfo.frames_ooo;
4759 } else {
4760 localjitter = -1;
4761 localdelay = 0;
4762 locallost = -1;
4763 locallosspct = -1;
4764 localdropped = 0;
4765 localooo = -1;
4767 if (limit_fmt)
4768 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4769 else
4770 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4771 if (s)
4773 astman_append(s, fmt,
4774 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4775 iaxs[x]->pingtime,
4776 localjitter,
4777 localdelay,
4778 locallost,
4779 locallosspct,
4780 localdropped,
4781 localooo,
4782 iaxs[x]->frames_received/1000,
4783 iaxs[x]->remote_rr.jitter,
4784 iaxs[x]->remote_rr.delay,
4785 iaxs[x]->remote_rr.losscnt,
4786 iaxs[x]->remote_rr.losspct,
4787 iaxs[x]->remote_rr.dropped,
4788 iaxs[x]->remote_rr.ooo,
4789 iaxs[x]->remote_rr.packets/1000);
4790 else
4791 ast_cli(fd, fmt,
4792 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4793 iaxs[x]->pingtime,
4794 localjitter,
4795 localdelay,
4796 locallost,
4797 locallosspct,
4798 localdropped,
4799 localooo,
4800 iaxs[x]->frames_received/1000,
4801 iaxs[x]->remote_rr.jitter,
4802 iaxs[x]->remote_rr.delay,
4803 iaxs[x]->remote_rr.losscnt,
4804 iaxs[x]->remote_rr.losspct,
4805 iaxs[x]->remote_rr.dropped,
4806 iaxs[x]->remote_rr.ooo,
4807 iaxs[x]->remote_rr.packets/1000
4809 numchans++;
4811 ast_mutex_unlock(&iaxsl[x]);
4813 return numchans;
4816 static int iax2_show_netstats(int fd, int argc, char *argv[])
4818 int numchans = 0;
4819 if (argc != 3)
4820 return RESULT_SHOWUSAGE;
4821 ast_cli(fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4822 ast_cli(fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4823 numchans = ast_cli_netstats(NULL, fd, 1);
4824 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4825 return RESULT_SUCCESS;
4828 static int iax2_do_debug(int fd, int argc, char *argv[])
4830 if (argc < 2 || argc > 3)
4831 return RESULT_SHOWUSAGE;
4832 iaxdebug = 1;
4833 ast_cli(fd, "IAX2 Debugging Enabled\n");
4834 return RESULT_SUCCESS;
4837 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
4839 if (argc < 3 || argc > 4)
4840 return RESULT_SHOWUSAGE;
4841 iaxtrunkdebug = 1;
4842 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
4843 return RESULT_SUCCESS;
4846 static int iax2_do_jb_debug(int fd, int argc, char *argv[])
4848 if (argc < 3 || argc > 4)
4849 return RESULT_SHOWUSAGE;
4850 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
4851 ast_cli(fd, "IAX2 Jitterbuffer Debugging Enabled\n");
4852 return RESULT_SUCCESS;
4855 static int iax2_no_debug(int fd, int argc, char *argv[])
4857 if (argc < 3 || argc > 4)
4858 return RESULT_SHOWUSAGE;
4859 iaxdebug = 0;
4860 ast_cli(fd, "IAX2 Debugging Disabled\n");
4861 return RESULT_SUCCESS;
4864 static int iax2_no_trunk_debug(int fd, int argc, char *argv[])
4866 if (argc < 4 || argc > 5)
4867 return RESULT_SHOWUSAGE;
4868 iaxtrunkdebug = 0;
4869 ast_cli(fd, "IAX2 Trunk Debugging Disabled\n");
4870 return RESULT_SUCCESS;
4873 static int iax2_no_jb_debug(int fd, int argc, char *argv[])
4875 if (argc < 4 || argc > 5)
4876 return RESULT_SHOWUSAGE;
4877 jb_setoutput(jb_error_output, jb_warning_output, NULL);
4878 jb_debug_output("\n");
4879 ast_cli(fd, "IAX2 Jitterbuffer Debugging Disabled\n");
4880 return RESULT_SUCCESS;
4883 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
4885 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4886 int res = -1;
4887 ast_mutex_lock(&iaxsl[callno]);
4888 if (iaxs[callno]) {
4889 /* If there's an outstanding error, return failure now */
4890 if (!iaxs[callno]->error) {
4891 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
4892 res = 0;
4893 /* Don't waste bandwidth sending null frames */
4894 else if (f->frametype == AST_FRAME_NULL)
4895 res = 0;
4896 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
4897 res = 0;
4898 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
4899 res = 0;
4900 else
4901 /* Simple, just queue for transmission */
4902 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
4903 } else {
4904 if (option_debug)
4905 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
4908 /* If it's already gone, just return */
4909 ast_mutex_unlock(&iaxsl[callno]);
4910 return res;
4913 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
4914 int now, int transfer, int final)
4916 struct ast_frame f = { 0, };
4918 f.frametype = type;
4919 f.subclass = command;
4920 f.datalen = datalen;
4921 f.src = __FUNCTION__;
4922 f.data = (void *) data;
4924 return iax2_send(i, &f, ts, seqno, now, transfer, final);
4927 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4929 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
4932 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4934 int res;
4935 ast_mutex_lock(&iaxsl[callno]);
4936 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
4937 ast_mutex_unlock(&iaxsl[callno]);
4938 return res;
4942 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
4943 * the pvt struct for the given call number may disappear during its
4944 * execution.
4946 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4948 int call_num = i->callno;
4949 /* It is assumed that the callno has already been locked */
4950 iax2_predestroy(i->callno);
4951 if (!iaxs[call_num])
4952 return -1;
4953 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
4956 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4958 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
4961 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
4963 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
4966 static int apply_context(struct iax2_context *con, const char *context)
4968 while(con) {
4969 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
4970 return -1;
4971 con = con->next;
4973 return 0;
4977 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
4979 /* Start pessimistic */
4980 int res = -1;
4981 int version = 2;
4982 struct iax2_user *user = NULL, *best = NULL;
4983 int bestscore = 0;
4984 int gotcapability = 0;
4985 struct ast_variable *v = NULL, *tmpvar = NULL;
4986 struct ao2_iterator i;
4988 if (!iaxs[callno])
4989 return res;
4990 if (ies->called_number)
4991 ast_string_field_set(iaxs[callno], exten, ies->called_number);
4992 if (ies->calling_number) {
4993 ast_shrink_phone_number(ies->calling_number);
4994 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
4996 if (ies->calling_name)
4997 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
4998 if (ies->calling_ani)
4999 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
5000 if (ies->dnid)
5001 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
5002 if (ies->rdnis)
5003 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
5004 if (ies->called_context)
5005 ast_string_field_set(iaxs[callno], context, ies->called_context);
5006 if (ies->language)
5007 ast_string_field_set(iaxs[callno], language, ies->language);
5008 if (ies->username)
5009 ast_string_field_set(iaxs[callno], username, ies->username);
5010 if (ies->calling_ton > -1)
5011 iaxs[callno]->calling_ton = ies->calling_ton;
5012 if (ies->calling_tns > -1)
5013 iaxs[callno]->calling_tns = ies->calling_tns;
5014 if (ies->calling_pres > -1)
5015 iaxs[callno]->calling_pres = ies->calling_pres;
5016 if (ies->format)
5017 iaxs[callno]->peerformat = ies->format;
5018 if (ies->adsicpe)
5019 iaxs[callno]->peeradsicpe = ies->adsicpe;
5020 if (ies->capability) {
5021 gotcapability = 1;
5022 iaxs[callno]->peercapability = ies->capability;
5024 if (ies->version)
5025 version = ies->version;
5027 /* Use provided preferences until told otherwise for actual preferences */
5028 if(ies->codec_prefs) {
5029 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
5030 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
5033 if (!gotcapability)
5034 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
5035 if (version > IAX_PROTO_VERSION) {
5036 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
5037 ast_inet_ntoa(sin->sin_addr), version);
5038 return res;
5040 /* Search the userlist for a compatible entry, and fill in the rest */
5041 i = ao2_iterator_init(users, 0);
5042 while ((user = ao2_iterator_next(&i))) {
5043 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
5044 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
5045 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
5046 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
5047 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
5048 if (!ast_strlen_zero(iaxs[callno]->username)) {
5049 /* Exact match, stop right now. */
5050 if (best)
5051 user_unref(best);
5052 best = user;
5053 break;
5054 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5055 /* No required authentication */
5056 if (user->ha) {
5057 /* There was host authentication and we passed, bonus! */
5058 if (bestscore < 4) {
5059 bestscore = 4;
5060 if (best)
5061 user_unref(best);
5062 best = user;
5063 continue;
5065 } else {
5066 /* No host access, but no secret, either, not bad */
5067 if (bestscore < 3) {
5068 bestscore = 3;
5069 if (best)
5070 user_unref(best);
5071 best = user;
5072 continue;
5075 } else {
5076 if (user->ha) {
5077 /* Authentication, but host access too, eh, it's something.. */
5078 if (bestscore < 2) {
5079 bestscore = 2;
5080 if (best)
5081 user_unref(best);
5082 best = user;
5083 continue;
5085 } else {
5086 /* Authentication and no host access... This is our baseline */
5087 if (bestscore < 1) {
5088 bestscore = 1;
5089 if (best)
5090 user_unref(best);
5091 best = user;
5092 continue;
5097 user_unref(user);
5099 user = best;
5100 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
5101 user = realtime_user(iaxs[callno]->username, sin);
5102 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
5103 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
5104 user = user_unref(user);
5107 if (user) {
5108 /* We found our match (use the first) */
5109 /* copy vars */
5110 for (v = user->vars ; v ; v = v->next) {
5111 if((tmpvar = ast_variable_new(v->name, v->value))) {
5112 tmpvar->next = iaxs[callno]->vars;
5113 iaxs[callno]->vars = tmpvar;
5116 /* If a max AUTHREQ restriction is in place, activate it */
5117 if (user->maxauthreq > 0)
5118 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
5119 iaxs[callno]->prefs = user->prefs;
5120 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
5121 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
5122 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
5123 iaxs[callno]->encmethods = user->encmethods;
5124 /* Store the requested username if not specified */
5125 if (ast_strlen_zero(iaxs[callno]->username))
5126 ast_string_field_set(iaxs[callno], username, user->name);
5127 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5128 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
5129 iaxs[callno]->capability = user->capability;
5130 /* And use the default context */
5131 if (ast_strlen_zero(iaxs[callno]->context)) {
5132 if (user->contexts)
5133 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5134 else
5135 ast_string_field_set(iaxs[callno], context, context);
5137 /* And any input keys */
5138 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
5139 /* And the permitted authentication methods */
5140 iaxs[callno]->authmethods = user->authmethods;
5141 iaxs[callno]->adsi = user->adsi;
5142 /* If they have callerid, override the given caller id. Always store the ANI */
5143 if (!ast_strlen_zero(iaxs[callno]->cid_num) || !ast_strlen_zero(iaxs[callno]->cid_name)) {
5144 if (ast_test_flag(user, IAX_HASCALLERID)) {
5145 iaxs[callno]->calling_tns = 0;
5146 iaxs[callno]->calling_ton = 0;
5147 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
5148 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
5149 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
5151 if (ast_strlen_zero(iaxs[callno]->ani))
5152 ast_string_field_set(iaxs[callno], ani, user->cid_num);
5153 } else {
5154 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
5156 if (!ast_strlen_zero(user->accountcode))
5157 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
5158 if (!ast_strlen_zero(user->mohinterpret))
5159 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
5160 if (!ast_strlen_zero(user->mohsuggest))
5161 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
5162 if (user->amaflags)
5163 iaxs[callno]->amaflags = user->amaflags;
5164 if (!ast_strlen_zero(user->language))
5165 ast_string_field_set(iaxs[callno], language, user->language);
5166 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
5167 /* Keep this check last */
5168 if (!ast_strlen_zero(user->dbsecret)) {
5169 char *family, *key=NULL;
5170 char buf[80];
5171 family = ast_strdupa(user->dbsecret);
5172 key = strchr(family, '/');
5173 if (key) {
5174 *key = '\0';
5175 key++;
5177 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
5178 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
5179 else
5180 ast_string_field_set(iaxs[callno], secret, buf);
5181 } else
5182 ast_string_field_set(iaxs[callno], secret, user->secret);
5183 res = 0;
5184 user = user_unref(user);
5186 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
5187 return res;
5190 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
5192 struct ast_iax2_full_hdr fh;
5193 fh.scallno = htons(src | IAX_FLAG_FULL);
5194 fh.dcallno = htons(dst);
5195 fh.ts = 0;
5196 fh.oseqno = 0;
5197 fh.iseqno = 0;
5198 fh.type = AST_FRAME_IAX;
5199 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
5200 if (iaxdebug)
5201 iax_showframe(NULL, &fh, 0, sin, 0);
5202 if (option_debug)
5203 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5204 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
5205 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
5208 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
5210 /* Select exactly one common encryption if there are any */
5211 p->encmethods &= enc;
5212 if (p->encmethods) {
5213 if (p->encmethods & IAX_ENCRYPT_AES128)
5214 p->encmethods = IAX_ENCRYPT_AES128;
5215 else
5216 p->encmethods = 0;
5221 * \pre iaxsl[call_num] is locked
5223 * \note Since this function calls send_command_final(), the pvt struct for the given
5224 * call number may disappear while executing this function.
5226 static int authenticate_request(int call_num)
5228 struct iax_ie_data ied;
5229 int res = -1, authreq_restrict = 0;
5230 char challenge[10];
5231 struct chan_iax2_pvt *p = iaxs[call_num];
5233 memset(&ied, 0, sizeof(ied));
5235 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5236 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5237 struct iax2_user *user, tmp_user = {
5238 .name = p->username,
5241 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5242 if (user) {
5243 if (user->curauthreq == user->maxauthreq)
5244 authreq_restrict = 1;
5245 else
5246 user->curauthreq++;
5247 user = user_unref(user);
5251 /* If the AUTHREQ limit test failed, send back an error */
5252 if (authreq_restrict) {
5253 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
5254 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
5255 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
5256 return 0;
5259 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
5260 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
5261 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
5262 ast_string_field_set(p, challenge, challenge);
5263 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5264 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
5266 if (p->encmethods)
5267 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
5269 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
5271 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
5273 if (p->encmethods)
5274 ast_set_flag(p, IAX_ENCRYPTED);
5276 return res;
5279 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
5281 char requeststr[256];
5282 char md5secret[256] = "";
5283 char secret[256] = "";
5284 char rsasecret[256] = "";
5285 int res = -1;
5286 int x;
5287 struct iax2_user *user, tmp_user = {
5288 .name = p->username,
5291 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5292 if (user) {
5293 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5294 ast_atomic_fetchadd_int(&user->curauthreq, -1);
5295 ast_clear_flag(p, IAX_MAXAUTHREQ);
5297 ast_string_field_set(p, host, user->name);
5298 user = user_unref(user);
5301 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
5302 return res;
5303 if (ies->password)
5304 ast_copy_string(secret, ies->password, sizeof(secret));
5305 if (ies->md5_result)
5306 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5307 if (ies->rsa_result)
5308 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5309 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
5310 struct ast_key *key;
5311 char *keyn;
5312 char tmpkey[256];
5313 char *stringp=NULL;
5314 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
5315 stringp=tmpkey;
5316 keyn = strsep(&stringp, ":");
5317 while(keyn) {
5318 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5319 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
5320 res = 0;
5321 break;
5322 } else if (!key)
5323 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
5324 keyn = strsep(&stringp, ":");
5326 } else if (p->authmethods & IAX_AUTH_MD5) {
5327 struct MD5Context md5;
5328 unsigned char digest[16];
5329 char *tmppw, *stringp;
5331 tmppw = ast_strdupa(p->secret);
5332 stringp = tmppw;
5333 while((tmppw = strsep(&stringp, ";"))) {
5334 MD5Init(&md5);
5335 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
5336 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5337 MD5Final(digest, &md5);
5338 /* If they support md5, authenticate with it. */
5339 for (x=0;x<16;x++)
5340 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5341 if (!strcasecmp(requeststr, md5secret)) {
5342 res = 0;
5343 break;
5346 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
5347 if (!strcmp(secret, p->secret))
5348 res = 0;
5350 return res;
5353 /*! \brief Verify inbound registration */
5354 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5356 char requeststr[256] = "";
5357 char peer[256] = "";
5358 char md5secret[256] = "";
5359 char rsasecret[256] = "";
5360 char secret[256] = "";
5361 struct iax2_peer *p = NULL;
5362 struct ast_key *key;
5363 char *keyn;
5364 int x;
5365 int expire = 0;
5366 int res = -1;
5368 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
5369 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5370 if (ies->username)
5371 ast_copy_string(peer, ies->username, sizeof(peer));
5372 if (ies->password)
5373 ast_copy_string(secret, ies->password, sizeof(secret));
5374 if (ies->md5_result)
5375 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5376 if (ies->rsa_result)
5377 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5378 if (ies->refresh)
5379 expire = ies->refresh;
5381 if (ast_strlen_zero(peer)) {
5382 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
5383 return -1;
5386 /* SLD: first call to lookup peer during registration */
5387 ast_mutex_unlock(&iaxsl[callno]);
5388 p = find_peer(peer, 1);
5389 ast_mutex_lock(&iaxsl[callno]);
5390 if (!p || !iaxs[callno]) {
5391 if (authdebug && !p)
5392 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5393 goto return_unref;
5396 if (!ast_test_flag(p, IAX_DYNAMIC)) {
5397 if (authdebug)
5398 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5399 goto return_unref;
5402 if (!ast_apply_ha(p->ha, sin)) {
5403 if (authdebug)
5404 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5405 goto return_unref;
5407 if (!inaddrcmp(&p->addr, sin))
5408 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
5409 ast_string_field_set(iaxs[callno], secret, p->secret);
5410 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
5411 /* Check secret against what we have on file */
5412 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5413 if (!ast_strlen_zero(p->inkeys)) {
5414 char tmpkeys[256];
5415 char *stringp=NULL;
5416 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
5417 stringp=tmpkeys;
5418 keyn = strsep(&stringp, ":");
5419 while(keyn) {
5420 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5421 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
5422 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5423 break;
5424 } else if (!key)
5425 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
5426 keyn = strsep(&stringp, ":");
5428 if (!keyn) {
5429 if (authdebug)
5430 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
5431 goto return_unref;
5433 } else {
5434 if (authdebug)
5435 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
5436 goto return_unref;
5438 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5439 struct MD5Context md5;
5440 unsigned char digest[16];
5441 char *tmppw, *stringp;
5443 tmppw = ast_strdupa(p->secret);
5444 stringp = tmppw;
5445 while((tmppw = strsep(&stringp, ";"))) {
5446 MD5Init(&md5);
5447 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
5448 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5449 MD5Final(digest, &md5);
5450 for (x=0;x<16;x++)
5451 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5452 if (!strcasecmp(requeststr, md5secret))
5453 break;
5455 if (tmppw) {
5456 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5457 } else {
5458 if (authdebug)
5459 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
5460 goto return_unref;
5462 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
5463 /* They've provided a plain text password and we support that */
5464 if (strcmp(secret, p->secret)) {
5465 if (authdebug)
5466 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5467 goto return_unref;
5468 } else
5469 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5470 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
5471 if (authdebug)
5472 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
5473 goto return_unref;
5475 ast_string_field_set(iaxs[callno], peer, peer);
5476 /* Choose lowest expiry number */
5477 if (expire && (expire < iaxs[callno]->expiry))
5478 iaxs[callno]->expiry = expire;
5480 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5482 res = 0;
5484 return_unref:
5485 if (p)
5486 peer_unref(p);
5488 return res;
5491 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
5493 int res = -1;
5494 int x;
5495 if (!ast_strlen_zero(keyn)) {
5496 if (!(authmethods & IAX_AUTH_RSA)) {
5497 if (ast_strlen_zero(secret))
5498 ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
5499 } else if (ast_strlen_zero(challenge)) {
5500 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
5501 } else {
5502 char sig[256];
5503 struct ast_key *key;
5504 key = ast_key_get(keyn, AST_KEY_PRIVATE);
5505 if (!key) {
5506 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
5507 } else {
5508 if (ast_sign(key, (char*)challenge, sig)) {
5509 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
5510 res = -1;
5511 } else {
5512 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
5513 res = 0;
5518 /* Fall back */
5519 if (res && !ast_strlen_zero(secret)) {
5520 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
5521 struct MD5Context md5;
5522 unsigned char digest[16];
5523 char digres[128];
5524 MD5Init(&md5);
5525 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
5526 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
5527 MD5Final(digest, &md5);
5528 /* If they support md5, authenticate with it. */
5529 for (x=0;x<16;x++)
5530 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
5531 if (ecx && dcx)
5532 build_enc_keys(digest, ecx, dcx);
5533 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
5534 res = 0;
5535 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
5536 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
5537 res = 0;
5538 } else
5539 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
5541 return res;
5545 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5546 * so do not call this function with a pvt lock held.
5548 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
5550 struct iax2_peer *peer = NULL;
5551 /* Start pessimistic */
5552 int res = -1;
5553 int authmethods = 0;
5554 struct iax_ie_data ied;
5555 uint16_t callno = p->callno;
5557 memset(&ied, 0, sizeof(ied));
5559 if (ies->username)
5560 ast_string_field_set(p, username, ies->username);
5561 if (ies->challenge)
5562 ast_string_field_set(p, challenge, ies->challenge);
5563 if (ies->authmethods)
5564 authmethods = ies->authmethods;
5565 if (authmethods & IAX_AUTH_MD5)
5566 merge_encryption(p, ies->encmethods);
5567 else
5568 p->encmethods = 0;
5570 /* Check for override RSA authentication first */
5571 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
5572 /* Normal password authentication */
5573 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5574 } else {
5575 struct ao2_iterator i = ao2_iterator_init(peers, 0);
5576 while ((peer = ao2_iterator_next(&i))) {
5577 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
5578 /* No peer specified at our end, or this is the peer */
5579 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
5580 /* No username specified in peer rule, or this is the right username */
5581 && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
5582 /* No specified host, or this is our host */
5584 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5585 if (!res) {
5586 peer_unref(peer);
5587 break;
5590 peer_unref(peer);
5592 if (!peer) {
5593 /* We checked our list and didn't find one. It's unlikely, but possible,
5594 that we're trying to authenticate *to* a realtime peer */
5595 const char *peer_name = ast_strdupa(p->peer);
5596 ast_mutex_unlock(&iaxsl[callno]);
5597 if ((peer = realtime_peer(peer_name, NULL))) {
5598 ast_mutex_lock(&iaxsl[callno]);
5599 if (!(p = iaxs[callno])) {
5600 peer_unref(peer);
5601 return -1;
5603 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5604 peer_unref(peer);
5606 if (!peer) {
5607 ast_mutex_lock(&iaxsl[callno]);
5608 if (!(p = iaxs[callno]))
5609 return -1;
5613 if (ies->encmethods)
5614 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
5615 if (!res)
5616 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
5617 return res;
5620 static int iax2_do_register(struct iax2_registry *reg);
5622 static void __iax2_do_register_s(const void *data)
5624 struct iax2_registry *reg = (struct iax2_registry *)data;
5625 reg->expire = -1;
5626 iax2_do_register(reg);
5629 static int iax2_do_register_s(const void *data)
5631 #ifdef SCHED_MULTITHREADED
5632 if (schedule_action(__iax2_do_register_s, data))
5633 #endif
5634 __iax2_do_register_s(data);
5635 return 0;
5638 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5640 int newcall = 0;
5641 char newip[256];
5642 struct iax_ie_data ied;
5643 struct sockaddr_in new;
5646 memset(&ied, 0, sizeof(ied));
5647 if (ies->apparent_addr)
5648 bcopy(ies->apparent_addr, &new, sizeof(new));
5649 if (ies->callno)
5650 newcall = ies->callno;
5651 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
5652 ast_log(LOG_WARNING, "Invalid transfer request\n");
5653 return -1;
5655 pvt->transfercallno = newcall;
5656 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
5657 inet_aton(newip, &pvt->transfer.sin_addr);
5658 pvt->transfer.sin_family = AF_INET;
5659 pvt->transferring = TRANSFER_BEGIN;
5660 pvt->transferid = ies->transferid;
5661 if (ies->transferid)
5662 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
5663 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
5664 return 0;
5667 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5669 char exten[256] = "";
5670 int status = CACHE_FLAG_UNKNOWN;
5671 int expiry = iaxdefaultdpcache;
5672 int x;
5673 int matchmore = 0;
5674 struct iax2_dpcache *dp, *prev;
5676 if (ies->called_number)
5677 ast_copy_string(exten, ies->called_number, sizeof(exten));
5679 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
5680 status = CACHE_FLAG_EXISTS;
5681 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
5682 status = CACHE_FLAG_CANEXIST;
5683 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
5684 status = CACHE_FLAG_NONEXISTENT;
5686 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
5687 /* Don't really do anything with this */
5689 if (ies->refresh)
5690 expiry = ies->refresh;
5691 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
5692 matchmore = CACHE_FLAG_MATCHMORE;
5693 ast_mutex_lock(&dpcache_lock);
5694 prev = NULL;
5695 dp = pvt->dpentries;
5696 while(dp) {
5697 if (!strcmp(dp->exten, exten)) {
5698 /* Let them go */
5699 if (prev)
5700 prev->peer = dp->peer;
5701 else
5702 pvt->dpentries = dp->peer;
5703 dp->peer = NULL;
5704 dp->callno = 0;
5705 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
5706 if (dp->flags & CACHE_FLAG_PENDING) {
5707 dp->flags &= ~CACHE_FLAG_PENDING;
5708 dp->flags |= status;
5709 dp->flags |= matchmore;
5711 /* Wake up waiters */
5712 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
5713 if (dp->waiters[x] > -1)
5714 write(dp->waiters[x], "asdf", 4);
5716 prev = dp;
5717 dp = dp->peer;
5719 ast_mutex_unlock(&dpcache_lock);
5720 return 0;
5723 static int complete_transfer(int callno, struct iax_ies *ies)
5725 int peercallno = 0;
5726 struct chan_iax2_pvt *pvt = iaxs[callno];
5727 struct iax_frame *cur;
5728 jb_frame frame;
5730 if (ies->callno)
5731 peercallno = ies->callno;
5733 if (peercallno < 1) {
5734 ast_log(LOG_WARNING, "Invalid transfer request\n");
5735 return -1;
5737 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
5738 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
5739 /* Reset sequence numbers */
5740 pvt->oseqno = 0;
5741 pvt->rseqno = 0;
5742 pvt->iseqno = 0;
5743 pvt->aseqno = 0;
5744 pvt->peercallno = peercallno;
5745 pvt->transferring = TRANSFER_NONE;
5746 pvt->svoiceformat = -1;
5747 pvt->voiceformat = 0;
5748 pvt->svideoformat = -1;
5749 pvt->videoformat = 0;
5750 pvt->transfercallno = -1;
5751 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
5752 memset(&pvt->offset, 0, sizeof(pvt->offset));
5753 /* reset jitterbuffer */
5754 while(jb_getall(pvt->jb,&frame) == JB_OK)
5755 iax2_frame_free(frame.data);
5756 jb_reset(pvt->jb);
5757 pvt->lag = 0;
5758 pvt->last = 0;
5759 pvt->lastsent = 0;
5760 pvt->nextpred = 0;
5761 pvt->pingtime = DEFAULT_RETRY_TIME;
5762 AST_LIST_LOCK(&iaxq.queue);
5763 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
5764 /* We must cancel any packets that would have been transmitted
5765 because now we're talking to someone new. It's okay, they
5766 were transmitted to someone that didn't care anyway. */
5767 if (callno == cur->callno)
5768 cur->retries = -1;
5770 AST_LIST_UNLOCK(&iaxq.queue);
5771 return 0;
5774 /*! \brief Acknowledgment received for OUR registration */
5775 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
5777 struct iax2_registry *reg;
5778 /* Start pessimistic */
5779 char peer[256] = "";
5780 char msgstatus[60];
5781 int refresh = 60;
5782 char ourip[256] = "<Unspecified>";
5783 struct sockaddr_in oldus;
5784 struct sockaddr_in us;
5785 int oldmsgs;
5787 memset(&us, 0, sizeof(us));
5788 if (ies->apparent_addr)
5789 bcopy(ies->apparent_addr, &us, sizeof(us));
5790 if (ies->username)
5791 ast_copy_string(peer, ies->username, sizeof(peer));
5792 if (ies->refresh)
5793 refresh = ies->refresh;
5794 if (ies->calling_number) {
5795 /* We don't do anything with it really, but maybe we should */
5797 reg = iaxs[callno]->reg;
5798 if (!reg) {
5799 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
5800 return -1;
5802 memcpy(&oldus, &reg->us, sizeof(oldus));
5803 oldmsgs = reg->messages;
5804 if (inaddrcmp(&reg->addr, sin)) {
5805 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
5806 return -1;
5808 memcpy(&reg->us, &us, sizeof(reg->us));
5809 if (ies->msgcount >= 0)
5810 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
5811 /* always refresh the registration at the interval requested by the server
5812 we are registering to
5814 reg->refresh = refresh;
5815 AST_SCHED_DEL(sched, reg->expire);
5816 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
5817 if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
5818 if (option_verbose > 2) {
5819 if (reg->messages > 255)
5820 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
5821 else if (reg->messages > 1)
5822 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
5823 else if (reg->messages > 0)
5824 snprintf(msgstatus, sizeof(msgstatus), " with 1 new message waiting\n");
5825 else
5826 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
5827 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
5828 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
5830 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
5832 reg->regstate = REG_STATE_REGISTERED;
5833 return 0;
5836 static int iax2_register(char *value, int lineno)
5838 struct iax2_registry *reg;
5839 char copy[256];
5840 char *username, *hostname, *secret;
5841 char *porta;
5842 char *stringp=NULL;
5844 if (!value)
5845 return -1;
5846 ast_copy_string(copy, value, sizeof(copy));
5847 stringp=copy;
5848 username = strsep(&stringp, "@");
5849 hostname = strsep(&stringp, "@");
5850 if (!hostname) {
5851 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
5852 return -1;
5854 stringp=username;
5855 username = strsep(&stringp, ":");
5856 secret = strsep(&stringp, ":");
5857 stringp=hostname;
5858 hostname = strsep(&stringp, ":");
5859 porta = strsep(&stringp, ":");
5861 if (porta && !atoi(porta)) {
5862 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
5863 return -1;
5865 if (!(reg = ast_calloc(1, sizeof(*reg))))
5866 return -1;
5867 if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
5868 free(reg);
5869 return -1;
5871 ast_copy_string(reg->username, username, sizeof(reg->username));
5872 if (secret)
5873 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
5874 reg->expire = -1;
5875 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
5876 reg->addr.sin_family = AF_INET;
5877 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
5878 AST_LIST_LOCK(&registrations);
5879 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
5880 AST_LIST_UNLOCK(&registrations);
5882 return 0;
5885 static void register_peer_exten(struct iax2_peer *peer, int onoff)
5887 char multi[256];
5888 char *stringp, *ext;
5889 if (!ast_strlen_zero(regcontext)) {
5890 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
5891 stringp = multi;
5892 while((ext = strsep(&stringp, "&"))) {
5893 if (onoff) {
5894 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
5895 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
5896 "Noop", ast_strdup(peer->name), ast_free, "IAX2");
5897 } else
5898 ast_context_remove_extension(regcontext, ext, 1, NULL);
5902 static void prune_peers(void);
5904 static void unlink_peer(struct iax2_peer *peer)
5906 if (peer->expire > -1) {
5907 if (!ast_sched_del(sched, peer->expire)) {
5908 peer->expire = -1;
5909 peer_unref(peer);
5913 if (peer->pokeexpire > -1) {
5914 if (!ast_sched_del(sched, peer->pokeexpire)) {
5915 peer->pokeexpire = -1;
5916 peer_unref(peer);
5920 ao2_unlink(peers, peer);
5923 static void __expire_registry(const void *data)
5925 struct iax2_peer *peer = (struct iax2_peer *) data;
5927 if (!peer)
5928 return;
5930 peer->expire = -1;
5932 if (option_debug)
5933 ast_log(LOG_DEBUG, "Expiring registration for peer '%s'\n", peer->name);
5934 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
5935 realtime_update_peer(peer->name, &peer->addr, 0);
5936 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
5937 /* Reset the address */
5938 memset(&peer->addr, 0, sizeof(peer->addr));
5939 /* Reset expiry value */
5940 peer->expiry = min_reg_expire;
5941 if (!ast_test_flag(peer, IAX_TEMPONLY))
5942 ast_db_del("IAX/Registry", peer->name);
5943 register_peer_exten(peer, 0);
5944 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
5945 if (iax2_regfunk)
5946 iax2_regfunk(peer->name, 0);
5948 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
5949 unlink_peer(peer);
5951 peer_unref(peer);
5954 static int expire_registry(const void *data)
5956 #ifdef SCHED_MULTITHREADED
5957 if (schedule_action(__expire_registry, data))
5958 #endif
5959 __expire_registry(data);
5960 return 0;
5963 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
5965 static void reg_source_db(struct iax2_peer *p)
5967 char data[80];
5968 struct in_addr in;
5969 char *c, *d;
5970 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
5971 c = strchr(data, ':');
5972 if (c) {
5973 *c = '\0';
5974 c++;
5975 if (inet_aton(data, &in)) {
5976 d = strchr(c, ':');
5977 if (d) {
5978 *d = '\0';
5979 d++;
5980 if (option_verbose > 2)
5981 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
5982 ast_inet_ntoa(in), atoi(c), atoi(d));
5983 iax2_poke_peer(p, 0);
5984 p->expiry = atoi(d);
5985 memset(&p->addr, 0, sizeof(p->addr));
5986 p->addr.sin_family = AF_INET;
5987 p->addr.sin_addr = in;
5988 p->addr.sin_port = htons(atoi(c));
5989 if (p->expire > -1) {
5990 if (!ast_sched_del(sched, p->expire)) {
5991 p->expire = -1;
5992 peer_unref(p);
5995 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5996 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
5997 if (p->expire == -1)
5998 peer_unref(p);
5999 if (iax2_regfunk)
6000 iax2_regfunk(p->name, 1);
6001 register_peer_exten(p, 1);
6010 * \pre iaxsl[callno] is locked
6012 * \note Since this function calls send_command_final(), the pvt struct for
6013 * the given call number may disappear while executing this function.
6015 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
6017 /* Called from IAX thread only, with proper iaxsl lock */
6018 struct iax_ie_data ied;
6019 struct iax2_peer *p;
6020 int msgcount;
6021 char data[80];
6022 int version;
6023 const char *peer_name;
6024 int res = -1;
6026 memset(&ied, 0, sizeof(ied));
6028 peer_name = ast_strdupa(iaxs[callno]->peer);
6030 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6031 ast_mutex_unlock(&iaxsl[callno]);
6032 if (!(p = find_peer(peer_name, 1))) {
6033 ast_mutex_lock(&iaxsl[callno]);
6034 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6035 return -1;
6037 ast_mutex_lock(&iaxsl[callno]);
6038 if (!iaxs[callno])
6039 goto return_unref;
6041 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6042 if (sin->sin_addr.s_addr) {
6043 time_t nowtime;
6044 time(&nowtime);
6045 realtime_update_peer(peer_name, sin, nowtime);
6046 } else {
6047 realtime_update_peer(peer_name, sin, 0);
6050 if (inaddrcmp(&p->addr, sin)) {
6051 if (iax2_regfunk)
6052 iax2_regfunk(p->name, 1);
6053 /* Stash the IP address from which they registered */
6054 memcpy(&p->addr, sin, sizeof(p->addr));
6055 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
6056 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
6057 ast_db_put("IAX/Registry", p->name, data);
6058 if (option_verbose > 2)
6059 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
6060 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
6061 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
6062 register_peer_exten(p, 1);
6063 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6064 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
6065 if (option_verbose > 2)
6066 ast_verbose(VERBOSE_PREFIX_3 "Unregistered IAX2 '%s' (%s)\n", p->name,
6067 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6068 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
6069 register_peer_exten(p, 0);
6070 ast_db_del("IAX/Registry", p->name);
6071 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6073 /* Update the host */
6074 /* Verify that the host is really there */
6075 iax2_poke_peer(p, callno);
6078 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6079 if (!iaxs[callno]) {
6080 res = 0;
6081 goto return_unref;
6084 /* Store socket fd */
6085 p->sockfd = fd;
6086 /* Setup the expiry */
6087 if (p->expire > -1) {
6088 if (!ast_sched_del(sched, p->expire)) {
6089 p->expire = -1;
6090 peer_unref(p);
6093 /* treat an unspecified refresh interval as the minimum */
6094 if (!refresh)
6095 refresh = min_reg_expire;
6096 if (refresh > max_reg_expire) {
6097 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6098 p->name, max_reg_expire, refresh);
6099 p->expiry = max_reg_expire;
6100 } else if (refresh < min_reg_expire) {
6101 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6102 p->name, min_reg_expire, refresh);
6103 p->expiry = min_reg_expire;
6104 } else {
6105 p->expiry = refresh;
6107 if (p->expiry && sin->sin_addr.s_addr) {
6108 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6109 if (p->expire == -1)
6110 peer_unref(p);
6112 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
6113 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
6114 if (sin->sin_addr.s_addr) {
6115 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
6116 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
6117 if (!ast_strlen_zero(p->mailbox)) {
6118 int new, old;
6119 ast_app_inboxcount(p->mailbox, &new, &old);
6120 if (new > 255)
6121 new = 255;
6122 if (old > 255)
6123 old = 255;
6124 msgcount = (old << 8) | new;
6125 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
6127 if (ast_test_flag(p, IAX_HASCALLERID)) {
6128 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
6129 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
6132 version = iax_check_version(devtype);
6133 if (version)
6134 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
6136 res = 0;
6138 return_unref:
6139 peer_unref(p);
6141 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
6144 static int registry_authrequest(int callno)
6146 struct iax_ie_data ied;
6147 struct iax2_peer *p;
6148 char challenge[10];
6149 const char *peer_name;
6150 int res = -1;
6152 peer_name = ast_strdupa(iaxs[callno]->peer);
6154 /* SLD: third call to find_peer in registration */
6155 ast_mutex_unlock(&iaxsl[callno]);
6156 p = find_peer(peer_name, 1);
6157 ast_mutex_lock(&iaxsl[callno]);
6158 if (!iaxs[callno])
6159 goto return_unref;
6160 if (!p) {
6161 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6162 goto return_unref;
6165 memset(&ied, 0, sizeof(ied));
6166 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
6167 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
6168 /* Build the challenge */
6169 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
6170 ast_string_field_set(iaxs[callno], challenge, challenge);
6171 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
6173 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
6175 res = 0;
6177 return_unref:
6178 peer_unref(p);
6180 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
6183 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
6185 struct iax2_registry *reg;
6186 /* Start pessimistic */
6187 struct iax_ie_data ied;
6188 char peer[256] = "";
6189 char challenge[256] = "";
6190 int res;
6191 int authmethods = 0;
6192 if (ies->authmethods)
6193 authmethods = ies->authmethods;
6194 if (ies->username)
6195 ast_copy_string(peer, ies->username, sizeof(peer));
6196 if (ies->challenge)
6197 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
6198 memset(&ied, 0, sizeof(ied));
6199 reg = iaxs[callno]->reg;
6200 if (reg) {
6201 if (inaddrcmp(&reg->addr, sin)) {
6202 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6203 return -1;
6205 if (ast_strlen_zero(reg->secret)) {
6206 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
6207 reg->regstate = REG_STATE_NOAUTH;
6208 return -1;
6210 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
6211 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
6212 if (reg->secret[0] == '[') {
6213 char tmpkey[256];
6214 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
6215 tmpkey[strlen(tmpkey) - 1] = '\0';
6216 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
6217 } else
6218 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
6219 if (!res) {
6220 reg->regstate = REG_STATE_AUTHSENT;
6221 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
6222 } else
6223 return -1;
6224 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
6225 } else
6226 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
6227 return -1;
6230 static void stop_stuff(int callno)
6232 iax2_destroy_helper(iaxs[callno]);
6235 static void __auth_reject(const void *nothing)
6237 /* Called from IAX thread only, without iaxs lock */
6238 int callno = (int)(long)(nothing);
6239 struct iax_ie_data ied;
6240 ast_mutex_lock(&iaxsl[callno]);
6241 if (iaxs[callno]) {
6242 memset(&ied, 0, sizeof(ied));
6243 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
6244 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
6245 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
6246 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
6247 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
6248 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
6250 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
6252 ast_mutex_unlock(&iaxsl[callno]);
6255 static int auth_reject(const void *data)
6257 int callno = (int)(long)(data);
6258 ast_mutex_lock(&iaxsl[callno]);
6259 if (iaxs[callno])
6260 iaxs[callno]->authid = -1;
6261 ast_mutex_unlock(&iaxsl[callno]);
6262 #ifdef SCHED_MULTITHREADED
6263 if (schedule_action(__auth_reject, data))
6264 #endif
6265 __auth_reject(data);
6266 return 0;
6269 static int auth_fail(int callno, int failcode)
6271 /* Schedule sending the authentication failure in one second, to prevent
6272 guessing */
6273 if (iaxs[callno]) {
6274 iaxs[callno]->authfail = failcode;
6275 if (delayreject) {
6276 AST_SCHED_DEL(sched, iaxs[callno]->authid);
6277 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
6278 } else
6279 auth_reject((void *)(long)callno);
6281 return 0;
6284 static void __auto_hangup(const void *nothing)
6286 /* Called from IAX thread only, without iaxs lock */
6287 int callno = (int)(long)(nothing);
6288 struct iax_ie_data ied;
6289 ast_mutex_lock(&iaxsl[callno]);
6290 if (iaxs[callno]) {
6291 memset(&ied, 0, sizeof(ied));
6292 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
6293 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
6294 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
6296 ast_mutex_unlock(&iaxsl[callno]);
6299 static int auto_hangup(const void *data)
6301 int callno = (int)(long)(data);
6302 ast_mutex_lock(&iaxsl[callno]);
6303 if (iaxs[callno]) {
6304 iaxs[callno]->autoid = -1;
6306 ast_mutex_unlock(&iaxsl[callno]);
6307 #ifdef SCHED_MULTITHREADED
6308 if (schedule_action(__auto_hangup, data))
6309 #endif
6310 __auto_hangup(data);
6311 return 0;
6314 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
6316 struct iax_ie_data ied;
6317 /* Auto-hangup with 30 seconds of inactivity */
6318 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
6319 iaxs[callno]->autoid = iax2_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
6320 memset(&ied, 0, sizeof(ied));
6321 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
6322 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
6323 dp->flags |= CACHE_FLAG_TRANSMITTED;
6326 static int iax2_vnak(int callno)
6328 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
6331 static void vnak_retransmit(int callno, int last)
6333 struct iax_frame *f;
6335 AST_LIST_LOCK(&iaxq.queue);
6336 AST_LIST_TRAVERSE(&iaxq.queue, f, list) {
6337 /* Send a copy immediately */
6338 if ((f->callno == callno) && iaxs[f->callno] &&
6339 ((unsigned char ) (f->oseqno - last) < 128) &&
6340 (f->retries >= 0)) {
6341 send_packet(f);
6344 AST_LIST_UNLOCK(&iaxq.queue);
6347 static void __iax2_poke_peer_s(const void *data)
6349 struct iax2_peer *peer = (struct iax2_peer *)data;
6350 iax2_poke_peer(peer, 0);
6351 peer_unref(peer);
6354 static int iax2_poke_peer_s(const void *data)
6356 struct iax2_peer *peer = (struct iax2_peer *)data;
6357 peer->pokeexpire = -1;
6358 #ifdef SCHED_MULTITHREADED
6359 if (schedule_action(__iax2_poke_peer_s, data))
6360 #endif
6361 __iax2_poke_peer_s(data);
6362 return 0;
6365 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
6367 int res = 0;
6368 struct iax_frame *fr;
6369 struct ast_iax2_meta_hdr *meta;
6370 struct ast_iax2_meta_trunk_hdr *mth;
6371 int calls = 0;
6373 /* Point to frame */
6374 fr = (struct iax_frame *)tpeer->trunkdata;
6375 /* Point to meta data */
6376 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
6377 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
6378 if (tpeer->trunkdatalen) {
6379 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6380 meta->zeros = 0;
6381 meta->metacmd = IAX_META_TRUNK;
6382 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
6383 meta->cmddata = IAX_META_TRUNK_MINI;
6384 else
6385 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
6386 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
6387 /* And the rest of the ast_iax2 header */
6388 fr->direction = DIRECTION_OUTGRESS;
6389 fr->retrans = -1;
6390 fr->transfer = 0;
6391 /* Any appropriate call will do */
6392 fr->data = fr->afdata;
6393 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
6394 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
6395 calls = tpeer->calls;
6396 #if 0
6397 if (option_debug)
6398 ast_log(LOG_DEBUG, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
6399 #endif
6400 /* Reset transmit trunk side data */
6401 tpeer->trunkdatalen = 0;
6402 tpeer->calls = 0;
6404 if (res < 0)
6405 return res;
6406 return calls;
6409 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
6411 /* Drop when trunk is about 5 seconds idle */
6412 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
6413 return 1;
6414 return 0;
6417 static int timing_read(int *id, int fd, short events, void *cbdata)
6419 char buf[1024];
6420 int res;
6421 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
6422 int processed = 0;
6423 int totalcalls = 0;
6424 #ifdef ZT_TIMERACK
6425 int x = 1;
6426 #endif
6427 struct timeval now;
6428 if (iaxtrunkdebug)
6429 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA);
6430 gettimeofday(&now, NULL);
6431 if (events & AST_IO_PRI) {
6432 #ifdef ZT_TIMERACK
6433 /* Great, this is a timing interface, just call the ioctl */
6434 if (ioctl(fd, ZT_TIMERACK, &x)) {
6435 ast_log(LOG_WARNING, "Unable to acknowledge zap timer. IAX trunking will fail!\n");
6436 usleep(1);
6437 return -1;
6439 #endif
6440 } else {
6441 /* Read and ignore from the pseudo channel for timing */
6442 res = read(fd, buf, sizeof(buf));
6443 if (res < 1) {
6444 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
6445 return 1;
6448 /* For each peer that supports trunking... */
6449 ast_mutex_lock(&tpeerlock);
6450 tpeer = tpeers;
6451 while(tpeer) {
6452 processed++;
6453 res = 0;
6454 ast_mutex_lock(&tpeer->lock);
6455 /* We can drop a single tpeer per pass. That makes all this logic
6456 substantially easier */
6457 if (!drop && iax2_trunk_expired(tpeer, &now)) {
6458 /* Take it out of the list, but don't free it yet, because it
6459 could be in use */
6460 if (prev)
6461 prev->next = tpeer->next;
6462 else
6463 tpeers = tpeer->next;
6464 drop = tpeer;
6465 } else {
6466 res = send_trunk(tpeer, &now);
6467 if (iaxtrunkdebug)
6468 ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
6470 totalcalls += res;
6471 res = 0;
6472 ast_mutex_unlock(&tpeer->lock);
6473 prev = tpeer;
6474 tpeer = tpeer->next;
6476 ast_mutex_unlock(&tpeerlock);
6477 if (drop) {
6478 ast_mutex_lock(&drop->lock);
6479 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6480 because by the time they could get tpeerlock, we've already grabbed it */
6481 if (option_debug)
6482 ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
6483 if (drop->trunkdata) {
6484 free(drop->trunkdata);
6485 drop->trunkdata = NULL;
6487 ast_mutex_unlock(&drop->lock);
6488 ast_mutex_destroy(&drop->lock);
6489 free(drop);
6492 if (iaxtrunkdebug)
6493 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
6494 iaxtrunkdebug =0;
6495 return 1;
6498 struct dpreq_data {
6499 int callno;
6500 char context[AST_MAX_EXTENSION];
6501 char callednum[AST_MAX_EXTENSION];
6502 char *callerid;
6505 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
6507 unsigned short dpstatus = 0;
6508 struct iax_ie_data ied1;
6509 int mm;
6511 memset(&ied1, 0, sizeof(ied1));
6512 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
6513 /* Must be started */
6514 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
6515 dpstatus = IAX_DPSTATUS_EXISTS;
6516 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
6517 dpstatus = IAX_DPSTATUS_CANEXIST;
6518 } else {
6519 dpstatus = IAX_DPSTATUS_NONEXISTENT;
6521 if (ast_ignore_pattern(context, callednum))
6522 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
6523 if (mm)
6524 dpstatus |= IAX_DPSTATUS_MATCHMORE;
6525 if (!skiplock)
6526 ast_mutex_lock(&iaxsl[callno]);
6527 if (iaxs[callno]) {
6528 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
6529 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
6530 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
6531 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
6533 if (!skiplock)
6534 ast_mutex_unlock(&iaxsl[callno]);
6537 static void *dp_lookup_thread(void *data)
6539 /* Look up for dpreq */
6540 struct dpreq_data *dpr = data;
6541 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
6542 if (dpr->callerid)
6543 free(dpr->callerid);
6544 free(dpr);
6545 return NULL;
6548 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
6550 pthread_t newthread;
6551 struct dpreq_data *dpr;
6552 pthread_attr_t attr;
6554 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
6555 return;
6557 pthread_attr_init(&attr);
6558 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6560 dpr->callno = callno;
6561 ast_copy_string(dpr->context, context, sizeof(dpr->context));
6562 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
6563 if (callerid)
6564 dpr->callerid = ast_strdup(callerid);
6565 if (ast_pthread_create(&newthread, &attr, dp_lookup_thread, dpr)) {
6566 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
6569 pthread_attr_destroy(&attr);
6572 struct iax_dual {
6573 struct ast_channel *chan1;
6574 struct ast_channel *chan2;
6577 static void *iax_park_thread(void *stuff)
6579 struct ast_channel *chan1, *chan2;
6580 struct iax_dual *d;
6581 struct ast_frame *f;
6582 int ext;
6583 int res;
6584 d = stuff;
6585 chan1 = d->chan1;
6586 chan2 = d->chan2;
6587 free(d);
6588 f = ast_read(chan1);
6589 if (f)
6590 ast_frfree(f);
6591 res = ast_park_call(chan1, chan2, 0, &ext);
6592 ast_hangup(chan2);
6593 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
6594 return NULL;
6597 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
6599 struct iax_dual *d;
6600 struct ast_channel *chan1m, *chan2m;
6601 pthread_t th;
6602 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
6603 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
6604 if (chan2m && chan1m) {
6605 /* Make formats okay */
6606 chan1m->readformat = chan1->readformat;
6607 chan1m->writeformat = chan1->writeformat;
6608 ast_channel_masquerade(chan1m, chan1);
6609 /* Setup the extensions and such */
6610 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
6611 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
6612 chan1m->priority = chan1->priority;
6614 /* We make a clone of the peer channel too, so we can play
6615 back the announcement */
6616 /* Make formats okay */
6617 chan2m->readformat = chan2->readformat;
6618 chan2m->writeformat = chan2->writeformat;
6619 ast_channel_masquerade(chan2m, chan2);
6620 /* Setup the extensions and such */
6621 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
6622 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
6623 chan2m->priority = chan2->priority;
6624 if (ast_do_masquerade(chan2m)) {
6625 ast_log(LOG_WARNING, "Masquerade failed :(\n");
6626 ast_hangup(chan2m);
6627 return -1;
6629 } else {
6630 if (chan1m)
6631 ast_hangup(chan1m);
6632 if (chan2m)
6633 ast_hangup(chan2m);
6634 return -1;
6636 if ((d = ast_calloc(1, sizeof(*d)))) {
6637 pthread_attr_t attr;
6639 pthread_attr_init(&attr);
6640 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6642 d->chan1 = chan1m;
6643 d->chan2 = chan2m;
6644 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
6645 pthread_attr_destroy(&attr);
6646 return 0;
6648 pthread_attr_destroy(&attr);
6649 free(d);
6651 return -1;
6655 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
6657 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
6659 unsigned int ourver;
6660 char rsi[80];
6661 snprintf(rsi, sizeof(rsi), "si-%s", si);
6662 if (iax_provision_version(&ourver, rsi, 1))
6663 return 0;
6664 if (option_debug)
6665 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
6666 if (ourver != ver)
6667 iax2_provision(sin, sockfd, NULL, rsi, 1);
6668 return 0;
6671 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
6673 jb_info stats;
6674 jb_getinfo(pvt->jb, &stats);
6676 memset(iep, 0, sizeof(*iep));
6678 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
6679 if(stats.frames_in == 0) stats.frames_in = 1;
6680 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
6681 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
6682 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
6683 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
6684 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
6687 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
6689 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
6690 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
6691 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
6692 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
6693 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
6694 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
6695 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
6698 static int socket_process(struct iax2_thread *thread);
6701 * \brief Handle any deferred full frames for this thread
6703 static void handle_deferred_full_frames(struct iax2_thread *thread)
6705 struct iax2_pkt_buf *pkt_buf;
6707 ast_mutex_lock(&thread->lock);
6709 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
6710 ast_mutex_unlock(&thread->lock);
6712 thread->buf = pkt_buf->buf;
6713 thread->buf_len = pkt_buf->len;
6714 thread->buf_size = pkt_buf->len + 1;
6716 socket_process(thread);
6718 thread->buf = NULL;
6719 ast_free(pkt_buf);
6721 ast_mutex_lock(&thread->lock);
6724 ast_mutex_unlock(&thread->lock);
6728 * \brief Queue the last read full frame for processing by a certain thread
6730 * If there are already any full frames queued, they are sorted
6731 * by sequence number.
6733 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
6735 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
6736 struct ast_iax2_full_hdr *fh, *cur_fh;
6738 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
6739 return;
6741 pkt_buf->len = from_here->buf_len;
6742 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
6744 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
6745 ast_mutex_lock(&to_here->lock);
6746 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
6747 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
6748 if (fh->oseqno < cur_fh->oseqno) {
6749 AST_LIST_INSERT_BEFORE_CURRENT(&to_here->full_frames, pkt_buf, entry);
6750 break;
6753 AST_LIST_TRAVERSE_SAFE_END
6755 if (!cur_pkt_buf)
6756 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
6758 ast_mutex_unlock(&to_here->lock);
6761 static int socket_read(int *id, int fd, short events, void *cbdata)
6763 struct iax2_thread *thread;
6764 socklen_t len;
6765 time_t t;
6766 static time_t last_errtime = 0;
6767 struct ast_iax2_full_hdr *fh;
6769 if (!(thread = find_idle_thread())) {
6770 time(&t);
6771 if (t != last_errtime && option_debug)
6772 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
6773 last_errtime = t;
6774 usleep(1);
6775 return 1;
6778 len = sizeof(thread->iosin);
6779 thread->iofd = fd;
6780 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
6781 thread->buf_size = sizeof(thread->readbuf);
6782 thread->buf = thread->readbuf;
6783 if (thread->buf_len < 0) {
6784 if (errno != ECONNREFUSED && errno != EAGAIN)
6785 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
6786 handle_error();
6787 thread->iostate = IAX_IOSTATE_IDLE;
6788 signal_condition(&thread->lock, &thread->cond);
6789 return 1;
6791 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
6792 thread->iostate = IAX_IOSTATE_IDLE;
6793 signal_condition(&thread->lock, &thread->cond);
6794 return 1;
6797 /* Determine if this frame is a full frame; if so, and any thread is currently
6798 processing a full frame for the same callno from this peer, then drop this
6799 frame (and the peer will retransmit it) */
6800 fh = (struct ast_iax2_full_hdr *) thread->buf;
6801 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6802 struct iax2_thread *cur = NULL;
6803 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
6805 AST_LIST_LOCK(&active_list);
6806 AST_LIST_TRAVERSE(&active_list, cur, list) {
6807 if ((cur->ffinfo.callno == callno) &&
6808 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
6809 break;
6811 if (cur) {
6812 /* we found another thread processing a full frame for this call,
6813 so queue it up for processing later. */
6814 defer_full_frame(thread, cur);
6815 AST_LIST_UNLOCK(&active_list);
6816 thread->iostate = IAX_IOSTATE_IDLE;
6817 signal_condition(&thread->lock, &thread->cond);
6818 return 1;
6819 } else {
6820 /* this thread is going to process this frame, so mark it */
6821 thread->ffinfo.callno = callno;
6822 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
6823 thread->ffinfo.type = fh->type;
6824 thread->ffinfo.csub = fh->csub;
6826 AST_LIST_UNLOCK(&active_list);
6829 /* Mark as ready and send on its way */
6830 thread->iostate = IAX_IOSTATE_READY;
6831 #ifdef DEBUG_SCHED_MULTITHREAD
6832 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
6833 #endif
6834 signal_condition(&thread->lock, &thread->cond);
6836 return 1;
6839 static int socket_process(struct iax2_thread *thread)
6841 struct sockaddr_in sin;
6842 int res;
6843 int updatehistory=1;
6844 int new = NEW_PREVENT;
6845 void *ptr;
6846 int dcallno = 0;
6847 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
6848 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
6849 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
6850 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
6851 struct ast_iax2_meta_trunk_hdr *mth;
6852 struct ast_iax2_meta_trunk_entry *mte;
6853 struct ast_iax2_meta_trunk_mini *mtm;
6854 struct iax_frame *fr;
6855 struct iax_frame *cur;
6856 struct ast_frame f = { 0, };
6857 struct ast_channel *c;
6858 struct iax2_dpcache *dp;
6859 struct iax2_peer *peer;
6860 struct iax2_trunk_peer *tpeer;
6861 struct timeval rxtrunktime;
6862 struct iax_ies ies;
6863 struct iax_ie_data ied0, ied1;
6864 int format;
6865 int fd;
6866 int exists;
6867 int minivid = 0;
6868 unsigned int ts;
6869 char empty[32]=""; /* Safety measure */
6870 struct iax_frame *duped_fr;
6871 char host_pref_buf[128];
6872 char caller_pref_buf[128];
6873 struct ast_codec_pref pref;
6874 char *using_prefs = "mine";
6876 /* allocate an iax_frame with 4096 bytes of data buffer */
6877 fr = alloca(sizeof(*fr) + 4096);
6878 fr->callno = 0;
6879 fr->afdatalen = 4096; /* From alloca() above */
6881 /* Copy frequently used parameters to the stack */
6882 res = thread->buf_len;
6883 fd = thread->iofd;
6884 memcpy(&sin, &thread->iosin, sizeof(sin));
6886 if (res < sizeof(*mh)) {
6887 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*mh));
6888 return 1;
6890 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
6891 if (res < sizeof(*vh)) {
6892 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6893 return 1;
6896 /* This is a video frame, get call number */
6897 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
6898 minivid = 1;
6899 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
6900 unsigned char metatype;
6902 if (res < sizeof(*meta)) {
6903 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6904 return 1;
6907 /* This is a meta header */
6908 switch(meta->metacmd) {
6909 case IAX_META_TRUNK:
6910 if (res < (sizeof(*meta) + sizeof(*mth))) {
6911 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %zd min)\n", res,
6912 sizeof(*meta) + sizeof(*mth));
6913 return 1;
6915 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
6916 ts = ntohl(mth->ts);
6917 metatype = meta->cmddata;
6918 res -= (sizeof(*meta) + sizeof(*mth));
6919 ptr = mth->data;
6920 tpeer = find_tpeer(&sin, fd);
6921 if (!tpeer) {
6922 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6923 return 1;
6925 tpeer->trunkact = ast_tvnow();
6926 if (!ts || ast_tvzero(tpeer->rxtrunktime))
6927 tpeer->rxtrunktime = tpeer->trunkact;
6928 rxtrunktime = tpeer->rxtrunktime;
6929 ast_mutex_unlock(&tpeer->lock);
6930 while(res >= sizeof(*mte)) {
6931 /* Process channels */
6932 unsigned short callno, trunked_ts, len;
6934 if (metatype == IAX_META_TRUNK_MINI) {
6935 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6936 ptr += sizeof(*mtm);
6937 res -= sizeof(*mtm);
6938 len = ntohs(mtm->len);
6939 callno = ntohs(mtm->mini.callno);
6940 trunked_ts = ntohs(mtm->mini.ts);
6941 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
6942 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
6943 ptr += sizeof(*mte);
6944 res -= sizeof(*mte);
6945 len = ntohs(mte->len);
6946 callno = ntohs(mte->callno);
6947 trunked_ts = 0;
6948 } else {
6949 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6950 break;
6952 /* Stop if we don't have enough data */
6953 if (len > res)
6954 break;
6955 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd, 0);
6956 if (fr->callno) {
6957 /* If it's a valid call, deliver the contents. If not, we
6958 drop it, since we don't have a scallno to use for an INVAL */
6959 /* Process as a mini frame */
6960 memset(&f, 0, sizeof(f));
6961 f.frametype = AST_FRAME_VOICE;
6962 if (iaxs[fr->callno]) {
6963 if (iaxs[fr->callno]->voiceformat > 0) {
6964 f.subclass = iaxs[fr->callno]->voiceformat;
6965 f.datalen = len;
6966 if (f.datalen >= 0) {
6967 if (f.datalen)
6968 f.data = ptr;
6969 if(trunked_ts) {
6970 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
6971 } else
6972 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
6973 /* Don't pass any packets until we're started */
6974 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
6975 /* Common things */
6976 f.src = "IAX2";
6977 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
6978 f.samples = ast_codec_get_samples(&f);
6979 iax_frame_wrap(fr, &f);
6980 duped_fr = iaxfrdup2(fr);
6981 if (duped_fr) {
6982 schedule_delivery(duped_fr, updatehistory, 1, &fr->ts);
6984 /* It is possible for the pvt structure to go away after we call schedule_delivery */
6985 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
6986 iaxs[fr->callno]->last = fr->ts;
6987 #if 1
6988 if (option_debug && iaxdebug)
6989 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
6990 #endif
6993 } else {
6994 ast_log(LOG_WARNING, "Datalen < 0?\n");
6996 } else {
6997 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n ");
6998 iax2_vnak(fr->callno);
7001 ast_mutex_unlock(&iaxsl[fr->callno]);
7003 ptr += len;
7004 res -= len;
7008 return 1;
7011 #ifdef DEBUG_SUPPORT
7012 if (iaxdebug && (res >= sizeof(*fh)))
7013 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
7014 #endif
7015 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7016 if (res < sizeof(*fh)) {
7017 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7018 return 1;
7021 /* Get the destination call number */
7022 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
7023 /* Retrieve the type and subclass */
7024 f.frametype = fh->type;
7025 if (f.frametype == AST_FRAME_VIDEO) {
7026 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
7027 } else {
7028 f.subclass = uncompress_subclass(fh->csub);
7030 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
7031 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
7032 (f.subclass == IAX_COMMAND_REGREL)))
7033 new = NEW_ALLOW;
7034 } else {
7035 /* Don't know anything about it yet */
7036 f.frametype = AST_FRAME_NULL;
7037 f.subclass = 0;
7040 if (!fr->callno)
7041 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, ntohs(mh->callno) & IAX_FLAG_FULL);
7043 if (fr->callno > 0)
7044 ast_mutex_lock(&iaxsl[fr->callno]);
7046 if (!fr->callno || !iaxs[fr->callno]) {
7047 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7048 frame, reply with an inval */
7049 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7050 /* We can only raw hangup control frames */
7051 if (((f.subclass != IAX_COMMAND_INVAL) &&
7052 (f.subclass != IAX_COMMAND_TXCNT) &&
7053 (f.subclass != IAX_COMMAND_TXACC) &&
7054 (f.subclass != IAX_COMMAND_FWDOWNL))||
7055 (f.frametype != AST_FRAME_IAX))
7056 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
7057 fd);
7059 if (fr->callno > 0)
7060 ast_mutex_unlock(&iaxsl[fr->callno]);
7061 return 1;
7063 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
7064 if (decrypt_frame(fr->callno, fh, &f, &res)) {
7065 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
7066 ast_mutex_unlock(&iaxsl[fr->callno]);
7067 return 1;
7069 #ifdef DEBUG_SUPPORT
7070 else if (iaxdebug)
7071 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
7072 #endif
7075 /* count this frame */
7076 iaxs[fr->callno]->frames_received++;
7078 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
7079 f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
7080 f.subclass != IAX_COMMAND_TXACC) /* for attended transfer */
7081 iaxs[fr->callno]->peercallno = (unsigned short)(ntohs(mh->callno) & ~IAX_FLAG_FULL);
7082 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7083 if (option_debug && iaxdebug)
7084 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
7085 /* Check if it's out of order (and not an ACK or INVAL) */
7086 fr->oseqno = fh->oseqno;
7087 fr->iseqno = fh->iseqno;
7088 fr->ts = ntohl(fh->ts);
7089 #ifdef IAXTESTS
7090 if (test_resync) {
7091 if (option_debug)
7092 ast_log(LOG_DEBUG, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
7093 fr->ts += test_resync;
7095 #endif /* IAXTESTS */
7096 #if 0
7097 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
7098 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
7099 (f.subclass == IAX_COMMAND_NEW ||
7100 f.subclass == IAX_COMMAND_AUTHREQ ||
7101 f.subclass == IAX_COMMAND_ACCEPT ||
7102 f.subclass == IAX_COMMAND_REJECT)) ) )
7103 #endif
7104 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
7105 updatehistory = 0;
7106 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
7107 (iaxs[fr->callno]->iseqno ||
7108 ((f.subclass != IAX_COMMAND_TXCNT) &&
7109 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7110 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7111 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7112 (f.subclass != IAX_COMMAND_TXACC)) ||
7113 (f.frametype != AST_FRAME_IAX))) {
7114 if (
7115 ((f.subclass != IAX_COMMAND_ACK) &&
7116 (f.subclass != IAX_COMMAND_INVAL) &&
7117 (f.subclass != IAX_COMMAND_TXCNT) &&
7118 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7119 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7120 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7121 (f.subclass != IAX_COMMAND_TXACC) &&
7122 (f.subclass != IAX_COMMAND_VNAK)) ||
7123 (f.frametype != AST_FRAME_IAX)) {
7124 /* If it's not an ACK packet, it's out of order. */
7125 if (option_debug)
7126 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7127 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
7128 /* Check to see if we need to request retransmission,
7129 * and take sequence number wraparound into account */
7130 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
7131 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7132 if ((f.frametype != AST_FRAME_IAX) ||
7133 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
7134 if (option_debug)
7135 ast_log(LOG_DEBUG, "Acking anyway\n");
7136 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7137 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7138 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7140 } else {
7141 /* Send a VNAK requesting retransmission */
7142 iax2_vnak(fr->callno);
7144 ast_mutex_unlock(&iaxsl[fr->callno]);
7145 return 1;
7147 } else {
7148 /* Increment unless it's an ACK or VNAK */
7149 if (((f.subclass != IAX_COMMAND_ACK) &&
7150 (f.subclass != IAX_COMMAND_INVAL) &&
7151 (f.subclass != IAX_COMMAND_TXCNT) &&
7152 (f.subclass != IAX_COMMAND_TXACC) &&
7153 (f.subclass != IAX_COMMAND_VNAK)) ||
7154 (f.frametype != AST_FRAME_IAX))
7155 iaxs[fr->callno]->iseqno++;
7157 /* A full frame */
7158 if (res < sizeof(*fh)) {
7159 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*fh));
7160 ast_mutex_unlock(&iaxsl[fr->callno]);
7161 return 1;
7163 /* Ensure text frames are NULL-terminated */
7164 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
7165 if (res < thread->buf_size)
7166 thread->buf[res++] = '\0';
7167 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7168 thread->buf[res - 1] = '\0';
7170 f.datalen = res - sizeof(*fh);
7172 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7173 from the real peer, not the transfer peer */
7174 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7175 ((f.subclass != IAX_COMMAND_INVAL) ||
7176 (f.frametype != AST_FRAME_IAX))) {
7177 unsigned char x;
7178 int call_to_destroy;
7179 /* XXX This code is not very efficient. Surely there is a better way which still
7180 properly handles boundary conditions? XXX */
7181 /* First we have to qualify that the ACKed value is within our window */
7182 for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
7183 if (fr->iseqno == x)
7184 break;
7185 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
7186 /* The acknowledgement is within our window. Time to acknowledge everything
7187 that it says to */
7188 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
7189 /* Ack the packet with the given timestamp */
7190 if (option_debug && iaxdebug)
7191 ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
7192 call_to_destroy = 0;
7193 AST_LIST_LOCK(&iaxq.queue);
7194 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7195 /* If it's our call, and our timestamp, mark -1 retries */
7196 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
7197 cur->retries = -1;
7198 /* Destroy call if this is the end */
7199 if (cur->final)
7200 call_to_destroy = fr->callno;
7203 AST_LIST_UNLOCK(&iaxq.queue);
7204 if (call_to_destroy) {
7205 if (iaxdebug && option_debug)
7206 ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", call_to_destroy);
7207 ast_mutex_lock(&iaxsl[call_to_destroy]);
7208 iax2_destroy(call_to_destroy);
7209 ast_mutex_unlock(&iaxsl[call_to_destroy]);
7212 /* Note how much we've received acknowledgement for */
7213 if (iaxs[fr->callno])
7214 iaxs[fr->callno]->rseqno = fr->iseqno;
7215 else {
7216 /* Stop processing now */
7217 ast_mutex_unlock(&iaxsl[fr->callno]);
7218 return 1;
7220 } else if (option_debug)
7221 ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
7223 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7224 ((f.frametype != AST_FRAME_IAX) ||
7225 ((f.subclass != IAX_COMMAND_TXACC) &&
7226 (f.subclass != IAX_COMMAND_TXCNT)))) {
7227 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7228 ast_mutex_unlock(&iaxsl[fr->callno]);
7229 return 1;
7232 if (f.datalen) {
7233 if (f.frametype == AST_FRAME_IAX) {
7234 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
7235 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
7236 ast_mutex_unlock(&iaxsl[fr->callno]);
7237 return 1;
7239 f.data = NULL;
7240 f.datalen = 0;
7241 } else
7242 f.data = thread->buf + sizeof(*fh);
7243 } else {
7244 if (f.frametype == AST_FRAME_IAX)
7245 f.data = NULL;
7246 else
7247 f.data = empty;
7248 memset(&ies, 0, sizeof(ies));
7251 /* when we receive the first full frame for a new incoming channel,
7252 it is safe to start the PBX on the channel because we have now
7253 completed a 3-way handshake with the peer */
7254 if ((f.frametype == AST_FRAME_VOICE) ||
7255 (f.frametype == AST_FRAME_VIDEO) ||
7256 (f.frametype == AST_FRAME_IAX)) {
7257 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
7258 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7259 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
7260 ast_mutex_unlock(&iaxsl[fr->callno]);
7261 return 1;
7266 if (f.frametype == AST_FRAME_VOICE) {
7267 if (f.subclass != iaxs[fr->callno]->voiceformat) {
7268 iaxs[fr->callno]->voiceformat = f.subclass;
7269 if (option_debug)
7270 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
7271 if (iaxs[fr->callno]->owner) {
7272 int orignative;
7273 retryowner:
7274 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7275 ast_mutex_unlock(&iaxsl[fr->callno]);
7276 usleep(1);
7277 ast_mutex_lock(&iaxsl[fr->callno]);
7278 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
7280 if (iaxs[fr->callno]) {
7281 if (iaxs[fr->callno]->owner) {
7282 orignative = iaxs[fr->callno]->owner->nativeformats;
7283 iaxs[fr->callno]->owner->nativeformats = f.subclass;
7284 if (iaxs[fr->callno]->owner->readformat)
7285 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7286 iaxs[fr->callno]->owner->nativeformats = orignative;
7287 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7289 } else {
7290 if (option_debug)
7291 ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
7292 ast_mutex_unlock(&iaxsl[fr->callno]);
7293 return 1;
7298 if (f.frametype == AST_FRAME_VIDEO) {
7299 if (f.subclass != iaxs[fr->callno]->videoformat) {
7300 if (option_debug)
7301 ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
7302 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
7305 if (f.frametype == AST_FRAME_IAX) {
7306 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
7307 /* Handle the IAX pseudo frame itself */
7308 if (option_debug && iaxdebug)
7309 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
7311 /* Update last ts unless the frame's timestamp originated with us. */
7312 if (iaxs[fr->callno]->last < fr->ts &&
7313 f.subclass != IAX_COMMAND_ACK &&
7314 f.subclass != IAX_COMMAND_PONG &&
7315 f.subclass != IAX_COMMAND_LAGRP) {
7316 iaxs[fr->callno]->last = fr->ts;
7317 if (option_debug && iaxdebug)
7318 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7321 switch(f.subclass) {
7322 case IAX_COMMAND_ACK:
7323 /* Do nothing */
7324 break;
7325 case IAX_COMMAND_QUELCH:
7326 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7327 /* Generate Manager Hold event, if necessary*/
7328 if (iaxs[fr->callno]->owner) {
7329 manager_event(EVENT_FLAG_CALL, "Hold",
7330 "Channel: %s\r\n"
7331 "Uniqueid: %s\r\n",
7332 iaxs[fr->callno]->owner->name,
7333 iaxs[fr->callno]->owner->uniqueid);
7336 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
7337 if (ies.musiconhold) {
7338 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7339 const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
7340 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
7341 S_OR(mohsuggest, NULL),
7342 !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
7343 if (!iaxs[fr->callno]) {
7344 ast_mutex_unlock(&iaxsl[fr->callno]);
7345 return 1;
7350 break;
7351 case IAX_COMMAND_UNQUELCH:
7352 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7353 /* Generate Manager Unhold event, if necessary*/
7354 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
7355 manager_event(EVENT_FLAG_CALL, "Unhold",
7356 "Channel: %s\r\n"
7357 "Uniqueid: %s\r\n",
7358 iaxs[fr->callno]->owner->name,
7359 iaxs[fr->callno]->owner->uniqueid);
7362 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
7363 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7364 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
7365 if (!iaxs[fr->callno]) {
7366 ast_mutex_unlock(&iaxsl[fr->callno]);
7367 return 1;
7371 break;
7372 case IAX_COMMAND_TXACC:
7373 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
7374 /* Ack the packet with the given timestamp */
7375 AST_LIST_LOCK(&iaxq.queue);
7376 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7377 /* Cancel any outstanding txcnt's */
7378 if ((fr->callno == cur->callno) && (cur->transfer))
7379 cur->retries = -1;
7381 AST_LIST_UNLOCK(&iaxq.queue);
7382 memset(&ied1, 0, sizeof(ied1));
7383 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
7384 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
7385 iaxs[fr->callno]->transferring = TRANSFER_READY;
7387 break;
7388 case IAX_COMMAND_NEW:
7389 /* Ignore if it's already up */
7390 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
7391 break;
7392 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
7393 ast_mutex_unlock(&iaxsl[fr->callno]);
7394 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
7395 ast_mutex_lock(&iaxsl[fr->callno]);
7396 if (!iaxs[fr->callno]) {
7397 ast_mutex_unlock(&iaxsl[fr->callno]);
7398 return 1;
7401 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7402 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
7403 int new_callno;
7404 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
7405 fr->callno = new_callno;
7407 /* For security, always ack immediately */
7408 if (delayreject)
7409 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7410 if (check_access(fr->callno, &sin, &ies)) {
7411 /* They're not allowed on */
7412 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7413 if (authdebug)
7414 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7415 break;
7417 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7418 const char *context, *exten, *cid_num;
7420 context = ast_strdupa(iaxs[fr->callno]->context);
7421 exten = ast_strdupa(iaxs[fr->callno]->exten);
7422 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
7424 /* This might re-enter the IAX code and need the lock */
7425 ast_mutex_unlock(&iaxsl[fr->callno]);
7426 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
7427 ast_mutex_lock(&iaxsl[fr->callno]);
7429 if (!iaxs[fr->callno]) {
7430 ast_mutex_unlock(&iaxsl[fr->callno]);
7431 return 1;
7433 } else
7434 exists = 0;
7435 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
7436 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7437 memset(&ied0, 0, sizeof(ied0));
7438 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7439 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7440 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7441 if (!iaxs[fr->callno]) {
7442 ast_mutex_unlock(&iaxsl[fr->callno]);
7443 return 1;
7445 if (authdebug)
7446 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7447 } else {
7448 /* Select an appropriate format */
7450 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7451 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7452 using_prefs = "reqonly";
7453 } else {
7454 using_prefs = "disabled";
7456 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7457 memset(&pref, 0, sizeof(pref));
7458 strcpy(caller_pref_buf, "disabled");
7459 strcpy(host_pref_buf, "disabled");
7460 } else {
7461 using_prefs = "mine";
7462 /* If the information elements are in here... use them */
7463 if (ies.codec_prefs)
7464 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7465 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7466 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7467 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7468 pref = iaxs[fr->callno]->rprefs;
7469 using_prefs = "caller";
7470 } else {
7471 pref = iaxs[fr->callno]->prefs;
7473 } else
7474 pref = iaxs[fr->callno]->prefs;
7476 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7477 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7478 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7480 if (!format) {
7481 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7482 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7483 if (!format) {
7484 memset(&ied0, 0, sizeof(ied0));
7485 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7486 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7487 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7488 if (!iaxs[fr->callno]) {
7489 ast_mutex_unlock(&iaxsl[fr->callno]);
7490 return 1;
7492 if (authdebug) {
7493 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7494 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7495 else
7496 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7498 } else {
7499 /* Pick one... */
7500 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7501 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7502 format = 0;
7503 } else {
7504 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7505 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7506 memset(&pref, 0, sizeof(pref));
7507 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7508 strcpy(caller_pref_buf,"disabled");
7509 strcpy(host_pref_buf,"disabled");
7510 } else {
7511 using_prefs = "mine";
7512 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7513 /* Do the opposite of what we tried above. */
7514 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7515 pref = iaxs[fr->callno]->prefs;
7516 } else {
7517 pref = iaxs[fr->callno]->rprefs;
7518 using_prefs = "caller";
7520 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7522 } else /* if no codec_prefs IE do it the old way */
7523 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7527 if (!format) {
7528 memset(&ied0, 0, sizeof(ied0));
7529 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7530 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7531 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7532 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7533 if (!iaxs[fr->callno]) {
7534 ast_mutex_unlock(&iaxsl[fr->callno]);
7535 return 1;
7537 if (authdebug)
7538 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7539 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7540 break;
7544 if (format) {
7545 /* No authentication required, let them in */
7546 memset(&ied1, 0, sizeof(ied1));
7547 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7548 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7549 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7550 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7551 if (option_verbose > 2)
7552 ast_verbose(VERBOSE_PREFIX_3 "Accepting UNAUTHENTICATED call from %s:\n"
7553 "%srequested format = %s,\n"
7554 "%srequested prefs = %s,\n"
7555 "%sactual format = %s,\n"
7556 "%shost prefs = %s,\n"
7557 "%spriority = %s\n",
7558 ast_inet_ntoa(sin.sin_addr),
7559 VERBOSE_PREFIX_4,
7560 ast_getformatname(iaxs[fr->callno]->peerformat),
7561 VERBOSE_PREFIX_4,
7562 caller_pref_buf,
7563 VERBOSE_PREFIX_4,
7564 ast_getformatname(format),
7565 VERBOSE_PREFIX_4,
7566 host_pref_buf,
7567 VERBOSE_PREFIX_4,
7568 using_prefs);
7570 iaxs[fr->callno]->chosenformat = format;
7571 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7572 } else {
7573 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7574 /* If this is a TBD call, we're ready but now what... */
7575 if (option_verbose > 2)
7576 ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
7580 break;
7582 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
7583 merge_encryption(iaxs[fr->callno],ies.encmethods);
7584 else
7585 iaxs[fr->callno]->encmethods = 0;
7586 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
7587 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
7588 if (!iaxs[fr->callno]) {
7589 ast_mutex_unlock(&iaxsl[fr->callno]);
7590 return 1;
7592 break;
7593 case IAX_COMMAND_DPREQ:
7594 /* Request status in the dialplan */
7595 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
7596 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
7597 if (iaxcompat) {
7598 /* Spawn a thread for the lookup */
7599 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
7600 } else {
7601 /* Just look it up */
7602 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
7605 break;
7606 case IAX_COMMAND_HANGUP:
7607 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7608 if (option_debug)
7609 ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr->callno);
7610 /* Set hangup cause according to remote */
7611 if (ies.causecode && iaxs[fr->callno]->owner)
7612 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7613 /* Send ack immediately, before we destroy */
7614 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7615 iax2_destroy(fr->callno);
7616 break;
7617 case IAX_COMMAND_REJECT:
7618 /* Set hangup cause according to remote */
7619 if (ies.causecode && iaxs[fr->callno]->owner)
7620 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7622 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7623 if (iaxs[fr->callno]->owner && authdebug)
7624 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
7625 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
7626 ies.cause ? ies.cause : "<Unknown>");
7627 if (option_debug)
7628 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
7629 fr->callno);
7631 /* Send ack immediately, before we destroy */
7632 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
7633 fr->ts, NULL, 0, fr->iseqno);
7634 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
7635 iaxs[fr->callno]->error = EPERM;
7636 iax2_destroy(fr->callno);
7637 break;
7638 case IAX_COMMAND_TRANSFER:
7640 struct ast_channel *bridged_chan;
7642 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
7643 /* Set BLINDTRANSFER channel variables */
7645 ast_mutex_unlock(&iaxsl[fr->callno]);
7646 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
7647 ast_mutex_lock(&iaxsl[fr->callno]);
7648 if (!iaxs[fr->callno]) {
7649 ast_mutex_unlock(&iaxsl[fr->callno]);
7650 return 1;
7653 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
7654 if (!strcmp(ies.called_number, ast_parking_ext())) {
7655 if (iax_park(bridged_chan, iaxs[fr->callno]->owner)) {
7656 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
7657 } else {
7658 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
7660 } else {
7661 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
7662 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
7663 ies.called_number, iaxs[fr->callno]->context);
7664 else
7665 ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
7666 ies.called_number, iaxs[fr->callno]->context);
7668 } else
7669 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
7671 break;
7673 case IAX_COMMAND_ACCEPT:
7674 /* Ignore if call is already up or needs authentication or is a TBD */
7675 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
7676 break;
7677 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7678 /* Send ack immediately, before we destroy */
7679 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7680 iax2_destroy(fr->callno);
7681 break;
7683 if (ies.format) {
7684 iaxs[fr->callno]->peerformat = ies.format;
7685 } else {
7686 if (iaxs[fr->callno]->owner)
7687 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
7688 else
7689 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
7691 if (option_verbose > 2)
7692 ast_verbose(VERBOSE_PREFIX_3 "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
7693 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
7694 memset(&ied0, 0, sizeof(ied0));
7695 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7696 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7697 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7698 if (!iaxs[fr->callno]) {
7699 ast_mutex_unlock(&iaxsl[fr->callno]);
7700 return 1;
7702 if (authdebug)
7703 ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7704 } else {
7705 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7706 if (iaxs[fr->callno]->owner) {
7707 /* Switch us to use a compatible format */
7708 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
7709 if (option_verbose > 2)
7710 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
7711 retryowner2:
7712 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7713 ast_mutex_unlock(&iaxsl[fr->callno]);
7714 usleep(1);
7715 ast_mutex_lock(&iaxsl[fr->callno]);
7716 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
7719 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
7720 /* Setup read/write formats properly. */
7721 if (iaxs[fr->callno]->owner->writeformat)
7722 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
7723 if (iaxs[fr->callno]->owner->readformat)
7724 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7725 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7729 if (iaxs[fr->callno]) {
7730 ast_mutex_lock(&dpcache_lock);
7731 dp = iaxs[fr->callno]->dpentries;
7732 while(dp) {
7733 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
7734 iax2_dprequest(dp, fr->callno);
7736 dp = dp->peer;
7738 ast_mutex_unlock(&dpcache_lock);
7740 break;
7741 case IAX_COMMAND_POKE:
7742 /* Send back a pong packet with the original timestamp */
7743 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
7744 if (!iaxs[fr->callno]) {
7745 ast_mutex_unlock(&iaxsl[fr->callno]);
7746 return 1;
7748 break;
7749 case IAX_COMMAND_PING:
7751 struct iax_ie_data pingied;
7752 construct_rr(iaxs[fr->callno], &pingied);
7753 /* Send back a pong packet with the original timestamp */
7754 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
7756 break;
7757 case IAX_COMMAND_PONG:
7758 /* Calculate ping time */
7759 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
7760 /* save RR info */
7761 save_rr(fr, &ies);
7763 if (iaxs[fr->callno]->peerpoke) {
7764 peer = iaxs[fr->callno]->peerpoke;
7765 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
7766 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
7767 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
7768 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7769 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7771 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
7772 if (iaxs[fr->callno]->pingtime > peer->maxms) {
7773 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
7774 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7775 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7778 peer->lastms = iaxs[fr->callno]->pingtime;
7779 if (peer->smoothing && (peer->lastms > -1))
7780 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
7781 else if (peer->smoothing && peer->lastms < 0)
7782 peer->historicms = (0 + peer->historicms) / 2;
7783 else
7784 peer->historicms = iaxs[fr->callno]->pingtime;
7786 /* Remove scheduled iax2_poke_noanswer */
7787 if (peer->pokeexpire > -1) {
7788 if (!ast_sched_del(sched, peer->pokeexpire)) {
7789 peer_unref(peer);
7790 peer->pokeexpire = -1;
7793 /* Schedule the next cycle */
7794 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
7795 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
7796 else
7797 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
7798 if (peer->pokeexpire == -1)
7799 peer_unref(peer);
7800 /* and finally send the ack */
7801 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7802 /* And wrap up the qualify call */
7803 iax2_destroy(fr->callno);
7804 peer->callno = 0;
7805 if (option_debug)
7806 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
7808 break;
7809 case IAX_COMMAND_LAGRQ:
7810 case IAX_COMMAND_LAGRP:
7811 f.src = "LAGRQ";
7812 f.mallocd = 0;
7813 f.offset = 0;
7814 f.samples = 0;
7815 iax_frame_wrap(fr, &f);
7816 if(f.subclass == IAX_COMMAND_LAGRQ) {
7817 /* Received a LAGRQ - echo back a LAGRP */
7818 fr->af.subclass = IAX_COMMAND_LAGRP;
7819 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
7820 } else {
7821 /* Received LAGRP in response to our LAGRQ */
7822 unsigned int ts;
7823 /* This is a reply we've been given, actually measure the difference */
7824 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
7825 iaxs[fr->callno]->lag = ts - fr->ts;
7826 if (option_debug && iaxdebug)
7827 ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
7828 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
7830 break;
7831 case IAX_COMMAND_AUTHREQ:
7832 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7833 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
7834 break;
7836 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
7837 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
7838 .subclass = AST_CONTROL_HANGUP,
7840 ast_log(LOG_WARNING,
7841 "I don't know how to authenticate %s to %s\n",
7842 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
7843 iax2_queue_frame(fr->callno, &hangup_fr);
7845 if (!iaxs[fr->callno]) {
7846 ast_mutex_unlock(&iaxsl[fr->callno]);
7847 return 1;
7849 break;
7850 case IAX_COMMAND_AUTHREP:
7851 /* For security, always ack immediately */
7852 if (delayreject)
7853 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7854 /* Ignore once we've started */
7855 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7856 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
7857 break;
7859 if (authenticate_verify(iaxs[fr->callno], &ies)) {
7860 if (authdebug)
7861 ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
7862 memset(&ied0, 0, sizeof(ied0));
7863 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7864 break;
7866 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7867 /* This might re-enter the IAX code and need the lock */
7868 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
7869 } else
7870 exists = 0;
7871 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7872 if (authdebug)
7873 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7874 memset(&ied0, 0, sizeof(ied0));
7875 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7876 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7877 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7878 if (!iaxs[fr->callno]) {
7879 ast_mutex_unlock(&iaxsl[fr->callno]);
7880 return 1;
7882 } else {
7883 /* Select an appropriate format */
7884 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7885 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7886 using_prefs = "reqonly";
7887 } else {
7888 using_prefs = "disabled";
7890 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7891 memset(&pref, 0, sizeof(pref));
7892 strcpy(caller_pref_buf, "disabled");
7893 strcpy(host_pref_buf, "disabled");
7894 } else {
7895 using_prefs = "mine";
7896 if (ies.codec_prefs)
7897 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7898 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7899 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7900 pref = iaxs[fr->callno]->rprefs;
7901 using_prefs = "caller";
7902 } else {
7903 pref = iaxs[fr->callno]->prefs;
7905 } else /* if no codec_prefs IE do it the old way */
7906 pref = iaxs[fr->callno]->prefs;
7908 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7909 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7910 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7912 if (!format) {
7913 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7914 if (option_debug)
7915 ast_log(LOG_DEBUG, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
7916 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7918 if (!format) {
7919 if (authdebug) {
7920 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7921 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7922 else
7923 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7925 memset(&ied0, 0, sizeof(ied0));
7926 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7927 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7928 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7929 if (!iaxs[fr->callno]) {
7930 ast_mutex_unlock(&iaxsl[fr->callno]);
7931 return 1;
7933 } else {
7934 /* Pick one... */
7935 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7936 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7937 format = 0;
7938 } else {
7939 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7940 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7941 memset(&pref, 0, sizeof(pref));
7942 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
7943 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7944 strcpy(caller_pref_buf,"disabled");
7945 strcpy(host_pref_buf,"disabled");
7946 } else {
7947 using_prefs = "mine";
7948 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7949 /* Do the opposite of what we tried above. */
7950 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7951 pref = iaxs[fr->callno]->prefs;
7952 } else {
7953 pref = iaxs[fr->callno]->rprefs;
7954 using_prefs = "caller";
7956 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7957 } else /* if no codec_prefs IE do it the old way */
7958 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7961 if (!format) {
7962 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7963 if (authdebug) {
7964 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7965 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7966 else
7967 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7969 memset(&ied0, 0, sizeof(ied0));
7970 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7971 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7972 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7973 if (!iaxs[fr->callno]) {
7974 ast_mutex_unlock(&iaxsl[fr->callno]);
7975 return 1;
7980 if (format) {
7981 /* Authentication received */
7982 memset(&ied1, 0, sizeof(ied1));
7983 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7984 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7985 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7986 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7987 if (option_verbose > 2)
7988 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s:\n"
7989 "%srequested format = %s,\n"
7990 "%srequested prefs = %s,\n"
7991 "%sactual format = %s,\n"
7992 "%shost prefs = %s,\n"
7993 "%spriority = %s\n",
7994 ast_inet_ntoa(sin.sin_addr),
7995 VERBOSE_PREFIX_4,
7996 ast_getformatname(iaxs[fr->callno]->peerformat),
7997 VERBOSE_PREFIX_4,
7998 caller_pref_buf,
7999 VERBOSE_PREFIX_4,
8000 ast_getformatname(format),
8001 VERBOSE_PREFIX_4,
8002 host_pref_buf,
8003 VERBOSE_PREFIX_4,
8004 using_prefs);
8006 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8007 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
8008 iax2_destroy(fr->callno);
8009 } else {
8010 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8011 /* If this is a TBD call, we're ready but now what... */
8012 if (option_verbose > 2)
8013 ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
8017 break;
8018 case IAX_COMMAND_DIAL:
8019 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
8020 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8021 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
8022 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
8023 if (authdebug)
8024 ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
8025 memset(&ied0, 0, sizeof(ied0));
8026 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
8027 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
8028 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8029 if (!iaxs[fr->callno]) {
8030 ast_mutex_unlock(&iaxsl[fr->callno]);
8031 return 1;
8033 } else {
8034 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8035 if (option_verbose > 2)
8036 ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
8037 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8038 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
8039 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
8040 iax2_destroy(fr->callno);
8043 break;
8044 case IAX_COMMAND_INVAL:
8045 iaxs[fr->callno]->error = ENOTCONN;
8046 if (option_debug)
8047 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
8048 iax2_destroy(fr->callno);
8049 if (option_debug)
8050 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
8051 break;
8052 case IAX_COMMAND_VNAK:
8053 if (option_debug)
8054 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
8055 /* Force retransmission */
8056 vnak_retransmit(fr->callno, fr->iseqno);
8057 break;
8058 case IAX_COMMAND_REGREQ:
8059 case IAX_COMMAND_REGREL:
8060 /* For security, always ack immediately */
8061 if (delayreject)
8062 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8063 if (register_verify(fr->callno, &sin, &ies)) {
8064 if (!iaxs[fr->callno]) {
8065 ast_mutex_unlock(&iaxsl[fr->callno]);
8066 return 1;
8068 /* Send delayed failure */
8069 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
8070 break;
8072 if (!iaxs[fr->callno]) {
8073 ast_mutex_unlock(&iaxsl[fr->callno]);
8074 return 1;
8076 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
8077 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
8078 if (f.subclass == IAX_COMMAND_REGREL)
8079 memset(&sin, 0, sizeof(sin));
8080 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
8081 ast_log(LOG_WARNING, "Registry error\n");
8082 if (!iaxs[fr->callno]) {
8083 ast_mutex_unlock(&iaxsl[fr->callno]);
8084 return 1;
8086 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
8087 ast_mutex_unlock(&iaxsl[fr->callno]);
8088 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
8089 ast_mutex_lock(&iaxsl[fr->callno]);
8090 if (!iaxs[fr->callno]) {
8091 ast_mutex_unlock(&iaxsl[fr->callno]);
8092 return 1;
8095 break;
8097 registry_authrequest(fr->callno);
8098 if (!iaxs[fr->callno]) {
8099 ast_mutex_unlock(&iaxsl[fr->callno]);
8100 return 1;
8102 break;
8103 case IAX_COMMAND_REGACK:
8104 if (iax2_ack_registry(&ies, &sin, fr->callno))
8105 ast_log(LOG_WARNING, "Registration failure\n");
8106 /* Send ack immediately, before we destroy */
8107 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8108 iax2_destroy(fr->callno);
8109 break;
8110 case IAX_COMMAND_REGREJ:
8111 if (iaxs[fr->callno]->reg) {
8112 if (authdebug) {
8113 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
8114 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
8116 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
8118 /* Send ack immediately, before we destroy */
8119 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8120 iax2_destroy(fr->callno);
8121 break;
8122 case IAX_COMMAND_REGAUTH:
8123 /* Authentication request */
8124 if (registry_rerequest(&ies, fr->callno, &sin)) {
8125 memset(&ied0, 0, sizeof(ied0));
8126 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
8127 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
8128 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8129 if (!iaxs[fr->callno]) {
8130 ast_mutex_unlock(&iaxsl[fr->callno]);
8131 return 1;
8134 break;
8135 case IAX_COMMAND_TXREJ:
8136 iaxs[fr->callno]->transferring = 0;
8137 if (option_verbose > 2)
8138 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8139 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
8140 if (iaxs[fr->callno]->bridgecallno) {
8141 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
8142 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
8143 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
8146 break;
8147 case IAX_COMMAND_TXREADY:
8148 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
8149 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
8150 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
8151 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
8152 else
8153 iaxs[fr->callno]->transferring = TRANSFER_READY;
8154 if (option_verbose > 2)
8155 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8156 if (iaxs[fr->callno]->bridgecallno) {
8157 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
8158 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
8159 /* They're both ready, now release them. */
8160 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
8161 if (option_verbose > 2)
8162 ast_verbose(VERBOSE_PREFIX_3 "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8163 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8165 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
8166 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
8168 memset(&ied0, 0, sizeof(ied0));
8169 memset(&ied1, 0, sizeof(ied1));
8170 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8171 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8172 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
8173 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
8174 } else {
8175 if (option_verbose > 2)
8176 ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8177 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8179 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
8180 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
8181 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
8182 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8184 /* Stop doing lag & ping requests */
8185 stop_stuff(fr->callno);
8186 stop_stuff(iaxs[fr->callno]->bridgecallno);
8188 memset(&ied0, 0, sizeof(ied0));
8189 memset(&ied1, 0, sizeof(ied1));
8190 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8191 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8192 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
8193 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
8199 break;
8200 case IAX_COMMAND_TXREQ:
8201 try_transfer(iaxs[fr->callno], &ies);
8202 break;
8203 case IAX_COMMAND_TXCNT:
8204 if (iaxs[fr->callno]->transferring)
8205 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
8206 break;
8207 case IAX_COMMAND_TXREL:
8208 /* Send ack immediately, rather than waiting until we've changed addresses */
8209 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8210 complete_transfer(fr->callno, &ies);
8211 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
8212 break;
8213 case IAX_COMMAND_TXMEDIA:
8214 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
8215 AST_LIST_LOCK(&iaxq.queue);
8216 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
8217 /* Cancel any outstanding frames and start anew */
8218 if ((fr->callno == cur->callno) && (cur->transfer)) {
8219 cur->retries = -1;
8222 AST_LIST_UNLOCK(&iaxq.queue);
8223 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8224 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
8226 break;
8227 case IAX_COMMAND_DPREP:
8228 complete_dpreply(iaxs[fr->callno], &ies);
8229 break;
8230 case IAX_COMMAND_UNSUPPORT:
8231 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
8232 break;
8233 case IAX_COMMAND_FWDOWNL:
8234 /* Firmware download */
8235 memset(&ied0, 0, sizeof(ied0));
8236 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
8237 if (res < 0)
8238 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8239 else if (res > 0)
8240 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8241 else
8242 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8243 if (!iaxs[fr->callno]) {
8244 ast_mutex_unlock(&iaxsl[fr->callno]);
8245 return 1;
8247 break;
8248 default:
8249 if (option_debug)
8250 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
8251 memset(&ied0, 0, sizeof(ied0));
8252 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
8253 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
8255 /* Don't actually pass these frames along */
8256 if ((f.subclass != IAX_COMMAND_ACK) &&
8257 (f.subclass != IAX_COMMAND_TXCNT) &&
8258 (f.subclass != IAX_COMMAND_TXACC) &&
8259 (f.subclass != IAX_COMMAND_INVAL) &&
8260 (f.subclass != IAX_COMMAND_VNAK)) {
8261 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8262 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8264 ast_mutex_unlock(&iaxsl[fr->callno]);
8265 return 1;
8267 /* Unless this is an ACK or INVAL frame, ack it */
8268 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8269 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8270 } else if (minivid) {
8271 f.frametype = AST_FRAME_VIDEO;
8272 if (iaxs[fr->callno]->videoformat > 0)
8273 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
8274 else {
8275 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n ");
8276 iax2_vnak(fr->callno);
8277 ast_mutex_unlock(&iaxsl[fr->callno]);
8278 return 1;
8280 f.datalen = res - sizeof(*vh);
8281 if (f.datalen)
8282 f.data = thread->buf + sizeof(*vh);
8283 else
8284 f.data = NULL;
8285 #ifdef IAXTESTS
8286 if (test_resync) {
8287 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
8288 } else
8289 #endif /* IAXTESTS */
8290 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
8291 } else {
8292 /* A mini frame */
8293 f.frametype = AST_FRAME_VOICE;
8294 if (iaxs[fr->callno]->voiceformat > 0)
8295 f.subclass = iaxs[fr->callno]->voiceformat;
8296 else {
8297 if (option_debug)
8298 ast_log(LOG_DEBUG, "Received mini frame before first full voice frame\n");
8299 iax2_vnak(fr->callno);
8300 ast_mutex_unlock(&iaxsl[fr->callno]);
8301 return 1;
8303 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
8304 if (f.datalen < 0) {
8305 ast_log(LOG_WARNING, "Datalen < 0?\n");
8306 ast_mutex_unlock(&iaxsl[fr->callno]);
8307 return 1;
8309 if (f.datalen)
8310 f.data = thread->buf + sizeof(*mh);
8311 else
8312 f.data = NULL;
8313 #ifdef IAXTESTS
8314 if (test_resync) {
8315 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
8316 } else
8317 #endif /* IAXTESTS */
8318 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
8319 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8321 /* Don't pass any packets until we're started */
8322 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8323 ast_mutex_unlock(&iaxsl[fr->callno]);
8324 return 1;
8326 /* Common things */
8327 f.src = "IAX2";
8328 f.mallocd = 0;
8329 f.offset = 0;
8330 f.len = 0;
8331 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
8332 f.samples = ast_codec_get_samples(&f);
8333 /* We need to byteswap incoming slinear samples from network byte order */
8334 if (f.subclass == AST_FORMAT_SLINEAR)
8335 ast_frame_byteswap_be(&f);
8336 } else
8337 f.samples = 0;
8338 iax_frame_wrap(fr, &f);
8340 /* If this is our most recent packet, use it as our basis for timestamping */
8341 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8342 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8343 fr->outoforder = 0;
8344 } else {
8345 if (option_debug && iaxdebug && iaxs[fr->callno])
8346 ast_log(LOG_DEBUG, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
8347 fr->outoforder = -1;
8349 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
8350 duped_fr = iaxfrdup2(fr);
8351 if (duped_fr) {
8352 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
8354 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8355 iaxs[fr->callno]->last = fr->ts;
8356 #if 1
8357 if (option_debug && iaxdebug)
8358 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8359 #endif
8362 /* Always run again */
8363 ast_mutex_unlock(&iaxsl[fr->callno]);
8364 return 1;
8367 /* Function to clean up process thread if it is cancelled */
8368 static void iax2_process_thread_cleanup(void *data)
8370 struct iax2_thread *thread = data;
8371 ast_mutex_destroy(&thread->lock);
8372 ast_cond_destroy(&thread->cond);
8373 free(thread);
8374 ast_atomic_dec_and_test(&iaxactivethreadcount);
8377 static void *iax2_process_thread(void *data)
8379 struct iax2_thread *thread = data;
8380 struct timeval tv;
8381 struct timespec ts;
8382 int put_into_idle = 0;
8384 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
8385 pthread_cleanup_push(iax2_process_thread_cleanup, data);
8386 for(;;) {
8387 /* Wait for something to signal us to be awake */
8388 ast_mutex_lock(&thread->lock);
8390 /* Flag that we're ready to accept signals */
8391 thread->ready_for_signal = 1;
8393 /* Put into idle list if applicable */
8394 if (put_into_idle)
8395 insert_idle_thread(thread);
8397 if (thread->type == IAX_TYPE_DYNAMIC) {
8398 struct iax2_thread *t = NULL;
8399 /* Wait to be signalled or time out */
8400 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8401 ts.tv_sec = tv.tv_sec;
8402 ts.tv_nsec = tv.tv_usec * 1000;
8403 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
8404 /* This thread was never put back into the available dynamic
8405 * thread list, so just go away. */
8406 if (!put_into_idle) {
8407 ast_mutex_unlock(&thread->lock);
8408 break;
8410 AST_LIST_LOCK(&dynamic_list);
8411 /* Account for the case where this thread is acquired *right* after a timeout */
8412 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
8413 iaxdynamicthreadcount--;
8414 AST_LIST_UNLOCK(&dynamic_list);
8415 if (t) {
8416 /* This dynamic thread timed out waiting for a task and was
8417 * not acquired immediately after the timeout,
8418 * so it's time to go away. */
8419 ast_mutex_unlock(&thread->lock);
8420 break;
8422 /* Someone grabbed our thread *right* after we timed out.
8423 * Wait for them to set us up with something to do and signal
8424 * us to continue. */
8425 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8426 ts.tv_sec = tv.tv_sec;
8427 ts.tv_nsec = tv.tv_usec * 1000;
8428 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
8430 ast_mutex_unlock(&thread->lock);
8431 break;
8434 } else {
8435 ast_cond_wait(&thread->cond, &thread->lock);
8438 /* Go back into our respective list */
8439 put_into_idle = 1;
8441 ast_mutex_unlock(&thread->lock);
8443 if (thread->iostate == IAX_IOSTATE_IDLE)
8444 continue;
8446 /* Add ourselves to the active list now */
8447 AST_LIST_LOCK(&active_list);
8448 AST_LIST_INSERT_HEAD(&active_list, thread, list);
8449 AST_LIST_UNLOCK(&active_list);
8451 /* See what we need to do */
8452 switch(thread->iostate) {
8453 case IAX_IOSTATE_READY:
8454 thread->actions++;
8455 thread->iostate = IAX_IOSTATE_PROCESSING;
8456 socket_process(thread);
8457 handle_deferred_full_frames(thread);
8458 break;
8459 case IAX_IOSTATE_SCHEDREADY:
8460 thread->actions++;
8461 thread->iostate = IAX_IOSTATE_PROCESSING;
8462 #ifdef SCHED_MULTITHREADED
8463 thread->schedfunc(thread->scheddata);
8464 #endif
8465 break;
8467 time(&thread->checktime);
8468 thread->iostate = IAX_IOSTATE_IDLE;
8469 #ifdef DEBUG_SCHED_MULTITHREAD
8470 thread->curfunc[0]='\0';
8471 #endif
8473 /* Now... remove ourselves from the active list, and return to the idle list */
8474 AST_LIST_LOCK(&active_list);
8475 AST_LIST_REMOVE(&active_list, thread, list);
8476 AST_LIST_UNLOCK(&active_list);
8478 /* Make sure another frame didn't sneak in there after we thought we were done. */
8479 handle_deferred_full_frames(thread);
8482 /*!\note For some reason, idle threads are exiting without being removed
8483 * from an idle list, which is causing memory corruption. Forcibly remove
8484 * it from the list, if it's there.
8486 AST_LIST_LOCK(&idle_list);
8487 AST_LIST_REMOVE(&idle_list, thread, list);
8488 AST_LIST_UNLOCK(&idle_list);
8490 AST_LIST_LOCK(&dynamic_list);
8491 AST_LIST_REMOVE(&dynamic_list, thread, list);
8492 AST_LIST_UNLOCK(&dynamic_list);
8494 /* I am exiting here on my own volition, I need to clean up my own data structures
8495 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8497 pthread_cleanup_pop(1);
8499 return NULL;
8502 static int iax2_do_register(struct iax2_registry *reg)
8504 struct iax_ie_data ied;
8505 if (option_debug && iaxdebug)
8506 ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
8508 if (reg->dnsmgr &&
8509 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
8510 /* Maybe the IP has changed, force DNS refresh */
8511 ast_dnsmgr_refresh(reg->dnsmgr);
8515 * if IP has Changed, free allocated call to create a new one with new IP
8516 * call has the pointer to IP and must be updated to the new one
8518 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
8519 ast_mutex_lock(&iaxsl[reg->callno]);
8520 iax2_destroy(reg->callno);
8521 ast_mutex_unlock(&iaxsl[reg->callno]);
8522 reg->callno = 0;
8524 if (!reg->addr.sin_addr.s_addr) {
8525 if (option_debug && iaxdebug)
8526 ast_log(LOG_DEBUG, "Unable to send registration request for '%s' without IP address\n", reg->username);
8527 /* Setup the next registration attempt */
8528 AST_SCHED_DEL(sched, reg->expire);
8529 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8530 return -1;
8533 if (!reg->callno) {
8534 if (option_debug)
8535 ast_log(LOG_DEBUG, "Allocate call number\n");
8536 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
8537 if (reg->callno < 1) {
8538 ast_log(LOG_WARNING, "Unable to create call for registration\n");
8539 return -1;
8540 } else if (option_debug)
8541 ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
8542 iaxs[reg->callno]->reg = reg;
8543 ast_mutex_unlock(&iaxsl[reg->callno]);
8545 /* Schedule the next registration attempt */
8546 AST_SCHED_DEL(sched, reg->expire);
8547 /* Setup the next registration a little early */
8548 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8549 /* Send the request */
8550 memset(&ied, 0, sizeof(ied));
8551 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
8552 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
8553 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
8554 reg->regstate = REG_STATE_REGSENT;
8555 return 0;
8558 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
8560 if (pos != 3)
8561 return NULL;
8562 return iax_prov_complete_template(line, word, pos, state);
8565 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
8567 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8568 is found for template */
8569 struct iax_ie_data provdata;
8570 struct iax_ie_data ied;
8571 unsigned int sig;
8572 struct sockaddr_in sin;
8573 int callno;
8574 struct create_addr_info cai;
8576 memset(&cai, 0, sizeof(cai));
8578 if (option_debug)
8579 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
8581 if (iax_provision_build(&provdata, &sig, template, force)) {
8582 if (option_debug)
8583 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
8584 return 0;
8587 if (end) {
8588 memcpy(&sin, end, sizeof(sin));
8589 cai.sockfd = sockfd;
8590 } else if (create_addr(dest, NULL, &sin, &cai))
8591 return -1;
8593 /* Build the rest of the message */
8594 memset(&ied, 0, sizeof(ied));
8595 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
8597 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8598 if (!callno)
8599 return -1;
8601 if (iaxs[callno]) {
8602 /* Schedule autodestruct in case they don't ever give us anything back */
8603 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
8604 iaxs[callno]->autoid = iax2_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
8605 ast_set_flag(iaxs[callno], IAX_PROVISION);
8606 /* Got a call number now, so go ahead and send the provisioning information */
8607 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
8609 ast_mutex_unlock(&iaxsl[callno]);
8611 return 1;
8614 static char *papp = "IAX2Provision";
8615 static char *psyn = "Provision a calling IAXy with a given template";
8616 static char *pdescrip =
8617 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8618 "the calling entity is in fact an IAXy) with the given template or\n"
8619 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8621 /*! iax2provision
8622 \ingroup applications
8624 static int iax2_prov_app(struct ast_channel *chan, void *data)
8626 int res;
8627 char *sdata;
8628 char *opts;
8629 int force =0;
8630 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
8631 if (ast_strlen_zero(data))
8632 data = "default";
8633 sdata = ast_strdupa(data);
8634 opts = strchr(sdata, '|');
8635 if (opts)
8636 *opts='\0';
8638 if (chan->tech != &iax2_tech) {
8639 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
8640 return -1;
8642 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
8643 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
8644 return -1;
8646 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
8647 if (option_verbose > 2)
8648 ast_verbose(VERBOSE_PREFIX_3 "Provisioned IAXY at '%s' with '%s'= %d\n",
8649 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
8650 sdata, res);
8651 return res;
8655 static int iax2_prov_cmd(int fd, int argc, char *argv[])
8657 int force = 0;
8658 int res;
8659 if (argc < 4)
8660 return RESULT_SHOWUSAGE;
8661 if ((argc > 4)) {
8662 if (!strcasecmp(argv[4], "forced"))
8663 force = 1;
8664 else
8665 return RESULT_SHOWUSAGE;
8667 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
8668 if (res < 0)
8669 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
8670 else if (res < 1)
8671 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
8672 else
8673 ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
8674 return RESULT_SUCCESS;
8677 static void __iax2_poke_noanswer(const void *data)
8679 struct iax2_peer *peer = (struct iax2_peer *)data;
8680 if (peer->lastms > -1) {
8681 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
8682 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
8683 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
8685 if (peer->callno > 0) {
8686 ast_mutex_lock(&iaxsl[peer->callno]);
8687 iax2_destroy(peer->callno);
8688 ast_mutex_unlock(&iaxsl[peer->callno]);
8690 peer->callno = 0;
8691 peer->lastms = -1;
8692 /* Try again quickly */
8693 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
8694 if (peer->pokeexpire == -1)
8695 peer_unref(peer);
8698 static int iax2_poke_noanswer(const void *data)
8700 struct iax2_peer *peer = (struct iax2_peer *)data;
8701 peer->pokeexpire = -1;
8702 #ifdef SCHED_MULTITHREADED
8703 if (schedule_action(__iax2_poke_noanswer, data))
8704 #endif
8705 __iax2_poke_noanswer(data);
8706 peer_unref(peer);
8707 return 0;
8710 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
8712 struct iax2_peer *peer = obj;
8714 iax2_poke_peer(peer, 0);
8716 return 0;
8719 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
8721 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
8722 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8723 immediately after clearing things out */
8724 peer->lastms = 0;
8725 peer->historicms = 0;
8726 peer->pokeexpire = -1;
8727 peer->callno = 0;
8728 return 0;
8730 if (peer->callno > 0) {
8731 ast_log(LOG_NOTICE, "Still have a callno...\n");
8732 ast_mutex_lock(&iaxsl[peer->callno]);
8733 iax2_destroy(peer->callno);
8734 ast_mutex_unlock(&iaxsl[peer->callno]);
8736 if (heldcall)
8737 ast_mutex_unlock(&iaxsl[heldcall]);
8738 peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
8739 if (heldcall)
8740 ast_mutex_lock(&iaxsl[heldcall]);
8741 if (peer->callno < 1) {
8742 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
8743 return -1;
8746 /* Speed up retransmission times for this qualify call */
8747 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
8748 iaxs[peer->callno]->peerpoke = peer;
8750 /* Remove any pending pokeexpire task */
8751 if (peer->pokeexpire > -1) {
8752 if (!ast_sched_del(sched, peer->pokeexpire)) {
8753 peer->pokeexpire = -1;
8754 peer_unref(peer);
8758 /* Queue up a new task to handle no reply */
8759 /* If the host is already unreachable then use the unreachable interval instead */
8760 if (peer->lastms < 0) {
8761 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
8762 } else
8763 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
8765 if (peer->pokeexpire == -1)
8766 peer_unref(peer);
8768 /* And send the poke */
8769 send_command(iaxs[peer->callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
8771 return 0;
8774 static void free_context(struct iax2_context *con)
8776 struct iax2_context *conl;
8777 while(con) {
8778 conl = con;
8779 con = con->next;
8780 free(conl);
8784 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
8786 int callno;
8787 int res;
8788 int fmt, native;
8789 struct sockaddr_in sin;
8790 struct ast_channel *c;
8791 struct parsed_dial_string pds;
8792 struct create_addr_info cai;
8793 char *tmpstr;
8795 memset(&pds, 0, sizeof(pds));
8796 tmpstr = ast_strdupa(data);
8797 parse_dial_string(tmpstr, &pds);
8799 if (ast_strlen_zero(pds.peer)) {
8800 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
8801 return NULL;
8804 memset(&cai, 0, sizeof(cai));
8805 cai.capability = iax2_capability;
8807 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8809 /* Populate our address from the given */
8810 if (create_addr(pds.peer, NULL, &sin, &cai)) {
8811 *cause = AST_CAUSE_UNREGISTERED;
8812 return NULL;
8815 if (pds.port)
8816 sin.sin_port = htons(atoi(pds.port));
8818 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8819 if (callno < 1) {
8820 ast_log(LOG_WARNING, "Unable to create call\n");
8821 *cause = AST_CAUSE_CONGESTION;
8822 return NULL;
8825 /* If this is a trunk, update it now */
8826 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8827 if (ast_test_flag(&cai, IAX_TRUNK)) {
8828 int new_callno;
8829 if ((new_callno = make_trunk(callno, 1)) != -1)
8830 callno = new_callno;
8832 iaxs[callno]->maxtime = cai.maxtime;
8833 if (cai.found)
8834 ast_string_field_set(iaxs[callno], host, pds.peer);
8836 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
8838 ast_mutex_unlock(&iaxsl[callno]);
8840 if (c) {
8841 /* Choose a format we can live with */
8842 if (c->nativeformats & format)
8843 c->nativeformats &= format;
8844 else {
8845 native = c->nativeformats;
8846 fmt = format;
8847 res = ast_translator_best_choice(&fmt, &native);
8848 if (res < 0) {
8849 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
8850 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
8851 ast_hangup(c);
8852 return NULL;
8854 c->nativeformats = native;
8856 c->readformat = ast_best_codec(c->nativeformats);
8857 c->writeformat = c->readformat;
8860 return c;
8863 static void *sched_thread(void *ignore)
8865 int count;
8866 int res;
8867 struct timeval tv;
8868 struct timespec ts;
8870 for (;;) {
8871 res = ast_sched_wait(sched);
8872 if ((res > 1000) || (res < 0))
8873 res = 1000;
8874 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
8875 ts.tv_sec = tv.tv_sec;
8876 ts.tv_nsec = tv.tv_usec * 1000;
8878 pthread_testcancel();
8879 ast_mutex_lock(&sched_lock);
8880 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
8881 ast_mutex_unlock(&sched_lock);
8882 pthread_testcancel();
8884 count = ast_sched_runq(sched);
8885 if (option_debug && count >= 20)
8886 ast_log(LOG_DEBUG, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
8888 return NULL;
8891 static void *network_thread(void *ignore)
8893 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
8894 from the network, and queue them for delivery to the channels */
8895 int res, count, wakeup;
8896 struct iax_frame *f;
8898 if (timingfd > -1)
8899 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
8901 for(;;) {
8902 pthread_testcancel();
8904 /* Go through the queue, sending messages which have not yet been
8905 sent, and scheduling retransmissions if appropriate */
8906 AST_LIST_LOCK(&iaxq.queue);
8907 count = 0;
8908 wakeup = -1;
8909 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
8910 if (f->sentyet)
8911 continue;
8913 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
8914 if (ast_mutex_trylock(&iaxsl[f->callno])) {
8915 wakeup = 1;
8916 continue;
8919 f->sentyet++;
8921 if (iaxs[f->callno]) {
8922 send_packet(f);
8923 count++;
8926 ast_mutex_unlock(&iaxsl[f->callno]);
8928 if (f->retries < 0) {
8929 /* This is not supposed to be retransmitted */
8930 AST_LIST_REMOVE_CURRENT(&iaxq.queue, list);
8931 iaxq.count--;
8932 /* Free the iax frame */
8933 iax_frame_free(f);
8934 } else {
8935 /* We need reliable delivery. Schedule a retransmission */
8936 f->retries++;
8937 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
8940 AST_LIST_TRAVERSE_SAFE_END
8941 AST_LIST_UNLOCK(&iaxq.queue);
8943 pthread_testcancel();
8945 if (option_debug && count >= 20)
8946 ast_log(LOG_DEBUG, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
8948 /* Now do the IO, and run scheduled tasks */
8949 res = ast_io_wait(io, wakeup);
8950 if (res >= 0) {
8951 if (option_debug && res >= 20)
8952 ast_log(LOG_DEBUG, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
8955 return NULL;
8958 static int start_network_thread(void)
8960 pthread_attr_t attr;
8961 int threadcount = 0;
8962 int x;
8963 for (x = 0; x < iaxthreadcount; x++) {
8964 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
8965 if (thread) {
8966 thread->type = IAX_TYPE_POOL;
8967 thread->threadnum = ++threadcount;
8968 ast_mutex_init(&thread->lock);
8969 ast_cond_init(&thread->cond, NULL);
8970 pthread_attr_init(&attr);
8971 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
8972 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
8973 ast_log(LOG_WARNING, "Failed to create new thread!\n");
8974 free(thread);
8975 thread = NULL;
8977 AST_LIST_LOCK(&idle_list);
8978 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
8979 AST_LIST_UNLOCK(&idle_list);
8982 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
8983 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
8984 if (option_verbose > 1)
8985 ast_verbose(VERBOSE_PREFIX_2 "%d helper threaads started\n", threadcount);
8986 return 0;
8989 static struct iax2_context *build_context(char *context)
8991 struct iax2_context *con;
8993 if ((con = ast_calloc(1, sizeof(*con))))
8994 ast_copy_string(con->context, context, sizeof(con->context));
8996 return con;
8999 static int get_auth_methods(char *value)
9001 int methods = 0;
9002 if (strstr(value, "rsa"))
9003 methods |= IAX_AUTH_RSA;
9004 if (strstr(value, "md5"))
9005 methods |= IAX_AUTH_MD5;
9006 if (strstr(value, "plaintext"))
9007 methods |= IAX_AUTH_PLAINTEXT;
9008 return methods;
9012 /*! \brief Check if address can be used as packet source.
9013 \return 0 address available, 1 address unavailable, -1 error
9015 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
9017 int sd;
9018 int res;
9020 sd = socket(AF_INET, SOCK_DGRAM, 0);
9021 if (sd < 0) {
9022 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
9023 return -1;
9026 res = bind(sd, sa, salen);
9027 if (res < 0) {
9028 if (option_debug)
9029 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
9030 close(sd);
9031 return 1;
9034 close(sd);
9035 return 0;
9038 /*! \brief Parse the "sourceaddress" value,
9039 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9040 not found. */
9041 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
9043 struct sockaddr_in sin;
9044 int nonlocal = 1;
9045 int port = IAX_DEFAULT_PORTNO;
9046 int sockfd = defaultsockfd;
9047 char *tmp;
9048 char *addr;
9049 char *portstr;
9051 if (!(tmp = ast_strdupa(srcaddr)))
9052 return -1;
9054 addr = strsep(&tmp, ":");
9055 portstr = tmp;
9057 if (portstr) {
9058 port = atoi(portstr);
9059 if (port < 1)
9060 port = IAX_DEFAULT_PORTNO;
9063 if (!ast_get_ip(&sin, addr)) {
9064 struct ast_netsock *sock;
9065 int res;
9067 sin.sin_port = 0;
9068 sin.sin_family = AF_INET;
9069 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
9070 if (res == 0) {
9071 /* ip address valid. */
9072 sin.sin_port = htons(port);
9073 if (!(sock = ast_netsock_find(netsock, &sin)))
9074 sock = ast_netsock_find(outsock, &sin);
9075 if (sock) {
9076 sockfd = ast_netsock_sockfd(sock);
9077 nonlocal = 0;
9078 } else {
9079 unsigned int orig_saddr = sin.sin_addr.s_addr;
9080 /* INADDR_ANY matches anyway! */
9081 sin.sin_addr.s_addr = INADDR_ANY;
9082 if (ast_netsock_find(netsock, &sin)) {
9083 sin.sin_addr.s_addr = orig_saddr;
9084 sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, socket_read, NULL);
9085 if (sock) {
9086 sockfd = ast_netsock_sockfd(sock);
9087 ast_netsock_unref(sock);
9088 nonlocal = 0;
9089 } else {
9090 nonlocal = 2;
9097 peer->sockfd = sockfd;
9099 if (nonlocal == 1) {
9100 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9101 srcaddr, peer->name);
9102 return -1;
9103 } else if (nonlocal == 2) {
9104 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9105 srcaddr, peer->name);
9106 return -1;
9107 } else {
9108 if (option_debug)
9109 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
9110 return 0;
9114 static void peer_destructor(void *obj)
9116 struct iax2_peer *peer = obj;
9118 ast_free_ha(peer->ha);
9120 if (peer->callno > 0) {
9121 ast_mutex_lock(&iaxsl[peer->callno]);
9122 iax2_destroy(peer->callno);
9123 ast_mutex_unlock(&iaxsl[peer->callno]);
9126 register_peer_exten(peer, 0);
9128 if (peer->dnsmgr)
9129 ast_dnsmgr_release(peer->dnsmgr);
9131 ast_string_field_free_memory(peer);
9134 /*! \brief Create peer structure based on configuration */
9135 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9137 struct iax2_peer *peer = NULL;
9138 struct ast_ha *oldha = NULL;
9139 int maskfound=0;
9140 int found=0;
9141 int firstpass=1;
9142 struct iax2_peer tmp_peer = {
9143 .name = name,
9146 if (!temponly) {
9147 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
9148 if (peer && !ast_test_flag(peer, IAX_DELME))
9149 firstpass = 0;
9152 if (peer) {
9153 found++;
9154 if (firstpass) {
9155 oldha = peer->ha;
9156 peer->ha = NULL;
9158 unlink_peer(peer);
9159 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
9160 peer->expire = -1;
9161 peer->pokeexpire = -1;
9162 peer->sockfd = defaultsockfd;
9163 if (ast_string_field_init(peer, 32))
9164 peer = peer_unref(peer);
9167 if (peer) {
9168 if (firstpass) {
9169 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
9170 peer->encmethods = iax2_encryption;
9171 peer->adsi = adsi;
9172 ast_string_field_set(peer,secret,"");
9173 if (!found) {
9174 ast_string_field_set(peer, name, name);
9175 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9176 peer->expiry = min_reg_expire;
9178 peer->prefs = prefs;
9179 peer->capability = iax2_capability;
9180 peer->smoothing = 0;
9181 peer->pokefreqok = DEFAULT_FREQ_OK;
9182 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
9183 ast_string_field_set(peer,context,"");
9184 ast_string_field_set(peer,peercontext,"");
9185 ast_clear_flag(peer, IAX_HASCALLERID);
9186 ast_string_field_set(peer, cid_name, "");
9187 ast_string_field_set(peer, cid_num, "");
9190 if (!v) {
9191 v = alt;
9192 alt = NULL;
9194 while(v) {
9195 if (!strcasecmp(v->name, "secret")) {
9196 ast_string_field_set(peer, secret, v->value);
9197 } else if (!strcasecmp(v->name, "mailbox")) {
9198 ast_string_field_set(peer, mailbox, v->value);
9199 } else if (!strcasecmp(v->name, "mohinterpret")) {
9200 ast_string_field_set(peer, mohinterpret, v->value);
9201 } else if (!strcasecmp(v->name, "mohsuggest")) {
9202 ast_string_field_set(peer, mohsuggest, v->value);
9203 } else if (!strcasecmp(v->name, "dbsecret")) {
9204 ast_string_field_set(peer, dbsecret, v->value);
9205 } else if (!strcasecmp(v->name, "trunk")) {
9206 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
9207 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
9208 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without zaptel timing\n", peer->name);
9209 ast_clear_flag(peer, IAX_TRUNK);
9211 } else if (!strcasecmp(v->name, "auth")) {
9212 peer->authmethods = get_auth_methods(v->value);
9213 } else if (!strcasecmp(v->name, "encryption")) {
9214 peer->encmethods = get_encrypt_methods(v->value);
9215 } else if (!strcasecmp(v->name, "notransfer")) {
9216 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9217 ast_clear_flag(peer, IAX_TRANSFERMEDIA);
9218 ast_set2_flag(peer, ast_true(v->value), IAX_NOTRANSFER);
9219 } else if (!strcasecmp(v->name, "transfer")) {
9220 if (!strcasecmp(v->value, "mediaonly")) {
9221 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9222 } else if (ast_true(v->value)) {
9223 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9224 } else
9225 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9226 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9227 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
9228 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9229 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
9230 } else if (!strcasecmp(v->name, "host")) {
9231 if (!strcasecmp(v->value, "dynamic")) {
9232 /* They'll register with us */
9233 ast_set_flag(peer, IAX_DYNAMIC);
9234 if (!found) {
9235 /* Initialize stuff iff we're not found, otherwise
9236 we keep going with what we had */
9237 memset(&peer->addr.sin_addr, 0, 4);
9238 if (peer->addr.sin_port) {
9239 /* If we've already got a port, make it the default rather than absolute */
9240 peer->defaddr.sin_port = peer->addr.sin_port;
9241 peer->addr.sin_port = 0;
9244 } else {
9245 /* Non-dynamic. Make sure we become that way if we're not */
9246 AST_SCHED_DEL(sched, peer->expire);
9247 ast_clear_flag(peer, IAX_DYNAMIC);
9248 if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
9249 return peer_unref(peer);
9250 if (!peer->addr.sin_port)
9251 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9253 if (!maskfound)
9254 inet_aton("255.255.255.255", &peer->mask);
9255 } else if (!strcasecmp(v->name, "defaultip")) {
9256 if (ast_get_ip(&peer->defaddr, v->value))
9257 return peer_unref(peer);
9258 } else if (!strcasecmp(v->name, "sourceaddress")) {
9259 peer_set_srcaddr(peer, v->value);
9260 } else if (!strcasecmp(v->name, "permit") ||
9261 !strcasecmp(v->name, "deny")) {
9262 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
9263 } else if (!strcasecmp(v->name, "mask")) {
9264 maskfound++;
9265 inet_aton(v->value, &peer->mask);
9266 } else if (!strcasecmp(v->name, "context")) {
9267 ast_string_field_set(peer, context, v->value);
9268 } else if (!strcasecmp(v->name, "regexten")) {
9269 ast_string_field_set(peer, regexten, v->value);
9270 } else if (!strcasecmp(v->name, "peercontext")) {
9271 ast_string_field_set(peer, peercontext, v->value);
9272 } else if (!strcasecmp(v->name, "port")) {
9273 if (ast_test_flag(peer, IAX_DYNAMIC))
9274 peer->defaddr.sin_port = htons(atoi(v->value));
9275 else
9276 peer->addr.sin_port = htons(atoi(v->value));
9277 } else if (!strcasecmp(v->name, "username")) {
9278 ast_string_field_set(peer, username, v->value);
9279 } else if (!strcasecmp(v->name, "allow")) {
9280 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
9281 } else if (!strcasecmp(v->name, "disallow")) {
9282 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
9283 } else if (!strcasecmp(v->name, "callerid")) {
9284 if (!ast_strlen_zero(v->value)) {
9285 char name2[80];
9286 char num2[80];
9287 ast_callerid_split(v->value, name2, 80, num2, 80);
9288 ast_string_field_set(peer, cid_name, name2);
9289 ast_string_field_set(peer, cid_num, num2);
9290 ast_set_flag(peer, IAX_HASCALLERID);
9291 } else {
9292 ast_clear_flag(peer, IAX_HASCALLERID);
9293 ast_string_field_set(peer, cid_name, "");
9294 ast_string_field_set(peer, cid_num, "");
9296 } else if (!strcasecmp(v->name, "fullname")) {
9297 if (!ast_strlen_zero(v->value)) {
9298 ast_string_field_set(peer, cid_name, v->value);
9299 ast_set_flag(peer, IAX_HASCALLERID);
9300 } else {
9301 ast_string_field_set(peer, cid_name, "");
9302 if (ast_strlen_zero(peer->cid_num))
9303 ast_clear_flag(peer, IAX_HASCALLERID);
9305 } else if (!strcasecmp(v->name, "cid_number")) {
9306 if (!ast_strlen_zero(v->value)) {
9307 ast_string_field_set(peer, cid_num, v->value);
9308 ast_set_flag(peer, IAX_HASCALLERID);
9309 } else {
9310 ast_string_field_set(peer, cid_num, "");
9311 if (ast_strlen_zero(peer->cid_name))
9312 ast_clear_flag(peer, IAX_HASCALLERID);
9314 } else if (!strcasecmp(v->name, "sendani")) {
9315 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
9316 } else if (!strcasecmp(v->name, "inkeys")) {
9317 ast_string_field_set(peer, inkeys, v->value);
9318 } else if (!strcasecmp(v->name, "outkey")) {
9319 ast_string_field_set(peer, outkey, v->value);
9320 } else if (!strcasecmp(v->name, "qualify")) {
9321 if (!strcasecmp(v->value, "no")) {
9322 peer->maxms = 0;
9323 } else if (!strcasecmp(v->value, "yes")) {
9324 peer->maxms = DEFAULT_MAXMS;
9325 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
9326 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9327 peer->maxms = 0;
9329 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
9330 peer->smoothing = ast_true(v->value);
9331 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
9332 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
9333 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9335 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
9336 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
9337 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9338 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
9339 } else if (!strcasecmp(v->name, "timezone")) {
9340 ast_string_field_set(peer, zonetag, v->value);
9341 } else if (!strcasecmp(v->name, "adsi")) {
9342 peer->adsi = ast_true(v->value);
9343 }/* else if (strcasecmp(v->name,"type")) */
9344 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9345 v = v->next;
9346 if (!v) {
9347 v = alt;
9348 alt = NULL;
9351 if (!peer->authmethods)
9352 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9353 ast_clear_flag(peer, IAX_DELME);
9354 /* Make sure these are IPv4 addresses */
9355 peer->addr.sin_family = AF_INET;
9357 if (oldha)
9358 ast_free_ha(oldha);
9359 return peer;
9362 static void user_destructor(void *obj)
9364 struct iax2_user *user = obj;
9366 ast_free_ha(user->ha);
9367 free_context(user->contexts);
9368 if(user->vars) {
9369 ast_variables_destroy(user->vars);
9370 user->vars = NULL;
9372 ast_string_field_free_memory(user);
9375 /*! \brief Create in-memory user structure from configuration */
9376 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9378 struct iax2_user *user = NULL;
9379 struct iax2_context *con, *conl = NULL;
9380 struct ast_ha *oldha = NULL;
9381 struct iax2_context *oldcon = NULL;
9382 int format;
9383 int firstpass=1;
9384 int oldcurauthreq = 0;
9385 char *varname = NULL, *varval = NULL;
9386 struct ast_variable *tmpvar = NULL;
9387 struct iax2_user tmp_user = {
9388 .name = name,
9391 if (!temponly) {
9392 user = ao2_find(users, &tmp_user, OBJ_POINTER);
9393 if (user && !ast_test_flag(user, IAX_DELME))
9394 firstpass = 0;
9397 if (user) {
9398 if (firstpass) {
9399 oldcurauthreq = user->curauthreq;
9400 oldha = user->ha;
9401 oldcon = user->contexts;
9402 user->ha = NULL;
9403 user->contexts = NULL;
9405 /* Already in the list, remove it and it will be added back (or FREE'd) */
9406 ao2_unlink(users, user);
9407 } else {
9408 user = ao2_alloc(sizeof(*user), user_destructor);
9411 if (user) {
9412 if (firstpass) {
9413 ast_string_field_free_memory(user);
9414 memset(user, 0, sizeof(struct iax2_user));
9415 if (ast_string_field_init(user, 32)) {
9416 user = user_unref(user);
9417 goto cleanup;
9419 user->maxauthreq = maxauthreq;
9420 user->curauthreq = oldcurauthreq;
9421 user->prefs = prefs;
9422 user->capability = iax2_capability;
9423 user->encmethods = iax2_encryption;
9424 user->adsi = adsi;
9425 ast_string_field_set(user, name, name);
9426 ast_string_field_set(user, language, language);
9427 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
9428 ast_clear_flag(user, IAX_HASCALLERID);
9429 ast_string_field_set(user, cid_name, "");
9430 ast_string_field_set(user, cid_num, "");
9432 if (!v) {
9433 v = alt;
9434 alt = NULL;
9436 while(v) {
9437 if (!strcasecmp(v->name, "context")) {
9438 con = build_context(v->value);
9439 if (con) {
9440 if (conl)
9441 conl->next = con;
9442 else
9443 user->contexts = con;
9444 conl = con;
9446 } else if (!strcasecmp(v->name, "permit") ||
9447 !strcasecmp(v->name, "deny")) {
9448 user->ha = ast_append_ha(v->name, v->value, user->ha);
9449 } else if (!strcasecmp(v->name, "setvar")) {
9450 varname = ast_strdupa(v->value);
9451 if (varname && (varval = strchr(varname,'='))) {
9452 *varval = '\0';
9453 varval++;
9454 if((tmpvar = ast_variable_new(varname, varval))) {
9455 tmpvar->next = user->vars;
9456 user->vars = tmpvar;
9459 } else if (!strcasecmp(v->name, "allow")) {
9460 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
9461 } else if (!strcasecmp(v->name, "disallow")) {
9462 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
9463 } else if (!strcasecmp(v->name, "trunk")) {
9464 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
9465 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
9466 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without zaptel timing\n", user->name);
9467 ast_clear_flag(user, IAX_TRUNK);
9469 } else if (!strcasecmp(v->name, "auth")) {
9470 user->authmethods = get_auth_methods(v->value);
9471 } else if (!strcasecmp(v->name, "encryption")) {
9472 user->encmethods = get_encrypt_methods(v->value);
9473 } else if (!strcasecmp(v->name, "notransfer")) {
9474 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9475 ast_clear_flag(user, IAX_TRANSFERMEDIA);
9476 ast_set2_flag(user, ast_true(v->value), IAX_NOTRANSFER);
9477 } else if (!strcasecmp(v->name, "transfer")) {
9478 if (!strcasecmp(v->value, "mediaonly")) {
9479 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9480 } else if (ast_true(v->value)) {
9481 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9482 } else
9483 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9484 } else if (!strcasecmp(v->name, "codecpriority")) {
9485 if(!strcasecmp(v->value, "caller"))
9486 ast_set_flag(user, IAX_CODEC_USER_FIRST);
9487 else if(!strcasecmp(v->value, "disabled"))
9488 ast_set_flag(user, IAX_CODEC_NOPREFS);
9489 else if(!strcasecmp(v->value, "reqonly")) {
9490 ast_set_flag(user, IAX_CODEC_NOCAP);
9491 ast_set_flag(user, IAX_CODEC_NOPREFS);
9493 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9494 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
9495 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9496 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
9497 } else if (!strcasecmp(v->name, "dbsecret")) {
9498 ast_string_field_set(user, dbsecret, v->value);
9499 } else if (!strcasecmp(v->name, "secret")) {
9500 if (!ast_strlen_zero(user->secret)) {
9501 char *old = ast_strdupa(user->secret);
9503 ast_string_field_build(user, secret, "%s;%s", old, v->value);
9504 } else
9505 ast_string_field_set(user, secret, v->value);
9506 } else if (!strcasecmp(v->name, "callerid")) {
9507 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
9508 char name2[80];
9509 char num2[80];
9510 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
9511 ast_string_field_set(user, cid_name, name2);
9512 ast_string_field_set(user, cid_num, num2);
9513 ast_set_flag(user, IAX_HASCALLERID);
9514 } else {
9515 ast_clear_flag(user, IAX_HASCALLERID);
9516 ast_string_field_set(user, cid_name, "");
9517 ast_string_field_set(user, cid_num, "");
9519 } else if (!strcasecmp(v->name, "fullname")) {
9520 if (!ast_strlen_zero(v->value)) {
9521 ast_string_field_set(user, cid_name, v->value);
9522 ast_set_flag(user, IAX_HASCALLERID);
9523 } else {
9524 ast_string_field_set(user, cid_name, "");
9525 if (ast_strlen_zero(user->cid_num))
9526 ast_clear_flag(user, IAX_HASCALLERID);
9528 } else if (!strcasecmp(v->name, "cid_number")) {
9529 if (!ast_strlen_zero(v->value)) {
9530 ast_string_field_set(user, cid_num, v->value);
9531 ast_set_flag(user, IAX_HASCALLERID);
9532 } else {
9533 ast_string_field_set(user, cid_num, "");
9534 if (ast_strlen_zero(user->cid_name))
9535 ast_clear_flag(user, IAX_HASCALLERID);
9537 } else if (!strcasecmp(v->name, "accountcode")) {
9538 ast_string_field_set(user, accountcode, v->value);
9539 } else if (!strcasecmp(v->name, "mohinterpret")) {
9540 ast_string_field_set(user, mohinterpret, v->value);
9541 } else if (!strcasecmp(v->name, "mohsuggest")) {
9542 ast_string_field_set(user, mohsuggest, v->value);
9543 } else if (!strcasecmp(v->name, "language")) {
9544 ast_string_field_set(user, language, v->value);
9545 } else if (!strcasecmp(v->name, "amaflags")) {
9546 format = ast_cdr_amaflags2int(v->value);
9547 if (format < 0) {
9548 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9549 } else {
9550 user->amaflags = format;
9552 } else if (!strcasecmp(v->name, "inkeys")) {
9553 ast_string_field_set(user, inkeys, v->value);
9554 } else if (!strcasecmp(v->name, "maxauthreq")) {
9555 user->maxauthreq = atoi(v->value);
9556 if (user->maxauthreq < 0)
9557 user->maxauthreq = 0;
9558 } else if (!strcasecmp(v->name, "adsi")) {
9559 user->adsi = ast_true(v->value);
9560 }/* else if (strcasecmp(v->name,"type")) */
9561 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9562 v = v->next;
9563 if (!v) {
9564 v = alt;
9565 alt = NULL;
9568 if (!user->authmethods) {
9569 if (!ast_strlen_zero(user->secret)) {
9570 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9571 if (!ast_strlen_zero(user->inkeys))
9572 user->authmethods |= IAX_AUTH_RSA;
9573 } else if (!ast_strlen_zero(user->inkeys)) {
9574 user->authmethods = IAX_AUTH_RSA;
9575 } else {
9576 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9579 ast_clear_flag(user, IAX_DELME);
9581 cleanup:
9582 if (oldha)
9583 ast_free_ha(oldha);
9584 if (oldcon)
9585 free_context(oldcon);
9586 return user;
9589 static int peer_delme_cb(void *obj, void *arg, int flags)
9591 struct iax2_peer *peer = obj;
9593 ast_set_flag(peer, IAX_DELME);
9595 return 0;
9598 static int user_delme_cb(void *obj, void *arg, int flags)
9600 struct iax2_user *user = obj;
9602 ast_set_flag(user, IAX_DELME);
9604 return 0;
9607 static void delete_users(void)
9609 struct iax2_registry *reg;
9611 ao2_callback(users, 0, user_delme_cb, NULL);
9613 AST_LIST_LOCK(&registrations);
9614 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
9615 ast_sched_del(sched, reg->expire);
9616 if (reg->callno) {
9617 ast_mutex_lock(&iaxsl[reg->callno]);
9618 if (iaxs[reg->callno]) {
9619 iaxs[reg->callno]->reg = NULL;
9620 iax2_destroy(reg->callno);
9622 ast_mutex_unlock(&iaxsl[reg->callno]);
9624 if (reg->dnsmgr)
9625 ast_dnsmgr_release(reg->dnsmgr);
9626 free(reg);
9628 AST_LIST_UNLOCK(&registrations);
9630 ao2_callback(peers, 0, peer_delme_cb, NULL);
9633 static void prune_users(void)
9635 struct iax2_user *user;
9636 struct ao2_iterator i;
9638 i = ao2_iterator_init(users, 0);
9639 while ((user = ao2_iterator_next(&i))) {
9640 if (ast_test_flag(user, IAX_DELME))
9641 ao2_unlink(users, user);
9642 user_unref(user);
9646 /* Prune peers who still are supposed to be deleted */
9647 static void prune_peers(void)
9649 struct iax2_peer *peer;
9650 struct ao2_iterator i;
9652 i = ao2_iterator_init(peers, 0);
9653 while ((peer = ao2_iterator_next(&i))) {
9654 if (ast_test_flag(peer, IAX_DELME))
9655 unlink_peer(peer);
9656 peer_unref(peer);
9660 static void set_timing(void)
9662 #ifdef HAVE_ZAPTEL
9663 int bs = trunkfreq * 8;
9664 if (timingfd > -1) {
9665 if (
9666 #ifdef ZT_TIMERACK
9667 ioctl(timingfd, ZT_TIMERCONFIG, &bs) &&
9668 #endif
9669 ioctl(timingfd, ZT_SET_BLOCKSIZE, &bs))
9670 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
9672 #endif
9675 static void set_config_destroy(void)
9677 strcpy(accountcode, "");
9678 strcpy(language, "");
9679 strcpy(mohinterpret, "default");
9680 strcpy(mohsuggest, "");
9681 amaflags = 0;
9682 delayreject = 0;
9683 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
9684 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9685 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
9686 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
9687 delete_users();
9690 /*! \brief Load configuration */
9691 static int set_config(char *config_file, int reload)
9693 struct ast_config *cfg, *ucfg;
9694 int capability=iax2_capability;
9695 struct ast_variable *v;
9696 char *cat;
9697 const char *utype;
9698 const char *tosval;
9699 int format;
9700 int portno = IAX_DEFAULT_PORTNO;
9701 int x;
9702 struct iax2_user *user;
9703 struct iax2_peer *peer;
9704 struct ast_netsock *ns;
9705 #if 0
9706 static unsigned short int last_port=0;
9707 #endif
9709 cfg = ast_config_load(config_file);
9711 if (!cfg) {
9712 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
9713 return -1;
9716 if (reload) {
9717 set_config_destroy();
9720 /* Reset global codec prefs */
9721 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
9723 /* Reset Global Flags */
9724 memset(&globalflags, 0, sizeof(globalflags));
9725 ast_set_flag(&globalflags, IAX_RTUPDATE);
9727 #ifdef SO_NO_CHECK
9728 nochecksums = 0;
9729 #endif
9731 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9732 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9734 maxauthreq = 3;
9736 v = ast_variable_browse(cfg, "general");
9738 /* Seed initial tos value */
9739 tosval = ast_variable_retrieve(cfg, "general", "tos");
9740 if (tosval) {
9741 if (ast_str2tos(tosval, &tos))
9742 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9744 while(v) {
9745 if (!strcasecmp(v->name, "bindport")){
9746 if (reload)
9747 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
9748 else
9749 portno = atoi(v->value);
9750 } else if (!strcasecmp(v->name, "pingtime"))
9751 ping_time = atoi(v->value);
9752 else if (!strcasecmp(v->name, "iaxthreadcount")) {
9753 if (reload) {
9754 if (atoi(v->value) != iaxthreadcount)
9755 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
9756 } else {
9757 iaxthreadcount = atoi(v->value);
9758 if (iaxthreadcount < 1) {
9759 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
9760 iaxthreadcount = 1;
9761 } else if (iaxthreadcount > 256) {
9762 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
9763 iaxthreadcount = 256;
9766 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
9767 if (reload) {
9768 AST_LIST_LOCK(&dynamic_list);
9769 iaxmaxthreadcount = atoi(v->value);
9770 AST_LIST_UNLOCK(&dynamic_list);
9771 } else {
9772 iaxmaxthreadcount = atoi(v->value);
9773 if (iaxmaxthreadcount < 0) {
9774 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
9775 iaxmaxthreadcount = 0;
9776 } else if (iaxmaxthreadcount > 256) {
9777 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
9778 iaxmaxthreadcount = 256;
9781 } else if (!strcasecmp(v->name, "nochecksums")) {
9782 #ifdef SO_NO_CHECK
9783 if (ast_true(v->value))
9784 nochecksums = 1;
9785 else
9786 nochecksums = 0;
9787 #else
9788 if (ast_true(v->value))
9789 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
9790 #endif
9792 else if (!strcasecmp(v->name, "maxjitterbuffer"))
9793 maxjitterbuffer = atoi(v->value);
9794 else if (!strcasecmp(v->name, "resyncthreshold"))
9795 resyncthreshold = atoi(v->value);
9796 else if (!strcasecmp(v->name, "maxjitterinterps"))
9797 maxjitterinterps = atoi(v->value);
9798 else if (!strcasecmp(v->name, "lagrqtime"))
9799 lagrq_time = atoi(v->value);
9800 else if (!strcasecmp(v->name, "maxregexpire"))
9801 max_reg_expire = atoi(v->value);
9802 else if (!strcasecmp(v->name, "minregexpire"))
9803 min_reg_expire = atoi(v->value);
9804 else if (!strcasecmp(v->name, "bindaddr")) {
9805 if (reload) {
9806 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
9807 } else {
9808 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, socket_read, NULL))) {
9809 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
9810 } else {
9811 if (option_verbose > 1) {
9812 if (strchr(v->value, ':'))
9813 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
9814 else
9815 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s:%d'\n", v->value, portno);
9817 if (defaultsockfd < 0)
9818 defaultsockfd = ast_netsock_sockfd(ns);
9819 ast_netsock_unref(ns);
9822 } else if (!strcasecmp(v->name, "authdebug"))
9823 authdebug = ast_true(v->value);
9824 else if (!strcasecmp(v->name, "encryption"))
9825 iax2_encryption = get_encrypt_methods(v->value);
9826 else if (!strcasecmp(v->name, "notransfer")) {
9827 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9828 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9829 ast_set2_flag((&globalflags), ast_true(v->value), IAX_NOTRANSFER);
9830 } else if (!strcasecmp(v->name, "transfer")) {
9831 if (!strcasecmp(v->value, "mediaonly")) {
9832 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9833 } else if (ast_true(v->value)) {
9834 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9835 } else
9836 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9837 } else if (!strcasecmp(v->name, "codecpriority")) {
9838 if(!strcasecmp(v->value, "caller"))
9839 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
9840 else if(!strcasecmp(v->value, "disabled"))
9841 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9842 else if(!strcasecmp(v->value, "reqonly")) {
9843 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
9844 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9846 } else if (!strcasecmp(v->name, "jitterbuffer"))
9847 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
9848 else if (!strcasecmp(v->name, "forcejitterbuffer"))
9849 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
9850 else if (!strcasecmp(v->name, "delayreject"))
9851 delayreject = ast_true(v->value);
9852 else if (!strcasecmp(v->name, "rtcachefriends"))
9853 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
9854 else if (!strcasecmp(v->name, "rtignoreregexpire"))
9855 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
9856 else if (!strcasecmp(v->name, "rtupdate"))
9857 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
9858 else if (!strcasecmp(v->name, "trunktimestamps"))
9859 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
9860 else if (!strcasecmp(v->name, "rtautoclear")) {
9861 int i = atoi(v->value);
9862 if(i > 0)
9863 global_rtautoclear = i;
9864 else
9865 i = 0;
9866 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
9867 } else if (!strcasecmp(v->name, "trunkfreq")) {
9868 trunkfreq = atoi(v->value);
9869 if (trunkfreq < 10)
9870 trunkfreq = 10;
9871 } else if (!strcasecmp(v->name, "autokill")) {
9872 if (sscanf(v->value, "%d", &x) == 1) {
9873 if (x >= 0)
9874 autokill = x;
9875 else
9876 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
9877 } else if (ast_true(v->value)) {
9878 autokill = DEFAULT_MAXMS;
9879 } else {
9880 autokill = 0;
9882 } else if (!strcasecmp(v->name, "bandwidth")) {
9883 if (!strcasecmp(v->value, "low")) {
9884 capability = IAX_CAPABILITY_LOWBANDWIDTH;
9885 } else if (!strcasecmp(v->value, "medium")) {
9886 capability = IAX_CAPABILITY_MEDBANDWIDTH;
9887 } else if (!strcasecmp(v->value, "high")) {
9888 capability = IAX_CAPABILITY_FULLBANDWIDTH;
9889 } else
9890 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
9891 } else if (!strcasecmp(v->name, "allow")) {
9892 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
9893 } else if (!strcasecmp(v->name, "disallow")) {
9894 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
9895 } else if (!strcasecmp(v->name, "register")) {
9896 iax2_register(v->value, v->lineno);
9897 } else if (!strcasecmp(v->name, "iaxcompat")) {
9898 iaxcompat = ast_true(v->value);
9899 } else if (!strcasecmp(v->name, "regcontext")) {
9900 ast_copy_string(regcontext, v->value, sizeof(regcontext));
9901 /* Create context if it doesn't exist already */
9902 if (!ast_context_find(regcontext))
9903 ast_context_create(NULL, regcontext, "IAX2");
9904 } else if (!strcasecmp(v->name, "tos")) {
9905 if (ast_str2tos(v->value, &tos))
9906 ast_log(LOG_WARNING, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v->lineno);
9907 } else if (!strcasecmp(v->name, "accountcode")) {
9908 ast_copy_string(accountcode, v->value, sizeof(accountcode));
9909 } else if (!strcasecmp(v->name, "mohinterpret")) {
9910 ast_copy_string(mohinterpret, v->value, sizeof(user->mohinterpret));
9911 } else if (!strcasecmp(v->name, "mohsuggest")) {
9912 ast_copy_string(mohsuggest, v->value, sizeof(user->mohsuggest));
9913 } else if (!strcasecmp(v->name, "amaflags")) {
9914 format = ast_cdr_amaflags2int(v->value);
9915 if (format < 0) {
9916 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9917 } else {
9918 amaflags = format;
9920 } else if (!strcasecmp(v->name, "language")) {
9921 ast_copy_string(language, v->value, sizeof(language));
9922 } else if (!strcasecmp(v->name, "maxauthreq")) {
9923 maxauthreq = atoi(v->value);
9924 if (maxauthreq < 0)
9925 maxauthreq = 0;
9926 } else if (!strcasecmp(v->name, "adsi")) {
9927 adsi = ast_true(v->value);
9928 } /*else if (strcasecmp(v->name,"type")) */
9929 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9930 v = v->next;
9933 if (defaultsockfd < 0) {
9934 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, socket_read, NULL))) {
9935 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
9936 } else {
9937 if (option_verbose > 1)
9938 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
9939 defaultsockfd = ast_netsock_sockfd(ns);
9940 ast_netsock_unref(ns);
9943 if (reload) {
9944 ast_netsock_release(outsock);
9945 outsock = ast_netsock_list_alloc();
9946 if (!outsock) {
9947 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
9948 return -1;
9950 ast_netsock_init(outsock);
9953 if (min_reg_expire > max_reg_expire) {
9954 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
9955 min_reg_expire, max_reg_expire, max_reg_expire);
9956 min_reg_expire = max_reg_expire;
9958 iax2_capability = capability;
9960 ucfg = ast_config_load("users.conf");
9961 if (ucfg) {
9962 struct ast_variable *gen;
9963 int genhasiax;
9964 int genregisteriax;
9965 const char *hasiax, *registeriax;
9967 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
9968 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
9969 gen = ast_variable_browse(ucfg, "general");
9970 cat = ast_category_browse(ucfg, NULL);
9971 while (cat) {
9972 if (strcasecmp(cat, "general")) {
9973 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
9974 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
9975 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
9976 /* Start with general parameters, then specific parameters, user and peer */
9977 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
9978 if (user) {
9979 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
9980 user = user_unref(user);
9982 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
9983 if (peer) {
9984 if (ast_test_flag(peer, IAX_DYNAMIC))
9985 reg_source_db(peer);
9986 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
9987 peer = peer_unref(peer);
9990 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
9991 char tmp[256];
9992 const char *host = ast_variable_retrieve(ucfg, cat, "host");
9993 const char *username = ast_variable_retrieve(ucfg, cat, "username");
9994 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
9995 if (!host)
9996 host = ast_variable_retrieve(ucfg, "general", "host");
9997 if (!username)
9998 username = ast_variable_retrieve(ucfg, "general", "username");
9999 if (!secret)
10000 secret = ast_variable_retrieve(ucfg, "general", "secret");
10001 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
10002 if (!ast_strlen_zero(secret))
10003 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
10004 else
10005 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
10006 iax2_register(tmp, 0);
10010 cat = ast_category_browse(ucfg, cat);
10012 ast_config_destroy(ucfg);
10015 cat = ast_category_browse(cfg, NULL);
10016 while(cat) {
10017 if (strcasecmp(cat, "general")) {
10018 utype = ast_variable_retrieve(cfg, cat, "type");
10019 if (utype) {
10020 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
10021 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
10022 if (user) {
10023 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10024 user = user_unref(user);
10027 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
10028 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
10029 if (peer) {
10030 if (ast_test_flag(peer, IAX_DYNAMIC))
10031 reg_source_db(peer);
10032 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10033 peer = peer_unref(peer);
10035 } else if (strcasecmp(utype, "user")) {
10036 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
10038 } else
10039 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10041 cat = ast_category_browse(cfg, cat);
10043 ast_config_destroy(cfg);
10044 set_timing();
10045 return 1;
10048 static void poke_all_peers(void)
10050 struct ao2_iterator i;
10051 struct iax2_peer *peer;
10053 i = ao2_iterator_init(peers, 0);
10054 while ((peer = ao2_iterator_next(&i))) {
10055 iax2_poke_peer(peer, 0);
10056 peer_unref(peer);
10059 static int reload_config(void)
10061 char *config = "iax.conf";
10062 struct iax2_registry *reg;
10064 if (set_config(config, 1) > 0) {
10065 prune_peers();
10066 prune_users();
10067 AST_LIST_LOCK(&registrations);
10068 AST_LIST_TRAVERSE(&registrations, reg, entry)
10069 iax2_do_register(reg);
10070 AST_LIST_UNLOCK(&registrations);
10071 /* Qualify hosts, too */
10072 poke_all_peers();
10074 reload_firmware(0);
10075 iax_provision_reload();
10077 return 0;
10080 static int iax2_reload(int fd, int argc, char *argv[])
10082 return reload_config();
10085 static int reload(void)
10087 return reload_config();
10090 static int cache_get_callno_locked(const char *data)
10092 struct sockaddr_in sin;
10093 int x;
10094 int callno;
10095 struct iax_ie_data ied;
10096 struct create_addr_info cai;
10097 struct parsed_dial_string pds;
10098 char *tmpstr;
10100 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10101 /* Look for an *exact match* call. Once a call is negotiated, it can only
10102 look up entries for a single context */
10103 if (!ast_mutex_trylock(&iaxsl[x])) {
10104 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
10105 return x;
10106 ast_mutex_unlock(&iaxsl[x]);
10110 /* No match found, we need to create a new one */
10112 memset(&cai, 0, sizeof(cai));
10113 memset(&ied, 0, sizeof(ied));
10114 memset(&pds, 0, sizeof(pds));
10116 tmpstr = ast_strdupa(data);
10117 parse_dial_string(tmpstr, &pds);
10119 if (ast_strlen_zero(pds.peer)) {
10120 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
10121 return -1;
10124 /* Populate our address from the given */
10125 if (create_addr(pds.peer, NULL, &sin, &cai))
10126 return -1;
10128 if (option_debug)
10129 ast_log(LOG_DEBUG, "peer: %s, username: %s, password: %s, context: %s\n",
10130 pds.peer, pds.username, pds.password, pds.context);
10132 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
10133 if (callno < 1) {
10134 ast_log(LOG_WARNING, "Unable to create call\n");
10135 return -1;
10138 ast_string_field_set(iaxs[callno], dproot, data);
10139 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
10141 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
10142 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
10143 /* the string format is slightly different from a standard dial string,
10144 because the context appears in the 'exten' position
10146 if (pds.exten)
10147 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10148 if (pds.username)
10149 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
10150 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
10151 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
10152 /* Keep password handy */
10153 if (pds.password)
10154 ast_string_field_set(iaxs[callno], secret, pds.password);
10155 if (pds.key)
10156 ast_string_field_set(iaxs[callno], outkey, pds.key);
10157 /* Start the call going */
10158 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
10160 return callno;
10163 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
10165 struct iax2_dpcache *dp, *prev = NULL, *next;
10166 struct timeval tv;
10167 int x;
10168 int com[2];
10169 int timeout;
10170 int old=0;
10171 int outfd;
10172 int abort;
10173 int callno;
10174 struct ast_channel *c;
10175 struct ast_frame *f;
10176 gettimeofday(&tv, NULL);
10177 dp = dpcache;
10178 while(dp) {
10179 next = dp->next;
10180 /* Expire old caches */
10181 if (ast_tvcmp(tv, dp->expiry) > 0) {
10182 /* It's expired, let it disappear */
10183 if (prev)
10184 prev->next = dp->next;
10185 else
10186 dpcache = dp->next;
10187 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10188 /* Free memory and go again */
10189 free(dp);
10190 } else {
10191 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = %p callno = %d)\n", dp->flags, dp->peer, dp->callno);
10193 dp = next;
10194 continue;
10196 /* We found an entry that matches us! */
10197 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10198 break;
10199 prev = dp;
10200 dp = next;
10202 if (!dp) {
10203 /* No matching entry. Create a new one. */
10204 /* First, can we make a callno? */
10205 callno = cache_get_callno_locked(data);
10206 if (callno < 0) {
10207 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10208 return NULL;
10210 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10211 ast_mutex_unlock(&iaxsl[callno]);
10212 return NULL;
10214 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
10215 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
10216 gettimeofday(&dp->expiry, NULL);
10217 dp->orig = dp->expiry;
10218 /* Expires in 30 mins by default */
10219 dp->expiry.tv_sec += iaxdefaultdpcache;
10220 dp->next = dpcache;
10221 dp->flags = CACHE_FLAG_PENDING;
10222 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10223 dp->waiters[x] = -1;
10224 dpcache = dp;
10225 dp->peer = iaxs[callno]->dpentries;
10226 iaxs[callno]->dpentries = dp;
10227 /* Send the request if we're already up */
10228 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
10229 iax2_dprequest(dp, callno);
10230 ast_mutex_unlock(&iaxsl[callno]);
10232 /* By here we must have a dp */
10233 if (dp->flags & CACHE_FLAG_PENDING) {
10234 /* Okay, here it starts to get nasty. We need a pipe now to wait
10235 for a reply to come back so long as it's pending */
10236 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
10237 /* Find an empty slot */
10238 if (dp->waiters[x] < 0)
10239 break;
10241 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10242 ast_log(LOG_WARNING, "No more waiter positions available\n");
10243 return NULL;
10245 if (pipe(com)) {
10246 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10247 return NULL;
10249 dp->waiters[x] = com[1];
10250 /* Okay, now we wait */
10251 timeout = iaxdefaulttimeout * 1000;
10252 /* Temporarily unlock */
10253 ast_mutex_unlock(&dpcache_lock);
10254 /* Defer any dtmf */
10255 if (chan)
10256 old = ast_channel_defer_dtmf(chan);
10257 abort = 0;
10258 while(timeout) {
10259 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10260 if (outfd > -1) {
10261 break;
10263 if (c) {
10264 f = ast_read(c);
10265 if (f)
10266 ast_frfree(f);
10267 else {
10268 /* Got hung up on, abort! */
10269 break;
10270 abort = 1;
10274 if (!timeout) {
10275 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
10277 ast_mutex_lock(&dpcache_lock);
10278 dp->waiters[x] = -1;
10279 close(com[1]);
10280 close(com[0]);
10281 if (abort) {
10282 /* Don't interpret anything, just abort. Not sure what th epoint
10283 of undeferring dtmf on a hung up channel is but hey whatever */
10284 if (!old && chan)
10285 ast_channel_undefer_dtmf(chan);
10286 return NULL;
10288 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
10289 /* Now to do non-independent analysis the results of our wait */
10290 if (dp->flags & CACHE_FLAG_PENDING) {
10291 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10292 pending. Don't let it take as long to timeout. */
10293 dp->flags &= ~CACHE_FLAG_PENDING;
10294 dp->flags |= CACHE_FLAG_TIMEOUT;
10295 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10296 systems without leaving it unavailable once the server comes back online */
10297 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
10298 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10299 if (dp->waiters[x] > -1)
10300 write(dp->waiters[x], "asdf", 4);
10303 /* Our caller will obtain the rest */
10304 if (!old && chan)
10305 ast_channel_undefer_dtmf(chan);
10307 return dp;
10310 /*! \brief Part of the IAX2 switch interface */
10311 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10313 struct iax2_dpcache *dp;
10314 int res = 0;
10315 #if 0
10316 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10317 #endif
10318 if ((priority != 1) && (priority != 2))
10319 return 0;
10320 ast_mutex_lock(&dpcache_lock);
10321 dp = find_cache(chan, data, context, exten, priority);
10322 if (dp) {
10323 if (dp->flags & CACHE_FLAG_EXISTS)
10324 res= 1;
10326 ast_mutex_unlock(&dpcache_lock);
10327 if (!dp) {
10328 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10330 return res;
10333 /*! \brief part of the IAX2 dial plan switch interface */
10334 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10336 int res = 0;
10337 struct iax2_dpcache *dp;
10338 #if 0
10339 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10340 #endif
10341 if ((priority != 1) && (priority != 2))
10342 return 0;
10343 ast_mutex_lock(&dpcache_lock);
10344 dp = find_cache(chan, data, context, exten, priority);
10345 if (dp) {
10346 if (dp->flags & CACHE_FLAG_CANEXIST)
10347 res= 1;
10349 ast_mutex_unlock(&dpcache_lock);
10350 if (!dp) {
10351 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10353 return res;
10356 /*! \brief Part of the IAX2 Switch interface */
10357 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10359 int res = 0;
10360 struct iax2_dpcache *dp;
10361 #if 0
10362 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10363 #endif
10364 if ((priority != 1) && (priority != 2))
10365 return 0;
10366 ast_mutex_lock(&dpcache_lock);
10367 dp = find_cache(chan, data, context, exten, priority);
10368 if (dp) {
10369 if (dp->flags & CACHE_FLAG_MATCHMORE)
10370 res= 1;
10372 ast_mutex_unlock(&dpcache_lock);
10373 if (!dp) {
10374 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10376 return res;
10379 /*! \brief Execute IAX2 dialplan switch */
10380 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10382 char odata[256];
10383 char req[256];
10384 char *ncontext;
10385 struct iax2_dpcache *dp;
10386 struct ast_app *dial;
10387 #if 0
10388 ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
10389 #endif
10390 if (priority == 2) {
10391 /* Indicate status, can be overridden in dialplan */
10392 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10393 if (dialstatus) {
10394 dial = pbx_findapp(dialstatus);
10395 if (dial)
10396 pbx_exec(chan, dial, "");
10398 return -1;
10399 } else if (priority != 1)
10400 return -1;
10401 ast_mutex_lock(&dpcache_lock);
10402 dp = find_cache(chan, data, context, exten, priority);
10403 if (dp) {
10404 if (dp->flags & CACHE_FLAG_EXISTS) {
10405 ast_copy_string(odata, data, sizeof(odata));
10406 ncontext = strchr(odata, '/');
10407 if (ncontext) {
10408 *ncontext = '\0';
10409 ncontext++;
10410 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10411 } else {
10412 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
10414 if (option_verbose > 2)
10415 ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
10416 } else {
10417 ast_mutex_unlock(&dpcache_lock);
10418 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
10419 return -1;
10422 ast_mutex_unlock(&dpcache_lock);
10423 dial = pbx_findapp("Dial");
10424 if (dial) {
10425 return pbx_exec(chan, dial, req);
10426 } else {
10427 ast_log(LOG_WARNING, "No dial application registered\n");
10429 return -1;
10432 static int function_iaxpeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10434 struct iax2_peer *peer;
10435 char *peername, *colname;
10437 peername = ast_strdupa(data);
10439 /* if our channel, return the IP address of the endpoint of current channel */
10440 if (!strcmp(peername,"CURRENTCHANNEL")) {
10441 unsigned short callno;
10442 if (chan->tech != &iax2_tech)
10443 return -1;
10444 callno = PTR_TO_CALLNO(chan->tech_pvt);
10445 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
10446 return 0;
10449 if ((colname = strchr(peername, ':'))) /*! \todo : will be removed after the 1.4 relese */
10450 *colname++ = '\0';
10451 else if ((colname = strchr(peername, '|')))
10452 *colname++ = '\0';
10453 else
10454 colname = "ip";
10456 if (!(peer = find_peer(peername, 1)))
10457 return -1;
10459 if (!strcasecmp(colname, "ip")) {
10460 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10461 } else if (!strcasecmp(colname, "status")) {
10462 peer_status(peer, buf, len);
10463 } else if (!strcasecmp(colname, "mailbox")) {
10464 ast_copy_string(buf, peer->mailbox, len);
10465 } else if (!strcasecmp(colname, "context")) {
10466 ast_copy_string(buf, peer->context, len);
10467 } else if (!strcasecmp(colname, "expire")) {
10468 snprintf(buf, len, "%d", peer->expire);
10469 } else if (!strcasecmp(colname, "dynamic")) {
10470 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
10471 } else if (!strcasecmp(colname, "callerid_name")) {
10472 ast_copy_string(buf, peer->cid_name, len);
10473 } else if (!strcasecmp(colname, "callerid_num")) {
10474 ast_copy_string(buf, peer->cid_num, len);
10475 } else if (!strcasecmp(colname, "codecs")) {
10476 ast_getformatname_multiple(buf, len -1, peer->capability);
10477 } else if (!strncasecmp(colname, "codec[", 6)) {
10478 char *codecnum, *ptr;
10479 int index = 0, codec = 0;
10481 codecnum = strchr(colname, '[');
10482 *codecnum = '\0';
10483 codecnum++;
10484 if ((ptr = strchr(codecnum, ']'))) {
10485 *ptr = '\0';
10487 index = atoi(codecnum);
10488 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10489 ast_copy_string(buf, ast_getformatname(codec), len);
10493 peer_unref(peer);
10495 return 0;
10498 struct ast_custom_function iaxpeer_function = {
10499 .name = "IAXPEER",
10500 .synopsis = "Gets IAX peer information",
10501 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10502 .read = function_iaxpeer,
10503 .desc = "If peername specified, valid items are:\n"
10504 "- ip (default) The IP address.\n"
10505 "- status The peer's status (if qualify=yes)\n"
10506 "- mailbox The configured mailbox.\n"
10507 "- context The configured context.\n"
10508 "- expire The epoch time of the next expire.\n"
10509 "- dynamic Is it dynamic? (yes/no).\n"
10510 "- callerid_name The configured Caller ID name.\n"
10511 "- callerid_num The configured Caller ID number.\n"
10512 "- codecs The configured codecs.\n"
10513 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10514 "\n"
10515 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10516 "\n"
10520 /*! \brief Part of the device state notification system ---*/
10521 static int iax2_devicestate(void *data)
10523 struct parsed_dial_string pds;
10524 char *tmp = ast_strdupa(data);
10525 struct iax2_peer *p;
10526 int res = AST_DEVICE_INVALID;
10528 memset(&pds, 0, sizeof(pds));
10529 parse_dial_string(tmp, &pds);
10531 if (ast_strlen_zero(pds.peer)) {
10532 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10533 return res;
10536 if (option_debug > 2)
10537 ast_log(LOG_DEBUG, "Checking device state for device %s\n", pds.peer);
10539 /* SLD: FIXME: second call to find_peer during registration */
10540 if (!(p = find_peer(pds.peer, 1)))
10541 return res;
10543 res = AST_DEVICE_UNAVAILABLE;
10544 if (option_debug > 2)
10545 ast_log(LOG_DEBUG, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10546 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
10548 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
10549 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
10550 /* Peer is registered, or have default IP address
10551 and a valid registration */
10552 if (p->historicms == 0 || p->historicms <= p->maxms)
10553 /* let the core figure out whether it is in use or not */
10554 res = AST_DEVICE_UNKNOWN;
10557 peer_unref(p);
10559 return res;
10562 static struct ast_switch iax2_switch =
10564 name: "IAX2",
10565 description: "IAX Remote Dialplan Switch",
10566 exists: iax2_exists,
10567 canmatch: iax2_canmatch,
10568 exec: iax2_exec,
10569 matchmore: iax2_matchmore,
10572 static char show_stats_usage[] =
10573 "Usage: iax2 show stats\n"
10574 " Display statistics on IAX channel driver.\n";
10576 static char show_cache_usage[] =
10577 "Usage: iax2 show cache\n"
10578 " Display currently cached IAX Dialplan results.\n";
10580 static char show_peer_usage[] =
10581 "Usage: iax2 show peer <name>\n"
10582 " Display details on specific IAX peer\n";
10584 static char prune_realtime_usage[] =
10585 "Usage: iax2 prune realtime [<peername>|all]\n"
10586 " Prunes object(s) from the cache\n";
10588 static char iax2_reload_usage[] =
10589 "Usage: iax2 reload\n"
10590 " Reloads IAX configuration from iax.conf\n";
10592 static char show_prov_usage[] =
10593 "Usage: iax2 provision <host> <template> [forced]\n"
10594 " Provisions the given peer or IP address using a template\n"
10595 " matching either 'template' or '*' if the template is not\n"
10596 " found. If 'forced' is specified, even empty provisioning\n"
10597 " fields will be provisioned as empty fields.\n";
10599 static char show_users_usage[] =
10600 "Usage: iax2 show users [like <pattern>]\n"
10601 " Lists all known IAX2 users.\n"
10602 " Optional regular expression pattern is used to filter the user list.\n";
10604 static char show_channels_usage[] =
10605 "Usage: iax2 show channels\n"
10606 " Lists all currently active IAX channels.\n";
10608 static char show_netstats_usage[] =
10609 "Usage: iax2 show netstats\n"
10610 " Lists network status for all currently active IAX channels.\n";
10612 static char show_threads_usage[] =
10613 "Usage: iax2 show threads\n"
10614 " Lists status of IAX helper threads\n";
10616 static char show_peers_usage[] =
10617 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10618 " Lists all known IAX2 peers.\n"
10619 " Optional 'registered' argument lists only peers with known addresses.\n"
10620 " Optional regular expression pattern is used to filter the peer list.\n";
10622 static char show_firmware_usage[] =
10623 "Usage: iax2 show firmware\n"
10624 " Lists all known IAX firmware images.\n";
10626 static char show_reg_usage[] =
10627 "Usage: iax2 show registry\n"
10628 " Lists all registration requests and status.\n";
10630 static char debug_usage[] =
10631 "Usage: iax2 set debug\n"
10632 " Enables dumping of IAX packets for debugging purposes\n";
10634 static char no_debug_usage[] =
10635 "Usage: iax2 set debug off\n"
10636 " Disables dumping of IAX packets for debugging purposes\n";
10638 static char debug_trunk_usage[] =
10639 "Usage: iax2 set debug trunk\n"
10640 " Requests current status of IAX trunking\n";
10642 static char no_debug_trunk_usage[] =
10643 "Usage: iax2 set debug trunk off\n"
10644 " Requests current status of IAX trunking\n";
10646 static char debug_jb_usage[] =
10647 "Usage: iax2 set debug jb\n"
10648 " Enables jitterbuffer debugging information\n";
10650 static char no_debug_jb_usage[] =
10651 "Usage: iax2 set debug jb off\n"
10652 " Disables jitterbuffer debugging information\n";
10654 static char iax2_test_losspct_usage[] =
10655 "Usage: iax2 test losspct <percentage>\n"
10656 " For testing, throws away <percentage> percent of incoming packets\n";
10658 #ifdef IAXTESTS
10659 static char iax2_test_late_usage[] =
10660 "Usage: iax2 test late <ms>\n"
10661 " For testing, count the next frame as <ms> ms late\n";
10663 static char iax2_test_resync_usage[] =
10664 "Usage: iax2 test resync <ms>\n"
10665 " For testing, adjust all future frames by <ms> ms\n";
10667 static char iax2_test_jitter_usage[] =
10668 "Usage: iax2 test jitter <ms> <pct>\n"
10669 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10670 #endif /* IAXTESTS */
10672 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated = {
10673 { "iax2", "trunk", "debug", NULL },
10674 iax2_do_trunk_debug, NULL,
10675 NULL };
10677 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10678 { "iax2", "jb", "debug", NULL },
10679 iax2_do_jb_debug, NULL,
10680 NULL };
10682 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10683 { "iax2", "no", "debug", NULL },
10684 iax2_no_debug, NULL,
10685 NULL };
10687 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated = {
10688 { "iax2", "no", "trunk", "debug", NULL },
10689 iax2_no_trunk_debug, NULL,
10690 NULL };
10692 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated = {
10693 { "iax2", "no", "jb", "debug", NULL },
10694 iax2_no_jb_debug, NULL,
10695 NULL };
10697 static struct ast_cli_entry cli_iax2[] = {
10698 { { "iax2", "show", "cache", NULL },
10699 iax2_show_cache, "Display IAX cached dialplan",
10700 show_cache_usage, NULL, },
10702 { { "iax2", "show", "channels", NULL },
10703 iax2_show_channels, "List active IAX channels",
10704 show_channels_usage, NULL, },
10706 { { "iax2", "show", "firmware", NULL },
10707 iax2_show_firmware, "List available IAX firmwares",
10708 show_firmware_usage, NULL, },
10710 { { "iax2", "show", "netstats", NULL },
10711 iax2_show_netstats, "List active IAX channel netstats",
10712 show_netstats_usage, NULL, },
10714 { { "iax2", "show", "peers", NULL },
10715 iax2_show_peers, "List defined IAX peers",
10716 show_peers_usage, NULL, },
10718 { { "iax2", "show", "registry", NULL },
10719 iax2_show_registry, "Display IAX registration status",
10720 show_reg_usage, NULL, },
10722 { { "iax2", "show", "stats", NULL },
10723 iax2_show_stats, "Display IAX statistics",
10724 show_stats_usage, NULL, },
10726 { { "iax2", "show", "threads", NULL },
10727 iax2_show_threads, "Display IAX helper thread info",
10728 show_threads_usage, NULL, },
10730 { { "iax2", "show", "users", NULL },
10731 iax2_show_users, "List defined IAX users",
10732 show_users_usage, NULL, },
10734 { { "iax2", "prune", "realtime", NULL },
10735 iax2_prune_realtime, "Prune a cached realtime lookup",
10736 prune_realtime_usage, complete_iax2_show_peer },
10738 { { "iax2", "reload", NULL },
10739 iax2_reload, "Reload IAX configuration",
10740 iax2_reload_usage },
10742 { { "iax2", "show", "peer", NULL },
10743 iax2_show_peer, "Show details on specific IAX peer",
10744 show_peer_usage, complete_iax2_show_peer },
10746 { { "iax2", "set", "debug", NULL },
10747 iax2_do_debug, "Enable IAX debugging",
10748 debug_usage },
10750 { { "iax2", "set", "debug", "trunk", NULL },
10751 iax2_do_trunk_debug, "Enable IAX trunk debugging",
10752 debug_trunk_usage, NULL, &cli_iax2_trunk_debug_deprecated },
10754 { { "iax2", "set", "debug", "jb", NULL },
10755 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
10756 debug_jb_usage, NULL, &cli_iax2_jb_debug_deprecated },
10758 { { "iax2", "set", "debug", "off", NULL },
10759 iax2_no_debug, "Disable IAX debugging",
10760 no_debug_usage, NULL, &cli_iax2_no_debug_deprecated },
10762 { { "iax2", "set", "debug", "trunk", "off", NULL },
10763 iax2_no_trunk_debug, "Disable IAX trunk debugging",
10764 no_debug_trunk_usage, NULL, &cli_iax2_no_trunk_debug_deprecated },
10766 { { "iax2", "set", "debug", "jb", "off", NULL },
10767 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
10768 no_debug_jb_usage, NULL, &cli_iax2_no_jb_debug_deprecated },
10770 { { "iax2", "test", "losspct", NULL },
10771 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
10772 iax2_test_losspct_usage },
10774 { { "iax2", "provision", NULL },
10775 iax2_prov_cmd, "Provision an IAX device",
10776 show_prov_usage, iax2_prov_complete_template_3rd },
10778 #ifdef IAXTESTS
10779 { { "iax2", "test", "late", NULL },
10780 iax2_test_late, "Test the receipt of a late frame",
10781 iax2_test_late_usage },
10783 { { "iax2", "test", "resync", NULL },
10784 iax2_test_resync, "Test a resync in received timestamps",
10785 iax2_test_resync_usage },
10787 { { "iax2", "test", "jitter", NULL },
10788 iax2_test_jitter, "Simulates jitter for testing",
10789 iax2_test_jitter_usage },
10790 #endif /* IAXTESTS */
10793 static int __unload_module(void)
10795 struct iax2_thread *thread = NULL;
10796 int x;
10798 /* Make sure threads do not hold shared resources when they are canceled */
10800 /* Grab the sched lock resource to keep it away from threads about to die */
10801 /* Cancel the network thread, close the net socket */
10802 if (netthreadid != AST_PTHREADT_NULL) {
10803 AST_LIST_LOCK(&iaxq.queue);
10804 ast_mutex_lock(&sched_lock);
10805 pthread_cancel(netthreadid);
10806 ast_cond_signal(&sched_cond);
10807 ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
10808 AST_LIST_UNLOCK(&iaxq.queue);
10809 pthread_join(netthreadid, NULL);
10811 if (schedthreadid != AST_PTHREADT_NULL) {
10812 ast_mutex_lock(&sched_lock);
10813 pthread_cancel(schedthreadid);
10814 ast_cond_signal(&sched_cond);
10815 ast_mutex_unlock(&sched_lock);
10816 pthread_join(schedthreadid, NULL);
10819 /* Call for all threads to halt */
10820 AST_LIST_LOCK(&idle_list);
10821 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list, thread, list) {
10822 AST_LIST_REMOVE_CURRENT(&idle_list, list);
10823 pthread_cancel(thread->threadid);
10825 AST_LIST_TRAVERSE_SAFE_END
10826 AST_LIST_UNLOCK(&idle_list);
10828 AST_LIST_LOCK(&active_list);
10829 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list, thread, list) {
10830 AST_LIST_REMOVE_CURRENT(&active_list, list);
10831 pthread_cancel(thread->threadid);
10833 AST_LIST_TRAVERSE_SAFE_END
10834 AST_LIST_UNLOCK(&active_list);
10836 AST_LIST_LOCK(&dynamic_list);
10837 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list, thread, list) {
10838 AST_LIST_REMOVE_CURRENT(&dynamic_list, list);
10839 pthread_cancel(thread->threadid);
10841 AST_LIST_TRAVERSE_SAFE_END
10842 AST_LIST_UNLOCK(&dynamic_list);
10844 AST_LIST_HEAD_DESTROY(&iaxq.queue);
10846 /* Wait for threads to exit */
10847 while(0 < iaxactivethreadcount)
10848 usleep(10000);
10850 ast_netsock_release(netsock);
10851 ast_netsock_release(outsock);
10852 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10853 if (iaxs[x]) {
10854 iax2_destroy(x);
10857 ast_manager_unregister( "IAXpeers" );
10858 ast_manager_unregister( "IAXnetstats" );
10859 ast_unregister_application(papp);
10860 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10861 ast_unregister_switch(&iax2_switch);
10862 ast_channel_unregister(&iax2_tech);
10863 delete_users();
10864 iax_provision_unload();
10865 sched_context_destroy(sched);
10866 reload_firmware(1);
10868 ast_mutex_destroy(&waresl.lock);
10870 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
10871 ast_mutex_destroy(&iaxsl[x]);
10874 ao2_ref(peers, -1);
10875 ao2_ref(users, -1);
10877 return 0;
10880 static int unload_module(void)
10882 ast_custom_function_unregister(&iaxpeer_function);
10883 return __unload_module();
10886 static int peer_set_sock_cb(void *obj, void *arg, int flags)
10888 struct iax2_peer *peer = obj;
10890 if (peer->sockfd < 0)
10891 peer->sockfd = defaultsockfd;
10893 return 0;
10896 /*! \brief Load IAX2 module, load configuraiton ---*/
10897 static int load_module(void)
10899 char *config = "iax.conf";
10900 int res = 0;
10901 int x;
10902 struct iax2_registry *reg = NULL;
10904 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
10905 if (!peers)
10906 return AST_MODULE_LOAD_FAILURE;
10907 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
10908 if (!users) {
10909 ao2_ref(peers, -1);
10910 return AST_MODULE_LOAD_FAILURE;
10913 ast_custom_function_register(&iaxpeer_function);
10915 iax_set_output(iax_debug_output);
10916 iax_set_error(iax_error_output);
10917 jb_setoutput(jb_error_output, jb_warning_output, NULL);
10919 #ifdef HAVE_ZAPTEL
10920 #ifdef ZT_TIMERACK
10921 timingfd = open("/dev/zap/timer", O_RDWR);
10922 if (timingfd < 0)
10923 #endif
10924 timingfd = open("/dev/zap/pseudo", O_RDWR);
10925 if (timingfd < 0)
10926 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
10927 #endif
10929 memset(iaxs, 0, sizeof(iaxs));
10931 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
10932 ast_mutex_init(&iaxsl[x]);
10935 ast_cond_init(&sched_cond, NULL);
10937 io = io_context_create();
10938 sched = sched_context_create();
10940 if (!io || !sched) {
10941 ast_log(LOG_ERROR, "Out of memory\n");
10942 return -1;
10945 netsock = ast_netsock_list_alloc();
10946 if (!netsock) {
10947 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
10948 return -1;
10950 ast_netsock_init(netsock);
10952 outsock = ast_netsock_list_alloc();
10953 if (!outsock) {
10954 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10955 return -1;
10957 ast_netsock_init(outsock);
10959 ast_mutex_init(&waresl.lock);
10961 AST_LIST_HEAD_INIT(&iaxq.queue);
10963 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10965 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
10967 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
10968 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats, "Show IAX Netstats" );
10970 if(set_config(config, 0) == -1)
10971 return AST_MODULE_LOAD_DECLINE;
10973 if (ast_channel_register(&iax2_tech)) {
10974 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
10975 __unload_module();
10976 return -1;
10979 if (ast_register_switch(&iax2_switch))
10980 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
10982 res = start_network_thread();
10983 if (!res) {
10984 if (option_verbose > 1)
10985 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
10986 } else {
10987 ast_log(LOG_ERROR, "Unable to start network thread\n");
10988 ast_netsock_release(netsock);
10989 ast_netsock_release(outsock);
10992 AST_LIST_LOCK(&registrations);
10993 AST_LIST_TRAVERSE(&registrations, reg, entry)
10994 iax2_do_register(reg);
10995 AST_LIST_UNLOCK(&registrations);
10997 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
10998 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
11000 reload_firmware(0);
11001 iax_provision_reload();
11002 return res;
11005 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
11006 .load = load_module,
11007 .unload = unload_module,
11008 .reload = reload,