Remove debug output.
[asterisk-bristuff.git] / channels / chan_iax2.c
blobdc65b11f09580969946c849f5fe781a230c4d38c
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)];
813 * \brief Another container of iax2_pvt structures
815 * Active IAX2 pvt structs are also stored in this container, if they are a part
816 * of an active call where we know the remote side's call number. The reason
817 * for this is that incoming media frames do not contain our call number. So,
818 * instead of having to iterate the entire iaxs array, we use this container to
819 * look up calls where the remote side is using a given call number.
821 static struct ao2_container *iax_peercallno_pvts;
823 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
824 but keeps the division between trunked and non-trunked better. */
825 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
827 static int maxtrunkcall = TRUNK_CALL_START;
828 static int maxnontrunkcall = 1;
830 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);
831 static int expire_registry(const void *data);
832 static int iax2_answer(struct ast_channel *c);
833 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
834 static int iax2_devicestate(void *data);
835 static int iax2_digit_begin(struct ast_channel *c, char digit);
836 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
837 static int iax2_do_register(struct iax2_registry *reg);
838 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
839 static int iax2_hangup(struct ast_channel *c);
840 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
841 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
842 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
843 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
844 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
845 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
846 static int iax2_sendtext(struct ast_channel *c, const char *text);
847 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
848 static int iax2_transfer(struct ast_channel *c, const char *dest);
849 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
850 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
851 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
852 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
853 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
854 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
855 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
856 static struct ast_frame *iax2_read(struct ast_channel *c);
857 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
858 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
859 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
860 static void prune_peers(void);
862 static const struct ast_channel_tech iax2_tech = {
863 .type = "IAX2",
864 .description = tdesc,
865 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
866 .properties = AST_CHAN_TP_WANTSJITTER,
867 .requester = iax2_request,
868 .devicestate = iax2_devicestate,
869 .send_digit_begin = iax2_digit_begin,
870 .send_digit_end = iax2_digit_end,
871 .send_text = iax2_sendtext,
872 .send_image = iax2_sendimage,
873 .send_html = iax2_sendhtml,
874 .call = iax2_call,
875 .hangup = iax2_hangup,
876 .answer = iax2_answer,
877 .read = iax2_read,
878 .write = iax2_write,
879 .write_video = iax2_write,
880 .indicate = iax2_indicate,
881 .setoption = iax2_setoption,
882 .bridge = iax2_bridge,
883 .transfer = iax2_transfer,
884 .fixup = iax2_fixup,
887 /* WARNING: insert_idle_thread should only ever be called within the
888 * context of an iax2_process_thread() thread.
890 static void insert_idle_thread(struct iax2_thread *thread)
892 if (thread->type == IAX_TYPE_DYNAMIC) {
893 AST_LIST_LOCK(&dynamic_list);
894 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
895 AST_LIST_UNLOCK(&dynamic_list);
896 } else {
897 AST_LIST_LOCK(&idle_list);
898 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
899 AST_LIST_UNLOCK(&idle_list);
902 return;
905 static struct iax2_thread *find_idle_thread(void)
907 pthread_attr_t attr;
908 struct iax2_thread *thread = NULL;
910 /* Pop the head of the list off */
911 AST_LIST_LOCK(&idle_list);
912 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
913 AST_LIST_UNLOCK(&idle_list);
915 /* If no idle thread is available from the regular list, try dynamic */
916 if (thread == NULL) {
917 AST_LIST_LOCK(&dynamic_list);
918 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
919 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
920 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
921 /* We need to MAKE a thread! */
922 if ((thread = ast_calloc(1, sizeof(*thread)))) {
923 thread->threadnum = iaxdynamicthreadcount;
924 thread->type = IAX_TYPE_DYNAMIC;
925 ast_mutex_init(&thread->lock);
926 ast_cond_init(&thread->cond, NULL);
927 pthread_attr_init(&attr);
928 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
929 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
930 free(thread);
931 thread = NULL;
932 } else {
933 /* All went well and the thread is up, so increment our count */
934 iaxdynamicthreadcount++;
936 /* Wait for the thread to be ready before returning it to the caller */
937 while (!thread->ready_for_signal)
938 usleep(1);
942 AST_LIST_UNLOCK(&dynamic_list);
945 /* this thread is not processing a full frame (since it is idle),
946 so ensure that the field for the full frame call number is empty */
947 if (thread)
948 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
950 return thread;
953 #ifdef SCHED_MULTITHREADED
954 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
956 struct iax2_thread *thread = NULL;
957 static time_t lasterror;
958 static time_t t;
960 thread = find_idle_thread();
962 if (thread != NULL) {
963 thread->schedfunc = func;
964 thread->scheddata = data;
965 thread->iostate = IAX_IOSTATE_SCHEDREADY;
966 #ifdef DEBUG_SCHED_MULTITHREAD
967 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
968 #endif
969 signal_condition(&thread->lock, &thread->cond);
970 return 0;
972 time(&t);
973 if (t != lasterror && option_debug)
974 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for scheduling!\n");
975 lasterror = t;
977 return -1;
979 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
980 #endif
982 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
984 int res;
986 res = ast_sched_add(con, when, callback, data);
987 signal_condition(&sched_lock, &sched_cond);
989 return res;
992 static int send_ping(const void *data);
994 static void __send_ping(const void *data)
996 int callno = (long)data;
997 ast_mutex_lock(&iaxsl[callno]);
998 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
999 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1000 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1002 ast_mutex_unlock(&iaxsl[callno]);
1005 static int send_ping(const void *data)
1007 #ifdef SCHED_MULTITHREADED
1008 if (schedule_action(__send_ping, data))
1009 #endif
1010 __send_ping(data);
1011 return 0;
1014 static int get_encrypt_methods(const char *s)
1016 int e;
1017 if (!strcasecmp(s, "aes128"))
1018 e = IAX_ENCRYPT_AES128;
1019 else if (ast_true(s))
1020 e = IAX_ENCRYPT_AES128;
1021 else
1022 e = 0;
1023 return e;
1026 static int send_lagrq(const void *data);
1028 static void __send_lagrq(const void *data)
1030 int callno = (long)data;
1031 /* Ping only if it's real not if it's bridged */
1032 ast_mutex_lock(&iaxsl[callno]);
1033 if (iaxs[callno] && iaxs[callno]->lagid > -1) {
1034 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1035 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1037 ast_mutex_unlock(&iaxsl[callno]);
1040 static int send_lagrq(const void *data)
1042 #ifdef SCHED_MULTITHREADED
1043 if (schedule_action(__send_lagrq, data))
1044 #endif
1045 __send_lagrq(data);
1046 return 0;
1049 static unsigned char compress_subclass(int subclass)
1051 int x;
1052 int power=-1;
1053 /* If it's 128 or smaller, just return it */
1054 if (subclass < IAX_FLAG_SC_LOG)
1055 return subclass;
1056 /* Otherwise find its power */
1057 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1058 if (subclass & (1 << x)) {
1059 if (power > -1) {
1060 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1061 return 0;
1062 } else
1063 power = x;
1066 return power | IAX_FLAG_SC_LOG;
1069 static int uncompress_subclass(unsigned char csub)
1071 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1072 if (csub & IAX_FLAG_SC_LOG) {
1073 /* special case for 'compressed' -1 */
1074 if (csub == 0xff)
1075 return -1;
1076 else
1077 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1079 else
1080 return csub;
1084 * \note The only member of the peer passed here guaranteed to be set is the name field
1086 static int peer_hash_cb(const void *obj, const int flags)
1088 const struct iax2_peer *peer = obj;
1090 return ast_str_hash(peer->name);
1094 * \note The only member of the peer passed here guaranteed to be set is the name field
1096 static int peer_cmp_cb(void *obj, void *arg, int flags)
1098 struct iax2_peer *peer = obj, *peer2 = arg;
1100 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1104 * \note The only member of the user passed here guaranteed to be set is the name field
1106 static int user_hash_cb(const void *obj, const int flags)
1108 const struct iax2_user *user = obj;
1110 return ast_str_hash(user->name);
1114 * \note The only member of the user passed here guaranteed to be set is the name field
1116 static int user_cmp_cb(void *obj, void *arg, int flags)
1118 struct iax2_user *user = obj, *user2 = arg;
1120 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1124 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1125 * so do not call it with a pvt lock held.
1127 static struct iax2_peer *find_peer(const char *name, int realtime)
1129 struct iax2_peer *peer = NULL;
1130 struct iax2_peer tmp_peer = {
1131 .name = name,
1134 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1136 /* Now go for realtime if applicable */
1137 if(!peer && realtime)
1138 peer = realtime_peer(name, NULL);
1140 return peer;
1143 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1145 ao2_ref(peer, +1);
1146 return peer;
1149 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1151 ao2_ref(peer, -1);
1152 return NULL;
1155 static inline struct iax2_user *user_ref(struct iax2_user *user)
1157 ao2_ref(user, +1);
1158 return user;
1161 static inline struct iax2_user *user_unref(struct iax2_user *user)
1163 ao2_ref(user, -1);
1164 return NULL;
1167 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1169 struct iax2_peer *peer = NULL;
1170 int res = 0;
1171 struct ao2_iterator i;
1173 i = ao2_iterator_init(peers, 0);
1174 while ((peer = ao2_iterator_next(&i))) {
1175 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1176 (peer->addr.sin_port == sin.sin_port)) {
1177 ast_copy_string(host, peer->name, len);
1178 peer_unref(peer);
1179 res = 1;
1180 break;
1182 peer_unref(peer);
1185 if (!peer) {
1186 peer = realtime_peer(NULL, &sin);
1187 if (peer) {
1188 ast_copy_string(host, peer->name, len);
1189 peer_unref(peer);
1190 res = 1;
1194 return res;
1197 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1199 /* Decrement AUTHREQ count if needed */
1200 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1201 struct iax2_user *user;
1202 struct iax2_user tmp_user = {
1203 .name = pvt->username,
1206 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1207 if (user) {
1208 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1209 user = user_unref(user);
1212 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1215 /* No more pings or lagrq's */
1216 AST_SCHED_DEL(sched, pvt->pingid);
1217 AST_SCHED_DEL(sched, pvt->lagid);
1218 AST_SCHED_DEL(sched, pvt->autoid);
1219 AST_SCHED_DEL(sched, pvt->authid);
1220 AST_SCHED_DEL(sched, pvt->initid);
1221 AST_SCHED_DEL(sched, pvt->jbid);
1224 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1226 if (!pvt->peercallno) {
1227 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1228 return;
1231 ao2_link(iax_peercallno_pvts, pvt);
1234 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1236 if (!pvt->peercallno) {
1237 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1238 return;
1241 ao2_unlink(iax_peercallno_pvts, pvt);
1244 static void update_max_trunk(void)
1246 int max = TRUNK_CALL_START;
1247 int x;
1249 /* XXX Prolly don't need locks here XXX */
1250 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1251 if (iaxs[x]) {
1252 max = x + 1;
1256 maxtrunkcall = max;
1257 if (option_debug && iaxdebug)
1258 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1261 static void iax2_frame_free(struct iax_frame *fr)
1263 AST_SCHED_DEL(sched, fr->retrans);
1264 iax_frame_free(fr);
1267 static void iax2_destroy(int callno)
1269 struct chan_iax2_pvt *pvt;
1270 struct ast_channel *owner;
1272 retry:
1273 pvt = iaxs[callno];
1274 gettimeofday(&lastused[callno], NULL);
1276 owner = pvt ? pvt->owner : NULL;
1278 if (owner) {
1279 if (ast_mutex_trylock(&owner->lock)) {
1280 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1281 ast_mutex_unlock(&iaxsl[callno]);
1282 usleep(1);
1283 ast_mutex_lock(&iaxsl[callno]);
1284 goto retry;
1287 if (!owner) {
1288 iaxs[callno] = NULL;
1291 if (pvt) {
1292 if (!owner) {
1293 pvt->owner = NULL;
1294 } else {
1295 /* If there's an owner, prod it to give up */
1296 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
1297 * because we already hold the owner channel lock. */
1298 ast_queue_hangup(owner);
1301 if (pvt->peercallno) {
1302 remove_by_peercallno(pvt);
1305 if (!owner) {
1306 ao2_ref(pvt, -1);
1307 pvt = NULL;
1311 if (owner) {
1312 ast_mutex_unlock(&owner->lock);
1315 if (callno & 0x4000) {
1316 update_max_trunk();
1320 static void pvt_destructor(void *obj)
1322 struct chan_iax2_pvt *pvt = obj;
1323 struct iax_frame *cur = NULL;
1325 iax2_destroy_helper(pvt);
1327 /* Already gone */
1328 ast_set_flag(pvt, IAX_ALREADYGONE);
1330 AST_LIST_LOCK(&iaxq.queue);
1331 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1332 /* Cancel any pending transmissions */
1333 if (cur->callno == pvt->callno) {
1334 cur->retries = -1;
1337 AST_LIST_UNLOCK(&iaxq.queue);
1339 if (pvt->reg) {
1340 pvt->reg->callno = 0;
1343 if (!pvt->owner) {
1344 jb_frame frame;
1345 if (pvt->vars) {
1346 ast_variables_destroy(pvt->vars);
1347 pvt->vars = NULL;
1350 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1351 iax2_frame_free(frame.data);
1354 jb_destroy(pvt->jb);
1355 ast_string_field_free_memory(pvt);
1359 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1361 struct chan_iax2_pvt *tmp;
1362 jb_conf jbconf;
1364 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1365 return NULL;
1368 if (ast_string_field_init(tmp, 32)) {
1369 ao2_ref(tmp, -1);
1370 tmp = NULL;
1371 return NULL;
1374 tmp->prefs = prefs;
1375 tmp->callno = 0;
1376 tmp->peercallno = 0;
1377 tmp->transfercallno = 0;
1378 tmp->bridgecallno = 0;
1379 tmp->pingid = -1;
1380 tmp->lagid = -1;
1381 tmp->autoid = -1;
1382 tmp->authid = -1;
1383 tmp->initid = -1;
1385 ast_string_field_set(tmp,exten, "s");
1386 ast_string_field_set(tmp,host, host);
1388 tmp->jb = jb_new();
1389 tmp->jbid = -1;
1390 jbconf.max_jitterbuf = maxjitterbuffer;
1391 jbconf.resync_threshold = resyncthreshold;
1392 jbconf.max_contig_interp = maxjitterinterps;
1393 jb_setconf(tmp->jb,&jbconf);
1395 return tmp;
1398 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1400 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1401 if (new) {
1402 size_t afdatalen = new->afdatalen;
1403 memcpy(new, fr, sizeof(*new));
1404 iax_frame_wrap(new, &fr->af);
1405 new->afdatalen = afdatalen;
1406 new->data = NULL;
1407 new->datalen = 0;
1408 new->direction = DIRECTION_INGRESS;
1409 new->retrans = -1;
1411 return new;
1414 #define NEW_PREVENT 0
1415 #define NEW_ALLOW 1
1416 #define NEW_FORCE 2
1418 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur, int full_frame)
1420 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1421 (cur->addr.sin_port == sin->sin_port)) {
1422 /* This is the main host */
1423 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1424 (full_frame ? dcallno == cur->callno : 1) ) {
1425 /* That's us. Be sure we keep track of the peer call number */
1426 return 1;
1429 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1430 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1431 /* We're transferring */
1432 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1433 return 1;
1435 return 0;
1438 static void update_max_nontrunk(void)
1440 int max = 1;
1441 int x;
1442 /* XXX Prolly don't need locks here XXX */
1443 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1444 if (iaxs[x])
1445 max = x + 1;
1447 maxnontrunkcall = max;
1448 if (option_debug && iaxdebug)
1449 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1452 static int make_trunk(unsigned short callno, int locked)
1454 int x;
1455 int res= 0;
1456 struct timeval now;
1457 if (iaxs[callno]->oseqno) {
1458 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1459 return -1;
1461 if (callno & TRUNK_CALL_START) {
1462 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1463 return -1;
1465 gettimeofday(&now, NULL);
1466 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1467 ast_mutex_lock(&iaxsl[x]);
1468 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1469 iaxs[x] = iaxs[callno];
1470 iaxs[x]->callno = x;
1471 iaxs[callno] = NULL;
1472 /* Update the two timers that should have been started */
1473 AST_SCHED_DEL(sched, iaxs[x]->pingid);
1474 AST_SCHED_DEL(sched, iaxs[x]->lagid);
1475 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1476 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1477 if (locked)
1478 ast_mutex_unlock(&iaxsl[callno]);
1479 res = x;
1480 if (!locked)
1481 ast_mutex_unlock(&iaxsl[x]);
1482 break;
1484 ast_mutex_unlock(&iaxsl[x]);
1486 if (x >= ARRAY_LEN(iaxs) - 1) {
1487 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1488 return -1;
1490 if (option_debug)
1491 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1492 /* We move this call from a non-trunked to a trunked call */
1493 update_max_trunk();
1494 update_max_nontrunk();
1495 return res;
1499 * \note Calling this function while holding another pvt lock can cause a deadlock.
1501 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int full_frame)
1503 int res = 0;
1504 int x;
1505 struct timeval now;
1506 char host[80];
1508 if (new <= NEW_ALLOW) {
1509 if (callno) {
1510 struct chan_iax2_pvt *pvt;
1511 struct chan_iax2_pvt tmp_pvt = {
1512 .callno = dcallno,
1513 .peercallno = callno,
1514 /* hack!! */
1515 .frames_received = full_frame,
1518 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1520 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1521 if (return_locked) {
1522 ast_mutex_lock(&iaxsl[pvt->callno]);
1524 res = pvt->callno;
1525 ao2_ref(pvt, -1);
1526 pvt = NULL;
1527 return res;
1531 /* Look for an existing connection first */
1532 for (x = 1; !res && x < maxnontrunkcall; x++) {
1533 ast_mutex_lock(&iaxsl[x]);
1534 if (iaxs[x]) {
1535 /* Look for an exact match */
1536 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1537 res = x;
1540 if (!res || !return_locked)
1541 ast_mutex_unlock(&iaxsl[x]);
1543 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1544 ast_mutex_lock(&iaxsl[x]);
1545 if (iaxs[x]) {
1546 /* Look for an exact match */
1547 if (match(sin, callno, dcallno, iaxs[x], full_frame)) {
1548 res = x;
1551 if (!res || !return_locked)
1552 ast_mutex_unlock(&iaxsl[x]);
1555 if (!res && (new >= NEW_ALLOW)) {
1556 int start, found = 0;
1558 /* It may seem odd that we look through the peer list for a name for
1559 * this *incoming* call. Well, it is weird. However, users don't
1560 * have an IP address/port number that we can match against. So,
1561 * this is just checking for a peer that has that IP/port and
1562 * assuming that we have a user of the same name. This isn't always
1563 * correct, but it will be changed if needed after authentication. */
1564 if (!iax2_getpeername(*sin, host, sizeof(host)))
1565 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1567 now = ast_tvnow();
1568 start = 1 + (ast_random() % (TRUNK_CALL_START - 1));
1569 for (x = start; 1; x++) {
1570 if (x == TRUNK_CALL_START) {
1571 x = 0;
1572 continue;
1575 /* Find first unused call number that hasn't been used in a while */
1576 ast_mutex_lock(&iaxsl[x]);
1577 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1578 found = 1;
1579 break;
1581 ast_mutex_unlock(&iaxsl[x]);
1583 if (x == start - 1) {
1584 break;
1587 /* We've still got lock held if we found a spot */
1588 if (x == start - 1 && !found) {
1589 ast_log(LOG_WARNING, "No more space\n");
1590 return 0;
1592 iaxs[x] = new_iax(sin, host);
1593 update_max_nontrunk();
1594 if (iaxs[x]) {
1595 if (option_debug && iaxdebug)
1596 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1597 iaxs[x]->sockfd = sockfd;
1598 iaxs[x]->addr.sin_port = sin->sin_port;
1599 iaxs[x]->addr.sin_family = sin->sin_family;
1600 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1601 iaxs[x]->peercallno = callno;
1602 iaxs[x]->callno = x;
1603 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1604 iaxs[x]->expiry = min_reg_expire;
1605 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1606 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1607 iaxs[x]->amaflags = amaflags;
1608 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1610 ast_string_field_set(iaxs[x], accountcode, accountcode);
1611 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1612 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1614 if (iaxs[x]->peercallno) {
1615 store_by_peercallno(iaxs[x]);
1617 } else {
1618 ast_log(LOG_WARNING, "Out of resources\n");
1619 ast_mutex_unlock(&iaxsl[x]);
1620 return 0;
1622 if (!return_locked)
1623 ast_mutex_unlock(&iaxsl[x]);
1624 res = x;
1626 return res;
1629 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1631 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1634 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1636 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1640 * \brief Queue a frame to a call's owning asterisk channel
1642 * \pre This function assumes that iaxsl[callno] is locked when called.
1644 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1645 * was valid before calling it, it may no longer be valid after calling it.
1646 * This function may unlock and lock the mutex associated with this callno,
1647 * meaning that another thread may grab it and destroy the call.
1649 static int iax2_queue_frame(int callno, struct ast_frame *f)
1651 for (;;) {
1652 if (iaxs[callno] && iaxs[callno]->owner) {
1653 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1654 /* Avoid deadlock by pausing and trying again */
1655 ast_mutex_unlock(&iaxsl[callno]);
1656 usleep(1);
1657 ast_mutex_lock(&iaxsl[callno]);
1658 } else {
1659 ast_queue_frame(iaxs[callno]->owner, f);
1660 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1661 break;
1663 } else
1664 break;
1666 return 0;
1670 * \brief Queue a hangup frame on the ast_channel owner
1672 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1673 * is active for the given call number.
1675 * \pre Assumes lock for callno is already held.
1677 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1678 * was valid before calling it, it may no longer be valid after calling it.
1679 * This function may unlock and lock the mutex associated with this callno,
1680 * meaning that another thread may grab it and destroy the call.
1682 static int iax2_queue_hangup(int callno)
1684 for (;;) {
1685 if (iaxs[callno] && iaxs[callno]->owner) {
1686 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1687 /* Avoid deadlock by pausing and trying again */
1688 ast_mutex_unlock(&iaxsl[callno]);
1689 usleep(1);
1690 ast_mutex_lock(&iaxsl[callno]);
1691 } else {
1692 ast_queue_hangup(iaxs[callno]->owner);
1693 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1694 break;
1696 } else
1697 break;
1699 return 0;
1703 * \brief Queue a control frame on the ast_channel owner
1705 * This function queues a control frame on the owner of the IAX2 pvt struct that
1706 * is active for the given call number.
1708 * \pre Assumes lock for callno is already held.
1710 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1711 * was valid before calling it, it may no longer be valid after calling it.
1712 * This function may unlock and lock the mutex associated with this callno,
1713 * meaning that another thread may grab it and destroy the call.
1715 static int iax2_queue_control_data(int callno,
1716 enum ast_control_frame_type control, const void *data, size_t datalen)
1718 for (;;) {
1719 if (iaxs[callno] && iaxs[callno]->owner) {
1720 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1721 /* Avoid deadlock by pausing and trying again */
1722 ast_mutex_unlock(&iaxsl[callno]);
1723 usleep(1);
1724 ast_mutex_lock(&iaxsl[callno]);
1725 } else {
1726 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1727 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1728 break;
1730 } else
1731 break;
1733 return 0;
1735 static void destroy_firmware(struct iax_firmware *cur)
1737 /* Close firmware */
1738 if (cur->fwh) {
1739 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1741 close(cur->fd);
1742 free(cur);
1745 static int try_firmware(char *s)
1747 struct stat stbuf;
1748 struct iax_firmware *cur;
1749 int ifd;
1750 int fd;
1751 int res;
1753 struct ast_iax2_firmware_header *fwh, fwh2;
1754 struct MD5Context md5;
1755 unsigned char sum[16];
1756 unsigned char buf[1024];
1757 int len, chunk;
1758 char *s2;
1759 char *last;
1760 s2 = alloca(strlen(s) + 100);
1761 if (!s2) {
1762 ast_log(LOG_WARNING, "Alloca failed!\n");
1763 return -1;
1765 last = strrchr(s, '/');
1766 if (last)
1767 last++;
1768 else
1769 last = s;
1770 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1771 res = stat(s, &stbuf);
1772 if (res < 0) {
1773 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1774 return -1;
1776 /* Make sure it's not a directory */
1777 if (S_ISDIR(stbuf.st_mode))
1778 return -1;
1779 ifd = open(s, O_RDONLY);
1780 if (ifd < 0) {
1781 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1782 return -1;
1784 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
1785 if (fd < 0) {
1786 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1787 close(ifd);
1788 return -1;
1790 /* Unlink our newly created file */
1791 unlink(s2);
1793 /* Now copy the firmware into it */
1794 len = stbuf.st_size;
1795 while(len) {
1796 chunk = len;
1797 if (chunk > sizeof(buf))
1798 chunk = sizeof(buf);
1799 res = read(ifd, buf, chunk);
1800 if (res != chunk) {
1801 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1802 close(ifd);
1803 close(fd);
1804 return -1;
1806 res = write(fd, buf, chunk);
1807 if (res != chunk) {
1808 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1809 close(ifd);
1810 close(fd);
1811 return -1;
1813 len -= chunk;
1815 close(ifd);
1816 /* Return to the beginning */
1817 lseek(fd, 0, SEEK_SET);
1818 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1819 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1820 close(fd);
1821 return -1;
1823 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1824 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1825 close(fd);
1826 return -1;
1828 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1829 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1830 close(fd);
1831 return -1;
1833 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1834 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1835 close(fd);
1836 return -1;
1838 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1839 if (fwh == (void *) -1) {
1840 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1841 close(fd);
1842 return -1;
1844 MD5Init(&md5);
1845 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1846 MD5Final(sum, &md5);
1847 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1848 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1849 munmap((void*)fwh, stbuf.st_size);
1850 close(fd);
1851 return -1;
1853 cur = waresl.wares;
1854 while(cur) {
1855 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1856 /* Found a candidate */
1857 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1858 /* The version we have on loaded is older, load this one instead */
1859 break;
1860 /* This version is no newer than what we have. Don't worry about it.
1861 We'll consider it a proper load anyhow though */
1862 munmap((void*)fwh, stbuf.st_size);
1863 close(fd);
1864 return 0;
1866 cur = cur->next;
1868 if (!cur) {
1869 /* Allocate a new one and link it */
1870 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1871 cur->fd = -1;
1872 cur->next = waresl.wares;
1873 waresl.wares = cur;
1876 if (cur) {
1877 if (cur->fwh) {
1878 munmap((void*)cur->fwh, cur->mmaplen);
1880 if (cur->fd > -1)
1881 close(cur->fd);
1882 cur->fwh = fwh;
1883 cur->fd = fd;
1884 cur->mmaplen = stbuf.st_size;
1885 cur->dead = 0;
1887 return 0;
1890 static int iax_check_version(char *dev)
1892 int res = 0;
1893 struct iax_firmware *cur;
1894 if (!ast_strlen_zero(dev)) {
1895 ast_mutex_lock(&waresl.lock);
1896 cur = waresl.wares;
1897 while(cur) {
1898 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1899 res = ntohs(cur->fwh->version);
1900 break;
1902 cur = cur->next;
1904 ast_mutex_unlock(&waresl.lock);
1906 return res;
1909 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1911 int res = -1;
1912 unsigned int bs = desc & 0xff;
1913 unsigned int start = (desc >> 8) & 0xffffff;
1914 unsigned int bytes;
1915 struct iax_firmware *cur;
1916 if (!ast_strlen_zero((char *)dev) && bs) {
1917 start *= bs;
1918 ast_mutex_lock(&waresl.lock);
1919 cur = waresl.wares;
1920 while(cur) {
1921 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1922 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1923 if (start < ntohl(cur->fwh->datalen)) {
1924 bytes = ntohl(cur->fwh->datalen) - start;
1925 if (bytes > bs)
1926 bytes = bs;
1927 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1928 } else {
1929 bytes = 0;
1930 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1932 if (bytes == bs)
1933 res = 0;
1934 else
1935 res = 1;
1936 break;
1938 cur = cur->next;
1940 ast_mutex_unlock(&waresl.lock);
1942 return res;
1946 static void reload_firmware(int unload)
1948 struct iax_firmware *cur, *curl, *curp;
1949 DIR *fwd;
1950 struct dirent *de;
1951 char dir[256];
1952 char fn[256];
1953 /* Mark all as dead */
1954 ast_mutex_lock(&waresl.lock);
1955 cur = waresl.wares;
1956 while(cur) {
1957 cur->dead = 1;
1958 cur = cur->next;
1961 /* Now that we've freed them, load the new ones */
1962 if (!unload) {
1963 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1964 fwd = opendir(dir);
1965 if (fwd) {
1966 while((de = readdir(fwd))) {
1967 if (de->d_name[0] != '.') {
1968 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1969 if (!try_firmware(fn)) {
1970 if (option_verbose > 1)
1971 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1975 closedir(fwd);
1976 } else
1977 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1980 /* Clean up leftovers */
1981 cur = waresl.wares;
1982 curp = NULL;
1983 while(cur) {
1984 curl = cur;
1985 cur = cur->next;
1986 if (curl->dead) {
1987 if (curp) {
1988 curp->next = cur;
1989 } else {
1990 waresl.wares = cur;
1992 destroy_firmware(curl);
1993 } else {
1994 curp = cur;
1997 ast_mutex_unlock(&waresl.lock);
2001 * \note This function assumes that iaxsl[callno] is locked when called.
2003 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2004 * was valid before calling it, it may no longer be valid after calling it.
2005 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2006 * associated with this callno, meaning that another thread may grab it and destroy the call.
2008 static int __do_deliver(void *data)
2010 /* Just deliver the packet by using queueing. This is called by
2011 the IAX thread with the iaxsl lock held. */
2012 struct iax_frame *fr = data;
2013 fr->retrans = -1;
2014 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2015 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2016 iax2_queue_frame(fr->callno, &fr->af);
2017 /* Free our iax frame */
2018 iax2_frame_free(fr);
2019 /* And don't run again */
2020 return 0;
2023 static int handle_error(void)
2025 /* XXX Ideally we should figure out why an error occured and then abort those
2026 rather than continuing to try. Unfortunately, the published interface does
2027 not seem to work XXX */
2028 #if 0
2029 struct sockaddr_in *sin;
2030 int res;
2031 struct msghdr m;
2032 struct sock_extended_err e;
2033 m.msg_name = NULL;
2034 m.msg_namelen = 0;
2035 m.msg_iov = NULL;
2036 m.msg_control = &e;
2037 m.msg_controllen = sizeof(e);
2038 m.msg_flags = 0;
2039 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2040 if (res < 0)
2041 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2042 else {
2043 if (m.msg_controllen) {
2044 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2045 if (sin)
2046 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2047 else
2048 ast_log(LOG_WARNING, "No address detected??\n");
2049 } else {
2050 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2053 #endif
2054 return 0;
2057 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2059 int res;
2060 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2061 sizeof(*sin));
2062 if (res < 0) {
2063 if (option_debug)
2064 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
2065 handle_error();
2066 } else
2067 res = 0;
2068 return res;
2071 static int send_packet(struct iax_frame *f)
2073 int res;
2074 int callno = f->callno;
2076 /* Don't send if there was an error, but return error instead */
2077 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2078 return -1;
2080 /* Called with iaxsl held */
2081 if (option_debug > 2 && iaxdebug)
2082 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));
2083 if (f->transfer) {
2084 if (iaxdebug)
2085 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2086 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
2087 sizeof(iaxs[callno]->transfer));
2088 } else {
2089 if (iaxdebug)
2090 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2091 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
2092 sizeof(iaxs[callno]->addr));
2094 if (res < 0) {
2095 if (option_debug && iaxdebug)
2096 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
2097 handle_error();
2098 } else
2099 res = 0;
2100 return res;
2104 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2105 * for the given call number may disappear during its execution.
2107 static int iax2_predestroy(int callno)
2109 struct ast_channel *c;
2110 struct chan_iax2_pvt *pvt = iaxs[callno];
2112 if (!pvt)
2113 return -1;
2114 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2115 iax2_destroy_helper(pvt);
2116 ast_set_flag(pvt, IAX_ALREADYGONE);
2118 c = pvt->owner;
2119 if (c) {
2120 c->tech_pvt = NULL;
2121 iax2_queue_hangup(callno);
2122 pvt->owner = NULL;
2123 ast_module_unref(ast_module_info->self);
2125 return 0;
2128 static int update_packet(struct iax_frame *f)
2130 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2131 struct ast_iax2_full_hdr *fh = f->data;
2132 /* Mark this as a retransmission */
2133 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2134 /* Update iseqno */
2135 f->iseqno = iaxs[f->callno]->iseqno;
2136 fh->iseqno = f->iseqno;
2137 return 0;
2140 static int attempt_transmit(const void *data);
2141 static void __attempt_transmit(const void *data)
2143 /* Attempt to transmit the frame to the remote peer...
2144 Called without iaxsl held. */
2145 struct iax_frame *f = (struct iax_frame *)data;
2146 int freeme=0;
2147 int callno = f->callno;
2148 /* Make sure this call is still active */
2149 if (callno)
2150 ast_mutex_lock(&iaxsl[callno]);
2151 if (callno && iaxs[callno]) {
2152 if ((f->retries < 0) /* Already ACK'd */ ||
2153 (f->retries >= max_retries) /* Too many attempts */) {
2154 /* Record an error if we've transmitted too many times */
2155 if (f->retries >= max_retries) {
2156 if (f->transfer) {
2157 /* Transfer timeout */
2158 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2159 } else if (f->final) {
2160 if (f->final)
2161 iax2_destroy(callno);
2162 } else {
2163 if (iaxs[callno]->owner)
2164 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);
2165 iaxs[callno]->error = ETIMEDOUT;
2166 if (iaxs[callno]->owner) {
2167 struct ast_frame fr = { 0, };
2168 /* Hangup the fd */
2169 fr.frametype = AST_FRAME_CONTROL;
2170 fr.subclass = AST_CONTROL_HANGUP;
2171 iax2_queue_frame(callno, &fr); // XXX
2172 /* Remember, owner could disappear */
2173 if (iaxs[callno] && iaxs[callno]->owner)
2174 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2175 } else {
2176 if (iaxs[callno]->reg) {
2177 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2178 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2179 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2181 iax2_destroy(callno);
2186 freeme++;
2187 } else {
2188 /* Update it if it needs it */
2189 update_packet(f);
2190 /* Attempt transmission */
2191 send_packet(f);
2192 f->retries++;
2193 /* Try again later after 10 times as long */
2194 f->retrytime *= 10;
2195 if (f->retrytime > MAX_RETRY_TIME)
2196 f->retrytime = MAX_RETRY_TIME;
2197 /* Transfer messages max out at one second */
2198 if (f->transfer && (f->retrytime > 1000))
2199 f->retrytime = 1000;
2200 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2202 } else {
2203 /* Make sure it gets freed */
2204 f->retries = -1;
2205 freeme++;
2207 if (callno)
2208 ast_mutex_unlock(&iaxsl[callno]);
2209 /* Do not try again */
2210 if (freeme) {
2211 /* Don't attempt delivery, just remove it from the queue */
2212 AST_LIST_LOCK(&iaxq.queue);
2213 AST_LIST_REMOVE(&iaxq.queue, f, list);
2214 iaxq.count--;
2215 AST_LIST_UNLOCK(&iaxq.queue);
2216 f->retrans = -1;
2217 /* Free the IAX frame */
2218 iax2_frame_free(f);
2222 static int attempt_transmit(const void *data)
2224 #ifdef SCHED_MULTITHREADED
2225 if (schedule_action(__attempt_transmit, data))
2226 #endif
2227 __attempt_transmit(data);
2228 return 0;
2231 static int iax2_prune_realtime(int fd, int argc, char *argv[])
2233 struct iax2_peer *peer;
2235 if (argc != 4)
2236 return RESULT_SHOWUSAGE;
2237 if (!strcmp(argv[3],"all")) {
2238 reload_config();
2239 ast_cli(fd, "OK cache is flushed.\n");
2240 } else if ((peer = find_peer(argv[3], 0))) {
2241 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2242 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2243 expire_registry(peer_ref(peer));
2244 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
2245 } else {
2246 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2248 peer_unref(peer);
2249 } else {
2250 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
2253 return RESULT_SUCCESS;
2256 static int iax2_test_losspct(int fd, int argc, char *argv[])
2258 if (argc != 4)
2259 return RESULT_SHOWUSAGE;
2261 test_losspct = atoi(argv[3]);
2263 return RESULT_SUCCESS;
2266 #ifdef IAXTESTS
2267 static int iax2_test_late(int fd, int argc, char *argv[])
2269 if (argc != 4)
2270 return RESULT_SHOWUSAGE;
2272 test_late = atoi(argv[3]);
2274 return RESULT_SUCCESS;
2277 static int iax2_test_resync(int fd, int argc, char *argv[])
2279 if (argc != 4)
2280 return RESULT_SHOWUSAGE;
2282 test_resync = atoi(argv[3]);
2284 return RESULT_SUCCESS;
2287 static int iax2_test_jitter(int fd, int argc, char *argv[])
2289 if (argc < 4 || argc > 5)
2290 return RESULT_SHOWUSAGE;
2292 test_jit = atoi(argv[3]);
2293 if (argc == 5)
2294 test_jitpct = atoi(argv[4]);
2296 return RESULT_SUCCESS;
2298 #endif /* IAXTESTS */
2300 /*! \brief peer_status: Report Peer status in character string */
2301 /* returns 1 if peer is online, -1 if unmonitored */
2302 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2304 int res = 0;
2305 if (peer->maxms) {
2306 if (peer->lastms < 0) {
2307 ast_copy_string(status, "UNREACHABLE", statuslen);
2308 } else if (peer->lastms > peer->maxms) {
2309 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2310 res = 1;
2311 } else if (peer->lastms) {
2312 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2313 res = 1;
2314 } else {
2315 ast_copy_string(status, "UNKNOWN", statuslen);
2317 } else {
2318 ast_copy_string(status, "Unmonitored", statuslen);
2319 res = -1;
2321 return res;
2324 /*! \brief Show one peer in detail */
2325 static int iax2_show_peer(int fd, int argc, char *argv[])
2327 char status[30];
2328 char cbuf[256];
2329 struct iax2_peer *peer;
2330 char codec_buf[512];
2331 int x = 0, codec = 0, load_realtime = 0;
2333 if (argc < 4)
2334 return RESULT_SHOWUSAGE;
2336 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2338 peer = find_peer(argv[3], load_realtime);
2339 if (peer) {
2340 ast_cli(fd,"\n\n");
2341 ast_cli(fd, " * Name : %s\n", peer->name);
2342 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2343 ast_cli(fd, " Context : %s\n", peer->context);
2344 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2345 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2346 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2347 ast_cli(fd, " Expire : %d\n", peer->expire);
2348 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2349 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));
2350 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2351 ast_cli(fd, " Username : %s\n", peer->username);
2352 ast_cli(fd, " Codecs : ");
2353 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2354 ast_cli(fd, "%s\n", codec_buf);
2356 ast_cli(fd, " Codec Order : (");
2357 for(x = 0; x < 32 ; x++) {
2358 codec = ast_codec_pref_index(&peer->prefs,x);
2359 if(!codec)
2360 break;
2361 ast_cli(fd, "%s", ast_getformatname(codec));
2362 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2363 ast_cli(fd, "|");
2366 if (!x)
2367 ast_cli(fd, "none");
2368 ast_cli(fd, ")\n");
2370 ast_cli(fd, " Status : ");
2371 peer_status(peer, status, sizeof(status));
2372 ast_cli(fd, "%s\n",status);
2373 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2374 ast_cli(fd,"\n");
2375 peer_unref(peer);
2376 } else {
2377 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2378 ast_cli(fd,"\n");
2381 return RESULT_SUCCESS;
2384 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2386 int which = 0;
2387 struct iax2_peer *peer;
2388 char *res = NULL;
2389 int wordlen = strlen(word);
2390 struct ao2_iterator i;
2392 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2393 if (pos != 3)
2394 return NULL;
2396 i = ao2_iterator_init(peers, 0);
2397 while ((peer = ao2_iterator_next(&i))) {
2398 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2399 res = ast_strdup(peer->name);
2400 peer_unref(peer);
2401 break;
2403 peer_unref(peer);
2406 return res;
2409 static int iax2_show_stats(int fd, int argc, char *argv[])
2411 struct iax_frame *cur;
2412 int cnt = 0, dead=0, final=0;
2414 if (argc != 3)
2415 return RESULT_SHOWUSAGE;
2417 AST_LIST_LOCK(&iaxq.queue);
2418 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2419 if (cur->retries < 0)
2420 dead++;
2421 if (cur->final)
2422 final++;
2423 cnt++;
2425 AST_LIST_UNLOCK(&iaxq.queue);
2427 ast_cli(fd, " IAX Statistics\n");
2428 ast_cli(fd, "---------------------\n");
2429 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2430 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2432 return RESULT_SUCCESS;
2435 static int iax2_show_cache(int fd, int argc, char *argv[])
2437 struct iax2_dpcache *dp;
2438 char tmp[1024], *pc;
2439 int s;
2440 int x,y;
2441 struct timeval tv;
2442 gettimeofday(&tv, NULL);
2443 ast_mutex_lock(&dpcache_lock);
2444 dp = dpcache;
2445 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2446 while(dp) {
2447 s = dp->expiry.tv_sec - tv.tv_sec;
2448 tmp[0] = '\0';
2449 if (dp->flags & CACHE_FLAG_EXISTS)
2450 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2451 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2452 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2453 if (dp->flags & CACHE_FLAG_CANEXIST)
2454 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2455 if (dp->flags & CACHE_FLAG_PENDING)
2456 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2457 if (dp->flags & CACHE_FLAG_TIMEOUT)
2458 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2459 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2460 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2461 if (dp->flags & CACHE_FLAG_MATCHMORE)
2462 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2463 if (dp->flags & CACHE_FLAG_UNKNOWN)
2464 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2465 /* Trim trailing pipe */
2466 if (!ast_strlen_zero(tmp))
2467 tmp[strlen(tmp) - 1] = '\0';
2468 else
2469 ast_copy_string(tmp, "(none)", sizeof(tmp));
2470 y=0;
2471 pc = strchr(dp->peercontext, '@');
2472 if (!pc)
2473 pc = dp->peercontext;
2474 else
2475 pc++;
2476 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2477 if (dp->waiters[x] > -1)
2478 y++;
2479 if (s > 0)
2480 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2481 else
2482 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2483 dp = dp->next;
2485 ast_mutex_unlock(&dpcache_lock);
2486 return RESULT_SUCCESS;
2489 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2491 static void unwrap_timestamp(struct iax_frame *fr)
2493 int x;
2495 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2496 x = fr->ts - iaxs[fr->callno]->last;
2497 if (x < -50000) {
2498 /* Sudden big jump backwards in timestamp:
2499 What likely happened here is that miniframe timestamp has circled but we haven't
2500 gotten the update from the main packet. We'll just pretend that we did, and
2501 update the timestamp appropriately. */
2502 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2503 if (option_debug && iaxdebug)
2504 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2506 if (x > 50000) {
2507 /* Sudden apparent big jump forwards in timestamp:
2508 What's likely happened is this is an old miniframe belonging to the previous
2509 top-16-bit timestamp that has turned up out of order.
2510 Adjust the timestamp appropriately. */
2511 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2512 if (option_debug && iaxdebug)
2513 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2518 static int get_from_jb(const void *p);
2520 static void update_jbsched(struct chan_iax2_pvt *pvt)
2522 int when;
2524 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2526 when = jb_next(pvt->jb) - when;
2528 AST_SCHED_DEL(sched, pvt->jbid);
2530 if(when <= 0) {
2531 /* XXX should really just empty until when > 0.. */
2532 when = 1;
2535 pvt->jbid = iax2_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2538 static void __get_from_jb(const void *p)
2540 int callno = PTR_TO_CALLNO(p);
2541 struct chan_iax2_pvt *pvt = NULL;
2542 struct iax_frame *fr;
2543 jb_frame frame;
2544 int ret;
2545 long now;
2546 long next;
2547 struct timeval tv;
2549 /* Make sure we have a valid private structure before going on */
2550 ast_mutex_lock(&iaxsl[callno]);
2551 pvt = iaxs[callno];
2552 if (!pvt) {
2553 /* No go! */
2554 ast_mutex_unlock(&iaxsl[callno]);
2555 return;
2558 pvt->jbid = -1;
2560 gettimeofday(&tv,NULL);
2561 /* round up a millisecond since ast_sched_runq does; */
2562 /* prevents us from spinning while waiting for our now */
2563 /* to catch up with runq's now */
2564 tv.tv_usec += 1000;
2566 now = ast_tvdiff_ms(tv, pvt->rxcore);
2568 if(now >= (next = jb_next(pvt->jb))) {
2569 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2570 switch(ret) {
2571 case JB_OK:
2572 fr = frame.data;
2573 __do_deliver(fr);
2574 /* __do_deliver() can cause the call to disappear */
2575 pvt = iaxs[callno];
2576 break;
2577 case JB_INTERP:
2579 struct ast_frame af = { 0, };
2581 /* create an interpolation frame */
2582 af.frametype = AST_FRAME_VOICE;
2583 af.subclass = pvt->voiceformat;
2584 af.samples = frame.ms * 8;
2585 af.src = "IAX2 JB interpolation";
2586 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2587 af.offset = AST_FRIENDLY_OFFSET;
2589 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2590 * which we'd need to malloc, and then it would free it. That seems like a drag */
2591 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2592 iax2_queue_frame(callno, &af);
2593 /* iax2_queue_frame() could cause the call to disappear */
2594 pvt = iaxs[callno];
2597 break;
2598 case JB_DROP:
2599 iax2_frame_free(frame.data);
2600 break;
2601 case JB_NOFRAME:
2602 case JB_EMPTY:
2603 /* do nothing */
2604 break;
2605 default:
2606 /* shouldn't happen */
2607 break;
2610 if (pvt)
2611 update_jbsched(pvt);
2612 ast_mutex_unlock(&iaxsl[callno]);
2615 static int get_from_jb(const void *data)
2617 #ifdef SCHED_MULTITHREADED
2618 if (schedule_action(__get_from_jb, data))
2619 #endif
2620 __get_from_jb(data);
2621 return 0;
2625 * \note This function assumes fr->callno is locked
2627 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2628 * was valid before calling it, it may no longer be valid after calling it.
2630 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2632 int type, len;
2633 int ret;
2634 int needfree = 0;
2635 struct ast_channel *owner = NULL;
2636 struct ast_channel *bridge = NULL;
2638 /* Attempt to recover wrapped timestamps */
2639 unwrap_timestamp(fr);
2641 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2642 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2643 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2644 else {
2645 #if 0
2646 if (option_debug)
2647 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2648 #endif
2649 fr->af.delivery = ast_tv(0,0);
2652 type = JB_TYPE_CONTROL;
2653 len = 0;
2655 if(fr->af.frametype == AST_FRAME_VOICE) {
2656 type = JB_TYPE_VOICE;
2657 len = ast_codec_get_samples(&fr->af) / 8;
2658 } else if(fr->af.frametype == AST_FRAME_CNG) {
2659 type = JB_TYPE_SILENCE;
2662 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2663 if (tsout)
2664 *tsout = fr->ts;
2665 __do_deliver(fr);
2666 return -1;
2669 if ((owner = iaxs[fr->callno]->owner))
2670 bridge = ast_bridged_channel(owner);
2672 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2673 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2674 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
2675 jb_frame frame;
2677 /* deliver any frames in the jb */
2678 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2679 __do_deliver(frame.data);
2680 /* __do_deliver() can make the call disappear */
2681 if (!iaxs[fr->callno])
2682 return -1;
2685 jb_reset(iaxs[fr->callno]->jb);
2687 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
2689 /* deliver this frame now */
2690 if (tsout)
2691 *tsout = fr->ts;
2692 __do_deliver(fr);
2693 return -1;
2696 /* insert into jitterbuffer */
2697 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2698 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2699 calc_rxstamp(iaxs[fr->callno],fr->ts));
2700 if (ret == JB_DROP) {
2701 needfree++;
2702 } else if (ret == JB_SCHED) {
2703 update_jbsched(iaxs[fr->callno]);
2705 if (tsout)
2706 *tsout = fr->ts;
2707 if (needfree) {
2708 /* Free our iax frame */
2709 iax2_frame_free(fr);
2710 return -1;
2712 return 0;
2715 static int iax2_transmit(struct iax_frame *fr)
2717 /* Lock the queue and place this packet at the end */
2718 /* By setting this to 0, the network thread will send it for us, and
2719 queue retransmission if necessary */
2720 fr->sentyet = 0;
2721 AST_LIST_LOCK(&iaxq.queue);
2722 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2723 iaxq.count++;
2724 AST_LIST_UNLOCK(&iaxq.queue);
2725 /* Wake up the network and scheduler thread */
2726 if (netthreadid != AST_PTHREADT_NULL)
2727 pthread_kill(netthreadid, SIGURG);
2728 signal_condition(&sched_lock, &sched_cond);
2729 return 0;
2734 static int iax2_digit_begin(struct ast_channel *c, char digit)
2736 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2739 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2741 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2744 static int iax2_sendtext(struct ast_channel *c, const char *text)
2747 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2748 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2751 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2753 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2756 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2758 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2761 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2763 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2764 ast_mutex_lock(&iaxsl[callno]);
2765 if (iaxs[callno])
2766 iaxs[callno]->owner = newchan;
2767 else
2768 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2769 ast_mutex_unlock(&iaxsl[callno]);
2770 return 0;
2774 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2775 * so do not call this with a pvt lock held.
2777 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2779 struct ast_variable *var = NULL;
2780 struct ast_variable *tmp;
2781 struct iax2_peer *peer=NULL;
2782 time_t regseconds = 0, nowtime;
2783 int dynamic=0;
2785 if (peername) {
2786 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
2787 if (!var && sin)
2788 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2789 } else if (sin) {
2790 char porta[25];
2791 sprintf(porta, "%d", ntohs(sin->sin_port));
2792 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2793 if (var) {
2794 /* We'll need the peer name in order to build the structure! */
2795 for (tmp = var; tmp; tmp = tmp->next) {
2796 if (!strcasecmp(tmp->name, "name"))
2797 peername = tmp->value;
2801 if (!var && peername) { /* Last ditch effort */
2802 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2803 /*!\note
2804 * If this one loaded something, then we need to ensure that the host
2805 * field matched. The only reason why we can't have this as a criteria
2806 * is because we only have the IP address and the host field might be
2807 * set as a name (and the reverse PTR might not match).
2809 if (var && sin) {
2810 for (tmp = var; tmp; tmp = tmp->next) {
2811 if (!strcasecmp(tmp->name, "host")) {
2812 struct ast_hostent ahp;
2813 struct hostent *hp;
2814 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2815 /* No match */
2816 ast_variables_destroy(var);
2817 var = NULL;
2819 break;
2824 if (!var)
2825 return NULL;
2827 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2829 if (!peer) {
2830 ast_variables_destroy(var);
2831 return NULL;
2834 for (tmp = var; tmp; tmp = tmp->next) {
2835 /* Make sure it's not a user only... */
2836 if (!strcasecmp(tmp->name, "type")) {
2837 if (strcasecmp(tmp->value, "friend") &&
2838 strcasecmp(tmp->value, "peer")) {
2839 /* Whoops, we weren't supposed to exist! */
2840 peer = peer_unref(peer);
2841 break;
2843 } else if (!strcasecmp(tmp->name, "regseconds")) {
2844 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2845 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2846 inet_aton(tmp->value, &(peer->addr.sin_addr));
2847 } else if (!strcasecmp(tmp->name, "port")) {
2848 peer->addr.sin_port = htons(atoi(tmp->value));
2849 } else if (!strcasecmp(tmp->name, "host")) {
2850 if (!strcasecmp(tmp->value, "dynamic"))
2851 dynamic = 1;
2855 ast_variables_destroy(var);
2857 if (!peer)
2858 return NULL;
2860 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2861 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2862 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2863 if (peer->expire > -1) {
2864 if (!ast_sched_del(sched, peer->expire)) {
2865 peer->expire = -1;
2866 peer_unref(peer);
2869 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
2870 if (peer->expire == -1)
2871 peer_unref(peer);
2873 ao2_link(peers, peer);
2874 if (ast_test_flag(peer, IAX_DYNAMIC))
2875 reg_source_db(peer);
2876 } else {
2877 ast_set_flag(peer, IAX_TEMPONLY);
2880 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2881 time(&nowtime);
2882 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2883 memset(&peer->addr, 0, sizeof(peer->addr));
2884 realtime_update_peer(peer->name, &peer->addr, 0);
2885 if (option_debug)
2886 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2887 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2889 else {
2890 if (option_debug)
2891 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2892 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2896 return peer;
2899 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
2901 struct ast_variable *var;
2902 struct ast_variable *tmp;
2903 struct iax2_user *user=NULL;
2905 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
2906 if (!var)
2907 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2908 if (!var && sin) {
2909 char porta[6];
2910 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
2911 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2912 if (!var)
2913 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2915 if (!var) { /* Last ditch effort */
2916 var = ast_load_realtime("iaxusers", "name", username, NULL);
2917 /*!\note
2918 * If this one loaded something, then we need to ensure that the host
2919 * field matched. The only reason why we can't have this as a criteria
2920 * is because we only have the IP address and the host field might be
2921 * set as a name (and the reverse PTR might not match).
2923 if (var) {
2924 for (tmp = var; tmp; tmp = tmp->next) {
2925 if (!strcasecmp(tmp->name, "host")) {
2926 struct ast_hostent ahp;
2927 struct hostent *hp;
2928 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2929 /* No match */
2930 ast_variables_destroy(var);
2931 var = NULL;
2933 break;
2938 if (!var)
2939 return NULL;
2941 tmp = var;
2942 while(tmp) {
2943 /* Make sure it's not a peer only... */
2944 if (!strcasecmp(tmp->name, "type")) {
2945 if (strcasecmp(tmp->value, "friend") &&
2946 strcasecmp(tmp->value, "user")) {
2947 return NULL;
2950 tmp = tmp->next;
2953 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2955 ast_variables_destroy(var);
2957 if (!user)
2958 return NULL;
2960 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2961 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2962 ao2_link(users, user);
2963 } else {
2964 ast_set_flag(user, IAX_TEMPONLY);
2967 return user;
2970 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2972 char port[10];
2973 char regseconds[20];
2975 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2976 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2977 ast_update_realtime("iaxpeers", "name", peername,
2978 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2979 "regseconds", regseconds, NULL);
2982 struct create_addr_info {
2983 int capability;
2984 unsigned int flags;
2985 int maxtime;
2986 int encmethods;
2987 int found;
2988 int sockfd;
2989 int adsi;
2990 char username[80];
2991 char secret[80];
2992 char outkey[80];
2993 char timezone[80];
2994 char prefs[32];
2995 char context[AST_MAX_CONTEXT];
2996 char peercontext[AST_MAX_CONTEXT];
2997 char mohinterpret[MAX_MUSICCLASS];
2998 char mohsuggest[MAX_MUSICCLASS];
3001 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
3003 struct ast_hostent ahp;
3004 struct hostent *hp;
3005 struct iax2_peer *peer;
3006 int res = -1;
3007 struct ast_codec_pref ourprefs;
3009 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3010 cai->sockfd = defaultsockfd;
3011 cai->maxtime = 0;
3012 sin->sin_family = AF_INET;
3014 if (!(peer = find_peer(peername, 1))) {
3015 cai->found = 0;
3017 hp = ast_gethostbyname(peername, &ahp);
3018 if (hp) {
3019 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
3020 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3021 /* use global iax prefs for unknown peer/user */
3022 /* But move the calling channel's native codec to the top of the preference list */
3023 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
3024 if (c)
3025 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3026 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3027 return 0;
3028 } else {
3029 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3030 return -1;
3034 cai->found = 1;
3036 /* if the peer has no address (current or default), return failure */
3037 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3038 goto return_unref;
3040 /* if the peer is being monitored and is currently unreachable, return failure */
3041 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3042 goto return_unref;
3044 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
3045 cai->maxtime = peer->maxms;
3046 cai->capability = peer->capability;
3047 cai->encmethods = peer->encmethods;
3048 cai->sockfd = peer->sockfd;
3049 cai->adsi = peer->adsi;
3050 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
3051 /* Move the calling channel's native codec to the top of the preference list */
3052 if (c) {
3053 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
3054 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3056 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3057 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3058 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3059 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3060 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3061 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3062 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3063 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3064 if (ast_strlen_zero(peer->dbsecret)) {
3065 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3066 } else {
3067 char *family;
3068 char *key = NULL;
3070 family = ast_strdupa(peer->dbsecret);
3071 key = strchr(family, '/');
3072 if (key)
3073 *key++ = '\0';
3074 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3075 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3076 goto return_unref;
3080 if (peer->addr.sin_addr.s_addr) {
3081 sin->sin_addr = peer->addr.sin_addr;
3082 sin->sin_port = peer->addr.sin_port;
3083 } else {
3084 sin->sin_addr = peer->defaddr.sin_addr;
3085 sin->sin_port = peer->defaddr.sin_port;
3088 res = 0;
3090 return_unref:
3091 peer_unref(peer);
3093 return res;
3096 static void __auto_congest(const void *nothing)
3098 int callno = PTR_TO_CALLNO(nothing);
3099 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3100 ast_mutex_lock(&iaxsl[callno]);
3101 if (iaxs[callno]) {
3102 iaxs[callno]->initid = -1;
3103 iax2_queue_frame(callno, &f);
3104 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3106 ast_mutex_unlock(&iaxsl[callno]);
3109 static int auto_congest(const void *data)
3111 #ifdef SCHED_MULTITHREADED
3112 if (schedule_action(__auto_congest, data))
3113 #endif
3114 __auto_congest(data);
3115 return 0;
3118 static unsigned int iax2_datetime(const char *tz)
3120 time_t t;
3121 struct tm tm;
3122 unsigned int tmp;
3123 time(&t);
3124 if (!ast_strlen_zero(tz))
3125 ast_localtime(&t, &tm, tz);
3126 else
3127 ast_localtime(&t, &tm, NULL);
3128 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3129 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3130 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3131 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3132 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3133 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3134 return tmp;
3137 struct parsed_dial_string {
3138 char *username;
3139 char *password;
3140 char *key;
3141 char *peer;
3142 char *port;
3143 char *exten;
3144 char *context;
3145 char *options;
3149 * \brief Parses an IAX dial string into its component parts.
3150 * \param data the string to be parsed
3151 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3152 * \return nothing
3154 * This function parses the string and fills the structure
3155 * with pointers to its component parts. The input string
3156 * will be modified.
3158 * \note This function supports both plaintext passwords and RSA
3159 * key names; if the password string is formatted as '[keyname]',
3160 * then the keyname will be placed into the key field, and the
3161 * password field will be set to NULL.
3163 * \note The dial string format is:
3164 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3166 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3168 if (ast_strlen_zero(data))
3169 return;
3171 pds->peer = strsep(&data, "/");
3172 pds->exten = strsep(&data, "/");
3173 pds->options = data;
3175 if (pds->exten) {
3176 data = pds->exten;
3177 pds->exten = strsep(&data, "@");
3178 pds->context = data;
3181 if (strchr(pds->peer, '@')) {
3182 data = pds->peer;
3183 pds->username = strsep(&data, "@");
3184 pds->peer = data;
3187 if (pds->username) {
3188 data = pds->username;
3189 pds->username = strsep(&data, ":");
3190 pds->password = data;
3193 data = pds->peer;
3194 pds->peer = strsep(&data, ":");
3195 pds->port = data;
3197 /* check for a key name wrapped in [] in the secret position, if found,
3198 move it to the key field instead
3200 if (pds->password && (pds->password[0] == '[')) {
3201 pds->key = ast_strip_quoted(pds->password, "[", "]");
3202 pds->password = NULL;
3206 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3208 struct sockaddr_in sin;
3209 char *l=NULL, *n=NULL, *tmpstr;
3210 struct iax_ie_data ied;
3211 char *defaultrdest = "s";
3212 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3213 struct parsed_dial_string pds;
3214 struct create_addr_info cai;
3216 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3217 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3218 return -1;
3221 memset(&cai, 0, sizeof(cai));
3222 cai.encmethods = iax2_encryption;
3224 memset(&pds, 0, sizeof(pds));
3225 tmpstr = ast_strdupa(dest);
3226 parse_dial_string(tmpstr, &pds);
3228 if (ast_strlen_zero(pds.peer)) {
3229 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3230 return -1;
3233 if (!pds.exten) {
3234 if (!ast_strlen_zero(c->exten))
3235 pds.exten = c->exten;
3236 else
3237 pds.exten = defaultrdest;
3240 if (create_addr(pds.peer, c, &sin, &cai)) {
3241 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3242 return -1;
3245 if (!pds.username && !ast_strlen_zero(cai.username))
3246 pds.username = cai.username;
3247 if (!pds.password && !ast_strlen_zero(cai.secret))
3248 pds.password = cai.secret;
3249 if (!pds.key && !ast_strlen_zero(cai.outkey))
3250 pds.key = cai.outkey;
3251 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3252 pds.context = cai.peercontext;
3254 /* Keep track of the context for outgoing calls too */
3255 ast_copy_string(c->context, cai.context, sizeof(c->context));
3257 if (pds.port)
3258 sin.sin_port = htons(atoi(pds.port));
3260 l = c->cid.cid_num;
3261 n = c->cid.cid_name;
3263 /* Now build request */
3264 memset(&ied, 0, sizeof(ied));
3266 /* On new call, first IE MUST be IAX version of caller */
3267 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3268 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3269 if (pds.options && strchr(pds.options, 'a')) {
3270 /* Request auto answer */
3271 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3274 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3276 if (l) {
3277 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3278 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3279 } else {
3280 if (n)
3281 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3282 else
3283 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3286 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3287 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3289 if (n)
3290 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3291 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3292 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3294 if (!ast_strlen_zero(c->language))
3295 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3296 if (!ast_strlen_zero(c->cid.cid_dnid))
3297 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3298 if (!ast_strlen_zero(c->cid.cid_rdnis))
3299 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3301 if (pds.context)
3302 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3304 if (pds.username)
3305 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3307 if (cai.encmethods)
3308 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3310 ast_mutex_lock(&iaxsl[callno]);
3312 if (!ast_strlen_zero(c->context))
3313 ast_string_field_set(iaxs[callno], context, c->context);
3315 if (pds.username)
3316 ast_string_field_set(iaxs[callno], username, pds.username);
3318 iaxs[callno]->encmethods = cai.encmethods;
3320 iaxs[callno]->adsi = cai.adsi;
3322 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3323 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3325 if (pds.key)
3326 ast_string_field_set(iaxs[callno], outkey, pds.key);
3327 if (pds.password)
3328 ast_string_field_set(iaxs[callno], secret, pds.password);
3330 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3331 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3332 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3333 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3335 if (iaxs[callno]->maxtime) {
3336 /* Initialize pingtime and auto-congest time */
3337 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3338 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3339 } else if (autokill) {
3340 iaxs[callno]->pingtime = autokill / 2;
3341 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3344 /* send the command using the appropriate socket for this peer */
3345 iaxs[callno]->sockfd = cai.sockfd;
3347 /* Transmit the string in a "NEW" request */
3348 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3350 ast_mutex_unlock(&iaxsl[callno]);
3351 ast_setstate(c, AST_STATE_RINGING);
3353 return 0;
3356 static int iax2_hangup(struct ast_channel *c)
3358 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3359 int alreadygone;
3360 struct iax_ie_data ied;
3361 memset(&ied, 0, sizeof(ied));
3362 ast_mutex_lock(&iaxsl[callno]);
3363 if (callno && iaxs[callno]) {
3364 if (option_debug)
3365 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3366 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3367 /* Send the hangup unless we have had a transmission error or are already gone */
3368 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3369 if (!iaxs[callno]->error && !alreadygone) {
3370 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3371 if (!iaxs[callno]) {
3372 ast_mutex_unlock(&iaxsl[callno]);
3373 return 0;
3376 /* Explicitly predestroy it */
3377 iax2_predestroy(callno);
3378 /* If we were already gone to begin with, destroy us now */
3379 if (alreadygone && iaxs[callno]) {
3380 if (option_debug)
3381 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3382 iax2_destroy(callno);
3385 ast_mutex_unlock(&iaxsl[callno]);
3386 if (option_verbose > 2)
3387 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3388 return 0;
3391 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3393 struct ast_option_header *h;
3394 int res;
3396 switch (option) {
3397 case AST_OPTION_TXGAIN:
3398 case AST_OPTION_RXGAIN:
3399 /* these two cannot be sent, because they require a result */
3400 errno = ENOSYS;
3401 return -1;
3402 default:
3403 if (!(h = ast_malloc(datalen + sizeof(*h))))
3404 return -1;
3406 h->flag = AST_OPTION_FLAG_REQUEST;
3407 h->option = htons(option);
3408 memcpy(h->data, data, datalen);
3409 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3410 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3411 datalen + sizeof(*h), -1);
3412 free(h);
3413 return res;
3417 static struct ast_frame *iax2_read(struct ast_channel *c)
3419 ast_log(LOG_NOTICE, "I should never be called!\n");
3420 return &ast_null_frame;
3423 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3425 int res;
3426 struct iax_ie_data ied0;
3427 struct iax_ie_data ied1;
3428 unsigned int transferid = (unsigned int)ast_random();
3429 memset(&ied0, 0, sizeof(ied0));
3430 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3431 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3432 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3434 memset(&ied1, 0, sizeof(ied1));
3435 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3436 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3437 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3439 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3440 if (res)
3441 return -1;
3442 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3443 if (res)
3444 return -1;
3445 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3446 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3447 return 0;
3450 static void lock_both(unsigned short callno0, unsigned short callno1)
3452 ast_mutex_lock(&iaxsl[callno0]);
3453 while (ast_mutex_trylock(&iaxsl[callno1])) {
3454 ast_mutex_unlock(&iaxsl[callno0]);
3455 usleep(10);
3456 ast_mutex_lock(&iaxsl[callno0]);
3460 static void unlock_both(unsigned short callno0, unsigned short callno1)
3462 ast_mutex_unlock(&iaxsl[callno1]);
3463 ast_mutex_unlock(&iaxsl[callno0]);
3466 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)
3468 struct ast_channel *cs[3];
3469 struct ast_channel *who, *other;
3470 int to = -1;
3471 int res = -1;
3472 int transferstarted=0;
3473 struct ast_frame *f;
3474 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3475 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3476 struct timeval waittimer = {0, 0}, tv;
3478 lock_both(callno0, callno1);
3479 if (!iaxs[callno0] || !iaxs[callno1]) {
3480 unlock_both(callno0, callno1);
3481 return AST_BRIDGE_FAILED;
3483 /* Put them in native bridge mode */
3484 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3485 iaxs[callno0]->bridgecallno = callno1;
3486 iaxs[callno1]->bridgecallno = callno0;
3488 unlock_both(callno0, callno1);
3490 /* If not, try to bridge until we can execute a transfer, if we can */
3491 cs[0] = c0;
3492 cs[1] = c1;
3493 for (/* ever */;;) {
3494 /* Check in case we got masqueraded into */
3495 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3496 if (option_verbose > 2)
3497 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3498 /* Remove from native mode */
3499 if (c0->tech == &iax2_tech) {
3500 ast_mutex_lock(&iaxsl[callno0]);
3501 iaxs[callno0]->bridgecallno = 0;
3502 ast_mutex_unlock(&iaxsl[callno0]);
3504 if (c1->tech == &iax2_tech) {
3505 ast_mutex_lock(&iaxsl[callno1]);
3506 iaxs[callno1]->bridgecallno = 0;
3507 ast_mutex_unlock(&iaxsl[callno1]);
3509 return AST_BRIDGE_FAILED_NOWARN;
3511 if (c0->nativeformats != c1->nativeformats) {
3512 if (option_verbose > 2) {
3513 char buf0[255];
3514 char buf1[255];
3515 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3516 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3517 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3519 /* Remove from native mode */
3520 lock_both(callno0, callno1);
3521 if (iaxs[callno0])
3522 iaxs[callno0]->bridgecallno = 0;
3523 if (iaxs[callno1])
3524 iaxs[callno1]->bridgecallno = 0;
3525 unlock_both(callno0, callno1);
3526 return AST_BRIDGE_FAILED_NOWARN;
3528 /* check if transfered and if we really want native bridging */
3529 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3530 /* Try the transfer */
3531 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3532 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3533 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3534 transferstarted = 1;
3536 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3537 /* Call has been transferred. We're no longer involved */
3538 gettimeofday(&tv, NULL);
3539 if (ast_tvzero(waittimer)) {
3540 waittimer = tv;
3541 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3542 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3543 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3544 *fo = NULL;
3545 *rc = c0;
3546 res = AST_BRIDGE_COMPLETE;
3547 break;
3550 to = 1000;
3551 who = ast_waitfor_n(cs, 2, &to);
3552 if (timeoutms > -1) {
3553 timeoutms -= (1000 - to);
3554 if (timeoutms < 0)
3555 timeoutms = 0;
3557 if (!who) {
3558 if (!timeoutms) {
3559 res = AST_BRIDGE_RETRY;
3560 break;
3562 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3563 res = AST_BRIDGE_FAILED;
3564 break;
3566 continue;
3568 f = ast_read(who);
3569 if (!f) {
3570 *fo = NULL;
3571 *rc = who;
3572 res = AST_BRIDGE_COMPLETE;
3573 break;
3575 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3576 *fo = f;
3577 *rc = who;
3578 res = AST_BRIDGE_COMPLETE;
3579 break;
3581 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3582 if ((f->frametype == AST_FRAME_VOICE) ||
3583 (f->frametype == AST_FRAME_TEXT) ||
3584 (f->frametype == AST_FRAME_VIDEO) ||
3585 (f->frametype == AST_FRAME_IMAGE) ||
3586 (f->frametype == AST_FRAME_DTMF)) {
3587 /* monitored dtmf take out of the bridge.
3588 * check if we monitor the specific source.
3590 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3591 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3592 *rc = who;
3593 *fo = f;
3594 res = AST_BRIDGE_COMPLETE;
3595 /* Remove from native mode */
3596 break;
3598 /* everything else goes to the other side */
3599 ast_write(other, f);
3601 ast_frfree(f);
3602 /* Swap who gets priority */
3603 cs[2] = cs[0];
3604 cs[0] = cs[1];
3605 cs[1] = cs[2];
3607 lock_both(callno0, callno1);
3608 if(iaxs[callno0])
3609 iaxs[callno0]->bridgecallno = 0;
3610 if(iaxs[callno1])
3611 iaxs[callno1]->bridgecallno = 0;
3612 unlock_both(callno0, callno1);
3613 return res;
3616 static int iax2_answer(struct ast_channel *c)
3618 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3619 if (option_debug)
3620 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3621 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3624 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
3626 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3627 struct chan_iax2_pvt *pvt;
3628 int res = 0;
3630 if (option_debug && iaxdebug)
3631 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3633 ast_mutex_lock(&iaxsl[callno]);
3634 pvt = iaxs[callno];
3636 if (!pvt->peercallno) {
3637 /* We don't know the remote side's call number, yet. :( */
3638 int count = 10;
3639 while (count-- && pvt && !pvt->peercallno) {
3640 ast_mutex_unlock(&iaxsl[callno]);
3641 usleep(1);
3642 ast_mutex_lock(&iaxsl[callno]);
3643 pvt = iaxs[callno];
3645 if (!pvt->peercallno) {
3646 res = -1;
3647 goto done;
3651 switch (condition) {
3652 case AST_CONTROL_HOLD:
3653 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3654 ast_moh_start(c, data, pvt->mohinterpret);
3655 goto done;
3657 break;
3658 case AST_CONTROL_UNHOLD:
3659 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3660 ast_moh_stop(c);
3661 goto done;
3665 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3667 done:
3668 ast_mutex_unlock(&iaxsl[callno]);
3670 return res;
3673 static int iax2_transfer(struct ast_channel *c, const char *dest)
3675 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3676 struct iax_ie_data ied;
3677 char tmp[256], *context;
3678 ast_copy_string(tmp, dest, sizeof(tmp));
3679 context = strchr(tmp, '@');
3680 if (context) {
3681 *context = '\0';
3682 context++;
3684 memset(&ied, 0, sizeof(ied));
3685 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3686 if (context)
3687 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3688 if (option_debug)
3689 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3690 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3693 static int iax2_getpeertrunk(struct sockaddr_in sin)
3695 struct iax2_peer *peer;
3696 int res = 0;
3697 struct ao2_iterator i;
3699 i = ao2_iterator_init(peers, 0);
3700 while ((peer = ao2_iterator_next(&i))) {
3701 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3702 (peer->addr.sin_port == sin.sin_port)) {
3703 res = ast_test_flag(peer, IAX_TRUNK);
3704 peer_unref(peer);
3705 break;
3707 peer_unref(peer);
3710 return res;
3713 /*! \brief Create new call, interface with the PBX core */
3714 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3716 struct ast_channel *tmp;
3717 struct chan_iax2_pvt *i;
3718 struct ast_variable *v = NULL;
3720 if (!(i = iaxs[callno])) {
3721 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
3722 return NULL;
3725 /* Don't hold call lock */
3726 ast_mutex_unlock(&iaxsl[callno]);
3727 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);
3728 ast_mutex_lock(&iaxsl[callno]);
3729 if (!iaxs[callno]) {
3730 if (tmp) {
3731 ast_channel_free(tmp);
3733 ast_mutex_unlock(&iaxsl[callno]);
3734 return NULL;
3737 if (!tmp)
3738 return NULL;
3739 tmp->tech = &iax2_tech;
3740 /* We can support any format by default, until we get restricted */
3741 tmp->nativeformats = capability;
3742 tmp->readformat = ast_best_codec(capability);
3743 tmp->writeformat = ast_best_codec(capability);
3744 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3746 /* Don't use ast_set_callerid() here because it will
3747 * generate a NewCallerID event before the NewChannel event */
3748 if (!ast_strlen_zero(i->ani))
3749 tmp->cid.cid_ani = ast_strdup(i->ani);
3750 else
3751 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3752 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3753 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3754 tmp->cid.cid_pres = i->calling_pres;
3755 tmp->cid.cid_ton = i->calling_ton;
3756 tmp->cid.cid_tns = i->calling_tns;
3757 if (!ast_strlen_zero(i->language))
3758 ast_string_field_set(tmp, language, i->language);
3759 if (!ast_strlen_zero(i->accountcode))
3760 ast_string_field_set(tmp, accountcode, i->accountcode);
3761 if (i->amaflags)
3762 tmp->amaflags = i->amaflags;
3763 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3764 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3765 if (i->adsi)
3766 tmp->adsicpe = i->peeradsicpe;
3767 else
3768 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3769 i->owner = tmp;
3770 i->capability = capability;
3772 for (v = i->vars ; v ; v = v->next)
3773 pbx_builtin_setvar_helper(tmp, v->name, v->value);
3775 if (state != AST_STATE_DOWN) {
3776 if (ast_pbx_start(tmp)) {
3777 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3778 ast_hangup(tmp);
3779 i->owner = NULL;
3780 return NULL;
3784 ast_module_ref(ast_module_info->self);
3786 return tmp;
3789 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3791 unsigned long int mssincetx; /* unsigned to handle overflows */
3792 long int ms, pred;
3794 tpeer->trunkact = *tv;
3795 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3796 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3797 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3798 tpeer->txtrunktime = *tv;
3799 tpeer->lastsent = 999999;
3801 /* Update last transmit time now */
3802 tpeer->lasttxtime = *tv;
3804 /* Calculate ms offset */
3805 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3806 /* Predict from last value */
3807 pred = tpeer->lastsent + sampms;
3808 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3809 ms = pred;
3811 /* We never send the same timestamp twice, so fudge a little if we must */
3812 if (ms == tpeer->lastsent)
3813 ms = tpeer->lastsent + 1;
3814 tpeer->lastsent = ms;
3815 return ms;
3818 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3820 long ms; /* NOT unsigned */
3821 if (ast_tvzero(iaxs[callno]->rxcore)) {
3822 /* Initialize rxcore time if appropriate */
3823 gettimeofday(&iaxs[callno]->rxcore, NULL);
3824 /* Round to nearest 20ms so traces look pretty */
3825 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3827 /* Calculate difference between trunk and channel */
3828 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3829 /* Return as the sum of trunk time and the difference between trunk and real time */
3830 return ms + ts;
3833 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3835 int ms;
3836 int voice = 0;
3837 int genuine = 0;
3838 int adjust;
3839 struct timeval *delivery = NULL;
3842 /* What sort of frame do we have?: voice is self-explanatory
3843 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3844 non-genuine frames are CONTROL frames [ringing etc], DTMF
3845 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3846 the others need a timestamp slaved to the voice frames so that they go in sequence
3848 if (f) {
3849 if (f->frametype == AST_FRAME_VOICE) {
3850 voice = 1;
3851 delivery = &f->delivery;
3852 } else if (f->frametype == AST_FRAME_IAX) {
3853 genuine = 1;
3854 } else if (f->frametype == AST_FRAME_CNG) {
3855 p->notsilenttx = 0;
3858 if (ast_tvzero(p->offset)) {
3859 gettimeofday(&p->offset, NULL);
3860 /* Round to nearest 20ms for nice looking traces */
3861 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3863 /* If the timestamp is specified, just send it as is */
3864 if (ts)
3865 return ts;
3866 /* If we have a time that the frame arrived, always use it to make our timestamp */
3867 if (delivery && !ast_tvzero(*delivery)) {
3868 ms = ast_tvdiff_ms(*delivery, p->offset);
3869 if (option_debug > 2 && iaxdebug)
3870 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3871 } else {
3872 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3873 if (ms < 0)
3874 ms = 0;
3875 if (voice) {
3876 /* On a voice frame, use predicted values if appropriate */
3877 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3878 /* Adjust our txcore, keeping voice and non-voice synchronized */
3879 /* AN EXPLANATION:
3880 When we send voice, we usually send "calculated" timestamps worked out
3881 on the basis of the number of samples sent. When we send other frames,
3882 we usually send timestamps worked out from the real clock.
3883 The problem is that they can tend to drift out of step because the
3884 source channel's clock and our clock may not be exactly at the same rate.
3885 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3886 for this call. Moving it adjusts timestamps for non-voice frames.
3887 We make the adjustment in the style of a moving average. Each time we
3888 adjust p->offset by 10% of the difference between our clock-derived
3889 timestamp and the predicted timestamp. That's why you see "10000"
3890 below even though IAX2 timestamps are in milliseconds.
3891 The use of a moving average avoids offset moving too radically.
3892 Generally, "adjust" roams back and forth around 0, with offset hardly
3893 changing at all. But if a consistent different starts to develop it
3894 will be eliminated over the course of 10 frames (200-300msecs)
3896 adjust = (ms - p->nextpred);
3897 if (adjust < 0)
3898 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3899 else if (adjust > 0)
3900 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3902 if (!p->nextpred) {
3903 p->nextpred = ms; /*f->samples / 8;*/
3904 if (p->nextpred <= p->lastsent)
3905 p->nextpred = p->lastsent + 3;
3907 ms = p->nextpred;
3908 } else {
3909 /* in this case, just use the actual
3910 * time, since we're either way off
3911 * (shouldn't happen), or we're ending a
3912 * silent period -- and seed the next
3913 * predicted time. Also, round ms to the
3914 * next multiple of frame size (so our
3915 * silent periods are multiples of
3916 * frame size too) */
3918 if (option_debug && iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3919 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3920 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3922 if (f->samples >= 8) /* check to make sure we dont core dump */
3924 int diff = ms % (f->samples / 8);
3925 if (diff)
3926 ms += f->samples/8 - diff;
3929 p->nextpred = ms;
3930 p->notsilenttx = 1;
3932 } else if ( f->frametype == AST_FRAME_VIDEO ) {
3934 * IAX2 draft 03 says that timestamps MUST be in order.
3935 * It does not say anything about several frames having the same timestamp
3936 * When transporting video, we can have a frame that spans multiple iax packets
3937 * (so called slices), so it would make sense to use the same timestamp for all of
3938 * them
3939 * We do want to make sure that frames don't go backwards though
3941 if ( (unsigned int)ms < p->lastsent )
3942 ms = p->lastsent;
3943 } else {
3944 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3945 it's a genuine frame */
3946 if (genuine) {
3947 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3948 if (ms <= p->lastsent)
3949 ms = p->lastsent + 3;
3950 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3951 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3952 ms = p->lastsent + 3;
3956 p->lastsent = ms;
3957 if (voice)
3958 p->nextpred = p->nextpred + f->samples / 8;
3959 return ms;
3962 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3964 /* Returns where in "receive time" we are. That is, how many ms
3965 since we received (or would have received) the frame with timestamp 0 */
3966 int ms;
3967 #ifdef IAXTESTS
3968 int jit;
3969 #endif /* IAXTESTS */
3970 /* Setup rxcore if necessary */
3971 if (ast_tvzero(p->rxcore)) {
3972 p->rxcore = ast_tvnow();
3973 if (option_debug && iaxdebug)
3974 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3975 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3976 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3977 #if 1
3978 if (option_debug && iaxdebug)
3979 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3980 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3981 #endif
3984 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3985 #ifdef IAXTESTS
3986 if (test_jit) {
3987 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3988 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3989 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3990 jit = -jit;
3991 ms += jit;
3994 if (test_late) {
3995 ms += test_late;
3996 test_late = 0;
3998 #endif /* IAXTESTS */
3999 return ms;
4002 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
4004 struct iax2_trunk_peer *tpeer;
4006 /* Finds and locks trunk peer */
4007 ast_mutex_lock(&tpeerlock);
4008 for (tpeer = tpeers; tpeer; tpeer = tpeer->next) {
4009 /* We don't lock here because tpeer->addr *never* changes */
4010 if (!inaddrcmp(&tpeer->addr, sin)) {
4011 ast_mutex_lock(&tpeer->lock);
4012 break;
4015 if (!tpeer) {
4016 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
4017 ast_mutex_init(&tpeer->lock);
4018 tpeer->lastsent = 9999;
4019 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
4020 tpeer->trunkact = ast_tvnow();
4021 ast_mutex_lock(&tpeer->lock);
4022 tpeer->next = tpeers;
4023 tpeer->sockfd = fd;
4024 tpeers = tpeer;
4025 #ifdef SO_NO_CHECK
4026 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
4027 #endif
4028 if (option_debug)
4029 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
4032 ast_mutex_unlock(&tpeerlock);
4033 return tpeer;
4036 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
4038 struct ast_frame *f;
4039 struct iax2_trunk_peer *tpeer;
4040 void *tmp, *ptr;
4041 struct ast_iax2_meta_trunk_entry *met;
4042 struct ast_iax2_meta_trunk_mini *mtm;
4044 f = &fr->af;
4045 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
4046 if (tpeer) {
4047 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
4048 /* Need to reallocate space */
4049 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
4050 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
4051 ast_mutex_unlock(&tpeer->lock);
4052 return -1;
4055 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
4056 tpeer->trunkdata = tmp;
4057 if (option_debug)
4058 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);
4059 } else {
4060 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));
4061 ast_mutex_unlock(&tpeer->lock);
4062 return -1;
4066 /* Append to meta frame */
4067 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
4068 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
4069 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
4070 mtm->len = htons(f->datalen);
4071 mtm->mini.callno = htons(pvt->callno);
4072 mtm->mini.ts = htons(0xffff & fr->ts);
4073 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
4074 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
4075 } else {
4076 met = (struct ast_iax2_meta_trunk_entry *)ptr;
4077 /* Store call number and length in meta header */
4078 met->callno = htons(pvt->callno);
4079 met->len = htons(f->datalen);
4080 /* Advance pointers/decrease length past trunk entry header */
4081 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
4082 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
4084 /* Copy actual trunk data */
4085 memcpy(ptr, f->data, f->datalen);
4086 tpeer->trunkdatalen += f->datalen;
4088 tpeer->calls++;
4089 ast_mutex_unlock(&tpeer->lock);
4091 return 0;
4094 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
4096 aes_encrypt_key128(digest, ecx);
4097 aes_decrypt_key128(digest, dcx);
4100 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
4102 #if 0
4103 /* Debug with "fake encryption" */
4104 int x;
4105 if (len % 16)
4106 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4107 for (x=0;x<len;x++)
4108 dst[x] = src[x] ^ 0xff;
4109 #else
4110 unsigned char lastblock[16] = { 0 };
4111 int x;
4112 while(len > 0) {
4113 aes_decrypt(src, dst, dcx);
4114 for (x=0;x<16;x++)
4115 dst[x] ^= lastblock[x];
4116 memcpy(lastblock, src, sizeof(lastblock));
4117 dst += 16;
4118 src += 16;
4119 len -= 16;
4121 #endif
4124 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
4126 #if 0
4127 /* Debug with "fake encryption" */
4128 int x;
4129 if (len % 16)
4130 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4131 for (x=0;x<len;x++)
4132 dst[x] = src[x] ^ 0xff;
4133 #else
4134 unsigned char curblock[16] = { 0 };
4135 int x;
4136 while(len > 0) {
4137 for (x=0;x<16;x++)
4138 curblock[x] ^= src[x];
4139 aes_encrypt(curblock, dst, ecx);
4140 memcpy(curblock, dst, sizeof(curblock));
4141 dst += 16;
4142 src += 16;
4143 len -= 16;
4145 #endif
4148 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4150 int padding;
4151 unsigned char *workspace;
4153 workspace = alloca(*datalen);
4154 memset(f, 0, sizeof(*f));
4155 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4156 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4157 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
4158 return -1;
4159 /* Decrypt */
4160 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
4162 padding = 16 + (workspace[15] & 0xf);
4163 if (option_debug && iaxdebug)
4164 ast_log(LOG_DEBUG, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
4165 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
4166 return -1;
4168 *datalen -= padding;
4169 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4170 f->frametype = fh->type;
4171 if (f->frametype == AST_FRAME_VIDEO) {
4172 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
4173 } else {
4174 f->subclass = uncompress_subclass(fh->csub);
4176 } else {
4177 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4178 if (option_debug && iaxdebug)
4179 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
4180 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
4181 return -1;
4182 /* Decrypt */
4183 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
4184 padding = 16 + (workspace[15] & 0x0f);
4185 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
4186 return -1;
4187 *datalen -= padding;
4188 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4190 return 0;
4193 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4195 int padding;
4196 unsigned char *workspace;
4197 workspace = alloca(*datalen + 32);
4198 if (!workspace)
4199 return -1;
4200 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4201 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4202 if (option_debug && iaxdebug)
4203 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
4204 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
4205 padding = 16 + (padding & 0xf);
4206 memcpy(workspace, poo, padding);
4207 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4208 workspace[15] &= 0xf0;
4209 workspace[15] |= (padding & 0xf);
4210 if (option_debug && iaxdebug)
4211 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]);
4212 *datalen += padding;
4213 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
4214 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
4215 memcpy(poo, workspace + *datalen - 32, 32);
4216 } else {
4217 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4218 if (option_debug && iaxdebug)
4219 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
4220 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
4221 padding = 16 + (padding & 0xf);
4222 memcpy(workspace, poo, padding);
4223 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4224 workspace[15] &= 0xf0;
4225 workspace[15] |= (padding & 0x0f);
4226 *datalen += padding;
4227 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
4228 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
4229 memcpy(poo, workspace + *datalen - 32, 32);
4231 return 0;
4234 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4236 int res=-1;
4237 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
4238 /* Search for possible keys, given secrets */
4239 struct MD5Context md5;
4240 unsigned char digest[16];
4241 char *tmppw, *stringp;
4243 tmppw = ast_strdupa(iaxs[callno]->secret);
4244 stringp = tmppw;
4245 while ((tmppw = strsep(&stringp, ";"))) {
4246 MD5Init(&md5);
4247 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
4248 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
4249 MD5Final(digest, &md5);
4250 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
4251 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4252 if (!res) {
4253 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4254 break;
4257 } else
4258 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4259 return res;
4262 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
4264 /* Queue a packet for delivery on a given private structure. Use "ts" for
4265 timestamp, or calculate if ts is 0. Send immediately without retransmission
4266 or delayed, with retransmission */
4267 struct ast_iax2_full_hdr *fh;
4268 struct ast_iax2_mini_hdr *mh;
4269 struct ast_iax2_video_hdr *vh;
4270 struct {
4271 struct iax_frame fr2;
4272 unsigned char buffer[4096];
4273 } frb;
4274 struct iax_frame *fr;
4275 int res;
4276 int sendmini=0;
4277 unsigned int lastsent;
4278 unsigned int fts;
4280 frb.fr2.afdatalen = sizeof(frb.buffer);
4282 if (!pvt) {
4283 ast_log(LOG_WARNING, "No private structure for packet?\n");
4284 return -1;
4287 lastsent = pvt->lastsent;
4289 /* Calculate actual timestamp */
4290 fts = calc_timestamp(pvt, ts, f);
4292 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4293 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4294 * increment the "predicted timestamps" for voice, if we're predecting */
4295 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
4296 return 0;
4299 if ((ast_test_flag(pvt, IAX_TRUNK) ||
4300 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
4301 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
4302 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4303 (f->frametype == AST_FRAME_VOICE)
4304 /* is a voice frame */ &&
4305 (f->subclass == pvt->svoiceformat)
4306 /* is the same type */ ) {
4307 /* Force immediate rather than delayed transmission */
4308 now = 1;
4309 /* Mark that mini-style frame is appropriate */
4310 sendmini = 1;
4312 if ( f->frametype == AST_FRAME_VIDEO ) {
4314 * If the lower 15 bits of the timestamp roll over, or if
4315 * the video format changed then send a full frame.
4316 * Otherwise send a mini video frame
4318 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
4319 ((f->subclass & ~0x1) == pvt->svideoformat)
4321 now = 1;
4322 sendmini = 1;
4323 } else {
4324 now = 0;
4325 sendmini = 0;
4327 pvt->lastvsent = fts;
4329 /* Allocate an iax_frame */
4330 if (now) {
4331 fr = &frb.fr2;
4332 } else
4333 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));
4334 if (!fr) {
4335 ast_log(LOG_WARNING, "Out of memory\n");
4336 return -1;
4338 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4339 iax_frame_wrap(fr, f);
4341 fr->ts = fts;
4342 fr->callno = pvt->callno;
4343 fr->transfer = transfer;
4344 fr->final = final;
4345 if (!sendmini) {
4346 /* We need a full frame */
4347 if (seqno > -1)
4348 fr->oseqno = seqno;
4349 else
4350 fr->oseqno = pvt->oseqno++;
4351 fr->iseqno = pvt->iseqno;
4352 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
4353 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
4354 fh->ts = htonl(fr->ts);
4355 fh->oseqno = fr->oseqno;
4356 if (transfer) {
4357 fh->iseqno = 0;
4358 } else
4359 fh->iseqno = fr->iseqno;
4360 /* Keep track of the last thing we've acknowledged */
4361 if (!transfer)
4362 pvt->aseqno = fr->iseqno;
4363 fh->type = fr->af.frametype & 0xFF;
4364 if (fr->af.frametype == AST_FRAME_VIDEO)
4365 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
4366 else
4367 fh->csub = compress_subclass(fr->af.subclass);
4368 if (transfer) {
4369 fr->dcallno = pvt->transfercallno;
4370 } else
4371 fr->dcallno = pvt->peercallno;
4372 fh->dcallno = htons(fr->dcallno);
4373 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4374 fr->data = fh;
4375 fr->retries = 0;
4376 /* Retry after 2x the ping time has passed */
4377 fr->retrytime = pvt->pingtime * 2;
4378 if (fr->retrytime < MIN_RETRY_TIME)
4379 fr->retrytime = MIN_RETRY_TIME;
4380 if (fr->retrytime > MAX_RETRY_TIME)
4381 fr->retrytime = MAX_RETRY_TIME;
4382 /* Acks' don't get retried */
4383 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
4384 fr->retries = -1;
4385 else if (f->frametype == AST_FRAME_VOICE)
4386 pvt->svoiceformat = f->subclass;
4387 else if (f->frametype == AST_FRAME_VIDEO)
4388 pvt->svideoformat = f->subclass & ~0x1;
4389 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4390 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4391 if (iaxdebug) {
4392 if (fr->transfer)
4393 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4394 else
4395 iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4397 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
4398 } else
4399 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4402 if (now) {
4403 res = send_packet(fr);
4404 } else
4405 res = iax2_transmit(fr);
4406 } else {
4407 if (ast_test_flag(pvt, IAX_TRUNK)) {
4408 iax2_trunk_queue(pvt, fr);
4409 res = 0;
4410 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4411 /* Video frame have no sequence number */
4412 fr->oseqno = -1;
4413 fr->iseqno = -1;
4414 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
4415 vh->zeros = 0;
4416 vh->callno = htons(0x8000 | fr->callno);
4417 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
4418 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
4419 fr->data = vh;
4420 fr->retries = -1;
4421 res = send_packet(fr);
4422 } else {
4423 /* Mini-frames have no sequence number */
4424 fr->oseqno = -1;
4425 fr->iseqno = -1;
4426 /* Mini frame will do */
4427 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
4428 mh->callno = htons(fr->callno);
4429 mh->ts = htons(fr->ts & 0xFFFF);
4430 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
4431 fr->data = mh;
4432 fr->retries = -1;
4433 if (pvt->transferring == TRANSFER_MEDIAPASS)
4434 fr->transfer = 1;
4435 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4436 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4437 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
4438 } else
4439 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4441 res = send_packet(fr);
4444 return res;
4447 static int iax2_show_users(int fd, int argc, char *argv[])
4449 regex_t regexbuf;
4450 int havepattern = 0;
4452 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4453 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4455 struct iax2_user *user = NULL;
4456 char auth[90];
4457 char *pstr = "";
4458 struct ao2_iterator i;
4460 switch (argc) {
4461 case 5:
4462 if (!strcasecmp(argv[3], "like")) {
4463 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4464 return RESULT_SHOWUSAGE;
4465 havepattern = 1;
4466 } else
4467 return RESULT_SHOWUSAGE;
4468 case 3:
4469 break;
4470 default:
4471 return RESULT_SHOWUSAGE;
4474 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4475 i = ao2_iterator_init(users, 0);
4476 for (user = ao2_iterator_next(&i); user;
4477 user_unref(user), user = ao2_iterator_next(&i)) {
4478 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
4479 continue;
4481 if (!ast_strlen_zero(user->secret)) {
4482 ast_copy_string(auth,user->secret,sizeof(auth));
4483 } else if (!ast_strlen_zero(user->inkeys)) {
4484 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
4485 } else
4486 ast_copy_string(auth, "-no secret-", sizeof(auth));
4488 if(ast_test_flag(user,IAX_CODEC_NOCAP))
4489 pstr = "REQ Only";
4490 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
4491 pstr = "Disabled";
4492 else
4493 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
4495 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
4496 user->contexts ? user->contexts->context : context,
4497 user->ha ? "Yes" : "No", pstr);
4500 if (havepattern)
4501 regfree(&regexbuf);
4503 return RESULT_SUCCESS;
4504 #undef FORMAT
4505 #undef FORMAT2
4508 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
4510 regex_t regexbuf;
4511 int havepattern = 0;
4512 int total_peers = 0;
4513 int online_peers = 0;
4514 int offline_peers = 0;
4515 int unmonitored_peers = 0;
4516 struct ao2_iterator i;
4518 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4519 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4521 struct iax2_peer *peer = NULL;
4522 char name[256];
4523 int registeredonly=0;
4524 char *term = manager ? "\r\n" : "\n";
4526 switch (argc) {
4527 case 6:
4528 if (!strcasecmp(argv[3], "registered"))
4529 registeredonly = 1;
4530 else
4531 return RESULT_SHOWUSAGE;
4532 if (!strcasecmp(argv[4], "like")) {
4533 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
4534 return RESULT_SHOWUSAGE;
4535 havepattern = 1;
4536 } else
4537 return RESULT_SHOWUSAGE;
4538 break;
4539 case 5:
4540 if (!strcasecmp(argv[3], "like")) {
4541 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4542 return RESULT_SHOWUSAGE;
4543 havepattern = 1;
4544 } else
4545 return RESULT_SHOWUSAGE;
4546 break;
4547 case 4:
4548 if (!strcasecmp(argv[3], "registered"))
4549 registeredonly = 1;
4550 else
4551 return RESULT_SHOWUSAGE;
4552 break;
4553 case 3:
4554 break;
4555 default:
4556 return RESULT_SHOWUSAGE;
4560 if (s)
4561 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4562 else
4563 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4565 i = ao2_iterator_init(peers, 0);
4566 for (peer = ao2_iterator_next(&i); peer;
4567 peer_unref(peer), peer = ao2_iterator_next(&i)) {
4568 char nm[20];
4569 char status[20];
4570 char srch[2000];
4571 int retstatus;
4573 if (registeredonly && !peer->addr.sin_addr.s_addr)
4574 continue;
4575 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
4576 continue;
4578 if (!ast_strlen_zero(peer->username))
4579 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
4580 else
4581 ast_copy_string(name, peer->name, sizeof(name));
4583 retstatus = peer_status(peer, status, sizeof(status));
4584 if (retstatus > 0)
4585 online_peers++;
4586 else if (!retstatus)
4587 offline_peers++;
4588 else
4589 unmonitored_peers++;
4591 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
4593 snprintf(srch, sizeof(srch), FORMAT, name,
4594 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4595 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4597 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4598 peer->encmethods ? "(E)" : " ", status, term);
4600 if (s)
4601 astman_append(s, FORMAT, name,
4602 peer->addr.sin_addr.s_addr ? ast_inet_ntoa( peer->addr.sin_addr) : "(Unspecified)",
4603 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4605 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4606 peer->encmethods ? "(E)" : " ", status, term);
4607 else
4608 ast_cli(fd, FORMAT, name,
4609 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4610 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4612 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4613 peer->encmethods ? "(E)" : " ", status, term);
4614 total_peers++;
4617 if (s)
4618 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4619 else
4620 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4622 if (havepattern)
4623 regfree(&regexbuf);
4625 return RESULT_SUCCESS;
4626 #undef FORMAT
4627 #undef FORMAT2
4630 static int iax2_show_threads(int fd, int argc, char *argv[])
4632 struct iax2_thread *thread = NULL;
4633 time_t t;
4634 int threadcount = 0, dynamiccount = 0;
4635 char type;
4637 if (argc != 3)
4638 return RESULT_SHOWUSAGE;
4640 ast_cli(fd, "IAX2 Thread Information\n");
4641 time(&t);
4642 ast_cli(fd, "Idle Threads:\n");
4643 AST_LIST_LOCK(&idle_list);
4644 AST_LIST_TRAVERSE(&idle_list, thread, list) {
4645 #ifdef DEBUG_SCHED_MULTITHREAD
4646 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4647 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4648 #else
4649 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4650 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4651 #endif
4652 threadcount++;
4654 AST_LIST_UNLOCK(&idle_list);
4655 ast_cli(fd, "Active Threads:\n");
4656 AST_LIST_LOCK(&active_list);
4657 AST_LIST_TRAVERSE(&active_list, thread, list) {
4658 if (thread->type == IAX_TYPE_DYNAMIC)
4659 type = 'D';
4660 else
4661 type = 'P';
4662 #ifdef DEBUG_SCHED_MULTITHREAD
4663 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4664 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4665 #else
4666 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4667 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4668 #endif
4669 threadcount++;
4671 AST_LIST_UNLOCK(&active_list);
4672 ast_cli(fd, "Dynamic Threads:\n");
4673 AST_LIST_LOCK(&dynamic_list);
4674 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
4675 #ifdef DEBUG_SCHED_MULTITHREAD
4676 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4677 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4678 #else
4679 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4680 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4681 #endif
4682 dynamiccount++;
4684 AST_LIST_UNLOCK(&dynamic_list);
4685 ast_cli(fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
4686 return RESULT_SUCCESS;
4689 static int iax2_show_peers(int fd, int argc, char *argv[])
4691 return __iax2_show_peers(0, fd, NULL, argc, argv);
4693 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
4695 ast_cli_netstats(s, -1, 0);
4696 astman_append(s, "\r\n");
4697 return RESULT_SUCCESS;
4700 static int iax2_show_firmware(int fd, int argc, char *argv[])
4702 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4703 #if !defined(__FreeBSD__)
4704 #define FORMAT "%-15.15s %-15d %-15d\n"
4705 #else /* __FreeBSD__ */
4706 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4707 #endif /* __FreeBSD__ */
4708 struct iax_firmware *cur;
4709 if ((argc != 3) && (argc != 4))
4710 return RESULT_SHOWUSAGE;
4711 ast_mutex_lock(&waresl.lock);
4713 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
4714 for (cur = waresl.wares;cur;cur = cur->next) {
4715 if ((argc == 3) || (!strcasecmp(argv[3], (char *)cur->fwh->devname)))
4716 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
4717 (int)ntohl(cur->fwh->datalen));
4719 ast_mutex_unlock(&waresl.lock);
4720 return RESULT_SUCCESS;
4721 #undef FORMAT
4722 #undef FORMAT2
4725 /* JDG: callback to display iax peers in manager */
4726 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
4728 char *a[] = { "iax2", "show", "users" };
4729 int ret;
4730 const char *id = astman_get_header(m,"ActionID");
4732 if (!ast_strlen_zero(id))
4733 astman_append(s, "ActionID: %s\r\n",id);
4734 ret = __iax2_show_peers(1, -1, s, 3, a );
4735 astman_append(s, "\r\n\r\n" );
4736 return ret;
4737 } /* /JDG */
4739 static char *regstate2str(int regstate)
4741 switch(regstate) {
4742 case REG_STATE_UNREGISTERED:
4743 return "Unregistered";
4744 case REG_STATE_REGSENT:
4745 return "Request Sent";
4746 case REG_STATE_AUTHSENT:
4747 return "Auth. Sent";
4748 case REG_STATE_REGISTERED:
4749 return "Registered";
4750 case REG_STATE_REJECTED:
4751 return "Rejected";
4752 case REG_STATE_TIMEOUT:
4753 return "Timeout";
4754 case REG_STATE_NOAUTH:
4755 return "No Authentication";
4756 default:
4757 return "Unknown";
4761 static int iax2_show_registry(int fd, int argc, char *argv[])
4763 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4764 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4765 struct iax2_registry *reg = NULL;
4767 char host[80];
4768 char perceived[80];
4769 if (argc != 3)
4770 return RESULT_SHOWUSAGE;
4771 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4772 AST_LIST_LOCK(&registrations);
4773 AST_LIST_TRAVERSE(&registrations, reg, entry) {
4774 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
4775 if (reg->us.sin_addr.s_addr)
4776 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
4777 else
4778 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
4779 ast_cli(fd, FORMAT, host,
4780 (reg->dnsmgr) ? "Y" : "N",
4781 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
4783 AST_LIST_UNLOCK(&registrations);
4784 return RESULT_SUCCESS;
4785 #undef FORMAT
4786 #undef FORMAT2
4789 static int iax2_show_channels(int fd, int argc, char *argv[])
4791 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4792 #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"
4793 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4794 int x;
4795 int numchans = 0;
4797 if (argc != 3)
4798 return RESULT_SHOWUSAGE;
4799 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4800 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4801 ast_mutex_lock(&iaxsl[x]);
4802 if (iaxs[x]) {
4803 int lag, jitter, localdelay;
4804 jb_info jbinfo;
4806 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4807 jb_getinfo(iaxs[x]->jb, &jbinfo);
4808 jitter = jbinfo.jitter;
4809 localdelay = jbinfo.current - jbinfo.min;
4810 } else {
4811 jitter = -1;
4812 localdelay = 0;
4814 lag = iaxs[x]->remote_rr.delay;
4815 ast_cli(fd, FORMAT,
4816 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4817 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
4818 S_OR(iaxs[x]->username, "(None)"),
4819 iaxs[x]->callno, iaxs[x]->peercallno,
4820 iaxs[x]->oseqno, iaxs[x]->iseqno,
4821 lag,
4822 jitter,
4823 localdelay,
4824 ast_getformatname(iaxs[x]->voiceformat) );
4825 numchans++;
4827 ast_mutex_unlock(&iaxsl[x]);
4829 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4830 return RESULT_SUCCESS;
4831 #undef FORMAT
4832 #undef FORMAT2
4833 #undef FORMATB
4836 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
4838 int x;
4839 int numchans = 0;
4840 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4841 ast_mutex_lock(&iaxsl[x]);
4842 if (iaxs[x]) {
4843 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
4844 char *fmt;
4845 jb_info jbinfo;
4847 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4848 jb_getinfo(iaxs[x]->jb, &jbinfo);
4849 localjitter = jbinfo.jitter;
4850 localdelay = jbinfo.current - jbinfo.min;
4851 locallost = jbinfo.frames_lost;
4852 locallosspct = jbinfo.losspct/1000;
4853 localdropped = jbinfo.frames_dropped;
4854 localooo = jbinfo.frames_ooo;
4855 } else {
4856 localjitter = -1;
4857 localdelay = 0;
4858 locallost = -1;
4859 locallosspct = -1;
4860 localdropped = 0;
4861 localooo = -1;
4863 if (limit_fmt)
4864 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4865 else
4866 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4867 if (s)
4869 astman_append(s, fmt,
4870 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4871 iaxs[x]->pingtime,
4872 localjitter,
4873 localdelay,
4874 locallost,
4875 locallosspct,
4876 localdropped,
4877 localooo,
4878 iaxs[x]->frames_received/1000,
4879 iaxs[x]->remote_rr.jitter,
4880 iaxs[x]->remote_rr.delay,
4881 iaxs[x]->remote_rr.losscnt,
4882 iaxs[x]->remote_rr.losspct,
4883 iaxs[x]->remote_rr.dropped,
4884 iaxs[x]->remote_rr.ooo,
4885 iaxs[x]->remote_rr.packets/1000);
4886 else
4887 ast_cli(fd, fmt,
4888 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4889 iaxs[x]->pingtime,
4890 localjitter,
4891 localdelay,
4892 locallost,
4893 locallosspct,
4894 localdropped,
4895 localooo,
4896 iaxs[x]->frames_received/1000,
4897 iaxs[x]->remote_rr.jitter,
4898 iaxs[x]->remote_rr.delay,
4899 iaxs[x]->remote_rr.losscnt,
4900 iaxs[x]->remote_rr.losspct,
4901 iaxs[x]->remote_rr.dropped,
4902 iaxs[x]->remote_rr.ooo,
4903 iaxs[x]->remote_rr.packets/1000
4905 numchans++;
4907 ast_mutex_unlock(&iaxsl[x]);
4909 return numchans;
4912 static int iax2_show_netstats(int fd, int argc, char *argv[])
4914 int numchans = 0;
4915 if (argc != 3)
4916 return RESULT_SHOWUSAGE;
4917 ast_cli(fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4918 ast_cli(fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4919 numchans = ast_cli_netstats(NULL, fd, 1);
4920 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4921 return RESULT_SUCCESS;
4924 static int iax2_do_debug(int fd, int argc, char *argv[])
4926 if (argc < 2 || argc > 3)
4927 return RESULT_SHOWUSAGE;
4928 iaxdebug = 1;
4929 ast_cli(fd, "IAX2 Debugging Enabled\n");
4930 return RESULT_SUCCESS;
4933 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
4935 if (argc < 3 || argc > 4)
4936 return RESULT_SHOWUSAGE;
4937 iaxtrunkdebug = 1;
4938 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
4939 return RESULT_SUCCESS;
4942 static int iax2_do_jb_debug(int fd, int argc, char *argv[])
4944 if (argc < 3 || argc > 4)
4945 return RESULT_SHOWUSAGE;
4946 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
4947 ast_cli(fd, "IAX2 Jitterbuffer Debugging Enabled\n");
4948 return RESULT_SUCCESS;
4951 static int iax2_no_debug(int fd, int argc, char *argv[])
4953 if (argc < 3 || argc > 4)
4954 return RESULT_SHOWUSAGE;
4955 iaxdebug = 0;
4956 ast_cli(fd, "IAX2 Debugging Disabled\n");
4957 return RESULT_SUCCESS;
4960 static int iax2_no_trunk_debug(int fd, int argc, char *argv[])
4962 if (argc < 4 || argc > 5)
4963 return RESULT_SHOWUSAGE;
4964 iaxtrunkdebug = 0;
4965 ast_cli(fd, "IAX2 Trunk Debugging Disabled\n");
4966 return RESULT_SUCCESS;
4969 static int iax2_no_jb_debug(int fd, int argc, char *argv[])
4971 if (argc < 4 || argc > 5)
4972 return RESULT_SHOWUSAGE;
4973 jb_setoutput(jb_error_output, jb_warning_output, NULL);
4974 jb_debug_output("\n");
4975 ast_cli(fd, "IAX2 Jitterbuffer Debugging Disabled\n");
4976 return RESULT_SUCCESS;
4979 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
4981 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4982 int res = -1;
4983 ast_mutex_lock(&iaxsl[callno]);
4984 if (iaxs[callno]) {
4985 /* If there's an outstanding error, return failure now */
4986 if (!iaxs[callno]->error) {
4987 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
4988 res = 0;
4989 /* Don't waste bandwidth sending null frames */
4990 else if (f->frametype == AST_FRAME_NULL)
4991 res = 0;
4992 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
4993 res = 0;
4994 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
4995 res = 0;
4996 else
4997 /* Simple, just queue for transmission */
4998 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
4999 } else {
5000 if (option_debug)
5001 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
5004 /* If it's already gone, just return */
5005 ast_mutex_unlock(&iaxsl[callno]);
5006 return res;
5009 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
5010 int now, int transfer, int final)
5012 struct ast_frame f = { 0, };
5014 f.frametype = type;
5015 f.subclass = command;
5016 f.datalen = datalen;
5017 f.src = __FUNCTION__;
5018 f.data = (void *) data;
5020 return iax2_send(i, &f, ts, seqno, now, transfer, final);
5023 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5025 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
5028 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5030 int res;
5031 ast_mutex_lock(&iaxsl[callno]);
5032 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
5033 ast_mutex_unlock(&iaxsl[callno]);
5034 return res;
5038 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5039 * the pvt struct for the given call number may disappear during its
5040 * execution.
5042 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)
5044 int call_num = i->callno;
5045 /* It is assumed that the callno has already been locked */
5046 iax2_predestroy(i->callno);
5047 if (!iaxs[call_num])
5048 return -1;
5049 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
5052 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)
5054 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
5057 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
5059 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
5062 static int apply_context(struct iax2_context *con, const char *context)
5064 while(con) {
5065 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
5066 return -1;
5067 con = con->next;
5069 return 0;
5073 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5075 /* Start pessimistic */
5076 int res = -1;
5077 int version = 2;
5078 struct iax2_user *user = NULL, *best = NULL;
5079 int bestscore = 0;
5080 int gotcapability = 0;
5081 struct ast_variable *v = NULL, *tmpvar = NULL;
5082 struct ao2_iterator i;
5084 if (!iaxs[callno])
5085 return res;
5086 if (ies->called_number)
5087 ast_string_field_set(iaxs[callno], exten, ies->called_number);
5088 if (ies->calling_number) {
5089 ast_shrink_phone_number(ies->calling_number);
5090 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
5092 if (ies->calling_name)
5093 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
5094 if (ies->calling_ani)
5095 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
5096 if (ies->dnid)
5097 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
5098 if (ies->rdnis)
5099 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
5100 if (ies->called_context)
5101 ast_string_field_set(iaxs[callno], context, ies->called_context);
5102 if (ies->language)
5103 ast_string_field_set(iaxs[callno], language, ies->language);
5104 if (ies->username)
5105 ast_string_field_set(iaxs[callno], username, ies->username);
5106 if (ies->calling_ton > -1)
5107 iaxs[callno]->calling_ton = ies->calling_ton;
5108 if (ies->calling_tns > -1)
5109 iaxs[callno]->calling_tns = ies->calling_tns;
5110 if (ies->calling_pres > -1)
5111 iaxs[callno]->calling_pres = ies->calling_pres;
5112 if (ies->format)
5113 iaxs[callno]->peerformat = ies->format;
5114 if (ies->adsicpe)
5115 iaxs[callno]->peeradsicpe = ies->adsicpe;
5116 if (ies->capability) {
5117 gotcapability = 1;
5118 iaxs[callno]->peercapability = ies->capability;
5120 if (ies->version)
5121 version = ies->version;
5123 /* Use provided preferences until told otherwise for actual preferences */
5124 if(ies->codec_prefs) {
5125 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
5126 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
5129 if (!gotcapability)
5130 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
5131 if (version > IAX_PROTO_VERSION) {
5132 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
5133 ast_inet_ntoa(sin->sin_addr), version);
5134 return res;
5136 /* Search the userlist for a compatible entry, and fill in the rest */
5137 i = ao2_iterator_init(users, 0);
5138 while ((user = ao2_iterator_next(&i))) {
5139 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
5140 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
5141 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
5142 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
5143 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
5144 if (!ast_strlen_zero(iaxs[callno]->username)) {
5145 /* Exact match, stop right now. */
5146 if (best)
5147 user_unref(best);
5148 best = user;
5149 break;
5150 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5151 /* No required authentication */
5152 if (user->ha) {
5153 /* There was host authentication and we passed, bonus! */
5154 if (bestscore < 4) {
5155 bestscore = 4;
5156 if (best)
5157 user_unref(best);
5158 best = user;
5159 continue;
5161 } else {
5162 /* No host access, but no secret, either, not bad */
5163 if (bestscore < 3) {
5164 bestscore = 3;
5165 if (best)
5166 user_unref(best);
5167 best = user;
5168 continue;
5171 } else {
5172 if (user->ha) {
5173 /* Authentication, but host access too, eh, it's something.. */
5174 if (bestscore < 2) {
5175 bestscore = 2;
5176 if (best)
5177 user_unref(best);
5178 best = user;
5179 continue;
5181 } else {
5182 /* Authentication and no host access... This is our baseline */
5183 if (bestscore < 1) {
5184 bestscore = 1;
5185 if (best)
5186 user_unref(best);
5187 best = user;
5188 continue;
5193 user_unref(user);
5195 user = best;
5196 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
5197 user = realtime_user(iaxs[callno]->username, sin);
5198 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
5199 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
5200 user = user_unref(user);
5203 if (user) {
5204 /* We found our match (use the first) */
5205 /* copy vars */
5206 for (v = user->vars ; v ; v = v->next) {
5207 if((tmpvar = ast_variable_new(v->name, v->value))) {
5208 tmpvar->next = iaxs[callno]->vars;
5209 iaxs[callno]->vars = tmpvar;
5212 /* If a max AUTHREQ restriction is in place, activate it */
5213 if (user->maxauthreq > 0)
5214 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
5215 iaxs[callno]->prefs = user->prefs;
5216 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
5217 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
5218 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
5219 iaxs[callno]->encmethods = user->encmethods;
5220 /* Store the requested username if not specified */
5221 if (ast_strlen_zero(iaxs[callno]->username))
5222 ast_string_field_set(iaxs[callno], username, user->name);
5223 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5224 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
5225 iaxs[callno]->capability = user->capability;
5226 /* And use the default context */
5227 if (ast_strlen_zero(iaxs[callno]->context)) {
5228 if (user->contexts)
5229 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5230 else
5231 ast_string_field_set(iaxs[callno], context, context);
5233 /* And any input keys */
5234 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
5235 /* And the permitted authentication methods */
5236 iaxs[callno]->authmethods = user->authmethods;
5237 iaxs[callno]->adsi = user->adsi;
5238 /* If they have callerid, override the given caller id. Always store the ANI */
5239 if (!ast_strlen_zero(iaxs[callno]->cid_num) || !ast_strlen_zero(iaxs[callno]->cid_name)) {
5240 if (ast_test_flag(user, IAX_HASCALLERID)) {
5241 iaxs[callno]->calling_tns = 0;
5242 iaxs[callno]->calling_ton = 0;
5243 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
5244 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
5245 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
5247 if (ast_strlen_zero(iaxs[callno]->ani))
5248 ast_string_field_set(iaxs[callno], ani, user->cid_num);
5249 } else {
5250 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
5252 if (!ast_strlen_zero(user->accountcode))
5253 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
5254 if (!ast_strlen_zero(user->mohinterpret))
5255 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
5256 if (!ast_strlen_zero(user->mohsuggest))
5257 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
5258 if (user->amaflags)
5259 iaxs[callno]->amaflags = user->amaflags;
5260 if (!ast_strlen_zero(user->language))
5261 ast_string_field_set(iaxs[callno], language, user->language);
5262 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
5263 /* Keep this check last */
5264 if (!ast_strlen_zero(user->dbsecret)) {
5265 char *family, *key=NULL;
5266 char buf[80];
5267 family = ast_strdupa(user->dbsecret);
5268 key = strchr(family, '/');
5269 if (key) {
5270 *key = '\0';
5271 key++;
5273 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
5274 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
5275 else
5276 ast_string_field_set(iaxs[callno], secret, buf);
5277 } else
5278 ast_string_field_set(iaxs[callno], secret, user->secret);
5279 res = 0;
5280 user = user_unref(user);
5282 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
5283 return res;
5286 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
5288 struct ast_iax2_full_hdr fh;
5289 fh.scallno = htons(src | IAX_FLAG_FULL);
5290 fh.dcallno = htons(dst);
5291 fh.ts = 0;
5292 fh.oseqno = 0;
5293 fh.iseqno = 0;
5294 fh.type = AST_FRAME_IAX;
5295 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
5296 if (iaxdebug)
5297 iax_showframe(NULL, &fh, 0, sin, 0);
5298 if (option_debug)
5299 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5300 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
5301 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
5304 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
5306 /* Select exactly one common encryption if there are any */
5307 p->encmethods &= enc;
5308 if (p->encmethods) {
5309 if (p->encmethods & IAX_ENCRYPT_AES128)
5310 p->encmethods = IAX_ENCRYPT_AES128;
5311 else
5312 p->encmethods = 0;
5317 * \pre iaxsl[call_num] is locked
5319 * \note Since this function calls send_command_final(), the pvt struct for the given
5320 * call number may disappear while executing this function.
5322 static int authenticate_request(int call_num)
5324 struct iax_ie_data ied;
5325 int res = -1, authreq_restrict = 0;
5326 char challenge[10];
5327 struct chan_iax2_pvt *p = iaxs[call_num];
5329 memset(&ied, 0, sizeof(ied));
5331 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5332 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5333 struct iax2_user *user, tmp_user = {
5334 .name = p->username,
5337 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5338 if (user) {
5339 if (user->curauthreq == user->maxauthreq)
5340 authreq_restrict = 1;
5341 else
5342 user->curauthreq++;
5343 user = user_unref(user);
5347 /* If the AUTHREQ limit test failed, send back an error */
5348 if (authreq_restrict) {
5349 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
5350 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
5351 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
5352 return 0;
5355 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
5356 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
5357 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
5358 ast_string_field_set(p, challenge, challenge);
5359 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5360 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
5362 if (p->encmethods)
5363 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
5365 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
5367 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
5369 if (p->encmethods)
5370 ast_set_flag(p, IAX_ENCRYPTED);
5372 return res;
5375 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
5377 char requeststr[256];
5378 char md5secret[256] = "";
5379 char secret[256] = "";
5380 char rsasecret[256] = "";
5381 int res = -1;
5382 int x;
5383 struct iax2_user *user, tmp_user = {
5384 .name = p->username,
5387 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5388 if (user) {
5389 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5390 ast_atomic_fetchadd_int(&user->curauthreq, -1);
5391 ast_clear_flag(p, IAX_MAXAUTHREQ);
5393 ast_string_field_set(p, host, user->name);
5394 user = user_unref(user);
5397 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
5398 return res;
5399 if (ies->password)
5400 ast_copy_string(secret, ies->password, sizeof(secret));
5401 if (ies->md5_result)
5402 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5403 if (ies->rsa_result)
5404 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5405 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
5406 struct ast_key *key;
5407 char *keyn;
5408 char tmpkey[256];
5409 char *stringp=NULL;
5410 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
5411 stringp=tmpkey;
5412 keyn = strsep(&stringp, ":");
5413 while(keyn) {
5414 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5415 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
5416 res = 0;
5417 break;
5418 } else if (!key)
5419 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
5420 keyn = strsep(&stringp, ":");
5422 } else if (p->authmethods & IAX_AUTH_MD5) {
5423 struct MD5Context md5;
5424 unsigned char digest[16];
5425 char *tmppw, *stringp;
5427 tmppw = ast_strdupa(p->secret);
5428 stringp = tmppw;
5429 while((tmppw = strsep(&stringp, ";"))) {
5430 MD5Init(&md5);
5431 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
5432 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5433 MD5Final(digest, &md5);
5434 /* If they support md5, authenticate with it. */
5435 for (x=0;x<16;x++)
5436 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5437 if (!strcasecmp(requeststr, md5secret)) {
5438 res = 0;
5439 break;
5442 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
5443 if (!strcmp(secret, p->secret))
5444 res = 0;
5446 return res;
5449 /*! \brief Verify inbound registration */
5450 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5452 char requeststr[256] = "";
5453 char peer[256] = "";
5454 char md5secret[256] = "";
5455 char rsasecret[256] = "";
5456 char secret[256] = "";
5457 struct iax2_peer *p = NULL;
5458 struct ast_key *key;
5459 char *keyn;
5460 int x;
5461 int expire = 0;
5462 int res = -1;
5464 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
5465 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5466 if (ies->username)
5467 ast_copy_string(peer, ies->username, sizeof(peer));
5468 if (ies->password)
5469 ast_copy_string(secret, ies->password, sizeof(secret));
5470 if (ies->md5_result)
5471 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5472 if (ies->rsa_result)
5473 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5474 if (ies->refresh)
5475 expire = ies->refresh;
5477 if (ast_strlen_zero(peer)) {
5478 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
5479 return -1;
5482 /* SLD: first call to lookup peer during registration */
5483 ast_mutex_unlock(&iaxsl[callno]);
5484 p = find_peer(peer, 1);
5485 ast_mutex_lock(&iaxsl[callno]);
5486 if (!p || !iaxs[callno]) {
5487 if (authdebug && !p)
5488 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5489 goto return_unref;
5492 if (!ast_test_flag(p, IAX_DYNAMIC)) {
5493 if (authdebug)
5494 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5495 goto return_unref;
5498 if (!ast_apply_ha(p->ha, sin)) {
5499 if (authdebug)
5500 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5501 goto return_unref;
5503 if (!inaddrcmp(&p->addr, sin))
5504 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
5505 ast_string_field_set(iaxs[callno], secret, p->secret);
5506 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
5507 /* Check secret against what we have on file */
5508 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5509 if (!ast_strlen_zero(p->inkeys)) {
5510 char tmpkeys[256];
5511 char *stringp=NULL;
5512 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
5513 stringp=tmpkeys;
5514 keyn = strsep(&stringp, ":");
5515 while(keyn) {
5516 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5517 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
5518 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5519 break;
5520 } else if (!key)
5521 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
5522 keyn = strsep(&stringp, ":");
5524 if (!keyn) {
5525 if (authdebug)
5526 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
5527 goto return_unref;
5529 } else {
5530 if (authdebug)
5531 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
5532 goto return_unref;
5534 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5535 struct MD5Context md5;
5536 unsigned char digest[16];
5537 char *tmppw, *stringp;
5539 tmppw = ast_strdupa(p->secret);
5540 stringp = tmppw;
5541 while((tmppw = strsep(&stringp, ";"))) {
5542 MD5Init(&md5);
5543 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
5544 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5545 MD5Final(digest, &md5);
5546 for (x=0;x<16;x++)
5547 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5548 if (!strcasecmp(requeststr, md5secret))
5549 break;
5551 if (tmppw) {
5552 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5553 } else {
5554 if (authdebug)
5555 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
5556 goto return_unref;
5558 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
5559 /* They've provided a plain text password and we support that */
5560 if (strcmp(secret, p->secret)) {
5561 if (authdebug)
5562 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5563 goto return_unref;
5564 } else
5565 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5566 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
5567 if (authdebug)
5568 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
5569 goto return_unref;
5571 ast_string_field_set(iaxs[callno], peer, peer);
5572 /* Choose lowest expiry number */
5573 if (expire && (expire < iaxs[callno]->expiry))
5574 iaxs[callno]->expiry = expire;
5576 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5578 res = 0;
5580 return_unref:
5581 if (p)
5582 peer_unref(p);
5584 return res;
5587 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)
5589 int res = -1;
5590 int x;
5591 if (!ast_strlen_zero(keyn)) {
5592 if (!(authmethods & IAX_AUTH_RSA)) {
5593 if (ast_strlen_zero(secret))
5594 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));
5595 } else if (ast_strlen_zero(challenge)) {
5596 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
5597 } else {
5598 char sig[256];
5599 struct ast_key *key;
5600 key = ast_key_get(keyn, AST_KEY_PRIVATE);
5601 if (!key) {
5602 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
5603 } else {
5604 if (ast_sign(key, (char*)challenge, sig)) {
5605 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
5606 res = -1;
5607 } else {
5608 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
5609 res = 0;
5614 /* Fall back */
5615 if (res && !ast_strlen_zero(secret)) {
5616 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
5617 struct MD5Context md5;
5618 unsigned char digest[16];
5619 char digres[128];
5620 MD5Init(&md5);
5621 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
5622 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
5623 MD5Final(digest, &md5);
5624 /* If they support md5, authenticate with it. */
5625 for (x=0;x<16;x++)
5626 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
5627 if (ecx && dcx)
5628 build_enc_keys(digest, ecx, dcx);
5629 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
5630 res = 0;
5631 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
5632 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
5633 res = 0;
5634 } else
5635 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
5637 return res;
5641 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5642 * so do not call this function with a pvt lock held.
5644 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
5646 struct iax2_peer *peer = NULL;
5647 /* Start pessimistic */
5648 int res = -1;
5649 int authmethods = 0;
5650 struct iax_ie_data ied;
5651 uint16_t callno = p->callno;
5653 memset(&ied, 0, sizeof(ied));
5655 if (ies->username)
5656 ast_string_field_set(p, username, ies->username);
5657 if (ies->challenge)
5658 ast_string_field_set(p, challenge, ies->challenge);
5659 if (ies->authmethods)
5660 authmethods = ies->authmethods;
5661 if (authmethods & IAX_AUTH_MD5)
5662 merge_encryption(p, ies->encmethods);
5663 else
5664 p->encmethods = 0;
5666 /* Check for override RSA authentication first */
5667 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
5668 /* Normal password authentication */
5669 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5670 } else {
5671 struct ao2_iterator i = ao2_iterator_init(peers, 0);
5672 while ((peer = ao2_iterator_next(&i))) {
5673 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
5674 /* No peer specified at our end, or this is the peer */
5675 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
5676 /* No username specified in peer rule, or this is the right username */
5677 && (!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)))
5678 /* No specified host, or this is our host */
5680 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5681 if (!res) {
5682 peer_unref(peer);
5683 break;
5686 peer_unref(peer);
5688 if (!peer) {
5689 /* We checked our list and didn't find one. It's unlikely, but possible,
5690 that we're trying to authenticate *to* a realtime peer */
5691 const char *peer_name = ast_strdupa(p->peer);
5692 ast_mutex_unlock(&iaxsl[callno]);
5693 if ((peer = realtime_peer(peer_name, NULL))) {
5694 ast_mutex_lock(&iaxsl[callno]);
5695 if (!(p = iaxs[callno])) {
5696 peer_unref(peer);
5697 return -1;
5699 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5700 peer_unref(peer);
5702 if (!peer) {
5703 ast_mutex_lock(&iaxsl[callno]);
5704 if (!(p = iaxs[callno]))
5705 return -1;
5709 if (ies->encmethods)
5710 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
5711 if (!res)
5712 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
5713 return res;
5716 static int iax2_do_register(struct iax2_registry *reg);
5718 static void __iax2_do_register_s(const void *data)
5720 struct iax2_registry *reg = (struct iax2_registry *)data;
5721 reg->expire = -1;
5722 iax2_do_register(reg);
5725 static int iax2_do_register_s(const void *data)
5727 #ifdef SCHED_MULTITHREADED
5728 if (schedule_action(__iax2_do_register_s, data))
5729 #endif
5730 __iax2_do_register_s(data);
5731 return 0;
5734 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5736 int newcall = 0;
5737 char newip[256];
5738 struct iax_ie_data ied;
5739 struct sockaddr_in new;
5742 memset(&ied, 0, sizeof(ied));
5743 if (ies->apparent_addr)
5744 bcopy(ies->apparent_addr, &new, sizeof(new));
5745 if (ies->callno)
5746 newcall = ies->callno;
5747 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
5748 ast_log(LOG_WARNING, "Invalid transfer request\n");
5749 return -1;
5751 pvt->transfercallno = newcall;
5752 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
5753 inet_aton(newip, &pvt->transfer.sin_addr);
5754 pvt->transfer.sin_family = AF_INET;
5755 pvt->transferring = TRANSFER_BEGIN;
5756 pvt->transferid = ies->transferid;
5757 if (ies->transferid)
5758 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
5759 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
5760 return 0;
5763 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5765 char exten[256] = "";
5766 int status = CACHE_FLAG_UNKNOWN;
5767 int expiry = iaxdefaultdpcache;
5768 int x;
5769 int matchmore = 0;
5770 struct iax2_dpcache *dp, *prev;
5772 if (ies->called_number)
5773 ast_copy_string(exten, ies->called_number, sizeof(exten));
5775 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
5776 status = CACHE_FLAG_EXISTS;
5777 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
5778 status = CACHE_FLAG_CANEXIST;
5779 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
5780 status = CACHE_FLAG_NONEXISTENT;
5782 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
5783 /* Don't really do anything with this */
5785 if (ies->refresh)
5786 expiry = ies->refresh;
5787 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
5788 matchmore = CACHE_FLAG_MATCHMORE;
5789 ast_mutex_lock(&dpcache_lock);
5790 prev = NULL;
5791 dp = pvt->dpentries;
5792 while(dp) {
5793 if (!strcmp(dp->exten, exten)) {
5794 /* Let them go */
5795 if (prev)
5796 prev->peer = dp->peer;
5797 else
5798 pvt->dpentries = dp->peer;
5799 dp->peer = NULL;
5800 dp->callno = 0;
5801 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
5802 if (dp->flags & CACHE_FLAG_PENDING) {
5803 dp->flags &= ~CACHE_FLAG_PENDING;
5804 dp->flags |= status;
5805 dp->flags |= matchmore;
5807 /* Wake up waiters */
5808 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
5809 if (dp->waiters[x] > -1)
5810 write(dp->waiters[x], "asdf", 4);
5812 prev = dp;
5813 dp = dp->peer;
5815 ast_mutex_unlock(&dpcache_lock);
5816 return 0;
5819 static int complete_transfer(int callno, struct iax_ies *ies)
5821 int peercallno = 0;
5822 struct chan_iax2_pvt *pvt = iaxs[callno];
5823 struct iax_frame *cur;
5824 jb_frame frame;
5826 if (ies->callno)
5827 peercallno = ies->callno;
5829 if (peercallno < 1) {
5830 ast_log(LOG_WARNING, "Invalid transfer request\n");
5831 return -1;
5833 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
5834 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
5835 /* Reset sequence numbers */
5836 pvt->oseqno = 0;
5837 pvt->rseqno = 0;
5838 pvt->iseqno = 0;
5839 pvt->aseqno = 0;
5841 if (pvt->peercallno) {
5842 remove_by_peercallno(pvt);
5844 pvt->peercallno = peercallno;
5845 store_by_peercallno(pvt);
5847 pvt->transferring = TRANSFER_NONE;
5848 pvt->svoiceformat = -1;
5849 pvt->voiceformat = 0;
5850 pvt->svideoformat = -1;
5851 pvt->videoformat = 0;
5852 pvt->transfercallno = -1;
5853 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
5854 memset(&pvt->offset, 0, sizeof(pvt->offset));
5855 /* reset jitterbuffer */
5856 while(jb_getall(pvt->jb,&frame) == JB_OK)
5857 iax2_frame_free(frame.data);
5858 jb_reset(pvt->jb);
5859 pvt->lag = 0;
5860 pvt->last = 0;
5861 pvt->lastsent = 0;
5862 pvt->nextpred = 0;
5863 pvt->pingtime = DEFAULT_RETRY_TIME;
5864 AST_LIST_LOCK(&iaxq.queue);
5865 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
5866 /* We must cancel any packets that would have been transmitted
5867 because now we're talking to someone new. It's okay, they
5868 were transmitted to someone that didn't care anyway. */
5869 if (callno == cur->callno)
5870 cur->retries = -1;
5872 AST_LIST_UNLOCK(&iaxq.queue);
5873 return 0;
5876 /*! \brief Acknowledgment received for OUR registration */
5877 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
5879 struct iax2_registry *reg;
5880 /* Start pessimistic */
5881 char peer[256] = "";
5882 char msgstatus[60];
5883 int refresh = 60;
5884 char ourip[256] = "<Unspecified>";
5885 struct sockaddr_in oldus;
5886 struct sockaddr_in us;
5887 int oldmsgs;
5889 memset(&us, 0, sizeof(us));
5890 if (ies->apparent_addr)
5891 bcopy(ies->apparent_addr, &us, sizeof(us));
5892 if (ies->username)
5893 ast_copy_string(peer, ies->username, sizeof(peer));
5894 if (ies->refresh)
5895 refresh = ies->refresh;
5896 if (ies->calling_number) {
5897 /* We don't do anything with it really, but maybe we should */
5899 reg = iaxs[callno]->reg;
5900 if (!reg) {
5901 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
5902 return -1;
5904 memcpy(&oldus, &reg->us, sizeof(oldus));
5905 oldmsgs = reg->messages;
5906 if (inaddrcmp(&reg->addr, sin)) {
5907 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
5908 return -1;
5910 memcpy(&reg->us, &us, sizeof(reg->us));
5911 if (ies->msgcount >= 0)
5912 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
5913 /* always refresh the registration at the interval requested by the server
5914 we are registering to
5916 reg->refresh = refresh;
5917 AST_SCHED_DEL(sched, reg->expire);
5918 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
5919 if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
5920 if (option_verbose > 2) {
5921 if (reg->messages > 255)
5922 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
5923 else if (reg->messages > 1)
5924 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
5925 else if (reg->messages > 0)
5926 snprintf(msgstatus, sizeof(msgstatus), " with 1 new message waiting\n");
5927 else
5928 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
5929 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
5930 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
5932 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
5934 reg->regstate = REG_STATE_REGISTERED;
5935 return 0;
5938 static int iax2_register(char *value, int lineno)
5940 struct iax2_registry *reg;
5941 char copy[256];
5942 char *username, *hostname, *secret;
5943 char *porta;
5944 char *stringp=NULL;
5946 if (!value)
5947 return -1;
5948 ast_copy_string(copy, value, sizeof(copy));
5949 stringp=copy;
5950 username = strsep(&stringp, "@");
5951 hostname = strsep(&stringp, "@");
5952 if (!hostname) {
5953 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
5954 return -1;
5956 stringp=username;
5957 username = strsep(&stringp, ":");
5958 secret = strsep(&stringp, ":");
5959 stringp=hostname;
5960 hostname = strsep(&stringp, ":");
5961 porta = strsep(&stringp, ":");
5963 if (porta && !atoi(porta)) {
5964 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
5965 return -1;
5967 if (!(reg = ast_calloc(1, sizeof(*reg))))
5968 return -1;
5969 if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
5970 free(reg);
5971 return -1;
5973 ast_copy_string(reg->username, username, sizeof(reg->username));
5974 if (secret)
5975 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
5976 reg->expire = -1;
5977 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
5978 reg->addr.sin_family = AF_INET;
5979 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
5980 AST_LIST_LOCK(&registrations);
5981 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
5982 AST_LIST_UNLOCK(&registrations);
5984 return 0;
5987 static void register_peer_exten(struct iax2_peer *peer, int onoff)
5989 char multi[256];
5990 char *stringp, *ext;
5991 if (!ast_strlen_zero(regcontext)) {
5992 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
5993 stringp = multi;
5994 while((ext = strsep(&stringp, "&"))) {
5995 if (onoff) {
5996 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
5997 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
5998 "Noop", ast_strdup(peer->name), ast_free, "IAX2");
5999 } else
6000 ast_context_remove_extension(regcontext, ext, 1, NULL);
6004 static void prune_peers(void);
6006 static void unlink_peer(struct iax2_peer *peer)
6008 if (peer->expire > -1) {
6009 if (!ast_sched_del(sched, peer->expire)) {
6010 peer->expire = -1;
6011 peer_unref(peer);
6015 if (peer->pokeexpire > -1) {
6016 if (!ast_sched_del(sched, peer->pokeexpire)) {
6017 peer->pokeexpire = -1;
6018 peer_unref(peer);
6022 ao2_unlink(peers, peer);
6025 static void __expire_registry(const void *data)
6027 struct iax2_peer *peer = (struct iax2_peer *) data;
6029 if (!peer)
6030 return;
6032 peer->expire = -1;
6034 if (option_debug)
6035 ast_log(LOG_DEBUG, "Expiring registration for peer '%s'\n", peer->name);
6036 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
6037 realtime_update_peer(peer->name, &peer->addr, 0);
6038 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
6039 /* Reset the address */
6040 memset(&peer->addr, 0, sizeof(peer->addr));
6041 /* Reset expiry value */
6042 peer->expiry = min_reg_expire;
6043 if (!ast_test_flag(peer, IAX_TEMPONLY))
6044 ast_db_del("IAX/Registry", peer->name);
6045 register_peer_exten(peer, 0);
6046 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
6047 if (iax2_regfunk)
6048 iax2_regfunk(peer->name, 0);
6050 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
6051 unlink_peer(peer);
6053 peer_unref(peer);
6056 static int expire_registry(const void *data)
6058 #ifdef SCHED_MULTITHREADED
6059 if (schedule_action(__expire_registry, data))
6060 #endif
6061 __expire_registry(data);
6062 return 0;
6065 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
6067 static void reg_source_db(struct iax2_peer *p)
6069 char data[80];
6070 struct in_addr in;
6071 char *c, *d;
6072 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
6073 c = strchr(data, ':');
6074 if (c) {
6075 *c = '\0';
6076 c++;
6077 if (inet_aton(data, &in)) {
6078 d = strchr(c, ':');
6079 if (d) {
6080 *d = '\0';
6081 d++;
6082 if (option_verbose > 2)
6083 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
6084 ast_inet_ntoa(in), atoi(c), atoi(d));
6085 iax2_poke_peer(p, 0);
6086 p->expiry = atoi(d);
6087 memset(&p->addr, 0, sizeof(p->addr));
6088 p->addr.sin_family = AF_INET;
6089 p->addr.sin_addr = in;
6090 p->addr.sin_port = htons(atoi(c));
6091 if (p->expire > -1) {
6092 if (!ast_sched_del(sched, p->expire)) {
6093 p->expire = -1;
6094 peer_unref(p);
6097 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6098 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6099 if (p->expire == -1)
6100 peer_unref(p);
6101 if (iax2_regfunk)
6102 iax2_regfunk(p->name, 1);
6103 register_peer_exten(p, 1);
6112 * \pre iaxsl[callno] is locked
6114 * \note Since this function calls send_command_final(), the pvt struct for
6115 * the given call number may disappear while executing this function.
6117 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
6119 /* Called from IAX thread only, with proper iaxsl lock */
6120 struct iax_ie_data ied;
6121 struct iax2_peer *p;
6122 int msgcount;
6123 char data[80];
6124 int version;
6125 const char *peer_name;
6126 int res = -1;
6128 memset(&ied, 0, sizeof(ied));
6130 peer_name = ast_strdupa(iaxs[callno]->peer);
6132 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6133 ast_mutex_unlock(&iaxsl[callno]);
6134 if (!(p = find_peer(peer_name, 1))) {
6135 ast_mutex_lock(&iaxsl[callno]);
6136 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6137 return -1;
6139 ast_mutex_lock(&iaxsl[callno]);
6140 if (!iaxs[callno])
6141 goto return_unref;
6143 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6144 if (sin->sin_addr.s_addr) {
6145 time_t nowtime;
6146 time(&nowtime);
6147 realtime_update_peer(peer_name, sin, nowtime);
6148 } else {
6149 realtime_update_peer(peer_name, sin, 0);
6152 if (inaddrcmp(&p->addr, sin)) {
6153 if (iax2_regfunk)
6154 iax2_regfunk(p->name, 1);
6155 /* Stash the IP address from which they registered */
6156 memcpy(&p->addr, sin, sizeof(p->addr));
6157 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
6158 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
6159 ast_db_put("IAX/Registry", p->name, data);
6160 if (option_verbose > 2)
6161 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
6162 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
6163 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
6164 register_peer_exten(p, 1);
6165 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6166 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
6167 if (option_verbose > 2)
6168 ast_verbose(VERBOSE_PREFIX_3 "Unregistered IAX2 '%s' (%s)\n", p->name,
6169 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6170 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
6171 register_peer_exten(p, 0);
6172 ast_db_del("IAX/Registry", p->name);
6173 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6175 /* Update the host */
6176 /* Verify that the host is really there */
6177 iax2_poke_peer(p, callno);
6180 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6181 if (!iaxs[callno]) {
6182 res = 0;
6183 goto return_unref;
6186 /* Store socket fd */
6187 p->sockfd = fd;
6188 /* Setup the expiry */
6189 if (p->expire > -1) {
6190 if (!ast_sched_del(sched, p->expire)) {
6191 p->expire = -1;
6192 peer_unref(p);
6195 /* treat an unspecified refresh interval as the minimum */
6196 if (!refresh)
6197 refresh = min_reg_expire;
6198 if (refresh > max_reg_expire) {
6199 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6200 p->name, max_reg_expire, refresh);
6201 p->expiry = max_reg_expire;
6202 } else if (refresh < min_reg_expire) {
6203 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6204 p->name, min_reg_expire, refresh);
6205 p->expiry = min_reg_expire;
6206 } else {
6207 p->expiry = refresh;
6209 if (p->expiry && sin->sin_addr.s_addr) {
6210 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6211 if (p->expire == -1)
6212 peer_unref(p);
6214 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
6215 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
6216 if (sin->sin_addr.s_addr) {
6217 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
6218 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
6219 if (!ast_strlen_zero(p->mailbox)) {
6220 int new, old;
6221 ast_app_inboxcount(p->mailbox, &new, &old);
6222 if (new > 255)
6223 new = 255;
6224 if (old > 255)
6225 old = 255;
6226 msgcount = (old << 8) | new;
6227 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
6229 if (ast_test_flag(p, IAX_HASCALLERID)) {
6230 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
6231 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
6234 version = iax_check_version(devtype);
6235 if (version)
6236 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
6238 res = 0;
6240 return_unref:
6241 peer_unref(p);
6243 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
6246 static int registry_authrequest(int callno)
6248 struct iax_ie_data ied;
6249 struct iax2_peer *p;
6250 char challenge[10];
6251 const char *peer_name;
6252 int res = -1;
6254 peer_name = ast_strdupa(iaxs[callno]->peer);
6256 /* SLD: third call to find_peer in registration */
6257 ast_mutex_unlock(&iaxsl[callno]);
6258 p = find_peer(peer_name, 1);
6259 ast_mutex_lock(&iaxsl[callno]);
6260 if (!iaxs[callno])
6261 goto return_unref;
6262 if (!p) {
6263 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6264 goto return_unref;
6267 memset(&ied, 0, sizeof(ied));
6268 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
6269 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
6270 /* Build the challenge */
6271 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
6272 ast_string_field_set(iaxs[callno], challenge, challenge);
6273 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
6275 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
6277 res = 0;
6279 return_unref:
6280 peer_unref(p);
6282 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
6285 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
6287 struct iax2_registry *reg;
6288 /* Start pessimistic */
6289 struct iax_ie_data ied;
6290 char peer[256] = "";
6291 char challenge[256] = "";
6292 int res;
6293 int authmethods = 0;
6294 if (ies->authmethods)
6295 authmethods = ies->authmethods;
6296 if (ies->username)
6297 ast_copy_string(peer, ies->username, sizeof(peer));
6298 if (ies->challenge)
6299 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
6300 memset(&ied, 0, sizeof(ied));
6301 reg = iaxs[callno]->reg;
6302 if (reg) {
6303 if (inaddrcmp(&reg->addr, sin)) {
6304 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6305 return -1;
6307 if (ast_strlen_zero(reg->secret)) {
6308 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
6309 reg->regstate = REG_STATE_NOAUTH;
6310 return -1;
6312 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
6313 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
6314 if (reg->secret[0] == '[') {
6315 char tmpkey[256];
6316 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
6317 tmpkey[strlen(tmpkey) - 1] = '\0';
6318 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
6319 } else
6320 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
6321 if (!res) {
6322 reg->regstate = REG_STATE_AUTHSENT;
6323 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
6324 } else
6325 return -1;
6326 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
6327 } else
6328 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
6329 return -1;
6332 static void stop_stuff(int callno)
6334 iax2_destroy_helper(iaxs[callno]);
6337 static void __auth_reject(const void *nothing)
6339 /* Called from IAX thread only, without iaxs lock */
6340 int callno = (int)(long)(nothing);
6341 struct iax_ie_data ied;
6342 ast_mutex_lock(&iaxsl[callno]);
6343 if (iaxs[callno]) {
6344 memset(&ied, 0, sizeof(ied));
6345 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
6346 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
6347 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
6348 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
6349 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
6350 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
6352 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
6354 ast_mutex_unlock(&iaxsl[callno]);
6357 static int auth_reject(const void *data)
6359 int callno = (int)(long)(data);
6360 ast_mutex_lock(&iaxsl[callno]);
6361 if (iaxs[callno])
6362 iaxs[callno]->authid = -1;
6363 ast_mutex_unlock(&iaxsl[callno]);
6364 #ifdef SCHED_MULTITHREADED
6365 if (schedule_action(__auth_reject, data))
6366 #endif
6367 __auth_reject(data);
6368 return 0;
6371 static int auth_fail(int callno, int failcode)
6373 /* Schedule sending the authentication failure in one second, to prevent
6374 guessing */
6375 if (iaxs[callno]) {
6376 iaxs[callno]->authfail = failcode;
6377 if (delayreject) {
6378 AST_SCHED_DEL(sched, iaxs[callno]->authid);
6379 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
6380 } else
6381 auth_reject((void *)(long)callno);
6383 return 0;
6386 static void __auto_hangup(const void *nothing)
6388 /* Called from IAX thread only, without iaxs lock */
6389 int callno = (int)(long)(nothing);
6390 struct iax_ie_data ied;
6391 ast_mutex_lock(&iaxsl[callno]);
6392 if (iaxs[callno]) {
6393 memset(&ied, 0, sizeof(ied));
6394 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
6395 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
6396 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
6398 ast_mutex_unlock(&iaxsl[callno]);
6401 static int auto_hangup(const void *data)
6403 int callno = (int)(long)(data);
6404 ast_mutex_lock(&iaxsl[callno]);
6405 if (iaxs[callno]) {
6406 iaxs[callno]->autoid = -1;
6408 ast_mutex_unlock(&iaxsl[callno]);
6409 #ifdef SCHED_MULTITHREADED
6410 if (schedule_action(__auto_hangup, data))
6411 #endif
6412 __auto_hangup(data);
6413 return 0;
6416 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
6418 struct iax_ie_data ied;
6419 /* Auto-hangup with 30 seconds of inactivity */
6420 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
6421 iaxs[callno]->autoid = iax2_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
6422 memset(&ied, 0, sizeof(ied));
6423 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
6424 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
6425 dp->flags |= CACHE_FLAG_TRANSMITTED;
6428 static int iax2_vnak(int callno)
6430 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
6433 static void vnak_retransmit(int callno, int last)
6435 struct iax_frame *f;
6437 AST_LIST_LOCK(&iaxq.queue);
6438 AST_LIST_TRAVERSE(&iaxq.queue, f, list) {
6439 /* Send a copy immediately */
6440 if ((f->callno == callno) && iaxs[f->callno] &&
6441 ((unsigned char ) (f->oseqno - last) < 128) &&
6442 (f->retries >= 0)) {
6443 send_packet(f);
6446 AST_LIST_UNLOCK(&iaxq.queue);
6449 static void __iax2_poke_peer_s(const void *data)
6451 struct iax2_peer *peer = (struct iax2_peer *)data;
6452 iax2_poke_peer(peer, 0);
6453 peer_unref(peer);
6456 static int iax2_poke_peer_s(const void *data)
6458 struct iax2_peer *peer = (struct iax2_peer *)data;
6459 peer->pokeexpire = -1;
6460 #ifdef SCHED_MULTITHREADED
6461 if (schedule_action(__iax2_poke_peer_s, data))
6462 #endif
6463 __iax2_poke_peer_s(data);
6464 return 0;
6467 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
6469 int res = 0;
6470 struct iax_frame *fr;
6471 struct ast_iax2_meta_hdr *meta;
6472 struct ast_iax2_meta_trunk_hdr *mth;
6473 int calls = 0;
6475 /* Point to frame */
6476 fr = (struct iax_frame *)tpeer->trunkdata;
6477 /* Point to meta data */
6478 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
6479 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
6480 if (tpeer->trunkdatalen) {
6481 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6482 meta->zeros = 0;
6483 meta->metacmd = IAX_META_TRUNK;
6484 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
6485 meta->cmddata = IAX_META_TRUNK_MINI;
6486 else
6487 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
6488 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
6489 /* And the rest of the ast_iax2 header */
6490 fr->direction = DIRECTION_OUTGRESS;
6491 fr->retrans = -1;
6492 fr->transfer = 0;
6493 /* Any appropriate call will do */
6494 fr->data = fr->afdata;
6495 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
6496 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
6497 calls = tpeer->calls;
6498 #if 0
6499 if (option_debug)
6500 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));
6501 #endif
6502 /* Reset transmit trunk side data */
6503 tpeer->trunkdatalen = 0;
6504 tpeer->calls = 0;
6506 if (res < 0)
6507 return res;
6508 return calls;
6511 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
6513 /* Drop when trunk is about 5 seconds idle */
6514 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
6515 return 1;
6516 return 0;
6519 static int timing_read(int *id, int fd, short events, void *cbdata)
6521 char buf[1024];
6522 int res;
6523 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
6524 int processed = 0;
6525 int totalcalls = 0;
6526 #ifdef ZT_TIMERACK
6527 int x = 1;
6528 #endif
6529 struct timeval now;
6530 if (iaxtrunkdebug)
6531 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA);
6532 gettimeofday(&now, NULL);
6533 if (events & AST_IO_PRI) {
6534 #ifdef ZT_TIMERACK
6535 /* Great, this is a timing interface, just call the ioctl */
6536 if (ioctl(fd, ZT_TIMERACK, &x)) {
6537 ast_log(LOG_WARNING, "Unable to acknowledge zap timer. IAX trunking will fail!\n");
6538 usleep(1);
6539 return -1;
6541 #endif
6542 } else {
6543 /* Read and ignore from the pseudo channel for timing */
6544 res = read(fd, buf, sizeof(buf));
6545 if (res < 1) {
6546 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
6547 return 1;
6550 /* For each peer that supports trunking... */
6551 ast_mutex_lock(&tpeerlock);
6552 tpeer = tpeers;
6553 while(tpeer) {
6554 processed++;
6555 res = 0;
6556 ast_mutex_lock(&tpeer->lock);
6557 /* We can drop a single tpeer per pass. That makes all this logic
6558 substantially easier */
6559 if (!drop && iax2_trunk_expired(tpeer, &now)) {
6560 /* Take it out of the list, but don't free it yet, because it
6561 could be in use */
6562 if (prev)
6563 prev->next = tpeer->next;
6564 else
6565 tpeers = tpeer->next;
6566 drop = tpeer;
6567 } else {
6568 res = send_trunk(tpeer, &now);
6569 if (iaxtrunkdebug)
6570 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);
6572 totalcalls += res;
6573 res = 0;
6574 ast_mutex_unlock(&tpeer->lock);
6575 prev = tpeer;
6576 tpeer = tpeer->next;
6578 ast_mutex_unlock(&tpeerlock);
6579 if (drop) {
6580 ast_mutex_lock(&drop->lock);
6581 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6582 because by the time they could get tpeerlock, we've already grabbed it */
6583 if (option_debug)
6584 ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
6585 if (drop->trunkdata) {
6586 free(drop->trunkdata);
6587 drop->trunkdata = NULL;
6589 ast_mutex_unlock(&drop->lock);
6590 ast_mutex_destroy(&drop->lock);
6591 free(drop);
6594 if (iaxtrunkdebug)
6595 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
6596 iaxtrunkdebug =0;
6597 return 1;
6600 struct dpreq_data {
6601 int callno;
6602 char context[AST_MAX_EXTENSION];
6603 char callednum[AST_MAX_EXTENSION];
6604 char *callerid;
6607 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
6609 unsigned short dpstatus = 0;
6610 struct iax_ie_data ied1;
6611 int mm;
6613 memset(&ied1, 0, sizeof(ied1));
6614 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
6615 /* Must be started */
6616 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
6617 dpstatus = IAX_DPSTATUS_EXISTS;
6618 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
6619 dpstatus = IAX_DPSTATUS_CANEXIST;
6620 } else {
6621 dpstatus = IAX_DPSTATUS_NONEXISTENT;
6623 if (ast_ignore_pattern(context, callednum))
6624 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
6625 if (mm)
6626 dpstatus |= IAX_DPSTATUS_MATCHMORE;
6627 if (!skiplock)
6628 ast_mutex_lock(&iaxsl[callno]);
6629 if (iaxs[callno]) {
6630 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
6631 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
6632 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
6633 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
6635 if (!skiplock)
6636 ast_mutex_unlock(&iaxsl[callno]);
6639 static void *dp_lookup_thread(void *data)
6641 /* Look up for dpreq */
6642 struct dpreq_data *dpr = data;
6643 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
6644 if (dpr->callerid)
6645 free(dpr->callerid);
6646 free(dpr);
6647 return NULL;
6650 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
6652 pthread_t newthread;
6653 struct dpreq_data *dpr;
6654 pthread_attr_t attr;
6656 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
6657 return;
6659 pthread_attr_init(&attr);
6660 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6662 dpr->callno = callno;
6663 ast_copy_string(dpr->context, context, sizeof(dpr->context));
6664 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
6665 if (callerid)
6666 dpr->callerid = ast_strdup(callerid);
6667 if (ast_pthread_create(&newthread, &attr, dp_lookup_thread, dpr)) {
6668 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
6671 pthread_attr_destroy(&attr);
6674 struct iax_dual {
6675 struct ast_channel *chan1;
6676 struct ast_channel *chan2;
6679 static void *iax_park_thread(void *stuff)
6681 struct ast_channel *chan1, *chan2;
6682 struct iax_dual *d;
6683 struct ast_frame *f;
6684 int ext;
6685 int res;
6686 d = stuff;
6687 chan1 = d->chan1;
6688 chan2 = d->chan2;
6689 free(d);
6690 f = ast_read(chan1);
6691 if (f)
6692 ast_frfree(f);
6693 res = ast_park_call(chan1, chan2, 0, &ext);
6694 ast_hangup(chan2);
6695 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
6696 return NULL;
6699 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
6701 struct iax_dual *d;
6702 struct ast_channel *chan1m, *chan2m;
6703 pthread_t th;
6704 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
6705 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
6706 if (chan2m && chan1m) {
6707 /* Make formats okay */
6708 chan1m->readformat = chan1->readformat;
6709 chan1m->writeformat = chan1->writeformat;
6710 ast_channel_masquerade(chan1m, chan1);
6711 /* Setup the extensions and such */
6712 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
6713 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
6714 chan1m->priority = chan1->priority;
6716 /* We make a clone of the peer channel too, so we can play
6717 back the announcement */
6718 /* Make formats okay */
6719 chan2m->readformat = chan2->readformat;
6720 chan2m->writeformat = chan2->writeformat;
6721 ast_channel_masquerade(chan2m, chan2);
6722 /* Setup the extensions and such */
6723 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
6724 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
6725 chan2m->priority = chan2->priority;
6726 if (ast_do_masquerade(chan2m)) {
6727 ast_log(LOG_WARNING, "Masquerade failed :(\n");
6728 ast_hangup(chan2m);
6729 return -1;
6731 } else {
6732 if (chan1m)
6733 ast_hangup(chan1m);
6734 if (chan2m)
6735 ast_hangup(chan2m);
6736 return -1;
6738 if ((d = ast_calloc(1, sizeof(*d)))) {
6739 pthread_attr_t attr;
6741 pthread_attr_init(&attr);
6742 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6744 d->chan1 = chan1m;
6745 d->chan2 = chan2m;
6746 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
6747 pthread_attr_destroy(&attr);
6748 return 0;
6750 pthread_attr_destroy(&attr);
6751 free(d);
6753 return -1;
6757 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
6759 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
6761 unsigned int ourver;
6762 char rsi[80];
6763 snprintf(rsi, sizeof(rsi), "si-%s", si);
6764 if (iax_provision_version(&ourver, rsi, 1))
6765 return 0;
6766 if (option_debug)
6767 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
6768 if (ourver != ver)
6769 iax2_provision(sin, sockfd, NULL, rsi, 1);
6770 return 0;
6773 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
6775 jb_info stats;
6776 jb_getinfo(pvt->jb, &stats);
6778 memset(iep, 0, sizeof(*iep));
6780 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
6781 if(stats.frames_in == 0) stats.frames_in = 1;
6782 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
6783 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
6784 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
6785 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
6786 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
6789 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
6791 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
6792 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
6793 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
6794 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
6795 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
6796 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
6797 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
6800 static int socket_process(struct iax2_thread *thread);
6803 * \brief Handle any deferred full frames for this thread
6805 static void handle_deferred_full_frames(struct iax2_thread *thread)
6807 struct iax2_pkt_buf *pkt_buf;
6809 ast_mutex_lock(&thread->lock);
6811 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
6812 ast_mutex_unlock(&thread->lock);
6814 thread->buf = pkt_buf->buf;
6815 thread->buf_len = pkt_buf->len;
6816 thread->buf_size = pkt_buf->len + 1;
6818 socket_process(thread);
6820 thread->buf = NULL;
6821 ast_free(pkt_buf);
6823 ast_mutex_lock(&thread->lock);
6826 ast_mutex_unlock(&thread->lock);
6830 * \brief Queue the last read full frame for processing by a certain thread
6832 * If there are already any full frames queued, they are sorted
6833 * by sequence number.
6835 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
6837 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
6838 struct ast_iax2_full_hdr *fh, *cur_fh;
6840 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
6841 return;
6843 pkt_buf->len = from_here->buf_len;
6844 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
6846 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
6847 ast_mutex_lock(&to_here->lock);
6848 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
6849 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
6850 if (fh->oseqno < cur_fh->oseqno) {
6851 AST_LIST_INSERT_BEFORE_CURRENT(&to_here->full_frames, pkt_buf, entry);
6852 break;
6855 AST_LIST_TRAVERSE_SAFE_END
6857 if (!cur_pkt_buf)
6858 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
6860 ast_mutex_unlock(&to_here->lock);
6863 static int socket_read(int *id, int fd, short events, void *cbdata)
6865 struct iax2_thread *thread;
6866 socklen_t len;
6867 time_t t;
6868 static time_t last_errtime = 0;
6869 struct ast_iax2_full_hdr *fh;
6871 if (!(thread = find_idle_thread())) {
6872 time(&t);
6873 if (t != last_errtime && option_debug)
6874 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
6875 last_errtime = t;
6876 usleep(1);
6877 return 1;
6880 len = sizeof(thread->iosin);
6881 thread->iofd = fd;
6882 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
6883 thread->buf_size = sizeof(thread->readbuf);
6884 thread->buf = thread->readbuf;
6885 if (thread->buf_len < 0) {
6886 if (errno != ECONNREFUSED && errno != EAGAIN)
6887 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
6888 handle_error();
6889 thread->iostate = IAX_IOSTATE_IDLE;
6890 signal_condition(&thread->lock, &thread->cond);
6891 return 1;
6893 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
6894 thread->iostate = IAX_IOSTATE_IDLE;
6895 signal_condition(&thread->lock, &thread->cond);
6896 return 1;
6899 /* Determine if this frame is a full frame; if so, and any thread is currently
6900 processing a full frame for the same callno from this peer, then drop this
6901 frame (and the peer will retransmit it) */
6902 fh = (struct ast_iax2_full_hdr *) thread->buf;
6903 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6904 struct iax2_thread *cur = NULL;
6905 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
6907 AST_LIST_LOCK(&active_list);
6908 AST_LIST_TRAVERSE(&active_list, cur, list) {
6909 if ((cur->ffinfo.callno == callno) &&
6910 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
6911 break;
6913 if (cur) {
6914 /* we found another thread processing a full frame for this call,
6915 so queue it up for processing later. */
6916 defer_full_frame(thread, cur);
6917 AST_LIST_UNLOCK(&active_list);
6918 thread->iostate = IAX_IOSTATE_IDLE;
6919 signal_condition(&thread->lock, &thread->cond);
6920 return 1;
6921 } else {
6922 /* this thread is going to process this frame, so mark it */
6923 thread->ffinfo.callno = callno;
6924 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
6925 thread->ffinfo.type = fh->type;
6926 thread->ffinfo.csub = fh->csub;
6928 AST_LIST_UNLOCK(&active_list);
6931 /* Mark as ready and send on its way */
6932 thread->iostate = IAX_IOSTATE_READY;
6933 #ifdef DEBUG_SCHED_MULTITHREAD
6934 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
6935 #endif
6936 signal_condition(&thread->lock, &thread->cond);
6938 return 1;
6941 static int socket_process(struct iax2_thread *thread)
6943 struct sockaddr_in sin;
6944 int res;
6945 int updatehistory=1;
6946 int new = NEW_PREVENT;
6947 void *ptr;
6948 int dcallno = 0;
6949 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
6950 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
6951 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
6952 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
6953 struct ast_iax2_meta_trunk_hdr *mth;
6954 struct ast_iax2_meta_trunk_entry *mte;
6955 struct ast_iax2_meta_trunk_mini *mtm;
6956 struct iax_frame *fr;
6957 struct iax_frame *cur;
6958 struct ast_frame f = { 0, };
6959 struct ast_channel *c;
6960 struct iax2_dpcache *dp;
6961 struct iax2_peer *peer;
6962 struct iax2_trunk_peer *tpeer;
6963 struct timeval rxtrunktime;
6964 struct iax_ies ies;
6965 struct iax_ie_data ied0, ied1;
6966 int format;
6967 int fd;
6968 int exists;
6969 int minivid = 0;
6970 unsigned int ts;
6971 char empty[32]=""; /* Safety measure */
6972 struct iax_frame *duped_fr;
6973 char host_pref_buf[128];
6974 char caller_pref_buf[128];
6975 struct ast_codec_pref pref;
6976 char *using_prefs = "mine";
6978 /* allocate an iax_frame with 4096 bytes of data buffer */
6979 fr = alloca(sizeof(*fr) + 4096);
6980 fr->callno = 0;
6981 fr->afdatalen = 4096; /* From alloca() above */
6983 /* Copy frequently used parameters to the stack */
6984 res = thread->buf_len;
6985 fd = thread->iofd;
6986 memcpy(&sin, &thread->iosin, sizeof(sin));
6988 if (res < sizeof(*mh)) {
6989 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*mh));
6990 return 1;
6992 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
6993 if (res < sizeof(*vh)) {
6994 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));
6995 return 1;
6998 /* This is a video frame, get call number */
6999 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
7000 minivid = 1;
7001 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
7002 unsigned char metatype;
7004 if (res < sizeof(*meta)) {
7005 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));
7006 return 1;
7009 /* This is a meta header */
7010 switch(meta->metacmd) {
7011 case IAX_META_TRUNK:
7012 if (res < (sizeof(*meta) + sizeof(*mth))) {
7013 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %zd min)\n", res,
7014 sizeof(*meta) + sizeof(*mth));
7015 return 1;
7017 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
7018 ts = ntohl(mth->ts);
7019 metatype = meta->cmddata;
7020 res -= (sizeof(*meta) + sizeof(*mth));
7021 ptr = mth->data;
7022 tpeer = find_tpeer(&sin, fd);
7023 if (!tpeer) {
7024 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));
7025 return 1;
7027 tpeer->trunkact = ast_tvnow();
7028 if (!ts || ast_tvzero(tpeer->rxtrunktime))
7029 tpeer->rxtrunktime = tpeer->trunkact;
7030 rxtrunktime = tpeer->rxtrunktime;
7031 ast_mutex_unlock(&tpeer->lock);
7032 while(res >= sizeof(*mte)) {
7033 /* Process channels */
7034 unsigned short callno, trunked_ts, len;
7036 if (metatype == IAX_META_TRUNK_MINI) {
7037 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
7038 ptr += sizeof(*mtm);
7039 res -= sizeof(*mtm);
7040 len = ntohs(mtm->len);
7041 callno = ntohs(mtm->mini.callno);
7042 trunked_ts = ntohs(mtm->mini.ts);
7043 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
7044 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
7045 ptr += sizeof(*mte);
7046 res -= sizeof(*mte);
7047 len = ntohs(mte->len);
7048 callno = ntohs(mte->callno);
7049 trunked_ts = 0;
7050 } else {
7051 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7052 break;
7054 /* Stop if we don't have enough data */
7055 if (len > res)
7056 break;
7057 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd, 0);
7058 if (fr->callno) {
7059 /* If it's a valid call, deliver the contents. If not, we
7060 drop it, since we don't have a scallno to use for an INVAL */
7061 /* Process as a mini frame */
7062 memset(&f, 0, sizeof(f));
7063 f.frametype = AST_FRAME_VOICE;
7064 if (iaxs[fr->callno]) {
7065 if (iaxs[fr->callno]->voiceformat > 0) {
7066 f.subclass = iaxs[fr->callno]->voiceformat;
7067 f.datalen = len;
7068 if (f.datalen >= 0) {
7069 if (f.datalen)
7070 f.data = ptr;
7071 if(trunked_ts) {
7072 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
7073 } else
7074 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
7075 /* Don't pass any packets until we're started */
7076 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7077 /* Common things */
7078 f.src = "IAX2";
7079 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
7080 f.samples = ast_codec_get_samples(&f);
7081 iax_frame_wrap(fr, &f);
7082 duped_fr = iaxfrdup2(fr);
7083 if (duped_fr) {
7084 schedule_delivery(duped_fr, updatehistory, 1, &fr->ts);
7086 /* It is possible for the pvt structure to go away after we call schedule_delivery */
7087 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
7088 iaxs[fr->callno]->last = fr->ts;
7089 #if 1
7090 if (option_debug && iaxdebug)
7091 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7092 #endif
7095 } else {
7096 ast_log(LOG_WARNING, "Datalen < 0?\n");
7098 } else {
7099 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n ");
7100 iax2_vnak(fr->callno);
7103 ast_mutex_unlock(&iaxsl[fr->callno]);
7105 ptr += len;
7106 res -= len;
7110 return 1;
7113 #ifdef DEBUG_SUPPORT
7114 if (iaxdebug && (res >= sizeof(*fh)))
7115 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
7116 #endif
7117 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7118 if (res < sizeof(*fh)) {
7119 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));
7120 return 1;
7123 /* Get the destination call number */
7124 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
7125 /* Retrieve the type and subclass */
7126 f.frametype = fh->type;
7127 if (f.frametype == AST_FRAME_VIDEO) {
7128 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
7129 } else {
7130 f.subclass = uncompress_subclass(fh->csub);
7132 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
7133 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
7134 (f.subclass == IAX_COMMAND_REGREL)))
7135 new = NEW_ALLOW;
7136 } else {
7137 /* Don't know anything about it yet */
7138 f.frametype = AST_FRAME_NULL;
7139 f.subclass = 0;
7142 if (!fr->callno)
7143 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, ntohs(mh->callno) & IAX_FLAG_FULL);
7145 if (fr->callno > 0)
7146 ast_mutex_lock(&iaxsl[fr->callno]);
7148 if (!fr->callno || !iaxs[fr->callno]) {
7149 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7150 frame, reply with an inval */
7151 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7152 /* We can only raw hangup control frames */
7153 if (((f.subclass != IAX_COMMAND_INVAL) &&
7154 (f.subclass != IAX_COMMAND_TXCNT) &&
7155 (f.subclass != IAX_COMMAND_TXACC) &&
7156 (f.subclass != IAX_COMMAND_FWDOWNL))||
7157 (f.frametype != AST_FRAME_IAX))
7158 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
7159 fd);
7161 if (fr->callno > 0)
7162 ast_mutex_unlock(&iaxsl[fr->callno]);
7163 return 1;
7165 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
7166 if (decrypt_frame(fr->callno, fh, &f, &res)) {
7167 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
7168 ast_mutex_unlock(&iaxsl[fr->callno]);
7169 return 1;
7171 #ifdef DEBUG_SUPPORT
7172 else if (iaxdebug)
7173 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
7174 #endif
7177 /* count this frame */
7178 iaxs[fr->callno]->frames_received++;
7180 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
7181 f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
7182 f.subclass != IAX_COMMAND_TXACC) { /* for attended transfer */
7183 unsigned short new_peercallno;
7185 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
7186 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
7187 if (iaxs[fr->callno]->peercallno) {
7188 remove_by_peercallno(iaxs[fr->callno]);
7190 iaxs[fr->callno]->peercallno = new_peercallno;
7191 store_by_peercallno(iaxs[fr->callno]);
7194 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7195 if (option_debug && iaxdebug)
7196 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
7197 /* Check if it's out of order (and not an ACK or INVAL) */
7198 fr->oseqno = fh->oseqno;
7199 fr->iseqno = fh->iseqno;
7200 fr->ts = ntohl(fh->ts);
7201 #ifdef IAXTESTS
7202 if (test_resync) {
7203 if (option_debug)
7204 ast_log(LOG_DEBUG, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
7205 fr->ts += test_resync;
7207 #endif /* IAXTESTS */
7208 #if 0
7209 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
7210 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
7211 (f.subclass == IAX_COMMAND_NEW ||
7212 f.subclass == IAX_COMMAND_AUTHREQ ||
7213 f.subclass == IAX_COMMAND_ACCEPT ||
7214 f.subclass == IAX_COMMAND_REJECT)) ) )
7215 #endif
7216 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
7217 updatehistory = 0;
7218 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
7219 (iaxs[fr->callno]->iseqno ||
7220 ((f.subclass != IAX_COMMAND_TXCNT) &&
7221 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7222 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7223 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7224 (f.subclass != IAX_COMMAND_TXACC)) ||
7225 (f.frametype != AST_FRAME_IAX))) {
7226 if (
7227 ((f.subclass != IAX_COMMAND_ACK) &&
7228 (f.subclass != IAX_COMMAND_INVAL) &&
7229 (f.subclass != IAX_COMMAND_TXCNT) &&
7230 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7231 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7232 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7233 (f.subclass != IAX_COMMAND_TXACC) &&
7234 (f.subclass != IAX_COMMAND_VNAK)) ||
7235 (f.frametype != AST_FRAME_IAX)) {
7236 /* If it's not an ACK packet, it's out of order. */
7237 if (option_debug)
7238 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7239 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
7240 /* Check to see if we need to request retransmission,
7241 * and take sequence number wraparound into account */
7242 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
7243 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7244 if ((f.frametype != AST_FRAME_IAX) ||
7245 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
7246 if (option_debug)
7247 ast_log(LOG_DEBUG, "Acking anyway\n");
7248 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7249 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7250 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7252 } else {
7253 /* Send a VNAK requesting retransmission */
7254 iax2_vnak(fr->callno);
7256 ast_mutex_unlock(&iaxsl[fr->callno]);
7257 return 1;
7259 } else {
7260 /* Increment unless it's an ACK or VNAK */
7261 if (((f.subclass != IAX_COMMAND_ACK) &&
7262 (f.subclass != IAX_COMMAND_INVAL) &&
7263 (f.subclass != IAX_COMMAND_TXCNT) &&
7264 (f.subclass != IAX_COMMAND_TXACC) &&
7265 (f.subclass != IAX_COMMAND_VNAK)) ||
7266 (f.frametype != AST_FRAME_IAX))
7267 iaxs[fr->callno]->iseqno++;
7269 /* A full frame */
7270 if (res < sizeof(*fh)) {
7271 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*fh));
7272 ast_mutex_unlock(&iaxsl[fr->callno]);
7273 return 1;
7275 /* Ensure text frames are NULL-terminated */
7276 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
7277 if (res < thread->buf_size)
7278 thread->buf[res++] = '\0';
7279 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7280 thread->buf[res - 1] = '\0';
7282 f.datalen = res - sizeof(*fh);
7284 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7285 from the real peer, not the transfer peer */
7286 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7287 ((f.subclass != IAX_COMMAND_INVAL) ||
7288 (f.frametype != AST_FRAME_IAX))) {
7289 unsigned char x;
7290 int call_to_destroy;
7291 /* XXX This code is not very efficient. Surely there is a better way which still
7292 properly handles boundary conditions? XXX */
7293 /* First we have to qualify that the ACKed value is within our window */
7294 for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
7295 if (fr->iseqno == x)
7296 break;
7297 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
7298 /* The acknowledgement is within our window. Time to acknowledge everything
7299 that it says to */
7300 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
7301 /* Ack the packet with the given timestamp */
7302 if (option_debug && iaxdebug)
7303 ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
7304 call_to_destroy = 0;
7305 AST_LIST_LOCK(&iaxq.queue);
7306 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7307 /* If it's our call, and our timestamp, mark -1 retries */
7308 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
7309 cur->retries = -1;
7310 /* Destroy call if this is the end */
7311 if (cur->final)
7312 call_to_destroy = fr->callno;
7315 AST_LIST_UNLOCK(&iaxq.queue);
7316 if (call_to_destroy) {
7317 if (iaxdebug && option_debug)
7318 ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", call_to_destroy);
7319 ast_mutex_lock(&iaxsl[call_to_destroy]);
7320 iax2_destroy(call_to_destroy);
7321 ast_mutex_unlock(&iaxsl[call_to_destroy]);
7324 /* Note how much we've received acknowledgement for */
7325 if (iaxs[fr->callno])
7326 iaxs[fr->callno]->rseqno = fr->iseqno;
7327 else {
7328 /* Stop processing now */
7329 ast_mutex_unlock(&iaxsl[fr->callno]);
7330 return 1;
7332 } else if (option_debug)
7333 ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
7335 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7336 ((f.frametype != AST_FRAME_IAX) ||
7337 ((f.subclass != IAX_COMMAND_TXACC) &&
7338 (f.subclass != IAX_COMMAND_TXCNT)))) {
7339 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7340 ast_mutex_unlock(&iaxsl[fr->callno]);
7341 return 1;
7344 if (f.datalen) {
7345 if (f.frametype == AST_FRAME_IAX) {
7346 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
7347 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
7348 ast_mutex_unlock(&iaxsl[fr->callno]);
7349 return 1;
7351 f.data = NULL;
7352 f.datalen = 0;
7353 } else
7354 f.data = thread->buf + sizeof(*fh);
7355 } else {
7356 if (f.frametype == AST_FRAME_IAX)
7357 f.data = NULL;
7358 else
7359 f.data = empty;
7360 memset(&ies, 0, sizeof(ies));
7363 /* when we receive the first full frame for a new incoming channel,
7364 it is safe to start the PBX on the channel because we have now
7365 completed a 3-way handshake with the peer */
7366 if ((f.frametype == AST_FRAME_VOICE) ||
7367 (f.frametype == AST_FRAME_VIDEO) ||
7368 (f.frametype == AST_FRAME_IAX)) {
7369 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
7370 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7371 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
7372 ast_mutex_unlock(&iaxsl[fr->callno]);
7373 return 1;
7378 if (f.frametype == AST_FRAME_VOICE) {
7379 if (f.subclass != iaxs[fr->callno]->voiceformat) {
7380 iaxs[fr->callno]->voiceformat = f.subclass;
7381 if (option_debug)
7382 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
7383 if (iaxs[fr->callno]->owner) {
7384 int orignative;
7385 retryowner:
7386 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7387 ast_mutex_unlock(&iaxsl[fr->callno]);
7388 usleep(1);
7389 ast_mutex_lock(&iaxsl[fr->callno]);
7390 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
7392 if (iaxs[fr->callno]) {
7393 if (iaxs[fr->callno]->owner) {
7394 orignative = iaxs[fr->callno]->owner->nativeformats;
7395 iaxs[fr->callno]->owner->nativeformats = f.subclass;
7396 if (iaxs[fr->callno]->owner->readformat)
7397 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7398 iaxs[fr->callno]->owner->nativeformats = orignative;
7399 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7401 } else {
7402 if (option_debug)
7403 ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
7404 ast_mutex_unlock(&iaxsl[fr->callno]);
7405 return 1;
7410 if (f.frametype == AST_FRAME_VIDEO) {
7411 if (f.subclass != iaxs[fr->callno]->videoformat) {
7412 if (option_debug)
7413 ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
7414 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
7417 if (f.frametype == AST_FRAME_IAX) {
7418 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
7419 /* Handle the IAX pseudo frame itself */
7420 if (option_debug && iaxdebug)
7421 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
7423 /* Update last ts unless the frame's timestamp originated with us. */
7424 if (iaxs[fr->callno]->last < fr->ts &&
7425 f.subclass != IAX_COMMAND_ACK &&
7426 f.subclass != IAX_COMMAND_PONG &&
7427 f.subclass != IAX_COMMAND_LAGRP) {
7428 iaxs[fr->callno]->last = fr->ts;
7429 if (option_debug && iaxdebug)
7430 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7433 switch(f.subclass) {
7434 case IAX_COMMAND_ACK:
7435 /* Do nothing */
7436 break;
7437 case IAX_COMMAND_QUELCH:
7438 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7439 /* Generate Manager Hold event, if necessary*/
7440 if (iaxs[fr->callno]->owner) {
7441 manager_event(EVENT_FLAG_CALL, "Hold",
7442 "Channel: %s\r\n"
7443 "Uniqueid: %s\r\n",
7444 iaxs[fr->callno]->owner->name,
7445 iaxs[fr->callno]->owner->uniqueid);
7448 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
7449 if (ies.musiconhold) {
7450 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7451 const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
7452 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
7453 S_OR(mohsuggest, NULL),
7454 !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
7455 if (!iaxs[fr->callno]) {
7456 ast_mutex_unlock(&iaxsl[fr->callno]);
7457 return 1;
7462 break;
7463 case IAX_COMMAND_UNQUELCH:
7464 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7465 /* Generate Manager Unhold event, if necessary*/
7466 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
7467 manager_event(EVENT_FLAG_CALL, "Unhold",
7468 "Channel: %s\r\n"
7469 "Uniqueid: %s\r\n",
7470 iaxs[fr->callno]->owner->name,
7471 iaxs[fr->callno]->owner->uniqueid);
7474 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
7475 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7476 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
7477 if (!iaxs[fr->callno]) {
7478 ast_mutex_unlock(&iaxsl[fr->callno]);
7479 return 1;
7483 break;
7484 case IAX_COMMAND_TXACC:
7485 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
7486 /* Ack the packet with the given timestamp */
7487 AST_LIST_LOCK(&iaxq.queue);
7488 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7489 /* Cancel any outstanding txcnt's */
7490 if ((fr->callno == cur->callno) && (cur->transfer))
7491 cur->retries = -1;
7493 AST_LIST_UNLOCK(&iaxq.queue);
7494 memset(&ied1, 0, sizeof(ied1));
7495 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
7496 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
7497 iaxs[fr->callno]->transferring = TRANSFER_READY;
7499 break;
7500 case IAX_COMMAND_NEW:
7501 /* Ignore if it's already up */
7502 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
7503 break;
7504 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
7505 ast_mutex_unlock(&iaxsl[fr->callno]);
7506 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
7507 ast_mutex_lock(&iaxsl[fr->callno]);
7508 if (!iaxs[fr->callno]) {
7509 ast_mutex_unlock(&iaxsl[fr->callno]);
7510 return 1;
7513 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7514 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
7515 int new_callno;
7516 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
7517 fr->callno = new_callno;
7519 /* For security, always ack immediately */
7520 if (delayreject)
7521 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7522 if (check_access(fr->callno, &sin, &ies)) {
7523 /* They're not allowed on */
7524 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7525 if (authdebug)
7526 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);
7527 break;
7529 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7530 const char *context, *exten, *cid_num;
7532 context = ast_strdupa(iaxs[fr->callno]->context);
7533 exten = ast_strdupa(iaxs[fr->callno]->exten);
7534 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
7536 /* This might re-enter the IAX code and need the lock */
7537 ast_mutex_unlock(&iaxsl[fr->callno]);
7538 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
7539 ast_mutex_lock(&iaxsl[fr->callno]);
7541 if (!iaxs[fr->callno]) {
7542 ast_mutex_unlock(&iaxsl[fr->callno]);
7543 return 1;
7545 } else
7546 exists = 0;
7547 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
7548 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7549 memset(&ied0, 0, sizeof(ied0));
7550 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7551 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7552 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7553 if (!iaxs[fr->callno]) {
7554 ast_mutex_unlock(&iaxsl[fr->callno]);
7555 return 1;
7557 if (authdebug)
7558 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);
7559 } else {
7560 /* Select an appropriate format */
7562 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7563 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7564 using_prefs = "reqonly";
7565 } else {
7566 using_prefs = "disabled";
7568 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7569 memset(&pref, 0, sizeof(pref));
7570 strcpy(caller_pref_buf, "disabled");
7571 strcpy(host_pref_buf, "disabled");
7572 } else {
7573 using_prefs = "mine";
7574 /* If the information elements are in here... use them */
7575 if (ies.codec_prefs)
7576 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7577 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7578 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7579 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7580 pref = iaxs[fr->callno]->rprefs;
7581 using_prefs = "caller";
7582 } else {
7583 pref = iaxs[fr->callno]->prefs;
7585 } else
7586 pref = iaxs[fr->callno]->prefs;
7588 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7589 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7590 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7592 if (!format) {
7593 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7594 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7595 if (!format) {
7596 memset(&ied0, 0, sizeof(ied0));
7597 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7598 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7599 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7600 if (!iaxs[fr->callno]) {
7601 ast_mutex_unlock(&iaxsl[fr->callno]);
7602 return 1;
7604 if (authdebug) {
7605 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7606 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);
7607 else
7608 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);
7610 } else {
7611 /* Pick one... */
7612 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7613 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7614 format = 0;
7615 } else {
7616 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7617 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7618 memset(&pref, 0, sizeof(pref));
7619 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7620 strcpy(caller_pref_buf,"disabled");
7621 strcpy(host_pref_buf,"disabled");
7622 } else {
7623 using_prefs = "mine";
7624 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7625 /* Do the opposite of what we tried above. */
7626 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7627 pref = iaxs[fr->callno]->prefs;
7628 } else {
7629 pref = iaxs[fr->callno]->rprefs;
7630 using_prefs = "caller";
7632 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7634 } else /* if no codec_prefs IE do it the old way */
7635 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7639 if (!format) {
7640 memset(&ied0, 0, sizeof(ied0));
7641 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7642 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7643 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7644 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7645 if (!iaxs[fr->callno]) {
7646 ast_mutex_unlock(&iaxsl[fr->callno]);
7647 return 1;
7649 if (authdebug)
7650 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);
7651 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7652 break;
7656 if (format) {
7657 /* No authentication required, let them in */
7658 memset(&ied1, 0, sizeof(ied1));
7659 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7660 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7661 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7662 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7663 if (option_verbose > 2)
7664 ast_verbose(VERBOSE_PREFIX_3 "Accepting UNAUTHENTICATED call from %s:\n"
7665 "%srequested format = %s,\n"
7666 "%srequested prefs = %s,\n"
7667 "%sactual format = %s,\n"
7668 "%shost prefs = %s,\n"
7669 "%spriority = %s\n",
7670 ast_inet_ntoa(sin.sin_addr),
7671 VERBOSE_PREFIX_4,
7672 ast_getformatname(iaxs[fr->callno]->peerformat),
7673 VERBOSE_PREFIX_4,
7674 caller_pref_buf,
7675 VERBOSE_PREFIX_4,
7676 ast_getformatname(format),
7677 VERBOSE_PREFIX_4,
7678 host_pref_buf,
7679 VERBOSE_PREFIX_4,
7680 using_prefs);
7682 iaxs[fr->callno]->chosenformat = format;
7683 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7684 } else {
7685 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7686 /* If this is a TBD call, we're ready but now what... */
7687 if (option_verbose > 2)
7688 ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
7692 break;
7694 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
7695 merge_encryption(iaxs[fr->callno],ies.encmethods);
7696 else
7697 iaxs[fr->callno]->encmethods = 0;
7698 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
7699 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
7700 if (!iaxs[fr->callno]) {
7701 ast_mutex_unlock(&iaxsl[fr->callno]);
7702 return 1;
7704 break;
7705 case IAX_COMMAND_DPREQ:
7706 /* Request status in the dialplan */
7707 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
7708 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
7709 if (iaxcompat) {
7710 /* Spawn a thread for the lookup */
7711 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
7712 } else {
7713 /* Just look it up */
7714 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
7717 break;
7718 case IAX_COMMAND_HANGUP:
7719 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7720 if (option_debug)
7721 ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr->callno);
7722 /* Set hangup cause according to remote */
7723 if (ies.causecode && iaxs[fr->callno]->owner)
7724 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7725 /* Send ack immediately, before we destroy */
7726 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7727 iax2_destroy(fr->callno);
7728 break;
7729 case IAX_COMMAND_REJECT:
7730 /* Set hangup cause according to remote */
7731 if (ies.causecode && iaxs[fr->callno]->owner)
7732 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7734 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7735 if (iaxs[fr->callno]->owner && authdebug)
7736 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
7737 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
7738 ies.cause ? ies.cause : "<Unknown>");
7739 if (option_debug)
7740 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
7741 fr->callno);
7743 /* Send ack immediately, before we destroy */
7744 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
7745 fr->ts, NULL, 0, fr->iseqno);
7746 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
7747 iaxs[fr->callno]->error = EPERM;
7748 iax2_destroy(fr->callno);
7749 break;
7750 case IAX_COMMAND_TRANSFER:
7752 struct ast_channel *bridged_chan;
7754 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
7755 /* Set BLINDTRANSFER channel variables */
7757 ast_mutex_unlock(&iaxsl[fr->callno]);
7758 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
7759 ast_mutex_lock(&iaxsl[fr->callno]);
7760 if (!iaxs[fr->callno]) {
7761 ast_mutex_unlock(&iaxsl[fr->callno]);
7762 return 1;
7765 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
7766 if (!strcmp(ies.called_number, ast_parking_ext())) {
7767 if (iax_park(bridged_chan, iaxs[fr->callno]->owner)) {
7768 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
7769 } else {
7770 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
7772 } else {
7773 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
7774 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
7775 ies.called_number, iaxs[fr->callno]->context);
7776 else
7777 ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
7778 ies.called_number, iaxs[fr->callno]->context);
7780 } else
7781 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
7783 break;
7785 case IAX_COMMAND_ACCEPT:
7786 /* Ignore if call is already up or needs authentication or is a TBD */
7787 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
7788 break;
7789 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7790 /* Send ack immediately, before we destroy */
7791 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7792 iax2_destroy(fr->callno);
7793 break;
7795 if (ies.format) {
7796 iaxs[fr->callno]->peerformat = ies.format;
7797 } else {
7798 if (iaxs[fr->callno]->owner)
7799 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
7800 else
7801 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
7803 if (option_verbose > 2)
7804 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));
7805 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
7806 memset(&ied0, 0, sizeof(ied0));
7807 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7808 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7809 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7810 if (!iaxs[fr->callno]) {
7811 ast_mutex_unlock(&iaxsl[fr->callno]);
7812 return 1;
7814 if (authdebug)
7815 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);
7816 } else {
7817 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7818 if (iaxs[fr->callno]->owner) {
7819 /* Switch us to use a compatible format */
7820 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
7821 if (option_verbose > 2)
7822 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
7823 retryowner2:
7824 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7825 ast_mutex_unlock(&iaxsl[fr->callno]);
7826 usleep(1);
7827 ast_mutex_lock(&iaxsl[fr->callno]);
7828 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
7831 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
7832 /* Setup read/write formats properly. */
7833 if (iaxs[fr->callno]->owner->writeformat)
7834 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
7835 if (iaxs[fr->callno]->owner->readformat)
7836 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7837 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7841 if (iaxs[fr->callno]) {
7842 ast_mutex_lock(&dpcache_lock);
7843 dp = iaxs[fr->callno]->dpentries;
7844 while(dp) {
7845 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
7846 iax2_dprequest(dp, fr->callno);
7848 dp = dp->peer;
7850 ast_mutex_unlock(&dpcache_lock);
7852 break;
7853 case IAX_COMMAND_POKE:
7854 /* Send back a pong packet with the original timestamp */
7855 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
7856 if (!iaxs[fr->callno]) {
7857 ast_mutex_unlock(&iaxsl[fr->callno]);
7858 return 1;
7860 break;
7861 case IAX_COMMAND_PING:
7863 struct iax_ie_data pingied;
7864 construct_rr(iaxs[fr->callno], &pingied);
7865 /* Send back a pong packet with the original timestamp */
7866 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
7868 break;
7869 case IAX_COMMAND_PONG:
7870 /* Calculate ping time */
7871 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
7872 /* save RR info */
7873 save_rr(fr, &ies);
7875 if (iaxs[fr->callno]->peerpoke) {
7876 peer = iaxs[fr->callno]->peerpoke;
7877 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
7878 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
7879 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
7880 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7881 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7883 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
7884 if (iaxs[fr->callno]->pingtime > peer->maxms) {
7885 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
7886 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7887 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7890 peer->lastms = iaxs[fr->callno]->pingtime;
7891 if (peer->smoothing && (peer->lastms > -1))
7892 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
7893 else if (peer->smoothing && peer->lastms < 0)
7894 peer->historicms = (0 + peer->historicms) / 2;
7895 else
7896 peer->historicms = iaxs[fr->callno]->pingtime;
7898 /* Remove scheduled iax2_poke_noanswer */
7899 if (peer->pokeexpire > -1) {
7900 if (!ast_sched_del(sched, peer->pokeexpire)) {
7901 peer_unref(peer);
7902 peer->pokeexpire = -1;
7905 /* Schedule the next cycle */
7906 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
7907 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
7908 else
7909 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
7910 if (peer->pokeexpire == -1)
7911 peer_unref(peer);
7912 /* and finally send the ack */
7913 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7914 /* And wrap up the qualify call */
7915 iax2_destroy(fr->callno);
7916 peer->callno = 0;
7917 if (option_debug)
7918 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
7920 break;
7921 case IAX_COMMAND_LAGRQ:
7922 case IAX_COMMAND_LAGRP:
7923 f.src = "LAGRQ";
7924 f.mallocd = 0;
7925 f.offset = 0;
7926 f.samples = 0;
7927 iax_frame_wrap(fr, &f);
7928 if(f.subclass == IAX_COMMAND_LAGRQ) {
7929 /* Received a LAGRQ - echo back a LAGRP */
7930 fr->af.subclass = IAX_COMMAND_LAGRP;
7931 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
7932 } else {
7933 /* Received LAGRP in response to our LAGRQ */
7934 unsigned int ts;
7935 /* This is a reply we've been given, actually measure the difference */
7936 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
7937 iaxs[fr->callno]->lag = ts - fr->ts;
7938 if (option_debug && iaxdebug)
7939 ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
7940 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
7942 break;
7943 case IAX_COMMAND_AUTHREQ:
7944 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7945 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>");
7946 break;
7948 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
7949 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
7950 .subclass = AST_CONTROL_HANGUP,
7952 ast_log(LOG_WARNING,
7953 "I don't know how to authenticate %s to %s\n",
7954 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
7955 iax2_queue_frame(fr->callno, &hangup_fr);
7957 if (!iaxs[fr->callno]) {
7958 ast_mutex_unlock(&iaxsl[fr->callno]);
7959 return 1;
7961 break;
7962 case IAX_COMMAND_AUTHREP:
7963 /* For security, always ack immediately */
7964 if (delayreject)
7965 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7966 /* Ignore once we've started */
7967 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7968 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>");
7969 break;
7971 if (authenticate_verify(iaxs[fr->callno], &ies)) {
7972 if (authdebug)
7973 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);
7974 memset(&ied0, 0, sizeof(ied0));
7975 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7976 break;
7978 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7979 /* This might re-enter the IAX code and need the lock */
7980 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
7981 } else
7982 exists = 0;
7983 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7984 if (authdebug)
7985 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);
7986 memset(&ied0, 0, sizeof(ied0));
7987 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7988 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7989 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7990 if (!iaxs[fr->callno]) {
7991 ast_mutex_unlock(&iaxsl[fr->callno]);
7992 return 1;
7994 } else {
7995 /* Select an appropriate format */
7996 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7997 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7998 using_prefs = "reqonly";
7999 } else {
8000 using_prefs = "disabled";
8002 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
8003 memset(&pref, 0, sizeof(pref));
8004 strcpy(caller_pref_buf, "disabled");
8005 strcpy(host_pref_buf, "disabled");
8006 } else {
8007 using_prefs = "mine";
8008 if (ies.codec_prefs)
8009 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
8010 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
8011 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
8012 pref = iaxs[fr->callno]->rprefs;
8013 using_prefs = "caller";
8014 } else {
8015 pref = iaxs[fr->callno]->prefs;
8017 } else /* if no codec_prefs IE do it the old way */
8018 pref = iaxs[fr->callno]->prefs;
8020 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
8021 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
8022 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
8024 if (!format) {
8025 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8026 if (option_debug)
8027 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);
8028 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
8030 if (!format) {
8031 if (authdebug) {
8032 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8033 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);
8034 else
8035 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);
8037 memset(&ied0, 0, sizeof(ied0));
8038 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8039 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8040 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8041 if (!iaxs[fr->callno]) {
8042 ast_mutex_unlock(&iaxsl[fr->callno]);
8043 return 1;
8045 } else {
8046 /* Pick one... */
8047 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8048 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
8049 format = 0;
8050 } else {
8051 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
8052 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
8053 memset(&pref, 0, sizeof(pref));
8054 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
8055 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8056 strcpy(caller_pref_buf,"disabled");
8057 strcpy(host_pref_buf,"disabled");
8058 } else {
8059 using_prefs = "mine";
8060 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
8061 /* Do the opposite of what we tried above. */
8062 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
8063 pref = iaxs[fr->callno]->prefs;
8064 } else {
8065 pref = iaxs[fr->callno]->rprefs;
8066 using_prefs = "caller";
8068 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
8069 } else /* if no codec_prefs IE do it the old way */
8070 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8073 if (!format) {
8074 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8075 if (authdebug) {
8076 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8077 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);
8078 else
8079 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);
8081 memset(&ied0, 0, sizeof(ied0));
8082 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8083 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8084 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8085 if (!iaxs[fr->callno]) {
8086 ast_mutex_unlock(&iaxsl[fr->callno]);
8087 return 1;
8092 if (format) {
8093 /* Authentication received */
8094 memset(&ied1, 0, sizeof(ied1));
8095 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
8096 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
8097 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
8098 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8099 if (option_verbose > 2)
8100 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s:\n"
8101 "%srequested format = %s,\n"
8102 "%srequested prefs = %s,\n"
8103 "%sactual format = %s,\n"
8104 "%shost prefs = %s,\n"
8105 "%spriority = %s\n",
8106 ast_inet_ntoa(sin.sin_addr),
8107 VERBOSE_PREFIX_4,
8108 ast_getformatname(iaxs[fr->callno]->peerformat),
8109 VERBOSE_PREFIX_4,
8110 caller_pref_buf,
8111 VERBOSE_PREFIX_4,
8112 ast_getformatname(format),
8113 VERBOSE_PREFIX_4,
8114 host_pref_buf,
8115 VERBOSE_PREFIX_4,
8116 using_prefs);
8118 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8119 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
8120 iax2_destroy(fr->callno);
8121 } else {
8122 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8123 /* If this is a TBD call, we're ready but now what... */
8124 if (option_verbose > 2)
8125 ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
8129 break;
8130 case IAX_COMMAND_DIAL:
8131 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
8132 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8133 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
8134 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
8135 if (authdebug)
8136 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);
8137 memset(&ied0, 0, sizeof(ied0));
8138 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
8139 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
8140 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8141 if (!iaxs[fr->callno]) {
8142 ast_mutex_unlock(&iaxsl[fr->callno]);
8143 return 1;
8145 } else {
8146 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8147 if (option_verbose > 2)
8148 ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
8149 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8150 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
8151 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
8152 iax2_destroy(fr->callno);
8155 break;
8156 case IAX_COMMAND_INVAL:
8157 iaxs[fr->callno]->error = ENOTCONN;
8158 if (option_debug)
8159 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
8160 iax2_destroy(fr->callno);
8161 if (option_debug)
8162 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
8163 break;
8164 case IAX_COMMAND_VNAK:
8165 if (option_debug)
8166 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
8167 /* Force retransmission */
8168 vnak_retransmit(fr->callno, fr->iseqno);
8169 break;
8170 case IAX_COMMAND_REGREQ:
8171 case IAX_COMMAND_REGREL:
8172 /* For security, always ack immediately */
8173 if (delayreject)
8174 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8175 if (register_verify(fr->callno, &sin, &ies)) {
8176 if (!iaxs[fr->callno]) {
8177 ast_mutex_unlock(&iaxsl[fr->callno]);
8178 return 1;
8180 /* Send delayed failure */
8181 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
8182 break;
8184 if (!iaxs[fr->callno]) {
8185 ast_mutex_unlock(&iaxsl[fr->callno]);
8186 return 1;
8188 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
8189 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
8190 if (f.subclass == IAX_COMMAND_REGREL)
8191 memset(&sin, 0, sizeof(sin));
8192 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
8193 ast_log(LOG_WARNING, "Registry error\n");
8194 if (!iaxs[fr->callno]) {
8195 ast_mutex_unlock(&iaxsl[fr->callno]);
8196 return 1;
8198 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
8199 ast_mutex_unlock(&iaxsl[fr->callno]);
8200 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
8201 ast_mutex_lock(&iaxsl[fr->callno]);
8202 if (!iaxs[fr->callno]) {
8203 ast_mutex_unlock(&iaxsl[fr->callno]);
8204 return 1;
8207 break;
8209 registry_authrequest(fr->callno);
8210 if (!iaxs[fr->callno]) {
8211 ast_mutex_unlock(&iaxsl[fr->callno]);
8212 return 1;
8214 break;
8215 case IAX_COMMAND_REGACK:
8216 if (iax2_ack_registry(&ies, &sin, fr->callno))
8217 ast_log(LOG_WARNING, "Registration failure\n");
8218 /* Send ack immediately, before we destroy */
8219 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8220 iax2_destroy(fr->callno);
8221 break;
8222 case IAX_COMMAND_REGREJ:
8223 if (iaxs[fr->callno]->reg) {
8224 if (authdebug) {
8225 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));
8226 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>");
8228 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
8230 /* Send ack immediately, before we destroy */
8231 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8232 iax2_destroy(fr->callno);
8233 break;
8234 case IAX_COMMAND_REGAUTH:
8235 /* Authentication request */
8236 if (registry_rerequest(&ies, fr->callno, &sin)) {
8237 memset(&ied0, 0, sizeof(ied0));
8238 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
8239 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
8240 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8241 if (!iaxs[fr->callno]) {
8242 ast_mutex_unlock(&iaxsl[fr->callno]);
8243 return 1;
8246 break;
8247 case IAX_COMMAND_TXREJ:
8248 iaxs[fr->callno]->transferring = 0;
8249 if (option_verbose > 2)
8250 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8251 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
8252 if (iaxs[fr->callno]->bridgecallno) {
8253 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
8254 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
8255 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
8258 break;
8259 case IAX_COMMAND_TXREADY:
8260 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
8261 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
8262 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
8263 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
8264 else
8265 iaxs[fr->callno]->transferring = TRANSFER_READY;
8266 if (option_verbose > 2)
8267 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8268 if (iaxs[fr->callno]->bridgecallno) {
8269 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
8270 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
8271 /* They're both ready, now release them. */
8272 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
8273 if (option_verbose > 2)
8274 ast_verbose(VERBOSE_PREFIX_3 "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8275 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8277 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
8278 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
8280 memset(&ied0, 0, sizeof(ied0));
8281 memset(&ied1, 0, sizeof(ied1));
8282 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8283 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8284 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
8285 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
8286 } else {
8287 if (option_verbose > 2)
8288 ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8289 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8291 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
8292 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
8293 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
8294 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8296 /* Stop doing lag & ping requests */
8297 stop_stuff(fr->callno);
8298 stop_stuff(iaxs[fr->callno]->bridgecallno);
8300 memset(&ied0, 0, sizeof(ied0));
8301 memset(&ied1, 0, sizeof(ied1));
8302 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8303 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8304 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
8305 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
8311 break;
8312 case IAX_COMMAND_TXREQ:
8313 try_transfer(iaxs[fr->callno], &ies);
8314 break;
8315 case IAX_COMMAND_TXCNT:
8316 if (iaxs[fr->callno]->transferring)
8317 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
8318 break;
8319 case IAX_COMMAND_TXREL:
8320 /* Send ack immediately, rather than waiting until we've changed addresses */
8321 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8322 complete_transfer(fr->callno, &ies);
8323 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
8324 break;
8325 case IAX_COMMAND_TXMEDIA:
8326 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
8327 AST_LIST_LOCK(&iaxq.queue);
8328 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
8329 /* Cancel any outstanding frames and start anew */
8330 if ((fr->callno == cur->callno) && (cur->transfer)) {
8331 cur->retries = -1;
8334 AST_LIST_UNLOCK(&iaxq.queue);
8335 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8336 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
8338 break;
8339 case IAX_COMMAND_DPREP:
8340 complete_dpreply(iaxs[fr->callno], &ies);
8341 break;
8342 case IAX_COMMAND_UNSUPPORT:
8343 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
8344 break;
8345 case IAX_COMMAND_FWDOWNL:
8346 /* Firmware download */
8347 memset(&ied0, 0, sizeof(ied0));
8348 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
8349 if (res < 0)
8350 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8351 else if (res > 0)
8352 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8353 else
8354 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8355 if (!iaxs[fr->callno]) {
8356 ast_mutex_unlock(&iaxsl[fr->callno]);
8357 return 1;
8359 break;
8360 default:
8361 if (option_debug)
8362 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
8363 memset(&ied0, 0, sizeof(ied0));
8364 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
8365 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
8367 /* Don't actually pass these frames along */
8368 if ((f.subclass != IAX_COMMAND_ACK) &&
8369 (f.subclass != IAX_COMMAND_TXCNT) &&
8370 (f.subclass != IAX_COMMAND_TXACC) &&
8371 (f.subclass != IAX_COMMAND_INVAL) &&
8372 (f.subclass != IAX_COMMAND_VNAK)) {
8373 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8374 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8376 ast_mutex_unlock(&iaxsl[fr->callno]);
8377 return 1;
8379 /* Unless this is an ACK or INVAL frame, ack it */
8380 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8381 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8382 } else if (minivid) {
8383 f.frametype = AST_FRAME_VIDEO;
8384 if (iaxs[fr->callno]->videoformat > 0)
8385 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
8386 else {
8387 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n ");
8388 iax2_vnak(fr->callno);
8389 ast_mutex_unlock(&iaxsl[fr->callno]);
8390 return 1;
8392 f.datalen = res - sizeof(*vh);
8393 if (f.datalen)
8394 f.data = thread->buf + sizeof(*vh);
8395 else
8396 f.data = NULL;
8397 #ifdef IAXTESTS
8398 if (test_resync) {
8399 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
8400 } else
8401 #endif /* IAXTESTS */
8402 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
8403 } else {
8404 /* A mini frame */
8405 f.frametype = AST_FRAME_VOICE;
8406 if (iaxs[fr->callno]->voiceformat > 0)
8407 f.subclass = iaxs[fr->callno]->voiceformat;
8408 else {
8409 if (option_debug)
8410 ast_log(LOG_DEBUG, "Received mini frame before first full voice frame\n");
8411 iax2_vnak(fr->callno);
8412 ast_mutex_unlock(&iaxsl[fr->callno]);
8413 return 1;
8415 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
8416 if (f.datalen < 0) {
8417 ast_log(LOG_WARNING, "Datalen < 0?\n");
8418 ast_mutex_unlock(&iaxsl[fr->callno]);
8419 return 1;
8421 if (f.datalen)
8422 f.data = thread->buf + sizeof(*mh);
8423 else
8424 f.data = NULL;
8425 #ifdef IAXTESTS
8426 if (test_resync) {
8427 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
8428 } else
8429 #endif /* IAXTESTS */
8430 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
8431 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8433 /* Don't pass any packets until we're started */
8434 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8435 ast_mutex_unlock(&iaxsl[fr->callno]);
8436 return 1;
8438 /* Common things */
8439 f.src = "IAX2";
8440 f.mallocd = 0;
8441 f.offset = 0;
8442 f.len = 0;
8443 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
8444 f.samples = ast_codec_get_samples(&f);
8445 /* We need to byteswap incoming slinear samples from network byte order */
8446 if (f.subclass == AST_FORMAT_SLINEAR)
8447 ast_frame_byteswap_be(&f);
8448 } else
8449 f.samples = 0;
8450 iax_frame_wrap(fr, &f);
8452 /* If this is our most recent packet, use it as our basis for timestamping */
8453 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8454 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8455 fr->outoforder = 0;
8456 } else {
8457 if (option_debug && iaxdebug && iaxs[fr->callno])
8458 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);
8459 fr->outoforder = -1;
8461 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
8462 duped_fr = iaxfrdup2(fr);
8463 if (duped_fr) {
8464 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
8466 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8467 iaxs[fr->callno]->last = fr->ts;
8468 #if 1
8469 if (option_debug && iaxdebug)
8470 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8471 #endif
8474 /* Always run again */
8475 ast_mutex_unlock(&iaxsl[fr->callno]);
8476 return 1;
8479 /* Function to clean up process thread if it is cancelled */
8480 static void iax2_process_thread_cleanup(void *data)
8482 struct iax2_thread *thread = data;
8483 ast_mutex_destroy(&thread->lock);
8484 ast_cond_destroy(&thread->cond);
8485 free(thread);
8486 ast_atomic_dec_and_test(&iaxactivethreadcount);
8489 static void *iax2_process_thread(void *data)
8491 struct iax2_thread *thread = data;
8492 struct timeval tv;
8493 struct timespec ts;
8494 int put_into_idle = 0;
8496 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
8497 pthread_cleanup_push(iax2_process_thread_cleanup, data);
8498 for(;;) {
8499 /* Wait for something to signal us to be awake */
8500 ast_mutex_lock(&thread->lock);
8502 /* Flag that we're ready to accept signals */
8503 thread->ready_for_signal = 1;
8505 /* Put into idle list if applicable */
8506 if (put_into_idle)
8507 insert_idle_thread(thread);
8509 if (thread->type == IAX_TYPE_DYNAMIC) {
8510 struct iax2_thread *t = NULL;
8511 /* Wait to be signalled or time out */
8512 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8513 ts.tv_sec = tv.tv_sec;
8514 ts.tv_nsec = tv.tv_usec * 1000;
8515 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
8516 /* This thread was never put back into the available dynamic
8517 * thread list, so just go away. */
8518 if (!put_into_idle) {
8519 ast_mutex_unlock(&thread->lock);
8520 break;
8522 AST_LIST_LOCK(&dynamic_list);
8523 /* Account for the case where this thread is acquired *right* after a timeout */
8524 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
8525 iaxdynamicthreadcount--;
8526 AST_LIST_UNLOCK(&dynamic_list);
8527 if (t) {
8528 /* This dynamic thread timed out waiting for a task and was
8529 * not acquired immediately after the timeout,
8530 * so it's time to go away. */
8531 ast_mutex_unlock(&thread->lock);
8532 break;
8534 /* Someone grabbed our thread *right* after we timed out.
8535 * Wait for them to set us up with something to do and signal
8536 * us to continue. */
8537 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8538 ts.tv_sec = tv.tv_sec;
8539 ts.tv_nsec = tv.tv_usec * 1000;
8540 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
8542 ast_mutex_unlock(&thread->lock);
8543 break;
8546 } else {
8547 ast_cond_wait(&thread->cond, &thread->lock);
8550 /* Go back into our respective list */
8551 put_into_idle = 1;
8553 ast_mutex_unlock(&thread->lock);
8555 if (thread->iostate == IAX_IOSTATE_IDLE)
8556 continue;
8558 /* Add ourselves to the active list now */
8559 AST_LIST_LOCK(&active_list);
8560 AST_LIST_INSERT_HEAD(&active_list, thread, list);
8561 AST_LIST_UNLOCK(&active_list);
8563 /* See what we need to do */
8564 switch(thread->iostate) {
8565 case IAX_IOSTATE_READY:
8566 thread->actions++;
8567 thread->iostate = IAX_IOSTATE_PROCESSING;
8568 socket_process(thread);
8569 handle_deferred_full_frames(thread);
8570 break;
8571 case IAX_IOSTATE_SCHEDREADY:
8572 thread->actions++;
8573 thread->iostate = IAX_IOSTATE_PROCESSING;
8574 #ifdef SCHED_MULTITHREADED
8575 thread->schedfunc(thread->scheddata);
8576 #endif
8577 break;
8579 time(&thread->checktime);
8580 thread->iostate = IAX_IOSTATE_IDLE;
8581 #ifdef DEBUG_SCHED_MULTITHREAD
8582 thread->curfunc[0]='\0';
8583 #endif
8585 /* Now... remove ourselves from the active list, and return to the idle list */
8586 AST_LIST_LOCK(&active_list);
8587 AST_LIST_REMOVE(&active_list, thread, list);
8588 AST_LIST_UNLOCK(&active_list);
8590 /* Make sure another frame didn't sneak in there after we thought we were done. */
8591 handle_deferred_full_frames(thread);
8594 /*!\note For some reason, idle threads are exiting without being removed
8595 * from an idle list, which is causing memory corruption. Forcibly remove
8596 * it from the list, if it's there.
8598 AST_LIST_LOCK(&idle_list);
8599 AST_LIST_REMOVE(&idle_list, thread, list);
8600 AST_LIST_UNLOCK(&idle_list);
8602 AST_LIST_LOCK(&dynamic_list);
8603 AST_LIST_REMOVE(&dynamic_list, thread, list);
8604 AST_LIST_UNLOCK(&dynamic_list);
8606 /* I am exiting here on my own volition, I need to clean up my own data structures
8607 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8609 pthread_cleanup_pop(1);
8611 return NULL;
8614 static int iax2_do_register(struct iax2_registry *reg)
8616 struct iax_ie_data ied;
8617 if (option_debug && iaxdebug)
8618 ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
8620 if (reg->dnsmgr &&
8621 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
8622 /* Maybe the IP has changed, force DNS refresh */
8623 ast_dnsmgr_refresh(reg->dnsmgr);
8627 * if IP has Changed, free allocated call to create a new one with new IP
8628 * call has the pointer to IP and must be updated to the new one
8630 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
8631 ast_mutex_lock(&iaxsl[reg->callno]);
8632 iax2_destroy(reg->callno);
8633 ast_mutex_unlock(&iaxsl[reg->callno]);
8634 reg->callno = 0;
8636 if (!reg->addr.sin_addr.s_addr) {
8637 if (option_debug && iaxdebug)
8638 ast_log(LOG_DEBUG, "Unable to send registration request for '%s' without IP address\n", reg->username);
8639 /* Setup the next registration attempt */
8640 AST_SCHED_DEL(sched, reg->expire);
8641 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8642 return -1;
8645 if (!reg->callno) {
8646 if (option_debug)
8647 ast_log(LOG_DEBUG, "Allocate call number\n");
8648 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
8649 if (reg->callno < 1) {
8650 ast_log(LOG_WARNING, "Unable to create call for registration\n");
8651 return -1;
8652 } else if (option_debug)
8653 ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
8654 iaxs[reg->callno]->reg = reg;
8655 ast_mutex_unlock(&iaxsl[reg->callno]);
8657 /* Schedule the next registration attempt */
8658 AST_SCHED_DEL(sched, reg->expire);
8659 /* Setup the next registration a little early */
8660 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8661 /* Send the request */
8662 memset(&ied, 0, sizeof(ied));
8663 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
8664 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
8665 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
8666 reg->regstate = REG_STATE_REGSENT;
8667 return 0;
8670 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
8672 if (pos != 3)
8673 return NULL;
8674 return iax_prov_complete_template(line, word, pos, state);
8677 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
8679 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8680 is found for template */
8681 struct iax_ie_data provdata;
8682 struct iax_ie_data ied;
8683 unsigned int sig;
8684 struct sockaddr_in sin;
8685 int callno;
8686 struct create_addr_info cai;
8688 memset(&cai, 0, sizeof(cai));
8690 if (option_debug)
8691 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
8693 if (iax_provision_build(&provdata, &sig, template, force)) {
8694 if (option_debug)
8695 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
8696 return 0;
8699 if (end) {
8700 memcpy(&sin, end, sizeof(sin));
8701 cai.sockfd = sockfd;
8702 } else if (create_addr(dest, NULL, &sin, &cai))
8703 return -1;
8705 /* Build the rest of the message */
8706 memset(&ied, 0, sizeof(ied));
8707 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
8709 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8710 if (!callno)
8711 return -1;
8713 if (iaxs[callno]) {
8714 /* Schedule autodestruct in case they don't ever give us anything back */
8715 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
8716 iaxs[callno]->autoid = iax2_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
8717 ast_set_flag(iaxs[callno], IAX_PROVISION);
8718 /* Got a call number now, so go ahead and send the provisioning information */
8719 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
8721 ast_mutex_unlock(&iaxsl[callno]);
8723 return 1;
8726 static char *papp = "IAX2Provision";
8727 static char *psyn = "Provision a calling IAXy with a given template";
8728 static char *pdescrip =
8729 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8730 "the calling entity is in fact an IAXy) with the given template or\n"
8731 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8733 /*! iax2provision
8734 \ingroup applications
8736 static int iax2_prov_app(struct ast_channel *chan, void *data)
8738 int res;
8739 char *sdata;
8740 char *opts;
8741 int force =0;
8742 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
8743 if (ast_strlen_zero(data))
8744 data = "default";
8745 sdata = ast_strdupa(data);
8746 opts = strchr(sdata, '|');
8747 if (opts)
8748 *opts='\0';
8750 if (chan->tech != &iax2_tech) {
8751 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
8752 return -1;
8754 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
8755 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
8756 return -1;
8758 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
8759 if (option_verbose > 2)
8760 ast_verbose(VERBOSE_PREFIX_3 "Provisioned IAXY at '%s' with '%s'= %d\n",
8761 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
8762 sdata, res);
8763 return res;
8767 static int iax2_prov_cmd(int fd, int argc, char *argv[])
8769 int force = 0;
8770 int res;
8771 if (argc < 4)
8772 return RESULT_SHOWUSAGE;
8773 if ((argc > 4)) {
8774 if (!strcasecmp(argv[4], "forced"))
8775 force = 1;
8776 else
8777 return RESULT_SHOWUSAGE;
8779 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
8780 if (res < 0)
8781 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
8782 else if (res < 1)
8783 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
8784 else
8785 ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
8786 return RESULT_SUCCESS;
8789 static void __iax2_poke_noanswer(const void *data)
8791 struct iax2_peer *peer = (struct iax2_peer *)data;
8792 if (peer->lastms > -1) {
8793 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
8794 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
8795 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
8797 if (peer->callno > 0) {
8798 ast_mutex_lock(&iaxsl[peer->callno]);
8799 iax2_destroy(peer->callno);
8800 ast_mutex_unlock(&iaxsl[peer->callno]);
8802 peer->callno = 0;
8803 peer->lastms = -1;
8804 /* Try again quickly */
8805 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
8806 if (peer->pokeexpire == -1)
8807 peer_unref(peer);
8810 static int iax2_poke_noanswer(const void *data)
8812 struct iax2_peer *peer = (struct iax2_peer *)data;
8813 peer->pokeexpire = -1;
8814 #ifdef SCHED_MULTITHREADED
8815 if (schedule_action(__iax2_poke_noanswer, data))
8816 #endif
8817 __iax2_poke_noanswer(data);
8818 peer_unref(peer);
8819 return 0;
8822 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
8824 struct iax2_peer *peer = obj;
8826 iax2_poke_peer(peer, 0);
8828 return 0;
8831 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
8833 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
8834 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8835 immediately after clearing things out */
8836 peer->lastms = 0;
8837 peer->historicms = 0;
8838 peer->pokeexpire = -1;
8839 peer->callno = 0;
8840 return 0;
8842 if (peer->callno > 0) {
8843 ast_log(LOG_NOTICE, "Still have a callno...\n");
8844 ast_mutex_lock(&iaxsl[peer->callno]);
8845 iax2_destroy(peer->callno);
8846 ast_mutex_unlock(&iaxsl[peer->callno]);
8848 if (heldcall)
8849 ast_mutex_unlock(&iaxsl[heldcall]);
8850 peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
8851 if (heldcall)
8852 ast_mutex_lock(&iaxsl[heldcall]);
8853 if (peer->callno < 1) {
8854 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
8855 return -1;
8858 /* Speed up retransmission times for this qualify call */
8859 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
8860 iaxs[peer->callno]->peerpoke = peer;
8862 /* Remove any pending pokeexpire task */
8863 if (peer->pokeexpire > -1) {
8864 if (!ast_sched_del(sched, peer->pokeexpire)) {
8865 peer->pokeexpire = -1;
8866 peer_unref(peer);
8870 /* Queue up a new task to handle no reply */
8871 /* If the host is already unreachable then use the unreachable interval instead */
8872 if (peer->lastms < 0) {
8873 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
8874 } else
8875 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
8877 if (peer->pokeexpire == -1)
8878 peer_unref(peer);
8880 /* And send the poke */
8881 send_command(iaxs[peer->callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
8883 return 0;
8886 static void free_context(struct iax2_context *con)
8888 struct iax2_context *conl;
8889 while(con) {
8890 conl = con;
8891 con = con->next;
8892 free(conl);
8896 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
8898 int callno;
8899 int res;
8900 int fmt, native;
8901 struct sockaddr_in sin;
8902 struct ast_channel *c;
8903 struct parsed_dial_string pds;
8904 struct create_addr_info cai;
8905 char *tmpstr;
8907 memset(&pds, 0, sizeof(pds));
8908 tmpstr = ast_strdupa(data);
8909 parse_dial_string(tmpstr, &pds);
8911 if (ast_strlen_zero(pds.peer)) {
8912 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
8913 return NULL;
8916 memset(&cai, 0, sizeof(cai));
8917 cai.capability = iax2_capability;
8919 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8921 /* Populate our address from the given */
8922 if (create_addr(pds.peer, NULL, &sin, &cai)) {
8923 *cause = AST_CAUSE_UNREGISTERED;
8924 return NULL;
8927 if (pds.port)
8928 sin.sin_port = htons(atoi(pds.port));
8930 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8931 if (callno < 1) {
8932 ast_log(LOG_WARNING, "Unable to create call\n");
8933 *cause = AST_CAUSE_CONGESTION;
8934 return NULL;
8937 /* If this is a trunk, update it now */
8938 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8939 if (ast_test_flag(&cai, IAX_TRUNK)) {
8940 int new_callno;
8941 if ((new_callno = make_trunk(callno, 1)) != -1)
8942 callno = new_callno;
8944 iaxs[callno]->maxtime = cai.maxtime;
8945 if (cai.found)
8946 ast_string_field_set(iaxs[callno], host, pds.peer);
8948 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
8950 ast_mutex_unlock(&iaxsl[callno]);
8952 if (c) {
8953 /* Choose a format we can live with */
8954 if (c->nativeformats & format)
8955 c->nativeformats &= format;
8956 else {
8957 native = c->nativeformats;
8958 fmt = format;
8959 res = ast_translator_best_choice(&fmt, &native);
8960 if (res < 0) {
8961 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
8962 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
8963 ast_hangup(c);
8964 return NULL;
8966 c->nativeformats = native;
8968 c->readformat = ast_best_codec(c->nativeformats);
8969 c->writeformat = c->readformat;
8972 return c;
8975 static void *sched_thread(void *ignore)
8977 int count;
8978 int res;
8979 struct timeval tv;
8980 struct timespec ts;
8982 for (;;) {
8983 res = ast_sched_wait(sched);
8984 if ((res > 1000) || (res < 0))
8985 res = 1000;
8986 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
8987 ts.tv_sec = tv.tv_sec;
8988 ts.tv_nsec = tv.tv_usec * 1000;
8990 pthread_testcancel();
8991 ast_mutex_lock(&sched_lock);
8992 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
8993 ast_mutex_unlock(&sched_lock);
8994 pthread_testcancel();
8996 count = ast_sched_runq(sched);
8997 if (option_debug && count >= 20)
8998 ast_log(LOG_DEBUG, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
9000 return NULL;
9003 static void *network_thread(void *ignore)
9005 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
9006 from the network, and queue them for delivery to the channels */
9007 int res, count, wakeup;
9008 struct iax_frame *f;
9010 if (timingfd > -1)
9011 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
9013 for(;;) {
9014 pthread_testcancel();
9016 /* Go through the queue, sending messages which have not yet been
9017 sent, and scheduling retransmissions if appropriate */
9018 AST_LIST_LOCK(&iaxq.queue);
9019 count = 0;
9020 wakeup = -1;
9021 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
9022 if (f->sentyet)
9023 continue;
9025 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
9026 if (ast_mutex_trylock(&iaxsl[f->callno])) {
9027 wakeup = 1;
9028 continue;
9031 f->sentyet++;
9033 if (iaxs[f->callno]) {
9034 send_packet(f);
9035 count++;
9038 ast_mutex_unlock(&iaxsl[f->callno]);
9040 if (f->retries < 0) {
9041 /* This is not supposed to be retransmitted */
9042 AST_LIST_REMOVE_CURRENT(&iaxq.queue, list);
9043 iaxq.count--;
9044 /* Free the iax frame */
9045 iax_frame_free(f);
9046 } else {
9047 /* We need reliable delivery. Schedule a retransmission */
9048 f->retries++;
9049 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
9052 AST_LIST_TRAVERSE_SAFE_END
9053 AST_LIST_UNLOCK(&iaxq.queue);
9055 pthread_testcancel();
9057 if (option_debug && count >= 20)
9058 ast_log(LOG_DEBUG, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
9060 /* Now do the IO, and run scheduled tasks */
9061 res = ast_io_wait(io, wakeup);
9062 if (res >= 0) {
9063 if (option_debug && res >= 20)
9064 ast_log(LOG_DEBUG, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
9067 return NULL;
9070 static int start_network_thread(void)
9072 pthread_attr_t attr;
9073 int threadcount = 0;
9074 int x;
9075 for (x = 0; x < iaxthreadcount; x++) {
9076 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
9077 if (thread) {
9078 thread->type = IAX_TYPE_POOL;
9079 thread->threadnum = ++threadcount;
9080 ast_mutex_init(&thread->lock);
9081 ast_cond_init(&thread->cond, NULL);
9082 pthread_attr_init(&attr);
9083 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
9084 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
9085 ast_log(LOG_WARNING, "Failed to create new thread!\n");
9086 free(thread);
9087 thread = NULL;
9089 AST_LIST_LOCK(&idle_list);
9090 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
9091 AST_LIST_UNLOCK(&idle_list);
9094 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
9095 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
9096 if (option_verbose > 1)
9097 ast_verbose(VERBOSE_PREFIX_2 "%d helper threaads started\n", threadcount);
9098 return 0;
9101 static struct iax2_context *build_context(char *context)
9103 struct iax2_context *con;
9105 if ((con = ast_calloc(1, sizeof(*con))))
9106 ast_copy_string(con->context, context, sizeof(con->context));
9108 return con;
9111 static int get_auth_methods(char *value)
9113 int methods = 0;
9114 if (strstr(value, "rsa"))
9115 methods |= IAX_AUTH_RSA;
9116 if (strstr(value, "md5"))
9117 methods |= IAX_AUTH_MD5;
9118 if (strstr(value, "plaintext"))
9119 methods |= IAX_AUTH_PLAINTEXT;
9120 return methods;
9124 /*! \brief Check if address can be used as packet source.
9125 \return 0 address available, 1 address unavailable, -1 error
9127 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
9129 int sd;
9130 int res;
9132 sd = socket(AF_INET, SOCK_DGRAM, 0);
9133 if (sd < 0) {
9134 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
9135 return -1;
9138 res = bind(sd, sa, salen);
9139 if (res < 0) {
9140 if (option_debug)
9141 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
9142 close(sd);
9143 return 1;
9146 close(sd);
9147 return 0;
9150 /*! \brief Parse the "sourceaddress" value,
9151 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9152 not found. */
9153 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
9155 struct sockaddr_in sin;
9156 int nonlocal = 1;
9157 int port = IAX_DEFAULT_PORTNO;
9158 int sockfd = defaultsockfd;
9159 char *tmp;
9160 char *addr;
9161 char *portstr;
9163 if (!(tmp = ast_strdupa(srcaddr)))
9164 return -1;
9166 addr = strsep(&tmp, ":");
9167 portstr = tmp;
9169 if (portstr) {
9170 port = atoi(portstr);
9171 if (port < 1)
9172 port = IAX_DEFAULT_PORTNO;
9175 if (!ast_get_ip(&sin, addr)) {
9176 struct ast_netsock *sock;
9177 int res;
9179 sin.sin_port = 0;
9180 sin.sin_family = AF_INET;
9181 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
9182 if (res == 0) {
9183 /* ip address valid. */
9184 sin.sin_port = htons(port);
9185 if (!(sock = ast_netsock_find(netsock, &sin)))
9186 sock = ast_netsock_find(outsock, &sin);
9187 if (sock) {
9188 sockfd = ast_netsock_sockfd(sock);
9189 nonlocal = 0;
9190 } else {
9191 unsigned int orig_saddr = sin.sin_addr.s_addr;
9192 /* INADDR_ANY matches anyway! */
9193 sin.sin_addr.s_addr = INADDR_ANY;
9194 if (ast_netsock_find(netsock, &sin)) {
9195 sin.sin_addr.s_addr = orig_saddr;
9196 sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, socket_read, NULL);
9197 if (sock) {
9198 sockfd = ast_netsock_sockfd(sock);
9199 ast_netsock_unref(sock);
9200 nonlocal = 0;
9201 } else {
9202 nonlocal = 2;
9209 peer->sockfd = sockfd;
9211 if (nonlocal == 1) {
9212 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9213 srcaddr, peer->name);
9214 return -1;
9215 } else if (nonlocal == 2) {
9216 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9217 srcaddr, peer->name);
9218 return -1;
9219 } else {
9220 if (option_debug)
9221 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
9222 return 0;
9226 static void peer_destructor(void *obj)
9228 struct iax2_peer *peer = obj;
9230 ast_free_ha(peer->ha);
9232 if (peer->callno > 0) {
9233 ast_mutex_lock(&iaxsl[peer->callno]);
9234 iax2_destroy(peer->callno);
9235 ast_mutex_unlock(&iaxsl[peer->callno]);
9238 register_peer_exten(peer, 0);
9240 if (peer->dnsmgr)
9241 ast_dnsmgr_release(peer->dnsmgr);
9243 ast_string_field_free_memory(peer);
9246 /*! \brief Create peer structure based on configuration */
9247 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9249 struct iax2_peer *peer = NULL;
9250 struct ast_ha *oldha = NULL;
9251 int maskfound=0;
9252 int found=0;
9253 int firstpass=1;
9254 struct iax2_peer tmp_peer = {
9255 .name = name,
9258 if (!temponly) {
9259 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
9260 if (peer && !ast_test_flag(peer, IAX_DELME))
9261 firstpass = 0;
9264 if (peer) {
9265 found++;
9266 if (firstpass) {
9267 oldha = peer->ha;
9268 peer->ha = NULL;
9270 unlink_peer(peer);
9271 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
9272 peer->expire = -1;
9273 peer->pokeexpire = -1;
9274 peer->sockfd = defaultsockfd;
9275 if (ast_string_field_init(peer, 32))
9276 peer = peer_unref(peer);
9279 if (peer) {
9280 if (firstpass) {
9281 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
9282 peer->encmethods = iax2_encryption;
9283 peer->adsi = adsi;
9284 ast_string_field_set(peer,secret,"");
9285 if (!found) {
9286 ast_string_field_set(peer, name, name);
9287 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9288 peer->expiry = min_reg_expire;
9290 peer->prefs = prefs;
9291 peer->capability = iax2_capability;
9292 peer->smoothing = 0;
9293 peer->pokefreqok = DEFAULT_FREQ_OK;
9294 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
9295 ast_string_field_set(peer,context,"");
9296 ast_string_field_set(peer,peercontext,"");
9297 ast_clear_flag(peer, IAX_HASCALLERID);
9298 ast_string_field_set(peer, cid_name, "");
9299 ast_string_field_set(peer, cid_num, "");
9302 if (!v) {
9303 v = alt;
9304 alt = NULL;
9306 while(v) {
9307 if (!strcasecmp(v->name, "secret")) {
9308 ast_string_field_set(peer, secret, v->value);
9309 } else if (!strcasecmp(v->name, "mailbox")) {
9310 ast_string_field_set(peer, mailbox, v->value);
9311 } else if (!strcasecmp(v->name, "mohinterpret")) {
9312 ast_string_field_set(peer, mohinterpret, v->value);
9313 } else if (!strcasecmp(v->name, "mohsuggest")) {
9314 ast_string_field_set(peer, mohsuggest, v->value);
9315 } else if (!strcasecmp(v->name, "dbsecret")) {
9316 ast_string_field_set(peer, dbsecret, v->value);
9317 } else if (!strcasecmp(v->name, "trunk")) {
9318 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
9319 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
9320 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without zaptel timing\n", peer->name);
9321 ast_clear_flag(peer, IAX_TRUNK);
9323 } else if (!strcasecmp(v->name, "auth")) {
9324 peer->authmethods = get_auth_methods(v->value);
9325 } else if (!strcasecmp(v->name, "encryption")) {
9326 peer->encmethods = get_encrypt_methods(v->value);
9327 } else if (!strcasecmp(v->name, "notransfer")) {
9328 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9329 ast_clear_flag(peer, IAX_TRANSFERMEDIA);
9330 ast_set2_flag(peer, ast_true(v->value), IAX_NOTRANSFER);
9331 } else if (!strcasecmp(v->name, "transfer")) {
9332 if (!strcasecmp(v->value, "mediaonly")) {
9333 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9334 } else if (ast_true(v->value)) {
9335 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9336 } else
9337 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9338 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9339 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
9340 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9341 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
9342 } else if (!strcasecmp(v->name, "host")) {
9343 if (!strcasecmp(v->value, "dynamic")) {
9344 /* They'll register with us */
9345 ast_set_flag(peer, IAX_DYNAMIC);
9346 if (!found) {
9347 /* Initialize stuff iff we're not found, otherwise
9348 we keep going with what we had */
9349 memset(&peer->addr.sin_addr, 0, 4);
9350 if (peer->addr.sin_port) {
9351 /* If we've already got a port, make it the default rather than absolute */
9352 peer->defaddr.sin_port = peer->addr.sin_port;
9353 peer->addr.sin_port = 0;
9356 } else {
9357 /* Non-dynamic. Make sure we become that way if we're not */
9358 AST_SCHED_DEL(sched, peer->expire);
9359 ast_clear_flag(peer, IAX_DYNAMIC);
9360 if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
9361 return peer_unref(peer);
9362 if (!peer->addr.sin_port)
9363 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9365 if (!maskfound)
9366 inet_aton("255.255.255.255", &peer->mask);
9367 } else if (!strcasecmp(v->name, "defaultip")) {
9368 if (ast_get_ip(&peer->defaddr, v->value))
9369 return peer_unref(peer);
9370 } else if (!strcasecmp(v->name, "sourceaddress")) {
9371 peer_set_srcaddr(peer, v->value);
9372 } else if (!strcasecmp(v->name, "permit") ||
9373 !strcasecmp(v->name, "deny")) {
9374 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
9375 } else if (!strcasecmp(v->name, "mask")) {
9376 maskfound++;
9377 inet_aton(v->value, &peer->mask);
9378 } else if (!strcasecmp(v->name, "context")) {
9379 ast_string_field_set(peer, context, v->value);
9380 } else if (!strcasecmp(v->name, "regexten")) {
9381 ast_string_field_set(peer, regexten, v->value);
9382 } else if (!strcasecmp(v->name, "peercontext")) {
9383 ast_string_field_set(peer, peercontext, v->value);
9384 } else if (!strcasecmp(v->name, "port")) {
9385 if (ast_test_flag(peer, IAX_DYNAMIC))
9386 peer->defaddr.sin_port = htons(atoi(v->value));
9387 else
9388 peer->addr.sin_port = htons(atoi(v->value));
9389 } else if (!strcasecmp(v->name, "username")) {
9390 ast_string_field_set(peer, username, v->value);
9391 } else if (!strcasecmp(v->name, "allow")) {
9392 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
9393 } else if (!strcasecmp(v->name, "disallow")) {
9394 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
9395 } else if (!strcasecmp(v->name, "callerid")) {
9396 if (!ast_strlen_zero(v->value)) {
9397 char name2[80];
9398 char num2[80];
9399 ast_callerid_split(v->value, name2, 80, num2, 80);
9400 ast_string_field_set(peer, cid_name, name2);
9401 ast_string_field_set(peer, cid_num, num2);
9402 ast_set_flag(peer, IAX_HASCALLERID);
9403 } else {
9404 ast_clear_flag(peer, IAX_HASCALLERID);
9405 ast_string_field_set(peer, cid_name, "");
9406 ast_string_field_set(peer, cid_num, "");
9408 } else if (!strcasecmp(v->name, "fullname")) {
9409 if (!ast_strlen_zero(v->value)) {
9410 ast_string_field_set(peer, cid_name, v->value);
9411 ast_set_flag(peer, IAX_HASCALLERID);
9412 } else {
9413 ast_string_field_set(peer, cid_name, "");
9414 if (ast_strlen_zero(peer->cid_num))
9415 ast_clear_flag(peer, IAX_HASCALLERID);
9417 } else if (!strcasecmp(v->name, "cid_number")) {
9418 if (!ast_strlen_zero(v->value)) {
9419 ast_string_field_set(peer, cid_num, v->value);
9420 ast_set_flag(peer, IAX_HASCALLERID);
9421 } else {
9422 ast_string_field_set(peer, cid_num, "");
9423 if (ast_strlen_zero(peer->cid_name))
9424 ast_clear_flag(peer, IAX_HASCALLERID);
9426 } else if (!strcasecmp(v->name, "sendani")) {
9427 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
9428 } else if (!strcasecmp(v->name, "inkeys")) {
9429 ast_string_field_set(peer, inkeys, v->value);
9430 } else if (!strcasecmp(v->name, "outkey")) {
9431 ast_string_field_set(peer, outkey, v->value);
9432 } else if (!strcasecmp(v->name, "qualify")) {
9433 if (!strcasecmp(v->value, "no")) {
9434 peer->maxms = 0;
9435 } else if (!strcasecmp(v->value, "yes")) {
9436 peer->maxms = DEFAULT_MAXMS;
9437 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
9438 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);
9439 peer->maxms = 0;
9441 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
9442 peer->smoothing = ast_true(v->value);
9443 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
9444 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
9445 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);
9447 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
9448 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
9449 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);
9450 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
9451 } else if (!strcasecmp(v->name, "timezone")) {
9452 ast_string_field_set(peer, zonetag, v->value);
9453 } else if (!strcasecmp(v->name, "adsi")) {
9454 peer->adsi = ast_true(v->value);
9455 }/* else if (strcasecmp(v->name,"type")) */
9456 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9457 v = v->next;
9458 if (!v) {
9459 v = alt;
9460 alt = NULL;
9463 if (!peer->authmethods)
9464 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9465 ast_clear_flag(peer, IAX_DELME);
9466 /* Make sure these are IPv4 addresses */
9467 peer->addr.sin_family = AF_INET;
9469 if (oldha)
9470 ast_free_ha(oldha);
9471 return peer;
9474 static void user_destructor(void *obj)
9476 struct iax2_user *user = obj;
9478 ast_free_ha(user->ha);
9479 free_context(user->contexts);
9480 if(user->vars) {
9481 ast_variables_destroy(user->vars);
9482 user->vars = NULL;
9484 ast_string_field_free_memory(user);
9487 /*! \brief Create in-memory user structure from configuration */
9488 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9490 struct iax2_user *user = NULL;
9491 struct iax2_context *con, *conl = NULL;
9492 struct ast_ha *oldha = NULL;
9493 struct iax2_context *oldcon = NULL;
9494 int format;
9495 int firstpass=1;
9496 int oldcurauthreq = 0;
9497 char *varname = NULL, *varval = NULL;
9498 struct ast_variable *tmpvar = NULL;
9499 struct iax2_user tmp_user = {
9500 .name = name,
9503 if (!temponly) {
9504 user = ao2_find(users, &tmp_user, OBJ_POINTER);
9505 if (user && !ast_test_flag(user, IAX_DELME))
9506 firstpass = 0;
9509 if (user) {
9510 if (firstpass) {
9511 oldcurauthreq = user->curauthreq;
9512 oldha = user->ha;
9513 oldcon = user->contexts;
9514 user->ha = NULL;
9515 user->contexts = NULL;
9517 /* Already in the list, remove it and it will be added back (or FREE'd) */
9518 ao2_unlink(users, user);
9519 } else {
9520 user = ao2_alloc(sizeof(*user), user_destructor);
9523 if (user) {
9524 if (firstpass) {
9525 ast_string_field_free_memory(user);
9526 memset(user, 0, sizeof(struct iax2_user));
9527 if (ast_string_field_init(user, 32)) {
9528 user = user_unref(user);
9529 goto cleanup;
9531 user->maxauthreq = maxauthreq;
9532 user->curauthreq = oldcurauthreq;
9533 user->prefs = prefs;
9534 user->capability = iax2_capability;
9535 user->encmethods = iax2_encryption;
9536 user->adsi = adsi;
9537 ast_string_field_set(user, name, name);
9538 ast_string_field_set(user, language, language);
9539 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
9540 ast_clear_flag(user, IAX_HASCALLERID);
9541 ast_string_field_set(user, cid_name, "");
9542 ast_string_field_set(user, cid_num, "");
9544 if (!v) {
9545 v = alt;
9546 alt = NULL;
9548 while(v) {
9549 if (!strcasecmp(v->name, "context")) {
9550 con = build_context(v->value);
9551 if (con) {
9552 if (conl)
9553 conl->next = con;
9554 else
9555 user->contexts = con;
9556 conl = con;
9558 } else if (!strcasecmp(v->name, "permit") ||
9559 !strcasecmp(v->name, "deny")) {
9560 user->ha = ast_append_ha(v->name, v->value, user->ha);
9561 } else if (!strcasecmp(v->name, "setvar")) {
9562 varname = ast_strdupa(v->value);
9563 if (varname && (varval = strchr(varname,'='))) {
9564 *varval = '\0';
9565 varval++;
9566 if((tmpvar = ast_variable_new(varname, varval))) {
9567 tmpvar->next = user->vars;
9568 user->vars = tmpvar;
9571 } else if (!strcasecmp(v->name, "allow")) {
9572 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
9573 } else if (!strcasecmp(v->name, "disallow")) {
9574 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
9575 } else if (!strcasecmp(v->name, "trunk")) {
9576 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
9577 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
9578 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without zaptel timing\n", user->name);
9579 ast_clear_flag(user, IAX_TRUNK);
9581 } else if (!strcasecmp(v->name, "auth")) {
9582 user->authmethods = get_auth_methods(v->value);
9583 } else if (!strcasecmp(v->name, "encryption")) {
9584 user->encmethods = get_encrypt_methods(v->value);
9585 } else if (!strcasecmp(v->name, "notransfer")) {
9586 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9587 ast_clear_flag(user, IAX_TRANSFERMEDIA);
9588 ast_set2_flag(user, ast_true(v->value), IAX_NOTRANSFER);
9589 } else if (!strcasecmp(v->name, "transfer")) {
9590 if (!strcasecmp(v->value, "mediaonly")) {
9591 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9592 } else if (ast_true(v->value)) {
9593 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9594 } else
9595 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9596 } else if (!strcasecmp(v->name, "codecpriority")) {
9597 if(!strcasecmp(v->value, "caller"))
9598 ast_set_flag(user, IAX_CODEC_USER_FIRST);
9599 else if(!strcasecmp(v->value, "disabled"))
9600 ast_set_flag(user, IAX_CODEC_NOPREFS);
9601 else if(!strcasecmp(v->value, "reqonly")) {
9602 ast_set_flag(user, IAX_CODEC_NOCAP);
9603 ast_set_flag(user, IAX_CODEC_NOPREFS);
9605 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9606 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
9607 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9608 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
9609 } else if (!strcasecmp(v->name, "dbsecret")) {
9610 ast_string_field_set(user, dbsecret, v->value);
9611 } else if (!strcasecmp(v->name, "secret")) {
9612 if (!ast_strlen_zero(user->secret)) {
9613 char *old = ast_strdupa(user->secret);
9615 ast_string_field_build(user, secret, "%s;%s", old, v->value);
9616 } else
9617 ast_string_field_set(user, secret, v->value);
9618 } else if (!strcasecmp(v->name, "callerid")) {
9619 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
9620 char name2[80];
9621 char num2[80];
9622 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
9623 ast_string_field_set(user, cid_name, name2);
9624 ast_string_field_set(user, cid_num, num2);
9625 ast_set_flag(user, IAX_HASCALLERID);
9626 } else {
9627 ast_clear_flag(user, IAX_HASCALLERID);
9628 ast_string_field_set(user, cid_name, "");
9629 ast_string_field_set(user, cid_num, "");
9631 } else if (!strcasecmp(v->name, "fullname")) {
9632 if (!ast_strlen_zero(v->value)) {
9633 ast_string_field_set(user, cid_name, v->value);
9634 ast_set_flag(user, IAX_HASCALLERID);
9635 } else {
9636 ast_string_field_set(user, cid_name, "");
9637 if (ast_strlen_zero(user->cid_num))
9638 ast_clear_flag(user, IAX_HASCALLERID);
9640 } else if (!strcasecmp(v->name, "cid_number")) {
9641 if (!ast_strlen_zero(v->value)) {
9642 ast_string_field_set(user, cid_num, v->value);
9643 ast_set_flag(user, IAX_HASCALLERID);
9644 } else {
9645 ast_string_field_set(user, cid_num, "");
9646 if (ast_strlen_zero(user->cid_name))
9647 ast_clear_flag(user, IAX_HASCALLERID);
9649 } else if (!strcasecmp(v->name, "accountcode")) {
9650 ast_string_field_set(user, accountcode, v->value);
9651 } else if (!strcasecmp(v->name, "mohinterpret")) {
9652 ast_string_field_set(user, mohinterpret, v->value);
9653 } else if (!strcasecmp(v->name, "mohsuggest")) {
9654 ast_string_field_set(user, mohsuggest, v->value);
9655 } else if (!strcasecmp(v->name, "language")) {
9656 ast_string_field_set(user, language, v->value);
9657 } else if (!strcasecmp(v->name, "amaflags")) {
9658 format = ast_cdr_amaflags2int(v->value);
9659 if (format < 0) {
9660 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9661 } else {
9662 user->amaflags = format;
9664 } else if (!strcasecmp(v->name, "inkeys")) {
9665 ast_string_field_set(user, inkeys, v->value);
9666 } else if (!strcasecmp(v->name, "maxauthreq")) {
9667 user->maxauthreq = atoi(v->value);
9668 if (user->maxauthreq < 0)
9669 user->maxauthreq = 0;
9670 } else if (!strcasecmp(v->name, "adsi")) {
9671 user->adsi = ast_true(v->value);
9672 }/* else if (strcasecmp(v->name,"type")) */
9673 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9674 v = v->next;
9675 if (!v) {
9676 v = alt;
9677 alt = NULL;
9680 if (!user->authmethods) {
9681 if (!ast_strlen_zero(user->secret)) {
9682 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9683 if (!ast_strlen_zero(user->inkeys))
9684 user->authmethods |= IAX_AUTH_RSA;
9685 } else if (!ast_strlen_zero(user->inkeys)) {
9686 user->authmethods = IAX_AUTH_RSA;
9687 } else {
9688 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9691 ast_clear_flag(user, IAX_DELME);
9693 cleanup:
9694 if (oldha)
9695 ast_free_ha(oldha);
9696 if (oldcon)
9697 free_context(oldcon);
9698 return user;
9701 static int peer_delme_cb(void *obj, void *arg, int flags)
9703 struct iax2_peer *peer = obj;
9705 ast_set_flag(peer, IAX_DELME);
9707 return 0;
9710 static int user_delme_cb(void *obj, void *arg, int flags)
9712 struct iax2_user *user = obj;
9714 ast_set_flag(user, IAX_DELME);
9716 return 0;
9719 static void delete_users(void)
9721 struct iax2_registry *reg;
9723 ao2_callback(users, 0, user_delme_cb, NULL);
9725 AST_LIST_LOCK(&registrations);
9726 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
9727 ast_sched_del(sched, reg->expire);
9728 if (reg->callno) {
9729 ast_mutex_lock(&iaxsl[reg->callno]);
9730 if (iaxs[reg->callno]) {
9731 iaxs[reg->callno]->reg = NULL;
9732 iax2_destroy(reg->callno);
9734 ast_mutex_unlock(&iaxsl[reg->callno]);
9736 if (reg->dnsmgr)
9737 ast_dnsmgr_release(reg->dnsmgr);
9738 free(reg);
9740 AST_LIST_UNLOCK(&registrations);
9742 ao2_callback(peers, 0, peer_delme_cb, NULL);
9745 static void prune_users(void)
9747 struct iax2_user *user;
9748 struct ao2_iterator i;
9750 i = ao2_iterator_init(users, 0);
9751 while ((user = ao2_iterator_next(&i))) {
9752 if (ast_test_flag(user, IAX_DELME))
9753 ao2_unlink(users, user);
9754 user_unref(user);
9758 /* Prune peers who still are supposed to be deleted */
9759 static void prune_peers(void)
9761 struct iax2_peer *peer;
9762 struct ao2_iterator i;
9764 i = ao2_iterator_init(peers, 0);
9765 while ((peer = ao2_iterator_next(&i))) {
9766 if (ast_test_flag(peer, IAX_DELME))
9767 unlink_peer(peer);
9768 peer_unref(peer);
9772 static void set_timing(void)
9774 #ifdef HAVE_ZAPTEL
9775 int bs = trunkfreq * 8;
9776 if (timingfd > -1) {
9777 if (
9778 #ifdef ZT_TIMERACK
9779 ioctl(timingfd, ZT_TIMERCONFIG, &bs) &&
9780 #endif
9781 ioctl(timingfd, ZT_SET_BLOCKSIZE, &bs))
9782 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
9784 #endif
9787 static void set_config_destroy(void)
9789 strcpy(accountcode, "");
9790 strcpy(language, "");
9791 strcpy(mohinterpret, "default");
9792 strcpy(mohsuggest, "");
9793 amaflags = 0;
9794 delayreject = 0;
9795 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
9796 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9797 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
9798 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
9799 delete_users();
9802 /*! \brief Load configuration */
9803 static int set_config(char *config_file, int reload)
9805 struct ast_config *cfg, *ucfg;
9806 int capability=iax2_capability;
9807 struct ast_variable *v;
9808 char *cat;
9809 const char *utype;
9810 const char *tosval;
9811 int format;
9812 int portno = IAX_DEFAULT_PORTNO;
9813 int x;
9814 struct iax2_user *user;
9815 struct iax2_peer *peer;
9816 struct ast_netsock *ns;
9817 #if 0
9818 static unsigned short int last_port=0;
9819 #endif
9821 cfg = ast_config_load(config_file);
9823 if (!cfg) {
9824 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
9825 return -1;
9828 if (reload) {
9829 set_config_destroy();
9832 /* Reset global codec prefs */
9833 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
9835 /* Reset Global Flags */
9836 memset(&globalflags, 0, sizeof(globalflags));
9837 ast_set_flag(&globalflags, IAX_RTUPDATE);
9839 #ifdef SO_NO_CHECK
9840 nochecksums = 0;
9841 #endif
9843 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9844 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9846 maxauthreq = 3;
9848 v = ast_variable_browse(cfg, "general");
9850 /* Seed initial tos value */
9851 tosval = ast_variable_retrieve(cfg, "general", "tos");
9852 if (tosval) {
9853 if (ast_str2tos(tosval, &tos))
9854 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9856 while(v) {
9857 if (!strcasecmp(v->name, "bindport")){
9858 if (reload)
9859 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
9860 else
9861 portno = atoi(v->value);
9862 } else if (!strcasecmp(v->name, "pingtime"))
9863 ping_time = atoi(v->value);
9864 else if (!strcasecmp(v->name, "iaxthreadcount")) {
9865 if (reload) {
9866 if (atoi(v->value) != iaxthreadcount)
9867 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
9868 } else {
9869 iaxthreadcount = atoi(v->value);
9870 if (iaxthreadcount < 1) {
9871 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
9872 iaxthreadcount = 1;
9873 } else if (iaxthreadcount > 256) {
9874 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
9875 iaxthreadcount = 256;
9878 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
9879 if (reload) {
9880 AST_LIST_LOCK(&dynamic_list);
9881 iaxmaxthreadcount = atoi(v->value);
9882 AST_LIST_UNLOCK(&dynamic_list);
9883 } else {
9884 iaxmaxthreadcount = atoi(v->value);
9885 if (iaxmaxthreadcount < 0) {
9886 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
9887 iaxmaxthreadcount = 0;
9888 } else if (iaxmaxthreadcount > 256) {
9889 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
9890 iaxmaxthreadcount = 256;
9893 } else if (!strcasecmp(v->name, "nochecksums")) {
9894 #ifdef SO_NO_CHECK
9895 if (ast_true(v->value))
9896 nochecksums = 1;
9897 else
9898 nochecksums = 0;
9899 #else
9900 if (ast_true(v->value))
9901 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
9902 #endif
9904 else if (!strcasecmp(v->name, "maxjitterbuffer"))
9905 maxjitterbuffer = atoi(v->value);
9906 else if (!strcasecmp(v->name, "resyncthreshold"))
9907 resyncthreshold = atoi(v->value);
9908 else if (!strcasecmp(v->name, "maxjitterinterps"))
9909 maxjitterinterps = atoi(v->value);
9910 else if (!strcasecmp(v->name, "lagrqtime"))
9911 lagrq_time = atoi(v->value);
9912 else if (!strcasecmp(v->name, "maxregexpire"))
9913 max_reg_expire = atoi(v->value);
9914 else if (!strcasecmp(v->name, "minregexpire"))
9915 min_reg_expire = atoi(v->value);
9916 else if (!strcasecmp(v->name, "bindaddr")) {
9917 if (reload) {
9918 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
9919 } else {
9920 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, socket_read, NULL))) {
9921 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
9922 } else {
9923 if (option_verbose > 1) {
9924 if (strchr(v->value, ':'))
9925 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
9926 else
9927 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s:%d'\n", v->value, portno);
9929 if (defaultsockfd < 0)
9930 defaultsockfd = ast_netsock_sockfd(ns);
9931 ast_netsock_unref(ns);
9934 } else if (!strcasecmp(v->name, "authdebug"))
9935 authdebug = ast_true(v->value);
9936 else if (!strcasecmp(v->name, "encryption"))
9937 iax2_encryption = get_encrypt_methods(v->value);
9938 else if (!strcasecmp(v->name, "notransfer")) {
9939 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9940 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9941 ast_set2_flag((&globalflags), ast_true(v->value), IAX_NOTRANSFER);
9942 } else if (!strcasecmp(v->name, "transfer")) {
9943 if (!strcasecmp(v->value, "mediaonly")) {
9944 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9945 } else if (ast_true(v->value)) {
9946 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9947 } else
9948 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9949 } else if (!strcasecmp(v->name, "codecpriority")) {
9950 if(!strcasecmp(v->value, "caller"))
9951 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
9952 else if(!strcasecmp(v->value, "disabled"))
9953 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9954 else if(!strcasecmp(v->value, "reqonly")) {
9955 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
9956 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9958 } else if (!strcasecmp(v->name, "jitterbuffer"))
9959 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
9960 else if (!strcasecmp(v->name, "forcejitterbuffer"))
9961 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
9962 else if (!strcasecmp(v->name, "delayreject"))
9963 delayreject = ast_true(v->value);
9964 else if (!strcasecmp(v->name, "rtcachefriends"))
9965 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
9966 else if (!strcasecmp(v->name, "rtignoreregexpire"))
9967 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
9968 else if (!strcasecmp(v->name, "rtupdate"))
9969 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
9970 else if (!strcasecmp(v->name, "trunktimestamps"))
9971 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
9972 else if (!strcasecmp(v->name, "rtautoclear")) {
9973 int i = atoi(v->value);
9974 if(i > 0)
9975 global_rtautoclear = i;
9976 else
9977 i = 0;
9978 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
9979 } else if (!strcasecmp(v->name, "trunkfreq")) {
9980 trunkfreq = atoi(v->value);
9981 if (trunkfreq < 10)
9982 trunkfreq = 10;
9983 } else if (!strcasecmp(v->name, "autokill")) {
9984 if (sscanf(v->value, "%d", &x) == 1) {
9985 if (x >= 0)
9986 autokill = x;
9987 else
9988 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
9989 } else if (ast_true(v->value)) {
9990 autokill = DEFAULT_MAXMS;
9991 } else {
9992 autokill = 0;
9994 } else if (!strcasecmp(v->name, "bandwidth")) {
9995 if (!strcasecmp(v->value, "low")) {
9996 capability = IAX_CAPABILITY_LOWBANDWIDTH;
9997 } else if (!strcasecmp(v->value, "medium")) {
9998 capability = IAX_CAPABILITY_MEDBANDWIDTH;
9999 } else if (!strcasecmp(v->value, "high")) {
10000 capability = IAX_CAPABILITY_FULLBANDWIDTH;
10001 } else
10002 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
10003 } else if (!strcasecmp(v->name, "allow")) {
10004 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
10005 } else if (!strcasecmp(v->name, "disallow")) {
10006 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
10007 } else if (!strcasecmp(v->name, "register")) {
10008 iax2_register(v->value, v->lineno);
10009 } else if (!strcasecmp(v->name, "iaxcompat")) {
10010 iaxcompat = ast_true(v->value);
10011 } else if (!strcasecmp(v->name, "regcontext")) {
10012 ast_copy_string(regcontext, v->value, sizeof(regcontext));
10013 /* Create context if it doesn't exist already */
10014 if (!ast_context_find(regcontext))
10015 ast_context_create(NULL, regcontext, "IAX2");
10016 } else if (!strcasecmp(v->name, "tos")) {
10017 if (ast_str2tos(v->value, &tos))
10018 ast_log(LOG_WARNING, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v->lineno);
10019 } else if (!strcasecmp(v->name, "accountcode")) {
10020 ast_copy_string(accountcode, v->value, sizeof(accountcode));
10021 } else if (!strcasecmp(v->name, "mohinterpret")) {
10022 ast_copy_string(mohinterpret, v->value, sizeof(user->mohinterpret));
10023 } else if (!strcasecmp(v->name, "mohsuggest")) {
10024 ast_copy_string(mohsuggest, v->value, sizeof(user->mohsuggest));
10025 } else if (!strcasecmp(v->name, "amaflags")) {
10026 format = ast_cdr_amaflags2int(v->value);
10027 if (format < 0) {
10028 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
10029 } else {
10030 amaflags = format;
10032 } else if (!strcasecmp(v->name, "language")) {
10033 ast_copy_string(language, v->value, sizeof(language));
10034 } else if (!strcasecmp(v->name, "maxauthreq")) {
10035 maxauthreq = atoi(v->value);
10036 if (maxauthreq < 0)
10037 maxauthreq = 0;
10038 } else if (!strcasecmp(v->name, "adsi")) {
10039 adsi = ast_true(v->value);
10040 } /*else if (strcasecmp(v->name,"type")) */
10041 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10042 v = v->next;
10045 if (defaultsockfd < 0) {
10046 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, socket_read, NULL))) {
10047 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
10048 } else {
10049 if (option_verbose > 1)
10050 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
10051 defaultsockfd = ast_netsock_sockfd(ns);
10052 ast_netsock_unref(ns);
10055 if (reload) {
10056 ast_netsock_release(outsock);
10057 outsock = ast_netsock_list_alloc();
10058 if (!outsock) {
10059 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10060 return -1;
10062 ast_netsock_init(outsock);
10065 if (min_reg_expire > max_reg_expire) {
10066 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
10067 min_reg_expire, max_reg_expire, max_reg_expire);
10068 min_reg_expire = max_reg_expire;
10070 iax2_capability = capability;
10072 ucfg = ast_config_load("users.conf");
10073 if (ucfg) {
10074 struct ast_variable *gen;
10075 int genhasiax;
10076 int genregisteriax;
10077 const char *hasiax, *registeriax;
10079 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
10080 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
10081 gen = ast_variable_browse(ucfg, "general");
10082 cat = ast_category_browse(ucfg, NULL);
10083 while (cat) {
10084 if (strcasecmp(cat, "general")) {
10085 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
10086 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
10087 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
10088 /* Start with general parameters, then specific parameters, user and peer */
10089 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
10090 if (user) {
10091 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10092 user = user_unref(user);
10094 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
10095 if (peer) {
10096 if (ast_test_flag(peer, IAX_DYNAMIC))
10097 reg_source_db(peer);
10098 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10099 peer = peer_unref(peer);
10102 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
10103 char tmp[256];
10104 const char *host = ast_variable_retrieve(ucfg, cat, "host");
10105 const char *username = ast_variable_retrieve(ucfg, cat, "username");
10106 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
10107 if (!host)
10108 host = ast_variable_retrieve(ucfg, "general", "host");
10109 if (!username)
10110 username = ast_variable_retrieve(ucfg, "general", "username");
10111 if (!secret)
10112 secret = ast_variable_retrieve(ucfg, "general", "secret");
10113 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
10114 if (!ast_strlen_zero(secret))
10115 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
10116 else
10117 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
10118 iax2_register(tmp, 0);
10122 cat = ast_category_browse(ucfg, cat);
10124 ast_config_destroy(ucfg);
10127 cat = ast_category_browse(cfg, NULL);
10128 while(cat) {
10129 if (strcasecmp(cat, "general")) {
10130 utype = ast_variable_retrieve(cfg, cat, "type");
10131 if (utype) {
10132 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
10133 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
10134 if (user) {
10135 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10136 user = user_unref(user);
10139 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
10140 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
10141 if (peer) {
10142 if (ast_test_flag(peer, IAX_DYNAMIC))
10143 reg_source_db(peer);
10144 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10145 peer = peer_unref(peer);
10147 } else if (strcasecmp(utype, "user")) {
10148 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
10150 } else
10151 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10153 cat = ast_category_browse(cfg, cat);
10155 ast_config_destroy(cfg);
10156 set_timing();
10157 return 1;
10160 static void poke_all_peers(void)
10162 struct ao2_iterator i;
10163 struct iax2_peer *peer;
10165 i = ao2_iterator_init(peers, 0);
10166 while ((peer = ao2_iterator_next(&i))) {
10167 iax2_poke_peer(peer, 0);
10168 peer_unref(peer);
10171 static int reload_config(void)
10173 char *config = "iax.conf";
10174 struct iax2_registry *reg;
10176 if (set_config(config, 1) > 0) {
10177 prune_peers();
10178 prune_users();
10179 AST_LIST_LOCK(&registrations);
10180 AST_LIST_TRAVERSE(&registrations, reg, entry)
10181 iax2_do_register(reg);
10182 AST_LIST_UNLOCK(&registrations);
10183 /* Qualify hosts, too */
10184 poke_all_peers();
10186 reload_firmware(0);
10187 iax_provision_reload();
10189 return 0;
10192 static int iax2_reload(int fd, int argc, char *argv[])
10194 return reload_config();
10197 static int reload(void)
10199 return reload_config();
10202 static int cache_get_callno_locked(const char *data)
10204 struct sockaddr_in sin;
10205 int x;
10206 int callno;
10207 struct iax_ie_data ied;
10208 struct create_addr_info cai;
10209 struct parsed_dial_string pds;
10210 char *tmpstr;
10212 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10213 /* Look for an *exact match* call. Once a call is negotiated, it can only
10214 look up entries for a single context */
10215 if (!ast_mutex_trylock(&iaxsl[x])) {
10216 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
10217 return x;
10218 ast_mutex_unlock(&iaxsl[x]);
10222 /* No match found, we need to create a new one */
10224 memset(&cai, 0, sizeof(cai));
10225 memset(&ied, 0, sizeof(ied));
10226 memset(&pds, 0, sizeof(pds));
10228 tmpstr = ast_strdupa(data);
10229 parse_dial_string(tmpstr, &pds);
10231 if (ast_strlen_zero(pds.peer)) {
10232 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
10233 return -1;
10236 /* Populate our address from the given */
10237 if (create_addr(pds.peer, NULL, &sin, &cai))
10238 return -1;
10240 if (option_debug)
10241 ast_log(LOG_DEBUG, "peer: %s, username: %s, password: %s, context: %s\n",
10242 pds.peer, pds.username, pds.password, pds.context);
10244 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
10245 if (callno < 1) {
10246 ast_log(LOG_WARNING, "Unable to create call\n");
10247 return -1;
10250 ast_string_field_set(iaxs[callno], dproot, data);
10251 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
10253 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
10254 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
10255 /* the string format is slightly different from a standard dial string,
10256 because the context appears in the 'exten' position
10258 if (pds.exten)
10259 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10260 if (pds.username)
10261 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
10262 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
10263 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
10264 /* Keep password handy */
10265 if (pds.password)
10266 ast_string_field_set(iaxs[callno], secret, pds.password);
10267 if (pds.key)
10268 ast_string_field_set(iaxs[callno], outkey, pds.key);
10269 /* Start the call going */
10270 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
10272 return callno;
10275 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
10277 struct iax2_dpcache *dp, *prev = NULL, *next;
10278 struct timeval tv;
10279 int x;
10280 int com[2];
10281 int timeout;
10282 int old=0;
10283 int outfd;
10284 int abort;
10285 int callno;
10286 struct ast_channel *c;
10287 struct ast_frame *f;
10288 gettimeofday(&tv, NULL);
10289 dp = dpcache;
10290 while(dp) {
10291 next = dp->next;
10292 /* Expire old caches */
10293 if (ast_tvcmp(tv, dp->expiry) > 0) {
10294 /* It's expired, let it disappear */
10295 if (prev)
10296 prev->next = dp->next;
10297 else
10298 dpcache = dp->next;
10299 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10300 /* Free memory and go again */
10301 free(dp);
10302 } else {
10303 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);
10305 dp = next;
10306 continue;
10308 /* We found an entry that matches us! */
10309 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10310 break;
10311 prev = dp;
10312 dp = next;
10314 if (!dp) {
10315 /* No matching entry. Create a new one. */
10316 /* First, can we make a callno? */
10317 callno = cache_get_callno_locked(data);
10318 if (callno < 0) {
10319 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10320 return NULL;
10322 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10323 ast_mutex_unlock(&iaxsl[callno]);
10324 return NULL;
10326 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
10327 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
10328 gettimeofday(&dp->expiry, NULL);
10329 dp->orig = dp->expiry;
10330 /* Expires in 30 mins by default */
10331 dp->expiry.tv_sec += iaxdefaultdpcache;
10332 dp->next = dpcache;
10333 dp->flags = CACHE_FLAG_PENDING;
10334 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10335 dp->waiters[x] = -1;
10336 dpcache = dp;
10337 dp->peer = iaxs[callno]->dpentries;
10338 iaxs[callno]->dpentries = dp;
10339 /* Send the request if we're already up */
10340 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
10341 iax2_dprequest(dp, callno);
10342 ast_mutex_unlock(&iaxsl[callno]);
10344 /* By here we must have a dp */
10345 if (dp->flags & CACHE_FLAG_PENDING) {
10346 /* Okay, here it starts to get nasty. We need a pipe now to wait
10347 for a reply to come back so long as it's pending */
10348 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
10349 /* Find an empty slot */
10350 if (dp->waiters[x] < 0)
10351 break;
10353 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10354 ast_log(LOG_WARNING, "No more waiter positions available\n");
10355 return NULL;
10357 if (pipe(com)) {
10358 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10359 return NULL;
10361 dp->waiters[x] = com[1];
10362 /* Okay, now we wait */
10363 timeout = iaxdefaulttimeout * 1000;
10364 /* Temporarily unlock */
10365 ast_mutex_unlock(&dpcache_lock);
10366 /* Defer any dtmf */
10367 if (chan)
10368 old = ast_channel_defer_dtmf(chan);
10369 abort = 0;
10370 while(timeout) {
10371 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10372 if (outfd > -1) {
10373 break;
10375 if (c) {
10376 f = ast_read(c);
10377 if (f)
10378 ast_frfree(f);
10379 else {
10380 /* Got hung up on, abort! */
10381 break;
10382 abort = 1;
10386 if (!timeout) {
10387 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
10389 ast_mutex_lock(&dpcache_lock);
10390 dp->waiters[x] = -1;
10391 close(com[1]);
10392 close(com[0]);
10393 if (abort) {
10394 /* Don't interpret anything, just abort. Not sure what th epoint
10395 of undeferring dtmf on a hung up channel is but hey whatever */
10396 if (!old && chan)
10397 ast_channel_undefer_dtmf(chan);
10398 return NULL;
10400 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
10401 /* Now to do non-independent analysis the results of our wait */
10402 if (dp->flags & CACHE_FLAG_PENDING) {
10403 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10404 pending. Don't let it take as long to timeout. */
10405 dp->flags &= ~CACHE_FLAG_PENDING;
10406 dp->flags |= CACHE_FLAG_TIMEOUT;
10407 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10408 systems without leaving it unavailable once the server comes back online */
10409 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
10410 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10411 if (dp->waiters[x] > -1)
10412 write(dp->waiters[x], "asdf", 4);
10415 /* Our caller will obtain the rest */
10416 if (!old && chan)
10417 ast_channel_undefer_dtmf(chan);
10419 return dp;
10422 /*! \brief Part of the IAX2 switch interface */
10423 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10425 struct iax2_dpcache *dp;
10426 int res = 0;
10427 #if 0
10428 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10429 #endif
10430 if ((priority != 1) && (priority != 2))
10431 return 0;
10432 ast_mutex_lock(&dpcache_lock);
10433 dp = find_cache(chan, data, context, exten, priority);
10434 if (dp) {
10435 if (dp->flags & CACHE_FLAG_EXISTS)
10436 res= 1;
10438 ast_mutex_unlock(&dpcache_lock);
10439 if (!dp) {
10440 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10442 return res;
10445 /*! \brief part of the IAX2 dial plan switch interface */
10446 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10448 int res = 0;
10449 struct iax2_dpcache *dp;
10450 #if 0
10451 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10452 #endif
10453 if ((priority != 1) && (priority != 2))
10454 return 0;
10455 ast_mutex_lock(&dpcache_lock);
10456 dp = find_cache(chan, data, context, exten, priority);
10457 if (dp) {
10458 if (dp->flags & CACHE_FLAG_CANEXIST)
10459 res= 1;
10461 ast_mutex_unlock(&dpcache_lock);
10462 if (!dp) {
10463 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10465 return res;
10468 /*! \brief Part of the IAX2 Switch interface */
10469 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10471 int res = 0;
10472 struct iax2_dpcache *dp;
10473 #if 0
10474 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10475 #endif
10476 if ((priority != 1) && (priority != 2))
10477 return 0;
10478 ast_mutex_lock(&dpcache_lock);
10479 dp = find_cache(chan, data, context, exten, priority);
10480 if (dp) {
10481 if (dp->flags & CACHE_FLAG_MATCHMORE)
10482 res= 1;
10484 ast_mutex_unlock(&dpcache_lock);
10485 if (!dp) {
10486 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10488 return res;
10491 /*! \brief Execute IAX2 dialplan switch */
10492 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10494 char odata[256];
10495 char req[256];
10496 char *ncontext;
10497 struct iax2_dpcache *dp;
10498 struct ast_app *dial;
10499 #if 0
10500 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);
10501 #endif
10502 if (priority == 2) {
10503 /* Indicate status, can be overridden in dialplan */
10504 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10505 if (dialstatus) {
10506 dial = pbx_findapp(dialstatus);
10507 if (dial)
10508 pbx_exec(chan, dial, "");
10510 return -1;
10511 } else if (priority != 1)
10512 return -1;
10513 ast_mutex_lock(&dpcache_lock);
10514 dp = find_cache(chan, data, context, exten, priority);
10515 if (dp) {
10516 if (dp->flags & CACHE_FLAG_EXISTS) {
10517 ast_copy_string(odata, data, sizeof(odata));
10518 ncontext = strchr(odata, '/');
10519 if (ncontext) {
10520 *ncontext = '\0';
10521 ncontext++;
10522 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10523 } else {
10524 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
10526 if (option_verbose > 2)
10527 ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
10528 } else {
10529 ast_mutex_unlock(&dpcache_lock);
10530 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
10531 return -1;
10534 ast_mutex_unlock(&dpcache_lock);
10535 dial = pbx_findapp("Dial");
10536 if (dial) {
10537 return pbx_exec(chan, dial, req);
10538 } else {
10539 ast_log(LOG_WARNING, "No dial application registered\n");
10541 return -1;
10544 static int function_iaxpeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10546 struct iax2_peer *peer;
10547 char *peername, *colname;
10549 peername = ast_strdupa(data);
10551 /* if our channel, return the IP address of the endpoint of current channel */
10552 if (!strcmp(peername,"CURRENTCHANNEL")) {
10553 unsigned short callno;
10554 if (chan->tech != &iax2_tech)
10555 return -1;
10556 callno = PTR_TO_CALLNO(chan->tech_pvt);
10557 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
10558 return 0;
10561 if ((colname = strchr(peername, ':'))) /*! \todo : will be removed after the 1.4 relese */
10562 *colname++ = '\0';
10563 else if ((colname = strchr(peername, '|')))
10564 *colname++ = '\0';
10565 else
10566 colname = "ip";
10568 if (!(peer = find_peer(peername, 1)))
10569 return -1;
10571 if (!strcasecmp(colname, "ip")) {
10572 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10573 } else if (!strcasecmp(colname, "status")) {
10574 peer_status(peer, buf, len);
10575 } else if (!strcasecmp(colname, "mailbox")) {
10576 ast_copy_string(buf, peer->mailbox, len);
10577 } else if (!strcasecmp(colname, "context")) {
10578 ast_copy_string(buf, peer->context, len);
10579 } else if (!strcasecmp(colname, "expire")) {
10580 snprintf(buf, len, "%d", peer->expire);
10581 } else if (!strcasecmp(colname, "dynamic")) {
10582 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
10583 } else if (!strcasecmp(colname, "callerid_name")) {
10584 ast_copy_string(buf, peer->cid_name, len);
10585 } else if (!strcasecmp(colname, "callerid_num")) {
10586 ast_copy_string(buf, peer->cid_num, len);
10587 } else if (!strcasecmp(colname, "codecs")) {
10588 ast_getformatname_multiple(buf, len -1, peer->capability);
10589 } else if (!strncasecmp(colname, "codec[", 6)) {
10590 char *codecnum, *ptr;
10591 int index = 0, codec = 0;
10593 codecnum = strchr(colname, '[');
10594 *codecnum = '\0';
10595 codecnum++;
10596 if ((ptr = strchr(codecnum, ']'))) {
10597 *ptr = '\0';
10599 index = atoi(codecnum);
10600 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10601 ast_copy_string(buf, ast_getformatname(codec), len);
10605 peer_unref(peer);
10607 return 0;
10610 struct ast_custom_function iaxpeer_function = {
10611 .name = "IAXPEER",
10612 .synopsis = "Gets IAX peer information",
10613 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10614 .read = function_iaxpeer,
10615 .desc = "If peername specified, valid items are:\n"
10616 "- ip (default) The IP address.\n"
10617 "- status The peer's status (if qualify=yes)\n"
10618 "- mailbox The configured mailbox.\n"
10619 "- context The configured context.\n"
10620 "- expire The epoch time of the next expire.\n"
10621 "- dynamic Is it dynamic? (yes/no).\n"
10622 "- callerid_name The configured Caller ID name.\n"
10623 "- callerid_num The configured Caller ID number.\n"
10624 "- codecs The configured codecs.\n"
10625 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10626 "\n"
10627 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10628 "\n"
10632 /*! \brief Part of the device state notification system ---*/
10633 static int iax2_devicestate(void *data)
10635 struct parsed_dial_string pds;
10636 char *tmp = ast_strdupa(data);
10637 struct iax2_peer *p;
10638 int res = AST_DEVICE_INVALID;
10640 memset(&pds, 0, sizeof(pds));
10641 parse_dial_string(tmp, &pds);
10643 if (ast_strlen_zero(pds.peer)) {
10644 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10645 return res;
10648 if (option_debug > 2)
10649 ast_log(LOG_DEBUG, "Checking device state for device %s\n", pds.peer);
10651 /* SLD: FIXME: second call to find_peer during registration */
10652 if (!(p = find_peer(pds.peer, 1)))
10653 return res;
10655 res = AST_DEVICE_UNAVAILABLE;
10656 if (option_debug > 2)
10657 ast_log(LOG_DEBUG, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10658 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
10660 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
10661 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
10662 /* Peer is registered, or have default IP address
10663 and a valid registration */
10664 if (p->historicms == 0 || p->historicms <= p->maxms)
10665 /* let the core figure out whether it is in use or not */
10666 res = AST_DEVICE_UNKNOWN;
10669 peer_unref(p);
10671 return res;
10674 static struct ast_switch iax2_switch =
10676 name: "IAX2",
10677 description: "IAX Remote Dialplan Switch",
10678 exists: iax2_exists,
10679 canmatch: iax2_canmatch,
10680 exec: iax2_exec,
10681 matchmore: iax2_matchmore,
10684 static char show_stats_usage[] =
10685 "Usage: iax2 show stats\n"
10686 " Display statistics on IAX channel driver.\n";
10688 static char show_cache_usage[] =
10689 "Usage: iax2 show cache\n"
10690 " Display currently cached IAX Dialplan results.\n";
10692 static char show_peer_usage[] =
10693 "Usage: iax2 show peer <name>\n"
10694 " Display details on specific IAX peer\n";
10696 static char prune_realtime_usage[] =
10697 "Usage: iax2 prune realtime [<peername>|all]\n"
10698 " Prunes object(s) from the cache\n";
10700 static char iax2_reload_usage[] =
10701 "Usage: iax2 reload\n"
10702 " Reloads IAX configuration from iax.conf\n";
10704 static char show_prov_usage[] =
10705 "Usage: iax2 provision <host> <template> [forced]\n"
10706 " Provisions the given peer or IP address using a template\n"
10707 " matching either 'template' or '*' if the template is not\n"
10708 " found. If 'forced' is specified, even empty provisioning\n"
10709 " fields will be provisioned as empty fields.\n";
10711 static char show_users_usage[] =
10712 "Usage: iax2 show users [like <pattern>]\n"
10713 " Lists all known IAX2 users.\n"
10714 " Optional regular expression pattern is used to filter the user list.\n";
10716 static char show_channels_usage[] =
10717 "Usage: iax2 show channels\n"
10718 " Lists all currently active IAX channels.\n";
10720 static char show_netstats_usage[] =
10721 "Usage: iax2 show netstats\n"
10722 " Lists network status for all currently active IAX channels.\n";
10724 static char show_threads_usage[] =
10725 "Usage: iax2 show threads\n"
10726 " Lists status of IAX helper threads\n";
10728 static char show_peers_usage[] =
10729 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10730 " Lists all known IAX2 peers.\n"
10731 " Optional 'registered' argument lists only peers with known addresses.\n"
10732 " Optional regular expression pattern is used to filter the peer list.\n";
10734 static char show_firmware_usage[] =
10735 "Usage: iax2 show firmware\n"
10736 " Lists all known IAX firmware images.\n";
10738 static char show_reg_usage[] =
10739 "Usage: iax2 show registry\n"
10740 " Lists all registration requests and status.\n";
10742 static char debug_usage[] =
10743 "Usage: iax2 set debug\n"
10744 " Enables dumping of IAX packets for debugging purposes\n";
10746 static char no_debug_usage[] =
10747 "Usage: iax2 set debug off\n"
10748 " Disables dumping of IAX packets for debugging purposes\n";
10750 static char debug_trunk_usage[] =
10751 "Usage: iax2 set debug trunk\n"
10752 " Requests current status of IAX trunking\n";
10754 static char no_debug_trunk_usage[] =
10755 "Usage: iax2 set debug trunk off\n"
10756 " Requests current status of IAX trunking\n";
10758 static char debug_jb_usage[] =
10759 "Usage: iax2 set debug jb\n"
10760 " Enables jitterbuffer debugging information\n";
10762 static char no_debug_jb_usage[] =
10763 "Usage: iax2 set debug jb off\n"
10764 " Disables jitterbuffer debugging information\n";
10766 static char iax2_test_losspct_usage[] =
10767 "Usage: iax2 test losspct <percentage>\n"
10768 " For testing, throws away <percentage> percent of incoming packets\n";
10770 #ifdef IAXTESTS
10771 static char iax2_test_late_usage[] =
10772 "Usage: iax2 test late <ms>\n"
10773 " For testing, count the next frame as <ms> ms late\n";
10775 static char iax2_test_resync_usage[] =
10776 "Usage: iax2 test resync <ms>\n"
10777 " For testing, adjust all future frames by <ms> ms\n";
10779 static char iax2_test_jitter_usage[] =
10780 "Usage: iax2 test jitter <ms> <pct>\n"
10781 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10782 #endif /* IAXTESTS */
10784 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated = {
10785 { "iax2", "trunk", "debug", NULL },
10786 iax2_do_trunk_debug, NULL,
10787 NULL };
10789 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10790 { "iax2", "jb", "debug", NULL },
10791 iax2_do_jb_debug, NULL,
10792 NULL };
10794 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10795 { "iax2", "no", "debug", NULL },
10796 iax2_no_debug, NULL,
10797 NULL };
10799 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated = {
10800 { "iax2", "no", "trunk", "debug", NULL },
10801 iax2_no_trunk_debug, NULL,
10802 NULL };
10804 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated = {
10805 { "iax2", "no", "jb", "debug", NULL },
10806 iax2_no_jb_debug, NULL,
10807 NULL };
10809 static struct ast_cli_entry cli_iax2[] = {
10810 { { "iax2", "show", "cache", NULL },
10811 iax2_show_cache, "Display IAX cached dialplan",
10812 show_cache_usage, NULL, },
10814 { { "iax2", "show", "channels", NULL },
10815 iax2_show_channels, "List active IAX channels",
10816 show_channels_usage, NULL, },
10818 { { "iax2", "show", "firmware", NULL },
10819 iax2_show_firmware, "List available IAX firmwares",
10820 show_firmware_usage, NULL, },
10822 { { "iax2", "show", "netstats", NULL },
10823 iax2_show_netstats, "List active IAX channel netstats",
10824 show_netstats_usage, NULL, },
10826 { { "iax2", "show", "peers", NULL },
10827 iax2_show_peers, "List defined IAX peers",
10828 show_peers_usage, NULL, },
10830 { { "iax2", "show", "registry", NULL },
10831 iax2_show_registry, "Display IAX registration status",
10832 show_reg_usage, NULL, },
10834 { { "iax2", "show", "stats", NULL },
10835 iax2_show_stats, "Display IAX statistics",
10836 show_stats_usage, NULL, },
10838 { { "iax2", "show", "threads", NULL },
10839 iax2_show_threads, "Display IAX helper thread info",
10840 show_threads_usage, NULL, },
10842 { { "iax2", "show", "users", NULL },
10843 iax2_show_users, "List defined IAX users",
10844 show_users_usage, NULL, },
10846 { { "iax2", "prune", "realtime", NULL },
10847 iax2_prune_realtime, "Prune a cached realtime lookup",
10848 prune_realtime_usage, complete_iax2_show_peer },
10850 { { "iax2", "reload", NULL },
10851 iax2_reload, "Reload IAX configuration",
10852 iax2_reload_usage },
10854 { { "iax2", "show", "peer", NULL },
10855 iax2_show_peer, "Show details on specific IAX peer",
10856 show_peer_usage, complete_iax2_show_peer },
10858 { { "iax2", "set", "debug", NULL },
10859 iax2_do_debug, "Enable IAX debugging",
10860 debug_usage },
10862 { { "iax2", "set", "debug", "trunk", NULL },
10863 iax2_do_trunk_debug, "Enable IAX trunk debugging",
10864 debug_trunk_usage, NULL, &cli_iax2_trunk_debug_deprecated },
10866 { { "iax2", "set", "debug", "jb", NULL },
10867 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
10868 debug_jb_usage, NULL, &cli_iax2_jb_debug_deprecated },
10870 { { "iax2", "set", "debug", "off", NULL },
10871 iax2_no_debug, "Disable IAX debugging",
10872 no_debug_usage, NULL, &cli_iax2_no_debug_deprecated },
10874 { { "iax2", "set", "debug", "trunk", "off", NULL },
10875 iax2_no_trunk_debug, "Disable IAX trunk debugging",
10876 no_debug_trunk_usage, NULL, &cli_iax2_no_trunk_debug_deprecated },
10878 { { "iax2", "set", "debug", "jb", "off", NULL },
10879 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
10880 no_debug_jb_usage, NULL, &cli_iax2_no_jb_debug_deprecated },
10882 { { "iax2", "test", "losspct", NULL },
10883 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
10884 iax2_test_losspct_usage },
10886 { { "iax2", "provision", NULL },
10887 iax2_prov_cmd, "Provision an IAX device",
10888 show_prov_usage, iax2_prov_complete_template_3rd },
10890 #ifdef IAXTESTS
10891 { { "iax2", "test", "late", NULL },
10892 iax2_test_late, "Test the receipt of a late frame",
10893 iax2_test_late_usage },
10895 { { "iax2", "test", "resync", NULL },
10896 iax2_test_resync, "Test a resync in received timestamps",
10897 iax2_test_resync_usage },
10899 { { "iax2", "test", "jitter", NULL },
10900 iax2_test_jitter, "Simulates jitter for testing",
10901 iax2_test_jitter_usage },
10902 #endif /* IAXTESTS */
10905 static int __unload_module(void)
10907 struct iax2_thread *thread = NULL;
10908 int x;
10910 /* Make sure threads do not hold shared resources when they are canceled */
10912 /* Grab the sched lock resource to keep it away from threads about to die */
10913 /* Cancel the network thread, close the net socket */
10914 if (netthreadid != AST_PTHREADT_NULL) {
10915 AST_LIST_LOCK(&iaxq.queue);
10916 ast_mutex_lock(&sched_lock);
10917 pthread_cancel(netthreadid);
10918 ast_cond_signal(&sched_cond);
10919 ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
10920 AST_LIST_UNLOCK(&iaxq.queue);
10921 pthread_join(netthreadid, NULL);
10923 if (schedthreadid != AST_PTHREADT_NULL) {
10924 ast_mutex_lock(&sched_lock);
10925 pthread_cancel(schedthreadid);
10926 ast_cond_signal(&sched_cond);
10927 ast_mutex_unlock(&sched_lock);
10928 pthread_join(schedthreadid, NULL);
10931 /* Call for all threads to halt */
10932 AST_LIST_LOCK(&idle_list);
10933 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list, thread, list) {
10934 AST_LIST_REMOVE_CURRENT(&idle_list, list);
10935 pthread_cancel(thread->threadid);
10937 AST_LIST_TRAVERSE_SAFE_END
10938 AST_LIST_UNLOCK(&idle_list);
10940 AST_LIST_LOCK(&active_list);
10941 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list, thread, list) {
10942 AST_LIST_REMOVE_CURRENT(&active_list, list);
10943 pthread_cancel(thread->threadid);
10945 AST_LIST_TRAVERSE_SAFE_END
10946 AST_LIST_UNLOCK(&active_list);
10948 AST_LIST_LOCK(&dynamic_list);
10949 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list, thread, list) {
10950 AST_LIST_REMOVE_CURRENT(&dynamic_list, list);
10951 pthread_cancel(thread->threadid);
10953 AST_LIST_TRAVERSE_SAFE_END
10954 AST_LIST_UNLOCK(&dynamic_list);
10956 AST_LIST_HEAD_DESTROY(&iaxq.queue);
10958 /* Wait for threads to exit */
10959 while(0 < iaxactivethreadcount)
10960 usleep(10000);
10962 ast_netsock_release(netsock);
10963 ast_netsock_release(outsock);
10964 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10965 if (iaxs[x]) {
10966 iax2_destroy(x);
10969 ast_manager_unregister( "IAXpeers" );
10970 ast_manager_unregister( "IAXnetstats" );
10971 ast_unregister_application(papp);
10972 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10973 ast_unregister_switch(&iax2_switch);
10974 ast_channel_unregister(&iax2_tech);
10975 delete_users();
10976 iax_provision_unload();
10977 sched_context_destroy(sched);
10978 reload_firmware(1);
10980 ast_mutex_destroy(&waresl.lock);
10982 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
10983 ast_mutex_destroy(&iaxsl[x]);
10986 ao2_ref(peers, -1);
10987 ao2_ref(users, -1);
10988 ao2_ref(iax_peercallno_pvts, -1);
10990 return 0;
10993 static int unload_module(void)
10995 ast_custom_function_unregister(&iaxpeer_function);
10996 return __unload_module();
10999 static int peer_set_sock_cb(void *obj, void *arg, int flags)
11001 struct iax2_peer *peer = obj;
11003 if (peer->sockfd < 0)
11004 peer->sockfd = defaultsockfd;
11006 return 0;
11009 static int pvt_hash_cb(const void *obj, const int flags)
11011 const struct chan_iax2_pvt *pvt = obj;
11013 return pvt->peercallno;
11016 static int pvt_cmp_cb(void *obj, void *arg, int flags)
11018 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
11020 /* The frames_received field is used to hold whether we're matching
11021 * against a full frame or not ... */
11023 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
11024 pvt2->frames_received) ? CMP_MATCH : 0;
11027 /*! \brief Load IAX2 module, load configuraiton ---*/
11028 static int load_module(void)
11030 char *config = "iax.conf";
11031 int res = 0;
11032 int x;
11033 struct iax2_registry *reg = NULL;
11035 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
11036 if (!peers)
11037 return AST_MODULE_LOAD_FAILURE;
11038 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
11039 if (!users) {
11040 ao2_ref(peers, -1);
11041 return AST_MODULE_LOAD_FAILURE;
11043 iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb);
11044 if (!iax_peercallno_pvts) {
11045 ao2_ref(peers, -1);
11046 ao2_ref(users, -1);
11047 return AST_MODULE_LOAD_FAILURE;
11050 ast_custom_function_register(&iaxpeer_function);
11052 iax_set_output(iax_debug_output);
11053 iax_set_error(iax_error_output);
11054 jb_setoutput(jb_error_output, jb_warning_output, NULL);
11056 #ifdef HAVE_ZAPTEL
11057 #ifdef ZT_TIMERACK
11058 timingfd = open("/dev/zap/timer", O_RDWR);
11059 if (timingfd < 0)
11060 #endif
11061 timingfd = open("/dev/zap/pseudo", O_RDWR);
11062 if (timingfd < 0)
11063 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
11064 #endif
11066 memset(iaxs, 0, sizeof(iaxs));
11068 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
11069 ast_mutex_init(&iaxsl[x]);
11072 ast_cond_init(&sched_cond, NULL);
11074 io = io_context_create();
11075 sched = sched_context_create();
11077 if (!io || !sched) {
11078 ast_log(LOG_ERROR, "Out of memory\n");
11079 return -1;
11082 netsock = ast_netsock_list_alloc();
11083 if (!netsock) {
11084 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
11085 return -1;
11087 ast_netsock_init(netsock);
11089 outsock = ast_netsock_list_alloc();
11090 if (!outsock) {
11091 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
11092 return -1;
11094 ast_netsock_init(outsock);
11096 ast_mutex_init(&waresl.lock);
11098 AST_LIST_HEAD_INIT(&iaxq.queue);
11100 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
11102 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
11104 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
11105 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats, "Show IAX Netstats" );
11107 if(set_config(config, 0) == -1)
11108 return AST_MODULE_LOAD_DECLINE;
11110 if (ast_channel_register(&iax2_tech)) {
11111 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
11112 __unload_module();
11113 return -1;
11116 if (ast_register_switch(&iax2_switch))
11117 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
11119 res = start_network_thread();
11120 if (!res) {
11121 if (option_verbose > 1)
11122 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
11123 } else {
11124 ast_log(LOG_ERROR, "Unable to start network thread\n");
11125 ast_netsock_release(netsock);
11126 ast_netsock_release(outsock);
11129 AST_LIST_LOCK(&registrations);
11130 AST_LIST_TRAVERSE(&registrations, reg, entry)
11131 iax2_do_register(reg);
11132 AST_LIST_UNLOCK(&registrations);
11134 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
11135 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
11137 reload_firmware(0);
11138 iax_provision_reload();
11139 return res;
11142 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
11143 .load = load_module,
11144 .unload = unload_module,
11145 .reload = reload,