Merged revisions 115511 via svnmerge from
[asterisk-bristuff.git] / channels / chan_iax2.c
blob8c81ca73dad80d21315e637ccd869cf0de9d757d
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 switch (condition) {
3637 case AST_CONTROL_HOLD:
3638 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3639 ast_moh_start(c, data, pvt->mohinterpret);
3640 goto done;
3642 break;
3643 case AST_CONTROL_UNHOLD:
3644 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3645 ast_moh_stop(c);
3646 goto done;
3650 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3652 done:
3653 ast_mutex_unlock(&iaxsl[callno]);
3655 return res;
3658 static int iax2_transfer(struct ast_channel *c, const char *dest)
3660 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3661 struct iax_ie_data ied;
3662 char tmp[256], *context;
3663 ast_copy_string(tmp, dest, sizeof(tmp));
3664 context = strchr(tmp, '@');
3665 if (context) {
3666 *context = '\0';
3667 context++;
3669 memset(&ied, 0, sizeof(ied));
3670 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3671 if (context)
3672 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3673 if (option_debug)
3674 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3675 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3678 static int iax2_getpeertrunk(struct sockaddr_in sin)
3680 struct iax2_peer *peer;
3681 int res = 0;
3682 struct ao2_iterator i;
3684 i = ao2_iterator_init(peers, 0);
3685 while ((peer = ao2_iterator_next(&i))) {
3686 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3687 (peer->addr.sin_port == sin.sin_port)) {
3688 res = ast_test_flag(peer, IAX_TRUNK);
3689 peer_unref(peer);
3690 break;
3692 peer_unref(peer);
3695 return res;
3698 /*! \brief Create new call, interface with the PBX core */
3699 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3701 struct ast_channel *tmp;
3702 struct chan_iax2_pvt *i;
3703 struct ast_variable *v = NULL;
3705 if (!(i = iaxs[callno])) {
3706 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
3707 return NULL;
3710 /* Don't hold call lock */
3711 ast_mutex_unlock(&iaxsl[callno]);
3712 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);
3713 ast_mutex_lock(&iaxsl[callno]);
3714 if (!iaxs[callno]) {
3715 if (tmp) {
3716 ast_channel_free(tmp);
3718 ast_mutex_unlock(&iaxsl[callno]);
3719 return NULL;
3722 if (!tmp)
3723 return NULL;
3724 tmp->tech = &iax2_tech;
3725 /* We can support any format by default, until we get restricted */
3726 tmp->nativeformats = capability;
3727 tmp->readformat = ast_best_codec(capability);
3728 tmp->writeformat = ast_best_codec(capability);
3729 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3731 /* Don't use ast_set_callerid() here because it will
3732 * generate a NewCallerID event before the NewChannel event */
3733 if (!ast_strlen_zero(i->ani))
3734 tmp->cid.cid_ani = ast_strdup(i->ani);
3735 else
3736 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3737 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3738 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3739 tmp->cid.cid_pres = i->calling_pres;
3740 tmp->cid.cid_ton = i->calling_ton;
3741 tmp->cid.cid_tns = i->calling_tns;
3742 if (!ast_strlen_zero(i->language))
3743 ast_string_field_set(tmp, language, i->language);
3744 if (!ast_strlen_zero(i->accountcode))
3745 ast_string_field_set(tmp, accountcode, i->accountcode);
3746 if (i->amaflags)
3747 tmp->amaflags = i->amaflags;
3748 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3749 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3750 if (i->adsi)
3751 tmp->adsicpe = i->peeradsicpe;
3752 else
3753 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3754 i->owner = tmp;
3755 i->capability = capability;
3757 for (v = i->vars ; v ; v = v->next)
3758 pbx_builtin_setvar_helper(tmp, v->name, v->value);
3760 if (state != AST_STATE_DOWN) {
3761 if (ast_pbx_start(tmp)) {
3762 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3763 ast_hangup(tmp);
3764 i->owner = NULL;
3765 return NULL;
3769 ast_module_ref(ast_module_info->self);
3771 return tmp;
3774 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3776 unsigned long int mssincetx; /* unsigned to handle overflows */
3777 long int ms, pred;
3779 tpeer->trunkact = *tv;
3780 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3781 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3782 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3783 tpeer->txtrunktime = *tv;
3784 tpeer->lastsent = 999999;
3786 /* Update last transmit time now */
3787 tpeer->lasttxtime = *tv;
3789 /* Calculate ms offset */
3790 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3791 /* Predict from last value */
3792 pred = tpeer->lastsent + sampms;
3793 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3794 ms = pred;
3796 /* We never send the same timestamp twice, so fudge a little if we must */
3797 if (ms == tpeer->lastsent)
3798 ms = tpeer->lastsent + 1;
3799 tpeer->lastsent = ms;
3800 return ms;
3803 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3805 long ms; /* NOT unsigned */
3806 if (ast_tvzero(iaxs[callno]->rxcore)) {
3807 /* Initialize rxcore time if appropriate */
3808 gettimeofday(&iaxs[callno]->rxcore, NULL);
3809 /* Round to nearest 20ms so traces look pretty */
3810 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3812 /* Calculate difference between trunk and channel */
3813 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3814 /* Return as the sum of trunk time and the difference between trunk and real time */
3815 return ms + ts;
3818 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3820 int ms;
3821 int voice = 0;
3822 int genuine = 0;
3823 int adjust;
3824 struct timeval *delivery = NULL;
3827 /* What sort of frame do we have?: voice is self-explanatory
3828 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3829 non-genuine frames are CONTROL frames [ringing etc], DTMF
3830 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3831 the others need a timestamp slaved to the voice frames so that they go in sequence
3833 if (f) {
3834 if (f->frametype == AST_FRAME_VOICE) {
3835 voice = 1;
3836 delivery = &f->delivery;
3837 } else if (f->frametype == AST_FRAME_IAX) {
3838 genuine = 1;
3839 } else if (f->frametype == AST_FRAME_CNG) {
3840 p->notsilenttx = 0;
3843 if (ast_tvzero(p->offset)) {
3844 gettimeofday(&p->offset, NULL);
3845 /* Round to nearest 20ms for nice looking traces */
3846 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3848 /* If the timestamp is specified, just send it as is */
3849 if (ts)
3850 return ts;
3851 /* If we have a time that the frame arrived, always use it to make our timestamp */
3852 if (delivery && !ast_tvzero(*delivery)) {
3853 ms = ast_tvdiff_ms(*delivery, p->offset);
3854 if (option_debug > 2 && iaxdebug)
3855 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3856 } else {
3857 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3858 if (ms < 0)
3859 ms = 0;
3860 if (voice) {
3861 /* On a voice frame, use predicted values if appropriate */
3862 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3863 /* Adjust our txcore, keeping voice and non-voice synchronized */
3864 /* AN EXPLANATION:
3865 When we send voice, we usually send "calculated" timestamps worked out
3866 on the basis of the number of samples sent. When we send other frames,
3867 we usually send timestamps worked out from the real clock.
3868 The problem is that they can tend to drift out of step because the
3869 source channel's clock and our clock may not be exactly at the same rate.
3870 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3871 for this call. Moving it adjusts timestamps for non-voice frames.
3872 We make the adjustment in the style of a moving average. Each time we
3873 adjust p->offset by 10% of the difference between our clock-derived
3874 timestamp and the predicted timestamp. That's why you see "10000"
3875 below even though IAX2 timestamps are in milliseconds.
3876 The use of a moving average avoids offset moving too radically.
3877 Generally, "adjust" roams back and forth around 0, with offset hardly
3878 changing at all. But if a consistent different starts to develop it
3879 will be eliminated over the course of 10 frames (200-300msecs)
3881 adjust = (ms - p->nextpred);
3882 if (adjust < 0)
3883 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3884 else if (adjust > 0)
3885 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3887 if (!p->nextpred) {
3888 p->nextpred = ms; /*f->samples / 8;*/
3889 if (p->nextpred <= p->lastsent)
3890 p->nextpred = p->lastsent + 3;
3892 ms = p->nextpred;
3893 } else {
3894 /* in this case, just use the actual
3895 * time, since we're either way off
3896 * (shouldn't happen), or we're ending a
3897 * silent period -- and seed the next
3898 * predicted time. Also, round ms to the
3899 * next multiple of frame size (so our
3900 * silent periods are multiples of
3901 * frame size too) */
3903 if (option_debug && iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3904 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3905 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3907 if (f->samples >= 8) /* check to make sure we dont core dump */
3909 int diff = ms % (f->samples / 8);
3910 if (diff)
3911 ms += f->samples/8 - diff;
3914 p->nextpred = ms;
3915 p->notsilenttx = 1;
3917 } else if ( f->frametype == AST_FRAME_VIDEO ) {
3919 * IAX2 draft 03 says that timestamps MUST be in order.
3920 * It does not say anything about several frames having the same timestamp
3921 * When transporting video, we can have a frame that spans multiple iax packets
3922 * (so called slices), so it would make sense to use the same timestamp for all of
3923 * them
3924 * We do want to make sure that frames don't go backwards though
3926 if ( (unsigned int)ms < p->lastsent )
3927 ms = p->lastsent;
3928 } else {
3929 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3930 it's a genuine frame */
3931 if (genuine) {
3932 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3933 if (ms <= p->lastsent)
3934 ms = p->lastsent + 3;
3935 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3936 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3937 ms = p->lastsent + 3;
3941 p->lastsent = ms;
3942 if (voice)
3943 p->nextpred = p->nextpred + f->samples / 8;
3944 return ms;
3947 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3949 /* Returns where in "receive time" we are. That is, how many ms
3950 since we received (or would have received) the frame with timestamp 0 */
3951 int ms;
3952 #ifdef IAXTESTS
3953 int jit;
3954 #endif /* IAXTESTS */
3955 /* Setup rxcore if necessary */
3956 if (ast_tvzero(p->rxcore)) {
3957 p->rxcore = ast_tvnow();
3958 if (option_debug && iaxdebug)
3959 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3960 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3961 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3962 #if 1
3963 if (option_debug && iaxdebug)
3964 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3965 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3966 #endif
3969 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3970 #ifdef IAXTESTS
3971 if (test_jit) {
3972 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3973 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3974 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3975 jit = -jit;
3976 ms += jit;
3979 if (test_late) {
3980 ms += test_late;
3981 test_late = 0;
3983 #endif /* IAXTESTS */
3984 return ms;
3987 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3989 struct iax2_trunk_peer *tpeer;
3991 /* Finds and locks trunk peer */
3992 ast_mutex_lock(&tpeerlock);
3993 for (tpeer = tpeers; tpeer; tpeer = tpeer->next) {
3994 /* We don't lock here because tpeer->addr *never* changes */
3995 if (!inaddrcmp(&tpeer->addr, sin)) {
3996 ast_mutex_lock(&tpeer->lock);
3997 break;
4000 if (!tpeer) {
4001 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
4002 ast_mutex_init(&tpeer->lock);
4003 tpeer->lastsent = 9999;
4004 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
4005 tpeer->trunkact = ast_tvnow();
4006 ast_mutex_lock(&tpeer->lock);
4007 tpeer->next = tpeers;
4008 tpeer->sockfd = fd;
4009 tpeers = tpeer;
4010 #ifdef SO_NO_CHECK
4011 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
4012 #endif
4013 if (option_debug)
4014 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
4017 ast_mutex_unlock(&tpeerlock);
4018 return tpeer;
4021 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
4023 struct ast_frame *f;
4024 struct iax2_trunk_peer *tpeer;
4025 void *tmp, *ptr;
4026 struct ast_iax2_meta_trunk_entry *met;
4027 struct ast_iax2_meta_trunk_mini *mtm;
4029 f = &fr->af;
4030 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
4031 if (tpeer) {
4032 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
4033 /* Need to reallocate space */
4034 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
4035 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
4036 ast_mutex_unlock(&tpeer->lock);
4037 return -1;
4040 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
4041 tpeer->trunkdata = tmp;
4042 if (option_debug)
4043 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);
4044 } else {
4045 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));
4046 ast_mutex_unlock(&tpeer->lock);
4047 return -1;
4051 /* Append to meta frame */
4052 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
4053 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
4054 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
4055 mtm->len = htons(f->datalen);
4056 mtm->mini.callno = htons(pvt->callno);
4057 mtm->mini.ts = htons(0xffff & fr->ts);
4058 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
4059 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
4060 } else {
4061 met = (struct ast_iax2_meta_trunk_entry *)ptr;
4062 /* Store call number and length in meta header */
4063 met->callno = htons(pvt->callno);
4064 met->len = htons(f->datalen);
4065 /* Advance pointers/decrease length past trunk entry header */
4066 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
4067 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
4069 /* Copy actual trunk data */
4070 memcpy(ptr, f->data, f->datalen);
4071 tpeer->trunkdatalen += f->datalen;
4073 tpeer->calls++;
4074 ast_mutex_unlock(&tpeer->lock);
4076 return 0;
4079 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
4081 aes_encrypt_key128(digest, ecx);
4082 aes_decrypt_key128(digest, dcx);
4085 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
4087 #if 0
4088 /* Debug with "fake encryption" */
4089 int x;
4090 if (len % 16)
4091 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4092 for (x=0;x<len;x++)
4093 dst[x] = src[x] ^ 0xff;
4094 #else
4095 unsigned char lastblock[16] = { 0 };
4096 int x;
4097 while(len > 0) {
4098 aes_decrypt(src, dst, dcx);
4099 for (x=0;x<16;x++)
4100 dst[x] ^= lastblock[x];
4101 memcpy(lastblock, src, sizeof(lastblock));
4102 dst += 16;
4103 src += 16;
4104 len -= 16;
4106 #endif
4109 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
4111 #if 0
4112 /* Debug with "fake encryption" */
4113 int x;
4114 if (len % 16)
4115 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4116 for (x=0;x<len;x++)
4117 dst[x] = src[x] ^ 0xff;
4118 #else
4119 unsigned char curblock[16] = { 0 };
4120 int x;
4121 while(len > 0) {
4122 for (x=0;x<16;x++)
4123 curblock[x] ^= src[x];
4124 aes_encrypt(curblock, dst, ecx);
4125 memcpy(curblock, dst, sizeof(curblock));
4126 dst += 16;
4127 src += 16;
4128 len -= 16;
4130 #endif
4133 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4135 int padding;
4136 unsigned char *workspace;
4138 workspace = alloca(*datalen);
4139 memset(f, 0, sizeof(*f));
4140 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4141 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4142 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
4143 return -1;
4144 /* Decrypt */
4145 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
4147 padding = 16 + (workspace[15] & 0xf);
4148 if (option_debug && iaxdebug)
4149 ast_log(LOG_DEBUG, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
4150 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
4151 return -1;
4153 *datalen -= padding;
4154 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4155 f->frametype = fh->type;
4156 if (f->frametype == AST_FRAME_VIDEO) {
4157 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
4158 } else {
4159 f->subclass = uncompress_subclass(fh->csub);
4161 } else {
4162 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4163 if (option_debug && iaxdebug)
4164 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
4165 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
4166 return -1;
4167 /* Decrypt */
4168 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
4169 padding = 16 + (workspace[15] & 0x0f);
4170 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
4171 return -1;
4172 *datalen -= padding;
4173 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4175 return 0;
4178 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4180 int padding;
4181 unsigned char *workspace;
4182 workspace = alloca(*datalen + 32);
4183 if (!workspace)
4184 return -1;
4185 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4186 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4187 if (option_debug && iaxdebug)
4188 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
4189 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
4190 padding = 16 + (padding & 0xf);
4191 memcpy(workspace, poo, padding);
4192 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4193 workspace[15] &= 0xf0;
4194 workspace[15] |= (padding & 0xf);
4195 if (option_debug && iaxdebug)
4196 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]);
4197 *datalen += padding;
4198 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
4199 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
4200 memcpy(poo, workspace + *datalen - 32, 32);
4201 } else {
4202 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4203 if (option_debug && iaxdebug)
4204 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
4205 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
4206 padding = 16 + (padding & 0xf);
4207 memcpy(workspace, poo, padding);
4208 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4209 workspace[15] &= 0xf0;
4210 workspace[15] |= (padding & 0x0f);
4211 *datalen += padding;
4212 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
4213 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
4214 memcpy(poo, workspace + *datalen - 32, 32);
4216 return 0;
4219 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4221 int res=-1;
4222 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
4223 /* Search for possible keys, given secrets */
4224 struct MD5Context md5;
4225 unsigned char digest[16];
4226 char *tmppw, *stringp;
4228 tmppw = ast_strdupa(iaxs[callno]->secret);
4229 stringp = tmppw;
4230 while ((tmppw = strsep(&stringp, ";"))) {
4231 MD5Init(&md5);
4232 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
4233 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
4234 MD5Final(digest, &md5);
4235 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
4236 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4237 if (!res) {
4238 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4239 break;
4242 } else
4243 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4244 return res;
4247 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
4249 /* Queue a packet for delivery on a given private structure. Use "ts" for
4250 timestamp, or calculate if ts is 0. Send immediately without retransmission
4251 or delayed, with retransmission */
4252 struct ast_iax2_full_hdr *fh;
4253 struct ast_iax2_mini_hdr *mh;
4254 struct ast_iax2_video_hdr *vh;
4255 struct {
4256 struct iax_frame fr2;
4257 unsigned char buffer[4096];
4258 } frb;
4259 struct iax_frame *fr;
4260 int res;
4261 int sendmini=0;
4262 unsigned int lastsent;
4263 unsigned int fts;
4265 frb.fr2.afdatalen = sizeof(frb.buffer);
4267 if (!pvt) {
4268 ast_log(LOG_WARNING, "No private structure for packet?\n");
4269 return -1;
4272 lastsent = pvt->lastsent;
4274 /* Calculate actual timestamp */
4275 fts = calc_timestamp(pvt, ts, f);
4277 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4278 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4279 * increment the "predicted timestamps" for voice, if we're predecting */
4280 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
4281 return 0;
4284 if ((ast_test_flag(pvt, IAX_TRUNK) ||
4285 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
4286 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
4287 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4288 (f->frametype == AST_FRAME_VOICE)
4289 /* is a voice frame */ &&
4290 (f->subclass == pvt->svoiceformat)
4291 /* is the same type */ ) {
4292 /* Force immediate rather than delayed transmission */
4293 now = 1;
4294 /* Mark that mini-style frame is appropriate */
4295 sendmini = 1;
4297 if ( f->frametype == AST_FRAME_VIDEO ) {
4299 * If the lower 15 bits of the timestamp roll over, or if
4300 * the video format changed then send a full frame.
4301 * Otherwise send a mini video frame
4303 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
4304 ((f->subclass & ~0x1) == pvt->svideoformat)
4306 now = 1;
4307 sendmini = 1;
4308 } else {
4309 now = 0;
4310 sendmini = 0;
4312 pvt->lastvsent = fts;
4314 /* Allocate an iax_frame */
4315 if (now) {
4316 fr = &frb.fr2;
4317 } else
4318 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));
4319 if (!fr) {
4320 ast_log(LOG_WARNING, "Out of memory\n");
4321 return -1;
4323 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4324 iax_frame_wrap(fr, f);
4326 fr->ts = fts;
4327 fr->callno = pvt->callno;
4328 fr->transfer = transfer;
4329 fr->final = final;
4330 if (!sendmini) {
4331 /* We need a full frame */
4332 if (seqno > -1)
4333 fr->oseqno = seqno;
4334 else
4335 fr->oseqno = pvt->oseqno++;
4336 fr->iseqno = pvt->iseqno;
4337 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
4338 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
4339 fh->ts = htonl(fr->ts);
4340 fh->oseqno = fr->oseqno;
4341 if (transfer) {
4342 fh->iseqno = 0;
4343 } else
4344 fh->iseqno = fr->iseqno;
4345 /* Keep track of the last thing we've acknowledged */
4346 if (!transfer)
4347 pvt->aseqno = fr->iseqno;
4348 fh->type = fr->af.frametype & 0xFF;
4349 if (fr->af.frametype == AST_FRAME_VIDEO)
4350 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
4351 else
4352 fh->csub = compress_subclass(fr->af.subclass);
4353 if (transfer) {
4354 fr->dcallno = pvt->transfercallno;
4355 } else
4356 fr->dcallno = pvt->peercallno;
4357 fh->dcallno = htons(fr->dcallno);
4358 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4359 fr->data = fh;
4360 fr->retries = 0;
4361 /* Retry after 2x the ping time has passed */
4362 fr->retrytime = pvt->pingtime * 2;
4363 if (fr->retrytime < MIN_RETRY_TIME)
4364 fr->retrytime = MIN_RETRY_TIME;
4365 if (fr->retrytime > MAX_RETRY_TIME)
4366 fr->retrytime = MAX_RETRY_TIME;
4367 /* Acks' don't get retried */
4368 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
4369 fr->retries = -1;
4370 else if (f->frametype == AST_FRAME_VOICE)
4371 pvt->svoiceformat = f->subclass;
4372 else if (f->frametype == AST_FRAME_VIDEO)
4373 pvt->svideoformat = f->subclass & ~0x1;
4374 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4375 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4376 if (iaxdebug) {
4377 if (fr->transfer)
4378 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4379 else
4380 iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4382 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
4383 } else
4384 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4387 if (now) {
4388 res = send_packet(fr);
4389 } else
4390 res = iax2_transmit(fr);
4391 } else {
4392 if (ast_test_flag(pvt, IAX_TRUNK)) {
4393 iax2_trunk_queue(pvt, fr);
4394 res = 0;
4395 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4396 /* Video frame have no sequence number */
4397 fr->oseqno = -1;
4398 fr->iseqno = -1;
4399 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
4400 vh->zeros = 0;
4401 vh->callno = htons(0x8000 | fr->callno);
4402 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
4403 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
4404 fr->data = vh;
4405 fr->retries = -1;
4406 res = send_packet(fr);
4407 } else {
4408 /* Mini-frames have no sequence number */
4409 fr->oseqno = -1;
4410 fr->iseqno = -1;
4411 /* Mini frame will do */
4412 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
4413 mh->callno = htons(fr->callno);
4414 mh->ts = htons(fr->ts & 0xFFFF);
4415 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
4416 fr->data = mh;
4417 fr->retries = -1;
4418 if (pvt->transferring == TRANSFER_MEDIAPASS)
4419 fr->transfer = 1;
4420 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4421 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4422 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
4423 } else
4424 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4426 res = send_packet(fr);
4429 return res;
4432 static int iax2_show_users(int fd, int argc, char *argv[])
4434 regex_t regexbuf;
4435 int havepattern = 0;
4437 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4438 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4440 struct iax2_user *user = NULL;
4441 char auth[90];
4442 char *pstr = "";
4443 struct ao2_iterator i;
4445 switch (argc) {
4446 case 5:
4447 if (!strcasecmp(argv[3], "like")) {
4448 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4449 return RESULT_SHOWUSAGE;
4450 havepattern = 1;
4451 } else
4452 return RESULT_SHOWUSAGE;
4453 case 3:
4454 break;
4455 default:
4456 return RESULT_SHOWUSAGE;
4459 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4460 i = ao2_iterator_init(users, 0);
4461 for (user = ao2_iterator_next(&i); user;
4462 user_unref(user), user = ao2_iterator_next(&i)) {
4463 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
4464 continue;
4466 if (!ast_strlen_zero(user->secret)) {
4467 ast_copy_string(auth,user->secret,sizeof(auth));
4468 } else if (!ast_strlen_zero(user->inkeys)) {
4469 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
4470 } else
4471 ast_copy_string(auth, "-no secret-", sizeof(auth));
4473 if(ast_test_flag(user,IAX_CODEC_NOCAP))
4474 pstr = "REQ Only";
4475 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
4476 pstr = "Disabled";
4477 else
4478 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
4480 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
4481 user->contexts ? user->contexts->context : context,
4482 user->ha ? "Yes" : "No", pstr);
4485 if (havepattern)
4486 regfree(&regexbuf);
4488 return RESULT_SUCCESS;
4489 #undef FORMAT
4490 #undef FORMAT2
4493 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
4495 regex_t regexbuf;
4496 int havepattern = 0;
4497 int total_peers = 0;
4498 int online_peers = 0;
4499 int offline_peers = 0;
4500 int unmonitored_peers = 0;
4501 struct ao2_iterator i;
4503 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4504 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4506 struct iax2_peer *peer = NULL;
4507 char name[256];
4508 int registeredonly=0;
4509 char *term = manager ? "\r\n" : "\n";
4511 switch (argc) {
4512 case 6:
4513 if (!strcasecmp(argv[3], "registered"))
4514 registeredonly = 1;
4515 else
4516 return RESULT_SHOWUSAGE;
4517 if (!strcasecmp(argv[4], "like")) {
4518 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
4519 return RESULT_SHOWUSAGE;
4520 havepattern = 1;
4521 } else
4522 return RESULT_SHOWUSAGE;
4523 break;
4524 case 5:
4525 if (!strcasecmp(argv[3], "like")) {
4526 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4527 return RESULT_SHOWUSAGE;
4528 havepattern = 1;
4529 } else
4530 return RESULT_SHOWUSAGE;
4531 break;
4532 case 4:
4533 if (!strcasecmp(argv[3], "registered"))
4534 registeredonly = 1;
4535 else
4536 return RESULT_SHOWUSAGE;
4537 break;
4538 case 3:
4539 break;
4540 default:
4541 return RESULT_SHOWUSAGE;
4545 if (s)
4546 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4547 else
4548 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4550 i = ao2_iterator_init(peers, 0);
4551 for (peer = ao2_iterator_next(&i); peer;
4552 peer_unref(peer), peer = ao2_iterator_next(&i)) {
4553 char nm[20];
4554 char status[20];
4555 char srch[2000];
4556 int retstatus;
4558 if (registeredonly && !peer->addr.sin_addr.s_addr)
4559 continue;
4560 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
4561 continue;
4563 if (!ast_strlen_zero(peer->username))
4564 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
4565 else
4566 ast_copy_string(name, peer->name, sizeof(name));
4568 retstatus = peer_status(peer, status, sizeof(status));
4569 if (retstatus > 0)
4570 online_peers++;
4571 else if (!retstatus)
4572 offline_peers++;
4573 else
4574 unmonitored_peers++;
4576 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
4578 snprintf(srch, sizeof(srch), FORMAT, name,
4579 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4580 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4582 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4583 peer->encmethods ? "(E)" : " ", status, term);
4585 if (s)
4586 astman_append(s, FORMAT, name,
4587 peer->addr.sin_addr.s_addr ? ast_inet_ntoa( peer->addr.sin_addr) : "(Unspecified)",
4588 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4590 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4591 peer->encmethods ? "(E)" : " ", status, term);
4592 else
4593 ast_cli(fd, 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);
4599 total_peers++;
4602 if (s)
4603 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4604 else
4605 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4607 if (havepattern)
4608 regfree(&regexbuf);
4610 return RESULT_SUCCESS;
4611 #undef FORMAT
4612 #undef FORMAT2
4615 static int iax2_show_threads(int fd, int argc, char *argv[])
4617 struct iax2_thread *thread = NULL;
4618 time_t t;
4619 int threadcount = 0, dynamiccount = 0;
4620 char type;
4622 if (argc != 3)
4623 return RESULT_SHOWUSAGE;
4625 ast_cli(fd, "IAX2 Thread Information\n");
4626 time(&t);
4627 ast_cli(fd, "Idle Threads:\n");
4628 AST_LIST_LOCK(&idle_list);
4629 AST_LIST_TRAVERSE(&idle_list, thread, list) {
4630 #ifdef DEBUG_SCHED_MULTITHREAD
4631 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4632 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4633 #else
4634 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4635 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4636 #endif
4637 threadcount++;
4639 AST_LIST_UNLOCK(&idle_list);
4640 ast_cli(fd, "Active Threads:\n");
4641 AST_LIST_LOCK(&active_list);
4642 AST_LIST_TRAVERSE(&active_list, thread, list) {
4643 if (thread->type == IAX_TYPE_DYNAMIC)
4644 type = 'D';
4645 else
4646 type = 'P';
4647 #ifdef DEBUG_SCHED_MULTITHREAD
4648 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4649 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4650 #else
4651 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4652 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4653 #endif
4654 threadcount++;
4656 AST_LIST_UNLOCK(&active_list);
4657 ast_cli(fd, "Dynamic Threads:\n");
4658 AST_LIST_LOCK(&dynamic_list);
4659 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
4660 #ifdef DEBUG_SCHED_MULTITHREAD
4661 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4662 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4663 #else
4664 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4665 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4666 #endif
4667 dynamiccount++;
4669 AST_LIST_UNLOCK(&dynamic_list);
4670 ast_cli(fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
4671 return RESULT_SUCCESS;
4674 static int iax2_show_peers(int fd, int argc, char *argv[])
4676 return __iax2_show_peers(0, fd, NULL, argc, argv);
4678 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
4680 ast_cli_netstats(s, -1, 0);
4681 astman_append(s, "\r\n");
4682 return RESULT_SUCCESS;
4685 static int iax2_show_firmware(int fd, int argc, char *argv[])
4687 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4688 #if !defined(__FreeBSD__)
4689 #define FORMAT "%-15.15s %-15d %-15d\n"
4690 #else /* __FreeBSD__ */
4691 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4692 #endif /* __FreeBSD__ */
4693 struct iax_firmware *cur;
4694 if ((argc != 3) && (argc != 4))
4695 return RESULT_SHOWUSAGE;
4696 ast_mutex_lock(&waresl.lock);
4698 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
4699 for (cur = waresl.wares;cur;cur = cur->next) {
4700 if ((argc == 3) || (!strcasecmp(argv[3], (char *)cur->fwh->devname)))
4701 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
4702 (int)ntohl(cur->fwh->datalen));
4704 ast_mutex_unlock(&waresl.lock);
4705 return RESULT_SUCCESS;
4706 #undef FORMAT
4707 #undef FORMAT2
4710 /* JDG: callback to display iax peers in manager */
4711 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
4713 char *a[] = { "iax2", "show", "users" };
4714 int ret;
4715 const char *id = astman_get_header(m,"ActionID");
4717 if (!ast_strlen_zero(id))
4718 astman_append(s, "ActionID: %s\r\n",id);
4719 ret = __iax2_show_peers(1, -1, s, 3, a );
4720 astman_append(s, "\r\n\r\n" );
4721 return ret;
4722 } /* /JDG */
4724 static char *regstate2str(int regstate)
4726 switch(regstate) {
4727 case REG_STATE_UNREGISTERED:
4728 return "Unregistered";
4729 case REG_STATE_REGSENT:
4730 return "Request Sent";
4731 case REG_STATE_AUTHSENT:
4732 return "Auth. Sent";
4733 case REG_STATE_REGISTERED:
4734 return "Registered";
4735 case REG_STATE_REJECTED:
4736 return "Rejected";
4737 case REG_STATE_TIMEOUT:
4738 return "Timeout";
4739 case REG_STATE_NOAUTH:
4740 return "No Authentication";
4741 default:
4742 return "Unknown";
4746 static int iax2_show_registry(int fd, int argc, char *argv[])
4748 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4749 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4750 struct iax2_registry *reg = NULL;
4752 char host[80];
4753 char perceived[80];
4754 if (argc != 3)
4755 return RESULT_SHOWUSAGE;
4756 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4757 AST_LIST_LOCK(&registrations);
4758 AST_LIST_TRAVERSE(&registrations, reg, entry) {
4759 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
4760 if (reg->us.sin_addr.s_addr)
4761 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
4762 else
4763 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
4764 ast_cli(fd, FORMAT, host,
4765 (reg->dnsmgr) ? "Y" : "N",
4766 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
4768 AST_LIST_UNLOCK(&registrations);
4769 return RESULT_SUCCESS;
4770 #undef FORMAT
4771 #undef FORMAT2
4774 static int iax2_show_channels(int fd, int argc, char *argv[])
4776 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4777 #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"
4778 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4779 int x;
4780 int numchans = 0;
4782 if (argc != 3)
4783 return RESULT_SHOWUSAGE;
4784 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4785 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4786 ast_mutex_lock(&iaxsl[x]);
4787 if (iaxs[x]) {
4788 int lag, jitter, localdelay;
4789 jb_info jbinfo;
4791 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4792 jb_getinfo(iaxs[x]->jb, &jbinfo);
4793 jitter = jbinfo.jitter;
4794 localdelay = jbinfo.current - jbinfo.min;
4795 } else {
4796 jitter = -1;
4797 localdelay = 0;
4799 lag = iaxs[x]->remote_rr.delay;
4800 ast_cli(fd, FORMAT,
4801 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4802 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
4803 S_OR(iaxs[x]->username, "(None)"),
4804 iaxs[x]->callno, iaxs[x]->peercallno,
4805 iaxs[x]->oseqno, iaxs[x]->iseqno,
4806 lag,
4807 jitter,
4808 localdelay,
4809 ast_getformatname(iaxs[x]->voiceformat) );
4810 numchans++;
4812 ast_mutex_unlock(&iaxsl[x]);
4814 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4815 return RESULT_SUCCESS;
4816 #undef FORMAT
4817 #undef FORMAT2
4818 #undef FORMATB
4821 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
4823 int x;
4824 int numchans = 0;
4825 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4826 ast_mutex_lock(&iaxsl[x]);
4827 if (iaxs[x]) {
4828 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
4829 char *fmt;
4830 jb_info jbinfo;
4832 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4833 jb_getinfo(iaxs[x]->jb, &jbinfo);
4834 localjitter = jbinfo.jitter;
4835 localdelay = jbinfo.current - jbinfo.min;
4836 locallost = jbinfo.frames_lost;
4837 locallosspct = jbinfo.losspct/1000;
4838 localdropped = jbinfo.frames_dropped;
4839 localooo = jbinfo.frames_ooo;
4840 } else {
4841 localjitter = -1;
4842 localdelay = 0;
4843 locallost = -1;
4844 locallosspct = -1;
4845 localdropped = 0;
4846 localooo = -1;
4848 if (limit_fmt)
4849 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4850 else
4851 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4852 if (s)
4854 astman_append(s, fmt,
4855 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4856 iaxs[x]->pingtime,
4857 localjitter,
4858 localdelay,
4859 locallost,
4860 locallosspct,
4861 localdropped,
4862 localooo,
4863 iaxs[x]->frames_received/1000,
4864 iaxs[x]->remote_rr.jitter,
4865 iaxs[x]->remote_rr.delay,
4866 iaxs[x]->remote_rr.losscnt,
4867 iaxs[x]->remote_rr.losspct,
4868 iaxs[x]->remote_rr.dropped,
4869 iaxs[x]->remote_rr.ooo,
4870 iaxs[x]->remote_rr.packets/1000);
4871 else
4872 ast_cli(fd, fmt,
4873 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4874 iaxs[x]->pingtime,
4875 localjitter,
4876 localdelay,
4877 locallost,
4878 locallosspct,
4879 localdropped,
4880 localooo,
4881 iaxs[x]->frames_received/1000,
4882 iaxs[x]->remote_rr.jitter,
4883 iaxs[x]->remote_rr.delay,
4884 iaxs[x]->remote_rr.losscnt,
4885 iaxs[x]->remote_rr.losspct,
4886 iaxs[x]->remote_rr.dropped,
4887 iaxs[x]->remote_rr.ooo,
4888 iaxs[x]->remote_rr.packets/1000
4890 numchans++;
4892 ast_mutex_unlock(&iaxsl[x]);
4894 return numchans;
4897 static int iax2_show_netstats(int fd, int argc, char *argv[])
4899 int numchans = 0;
4900 if (argc != 3)
4901 return RESULT_SHOWUSAGE;
4902 ast_cli(fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4903 ast_cli(fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4904 numchans = ast_cli_netstats(NULL, fd, 1);
4905 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4906 return RESULT_SUCCESS;
4909 static int iax2_do_debug(int fd, int argc, char *argv[])
4911 if (argc < 2 || argc > 3)
4912 return RESULT_SHOWUSAGE;
4913 iaxdebug = 1;
4914 ast_cli(fd, "IAX2 Debugging Enabled\n");
4915 return RESULT_SUCCESS;
4918 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
4920 if (argc < 3 || argc > 4)
4921 return RESULT_SHOWUSAGE;
4922 iaxtrunkdebug = 1;
4923 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
4924 return RESULT_SUCCESS;
4927 static int iax2_do_jb_debug(int fd, int argc, char *argv[])
4929 if (argc < 3 || argc > 4)
4930 return RESULT_SHOWUSAGE;
4931 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
4932 ast_cli(fd, "IAX2 Jitterbuffer Debugging Enabled\n");
4933 return RESULT_SUCCESS;
4936 static int iax2_no_debug(int fd, int argc, char *argv[])
4938 if (argc < 3 || argc > 4)
4939 return RESULT_SHOWUSAGE;
4940 iaxdebug = 0;
4941 ast_cli(fd, "IAX2 Debugging Disabled\n");
4942 return RESULT_SUCCESS;
4945 static int iax2_no_trunk_debug(int fd, int argc, char *argv[])
4947 if (argc < 4 || argc > 5)
4948 return RESULT_SHOWUSAGE;
4949 iaxtrunkdebug = 0;
4950 ast_cli(fd, "IAX2 Trunk Debugging Disabled\n");
4951 return RESULT_SUCCESS;
4954 static int iax2_no_jb_debug(int fd, int argc, char *argv[])
4956 if (argc < 4 || argc > 5)
4957 return RESULT_SHOWUSAGE;
4958 jb_setoutput(jb_error_output, jb_warning_output, NULL);
4959 jb_debug_output("\n");
4960 ast_cli(fd, "IAX2 Jitterbuffer Debugging Disabled\n");
4961 return RESULT_SUCCESS;
4964 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
4966 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4967 int res = -1;
4968 ast_mutex_lock(&iaxsl[callno]);
4969 if (iaxs[callno]) {
4970 /* If there's an outstanding error, return failure now */
4971 if (!iaxs[callno]->error) {
4972 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
4973 res = 0;
4974 /* Don't waste bandwidth sending null frames */
4975 else if (f->frametype == AST_FRAME_NULL)
4976 res = 0;
4977 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
4978 res = 0;
4979 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
4980 res = 0;
4981 else
4982 /* Simple, just queue for transmission */
4983 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
4984 } else {
4985 if (option_debug)
4986 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
4989 /* If it's already gone, just return */
4990 ast_mutex_unlock(&iaxsl[callno]);
4991 return res;
4994 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
4995 int now, int transfer, int final)
4997 struct ast_frame f = { 0, };
4999 f.frametype = type;
5000 f.subclass = command;
5001 f.datalen = datalen;
5002 f.src = __FUNCTION__;
5003 f.data = (void *) data;
5005 return iax2_send(i, &f, ts, seqno, now, transfer, final);
5008 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 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
5013 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5015 int res;
5016 ast_mutex_lock(&iaxsl[callno]);
5017 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
5018 ast_mutex_unlock(&iaxsl[callno]);
5019 return res;
5023 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5024 * the pvt struct for the given call number may disappear during its
5025 * execution.
5027 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)
5029 int call_num = i->callno;
5030 /* It is assumed that the callno has already been locked */
5031 iax2_predestroy(i->callno);
5032 if (!iaxs[call_num])
5033 return -1;
5034 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
5037 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)
5039 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
5042 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
5044 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
5047 static int apply_context(struct iax2_context *con, const char *context)
5049 while(con) {
5050 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
5051 return -1;
5052 con = con->next;
5054 return 0;
5058 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5060 /* Start pessimistic */
5061 int res = -1;
5062 int version = 2;
5063 struct iax2_user *user = NULL, *best = NULL;
5064 int bestscore = 0;
5065 int gotcapability = 0;
5066 struct ast_variable *v = NULL, *tmpvar = NULL;
5067 struct ao2_iterator i;
5069 if (!iaxs[callno])
5070 return res;
5071 if (ies->called_number)
5072 ast_string_field_set(iaxs[callno], exten, ies->called_number);
5073 if (ies->calling_number) {
5074 ast_shrink_phone_number(ies->calling_number);
5075 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
5077 if (ies->calling_name)
5078 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
5079 if (ies->calling_ani)
5080 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
5081 if (ies->dnid)
5082 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
5083 if (ies->rdnis)
5084 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
5085 if (ies->called_context)
5086 ast_string_field_set(iaxs[callno], context, ies->called_context);
5087 if (ies->language)
5088 ast_string_field_set(iaxs[callno], language, ies->language);
5089 if (ies->username)
5090 ast_string_field_set(iaxs[callno], username, ies->username);
5091 if (ies->calling_ton > -1)
5092 iaxs[callno]->calling_ton = ies->calling_ton;
5093 if (ies->calling_tns > -1)
5094 iaxs[callno]->calling_tns = ies->calling_tns;
5095 if (ies->calling_pres > -1)
5096 iaxs[callno]->calling_pres = ies->calling_pres;
5097 if (ies->format)
5098 iaxs[callno]->peerformat = ies->format;
5099 if (ies->adsicpe)
5100 iaxs[callno]->peeradsicpe = ies->adsicpe;
5101 if (ies->capability) {
5102 gotcapability = 1;
5103 iaxs[callno]->peercapability = ies->capability;
5105 if (ies->version)
5106 version = ies->version;
5108 /* Use provided preferences until told otherwise for actual preferences */
5109 if(ies->codec_prefs) {
5110 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
5111 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
5114 if (!gotcapability)
5115 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
5116 if (version > IAX_PROTO_VERSION) {
5117 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
5118 ast_inet_ntoa(sin->sin_addr), version);
5119 return res;
5121 /* Search the userlist for a compatible entry, and fill in the rest */
5122 i = ao2_iterator_init(users, 0);
5123 while ((user = ao2_iterator_next(&i))) {
5124 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
5125 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
5126 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
5127 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
5128 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
5129 if (!ast_strlen_zero(iaxs[callno]->username)) {
5130 /* Exact match, stop right now. */
5131 if (best)
5132 user_unref(best);
5133 best = user;
5134 break;
5135 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5136 /* No required authentication */
5137 if (user->ha) {
5138 /* There was host authentication and we passed, bonus! */
5139 if (bestscore < 4) {
5140 bestscore = 4;
5141 if (best)
5142 user_unref(best);
5143 best = user;
5144 continue;
5146 } else {
5147 /* No host access, but no secret, either, not bad */
5148 if (bestscore < 3) {
5149 bestscore = 3;
5150 if (best)
5151 user_unref(best);
5152 best = user;
5153 continue;
5156 } else {
5157 if (user->ha) {
5158 /* Authentication, but host access too, eh, it's something.. */
5159 if (bestscore < 2) {
5160 bestscore = 2;
5161 if (best)
5162 user_unref(best);
5163 best = user;
5164 continue;
5166 } else {
5167 /* Authentication and no host access... This is our baseline */
5168 if (bestscore < 1) {
5169 bestscore = 1;
5170 if (best)
5171 user_unref(best);
5172 best = user;
5173 continue;
5178 user_unref(user);
5180 user = best;
5181 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
5182 user = realtime_user(iaxs[callno]->username, sin);
5183 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
5184 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
5185 user = user_unref(user);
5188 if (user) {
5189 /* We found our match (use the first) */
5190 /* copy vars */
5191 for (v = user->vars ; v ; v = v->next) {
5192 if((tmpvar = ast_variable_new(v->name, v->value))) {
5193 tmpvar->next = iaxs[callno]->vars;
5194 iaxs[callno]->vars = tmpvar;
5197 /* If a max AUTHREQ restriction is in place, activate it */
5198 if (user->maxauthreq > 0)
5199 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
5200 iaxs[callno]->prefs = user->prefs;
5201 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
5202 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
5203 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
5204 iaxs[callno]->encmethods = user->encmethods;
5205 /* Store the requested username if not specified */
5206 if (ast_strlen_zero(iaxs[callno]->username))
5207 ast_string_field_set(iaxs[callno], username, user->name);
5208 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5209 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
5210 iaxs[callno]->capability = user->capability;
5211 /* And use the default context */
5212 if (ast_strlen_zero(iaxs[callno]->context)) {
5213 if (user->contexts)
5214 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5215 else
5216 ast_string_field_set(iaxs[callno], context, context);
5218 /* And any input keys */
5219 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
5220 /* And the permitted authentication methods */
5221 iaxs[callno]->authmethods = user->authmethods;
5222 iaxs[callno]->adsi = user->adsi;
5223 /* If they have callerid, override the given caller id. Always store the ANI */
5224 if (!ast_strlen_zero(iaxs[callno]->cid_num) || !ast_strlen_zero(iaxs[callno]->cid_name)) {
5225 if (ast_test_flag(user, IAX_HASCALLERID)) {
5226 iaxs[callno]->calling_tns = 0;
5227 iaxs[callno]->calling_ton = 0;
5228 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
5229 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
5230 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
5232 if (ast_strlen_zero(iaxs[callno]->ani))
5233 ast_string_field_set(iaxs[callno], ani, user->cid_num);
5234 } else {
5235 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
5237 if (!ast_strlen_zero(user->accountcode))
5238 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
5239 if (!ast_strlen_zero(user->mohinterpret))
5240 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
5241 if (!ast_strlen_zero(user->mohsuggest))
5242 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
5243 if (user->amaflags)
5244 iaxs[callno]->amaflags = user->amaflags;
5245 if (!ast_strlen_zero(user->language))
5246 ast_string_field_set(iaxs[callno], language, user->language);
5247 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
5248 /* Keep this check last */
5249 if (!ast_strlen_zero(user->dbsecret)) {
5250 char *family, *key=NULL;
5251 char buf[80];
5252 family = ast_strdupa(user->dbsecret);
5253 key = strchr(family, '/');
5254 if (key) {
5255 *key = '\0';
5256 key++;
5258 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
5259 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
5260 else
5261 ast_string_field_set(iaxs[callno], secret, buf);
5262 } else
5263 ast_string_field_set(iaxs[callno], secret, user->secret);
5264 res = 0;
5265 user = user_unref(user);
5267 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
5268 return res;
5271 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
5273 struct ast_iax2_full_hdr fh;
5274 fh.scallno = htons(src | IAX_FLAG_FULL);
5275 fh.dcallno = htons(dst);
5276 fh.ts = 0;
5277 fh.oseqno = 0;
5278 fh.iseqno = 0;
5279 fh.type = AST_FRAME_IAX;
5280 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
5281 if (iaxdebug)
5282 iax_showframe(NULL, &fh, 0, sin, 0);
5283 if (option_debug)
5284 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5285 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
5286 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
5289 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
5291 /* Select exactly one common encryption if there are any */
5292 p->encmethods &= enc;
5293 if (p->encmethods) {
5294 if (p->encmethods & IAX_ENCRYPT_AES128)
5295 p->encmethods = IAX_ENCRYPT_AES128;
5296 else
5297 p->encmethods = 0;
5302 * \pre iaxsl[call_num] is locked
5304 * \note Since this function calls send_command_final(), the pvt struct for the given
5305 * call number may disappear while executing this function.
5307 static int authenticate_request(int call_num)
5309 struct iax_ie_data ied;
5310 int res = -1, authreq_restrict = 0;
5311 char challenge[10];
5312 struct chan_iax2_pvt *p = iaxs[call_num];
5314 memset(&ied, 0, sizeof(ied));
5316 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5317 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5318 struct iax2_user *user, tmp_user = {
5319 .name = p->username,
5322 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5323 if (user) {
5324 if (user->curauthreq == user->maxauthreq)
5325 authreq_restrict = 1;
5326 else
5327 user->curauthreq++;
5328 user = user_unref(user);
5332 /* If the AUTHREQ limit test failed, send back an error */
5333 if (authreq_restrict) {
5334 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
5335 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
5336 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
5337 return 0;
5340 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
5341 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
5342 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
5343 ast_string_field_set(p, challenge, challenge);
5344 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5345 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
5347 if (p->encmethods)
5348 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
5350 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
5352 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
5354 if (p->encmethods)
5355 ast_set_flag(p, IAX_ENCRYPTED);
5357 return res;
5360 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
5362 char requeststr[256];
5363 char md5secret[256] = "";
5364 char secret[256] = "";
5365 char rsasecret[256] = "";
5366 int res = -1;
5367 int x;
5368 struct iax2_user *user, tmp_user = {
5369 .name = p->username,
5372 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5373 if (user) {
5374 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5375 ast_atomic_fetchadd_int(&user->curauthreq, -1);
5376 ast_clear_flag(p, IAX_MAXAUTHREQ);
5378 ast_string_field_set(p, host, user->name);
5379 user = user_unref(user);
5382 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
5383 return res;
5384 if (ies->password)
5385 ast_copy_string(secret, ies->password, sizeof(secret));
5386 if (ies->md5_result)
5387 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5388 if (ies->rsa_result)
5389 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5390 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
5391 struct ast_key *key;
5392 char *keyn;
5393 char tmpkey[256];
5394 char *stringp=NULL;
5395 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
5396 stringp=tmpkey;
5397 keyn = strsep(&stringp, ":");
5398 while(keyn) {
5399 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5400 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
5401 res = 0;
5402 break;
5403 } else if (!key)
5404 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
5405 keyn = strsep(&stringp, ":");
5407 } else if (p->authmethods & IAX_AUTH_MD5) {
5408 struct MD5Context md5;
5409 unsigned char digest[16];
5410 char *tmppw, *stringp;
5412 tmppw = ast_strdupa(p->secret);
5413 stringp = tmppw;
5414 while((tmppw = strsep(&stringp, ";"))) {
5415 MD5Init(&md5);
5416 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
5417 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5418 MD5Final(digest, &md5);
5419 /* If they support md5, authenticate with it. */
5420 for (x=0;x<16;x++)
5421 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5422 if (!strcasecmp(requeststr, md5secret)) {
5423 res = 0;
5424 break;
5427 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
5428 if (!strcmp(secret, p->secret))
5429 res = 0;
5431 return res;
5434 /*! \brief Verify inbound registration */
5435 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5437 char requeststr[256] = "";
5438 char peer[256] = "";
5439 char md5secret[256] = "";
5440 char rsasecret[256] = "";
5441 char secret[256] = "";
5442 struct iax2_peer *p = NULL;
5443 struct ast_key *key;
5444 char *keyn;
5445 int x;
5446 int expire = 0;
5447 int res = -1;
5449 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
5450 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5451 if (ies->username)
5452 ast_copy_string(peer, ies->username, sizeof(peer));
5453 if (ies->password)
5454 ast_copy_string(secret, ies->password, sizeof(secret));
5455 if (ies->md5_result)
5456 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5457 if (ies->rsa_result)
5458 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5459 if (ies->refresh)
5460 expire = ies->refresh;
5462 if (ast_strlen_zero(peer)) {
5463 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
5464 return -1;
5467 /* SLD: first call to lookup peer during registration */
5468 ast_mutex_unlock(&iaxsl[callno]);
5469 p = find_peer(peer, 1);
5470 ast_mutex_lock(&iaxsl[callno]);
5471 if (!p || !iaxs[callno]) {
5472 if (authdebug && !p)
5473 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5474 goto return_unref;
5477 if (!ast_test_flag(p, IAX_DYNAMIC)) {
5478 if (authdebug)
5479 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5480 goto return_unref;
5483 if (!ast_apply_ha(p->ha, sin)) {
5484 if (authdebug)
5485 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5486 goto return_unref;
5488 if (!inaddrcmp(&p->addr, sin))
5489 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
5490 ast_string_field_set(iaxs[callno], secret, p->secret);
5491 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
5492 /* Check secret against what we have on file */
5493 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5494 if (!ast_strlen_zero(p->inkeys)) {
5495 char tmpkeys[256];
5496 char *stringp=NULL;
5497 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
5498 stringp=tmpkeys;
5499 keyn = strsep(&stringp, ":");
5500 while(keyn) {
5501 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5502 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
5503 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5504 break;
5505 } else if (!key)
5506 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
5507 keyn = strsep(&stringp, ":");
5509 if (!keyn) {
5510 if (authdebug)
5511 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
5512 goto return_unref;
5514 } else {
5515 if (authdebug)
5516 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
5517 goto return_unref;
5519 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5520 struct MD5Context md5;
5521 unsigned char digest[16];
5522 char *tmppw, *stringp;
5524 tmppw = ast_strdupa(p->secret);
5525 stringp = tmppw;
5526 while((tmppw = strsep(&stringp, ";"))) {
5527 MD5Init(&md5);
5528 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
5529 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5530 MD5Final(digest, &md5);
5531 for (x=0;x<16;x++)
5532 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5533 if (!strcasecmp(requeststr, md5secret))
5534 break;
5536 if (tmppw) {
5537 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5538 } else {
5539 if (authdebug)
5540 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
5541 goto return_unref;
5543 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
5544 /* They've provided a plain text password and we support that */
5545 if (strcmp(secret, p->secret)) {
5546 if (authdebug)
5547 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5548 goto return_unref;
5549 } else
5550 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5551 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
5552 if (authdebug)
5553 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
5554 goto return_unref;
5556 ast_string_field_set(iaxs[callno], peer, peer);
5557 /* Choose lowest expiry number */
5558 if (expire && (expire < iaxs[callno]->expiry))
5559 iaxs[callno]->expiry = expire;
5561 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5563 res = 0;
5565 return_unref:
5566 if (p)
5567 peer_unref(p);
5569 return res;
5572 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)
5574 int res = -1;
5575 int x;
5576 if (!ast_strlen_zero(keyn)) {
5577 if (!(authmethods & IAX_AUTH_RSA)) {
5578 if (ast_strlen_zero(secret))
5579 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));
5580 } else if (ast_strlen_zero(challenge)) {
5581 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
5582 } else {
5583 char sig[256];
5584 struct ast_key *key;
5585 key = ast_key_get(keyn, AST_KEY_PRIVATE);
5586 if (!key) {
5587 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
5588 } else {
5589 if (ast_sign(key, (char*)challenge, sig)) {
5590 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
5591 res = -1;
5592 } else {
5593 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
5594 res = 0;
5599 /* Fall back */
5600 if (res && !ast_strlen_zero(secret)) {
5601 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
5602 struct MD5Context md5;
5603 unsigned char digest[16];
5604 char digres[128];
5605 MD5Init(&md5);
5606 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
5607 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
5608 MD5Final(digest, &md5);
5609 /* If they support md5, authenticate with it. */
5610 for (x=0;x<16;x++)
5611 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
5612 if (ecx && dcx)
5613 build_enc_keys(digest, ecx, dcx);
5614 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
5615 res = 0;
5616 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
5617 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
5618 res = 0;
5619 } else
5620 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
5622 return res;
5626 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5627 * so do not call this function with a pvt lock held.
5629 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
5631 struct iax2_peer *peer = NULL;
5632 /* Start pessimistic */
5633 int res = -1;
5634 int authmethods = 0;
5635 struct iax_ie_data ied;
5636 uint16_t callno = p->callno;
5638 memset(&ied, 0, sizeof(ied));
5640 if (ies->username)
5641 ast_string_field_set(p, username, ies->username);
5642 if (ies->challenge)
5643 ast_string_field_set(p, challenge, ies->challenge);
5644 if (ies->authmethods)
5645 authmethods = ies->authmethods;
5646 if (authmethods & IAX_AUTH_MD5)
5647 merge_encryption(p, ies->encmethods);
5648 else
5649 p->encmethods = 0;
5651 /* Check for override RSA authentication first */
5652 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
5653 /* Normal password authentication */
5654 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5655 } else {
5656 struct ao2_iterator i = ao2_iterator_init(peers, 0);
5657 while ((peer = ao2_iterator_next(&i))) {
5658 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
5659 /* No peer specified at our end, or this is the peer */
5660 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
5661 /* No username specified in peer rule, or this is the right username */
5662 && (!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)))
5663 /* No specified host, or this is our host */
5665 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5666 if (!res) {
5667 peer_unref(peer);
5668 break;
5671 peer_unref(peer);
5673 if (!peer) {
5674 /* We checked our list and didn't find one. It's unlikely, but possible,
5675 that we're trying to authenticate *to* a realtime peer */
5676 const char *peer_name = ast_strdupa(p->peer);
5677 ast_mutex_unlock(&iaxsl[callno]);
5678 if ((peer = realtime_peer(peer_name, NULL))) {
5679 ast_mutex_lock(&iaxsl[callno]);
5680 if (!(p = iaxs[callno])) {
5681 peer_unref(peer);
5682 return -1;
5684 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5685 peer_unref(peer);
5687 if (!peer) {
5688 ast_mutex_lock(&iaxsl[callno]);
5689 if (!(p = iaxs[callno]))
5690 return -1;
5694 if (ies->encmethods)
5695 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
5696 if (!res)
5697 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
5698 return res;
5701 static int iax2_do_register(struct iax2_registry *reg);
5703 static void __iax2_do_register_s(const void *data)
5705 struct iax2_registry *reg = (struct iax2_registry *)data;
5706 reg->expire = -1;
5707 iax2_do_register(reg);
5710 static int iax2_do_register_s(const void *data)
5712 #ifdef SCHED_MULTITHREADED
5713 if (schedule_action(__iax2_do_register_s, data))
5714 #endif
5715 __iax2_do_register_s(data);
5716 return 0;
5719 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5721 int newcall = 0;
5722 char newip[256];
5723 struct iax_ie_data ied;
5724 struct sockaddr_in new;
5727 memset(&ied, 0, sizeof(ied));
5728 if (ies->apparent_addr)
5729 bcopy(ies->apparent_addr, &new, sizeof(new));
5730 if (ies->callno)
5731 newcall = ies->callno;
5732 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
5733 ast_log(LOG_WARNING, "Invalid transfer request\n");
5734 return -1;
5736 pvt->transfercallno = newcall;
5737 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
5738 inet_aton(newip, &pvt->transfer.sin_addr);
5739 pvt->transfer.sin_family = AF_INET;
5740 pvt->transferring = TRANSFER_BEGIN;
5741 pvt->transferid = ies->transferid;
5742 if (ies->transferid)
5743 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
5744 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
5745 return 0;
5748 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5750 char exten[256] = "";
5751 int status = CACHE_FLAG_UNKNOWN;
5752 int expiry = iaxdefaultdpcache;
5753 int x;
5754 int matchmore = 0;
5755 struct iax2_dpcache *dp, *prev;
5757 if (ies->called_number)
5758 ast_copy_string(exten, ies->called_number, sizeof(exten));
5760 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
5761 status = CACHE_FLAG_EXISTS;
5762 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
5763 status = CACHE_FLAG_CANEXIST;
5764 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
5765 status = CACHE_FLAG_NONEXISTENT;
5767 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
5768 /* Don't really do anything with this */
5770 if (ies->refresh)
5771 expiry = ies->refresh;
5772 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
5773 matchmore = CACHE_FLAG_MATCHMORE;
5774 ast_mutex_lock(&dpcache_lock);
5775 prev = NULL;
5776 dp = pvt->dpentries;
5777 while(dp) {
5778 if (!strcmp(dp->exten, exten)) {
5779 /* Let them go */
5780 if (prev)
5781 prev->peer = dp->peer;
5782 else
5783 pvt->dpentries = dp->peer;
5784 dp->peer = NULL;
5785 dp->callno = 0;
5786 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
5787 if (dp->flags & CACHE_FLAG_PENDING) {
5788 dp->flags &= ~CACHE_FLAG_PENDING;
5789 dp->flags |= status;
5790 dp->flags |= matchmore;
5792 /* Wake up waiters */
5793 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
5794 if (dp->waiters[x] > -1)
5795 write(dp->waiters[x], "asdf", 4);
5797 prev = dp;
5798 dp = dp->peer;
5800 ast_mutex_unlock(&dpcache_lock);
5801 return 0;
5804 static int complete_transfer(int callno, struct iax_ies *ies)
5806 int peercallno = 0;
5807 struct chan_iax2_pvt *pvt = iaxs[callno];
5808 struct iax_frame *cur;
5809 jb_frame frame;
5811 if (ies->callno)
5812 peercallno = ies->callno;
5814 if (peercallno < 1) {
5815 ast_log(LOG_WARNING, "Invalid transfer request\n");
5816 return -1;
5818 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
5819 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
5820 /* Reset sequence numbers */
5821 pvt->oseqno = 0;
5822 pvt->rseqno = 0;
5823 pvt->iseqno = 0;
5824 pvt->aseqno = 0;
5826 if (pvt->peercallno) {
5827 remove_by_peercallno(pvt);
5829 pvt->peercallno = peercallno;
5830 store_by_peercallno(pvt);
5832 pvt->transferring = TRANSFER_NONE;
5833 pvt->svoiceformat = -1;
5834 pvt->voiceformat = 0;
5835 pvt->svideoformat = -1;
5836 pvt->videoformat = 0;
5837 pvt->transfercallno = -1;
5838 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
5839 memset(&pvt->offset, 0, sizeof(pvt->offset));
5840 /* reset jitterbuffer */
5841 while(jb_getall(pvt->jb,&frame) == JB_OK)
5842 iax2_frame_free(frame.data);
5843 jb_reset(pvt->jb);
5844 pvt->lag = 0;
5845 pvt->last = 0;
5846 pvt->lastsent = 0;
5847 pvt->nextpred = 0;
5848 pvt->pingtime = DEFAULT_RETRY_TIME;
5849 AST_LIST_LOCK(&iaxq.queue);
5850 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
5851 /* We must cancel any packets that would have been transmitted
5852 because now we're talking to someone new. It's okay, they
5853 were transmitted to someone that didn't care anyway. */
5854 if (callno == cur->callno)
5855 cur->retries = -1;
5857 AST_LIST_UNLOCK(&iaxq.queue);
5858 return 0;
5861 /*! \brief Acknowledgment received for OUR registration */
5862 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
5864 struct iax2_registry *reg;
5865 /* Start pessimistic */
5866 char peer[256] = "";
5867 char msgstatus[60];
5868 int refresh = 60;
5869 char ourip[256] = "<Unspecified>";
5870 struct sockaddr_in oldus;
5871 struct sockaddr_in us;
5872 int oldmsgs;
5874 memset(&us, 0, sizeof(us));
5875 if (ies->apparent_addr)
5876 bcopy(ies->apparent_addr, &us, sizeof(us));
5877 if (ies->username)
5878 ast_copy_string(peer, ies->username, sizeof(peer));
5879 if (ies->refresh)
5880 refresh = ies->refresh;
5881 if (ies->calling_number) {
5882 /* We don't do anything with it really, but maybe we should */
5884 reg = iaxs[callno]->reg;
5885 if (!reg) {
5886 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
5887 return -1;
5889 memcpy(&oldus, &reg->us, sizeof(oldus));
5890 oldmsgs = reg->messages;
5891 if (inaddrcmp(&reg->addr, sin)) {
5892 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
5893 return -1;
5895 memcpy(&reg->us, &us, sizeof(reg->us));
5896 if (ies->msgcount >= 0)
5897 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
5898 /* always refresh the registration at the interval requested by the server
5899 we are registering to
5901 reg->refresh = refresh;
5902 AST_SCHED_DEL(sched, reg->expire);
5903 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
5904 if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
5905 if (option_verbose > 2) {
5906 if (reg->messages > 255)
5907 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
5908 else if (reg->messages > 1)
5909 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
5910 else if (reg->messages > 0)
5911 snprintf(msgstatus, sizeof(msgstatus), " with 1 new message waiting\n");
5912 else
5913 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
5914 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
5915 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
5917 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
5919 reg->regstate = REG_STATE_REGISTERED;
5920 return 0;
5923 static int iax2_register(char *value, int lineno)
5925 struct iax2_registry *reg;
5926 char copy[256];
5927 char *username, *hostname, *secret;
5928 char *porta;
5929 char *stringp=NULL;
5931 if (!value)
5932 return -1;
5933 ast_copy_string(copy, value, sizeof(copy));
5934 stringp=copy;
5935 username = strsep(&stringp, "@");
5936 hostname = strsep(&stringp, "@");
5937 if (!hostname) {
5938 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
5939 return -1;
5941 stringp=username;
5942 username = strsep(&stringp, ":");
5943 secret = strsep(&stringp, ":");
5944 stringp=hostname;
5945 hostname = strsep(&stringp, ":");
5946 porta = strsep(&stringp, ":");
5948 if (porta && !atoi(porta)) {
5949 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
5950 return -1;
5952 if (!(reg = ast_calloc(1, sizeof(*reg))))
5953 return -1;
5954 if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
5955 free(reg);
5956 return -1;
5958 ast_copy_string(reg->username, username, sizeof(reg->username));
5959 if (secret)
5960 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
5961 reg->expire = -1;
5962 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
5963 reg->addr.sin_family = AF_INET;
5964 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
5965 AST_LIST_LOCK(&registrations);
5966 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
5967 AST_LIST_UNLOCK(&registrations);
5969 return 0;
5972 static void register_peer_exten(struct iax2_peer *peer, int onoff)
5974 char multi[256];
5975 char *stringp, *ext;
5976 if (!ast_strlen_zero(regcontext)) {
5977 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
5978 stringp = multi;
5979 while((ext = strsep(&stringp, "&"))) {
5980 if (onoff) {
5981 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
5982 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
5983 "Noop", ast_strdup(peer->name), ast_free, "IAX2");
5984 } else
5985 ast_context_remove_extension(regcontext, ext, 1, NULL);
5989 static void prune_peers(void);
5991 static void unlink_peer(struct iax2_peer *peer)
5993 if (peer->expire > -1) {
5994 if (!ast_sched_del(sched, peer->expire)) {
5995 peer->expire = -1;
5996 peer_unref(peer);
6000 if (peer->pokeexpire > -1) {
6001 if (!ast_sched_del(sched, peer->pokeexpire)) {
6002 peer->pokeexpire = -1;
6003 peer_unref(peer);
6007 ao2_unlink(peers, peer);
6010 static void __expire_registry(const void *data)
6012 struct iax2_peer *peer = (struct iax2_peer *) data;
6014 if (!peer)
6015 return;
6017 peer->expire = -1;
6019 if (option_debug)
6020 ast_log(LOG_DEBUG, "Expiring registration for peer '%s'\n", peer->name);
6021 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
6022 realtime_update_peer(peer->name, &peer->addr, 0);
6023 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
6024 /* Reset the address */
6025 memset(&peer->addr, 0, sizeof(peer->addr));
6026 /* Reset expiry value */
6027 peer->expiry = min_reg_expire;
6028 if (!ast_test_flag(peer, IAX_TEMPONLY))
6029 ast_db_del("IAX/Registry", peer->name);
6030 register_peer_exten(peer, 0);
6031 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
6032 if (iax2_regfunk)
6033 iax2_regfunk(peer->name, 0);
6035 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
6036 unlink_peer(peer);
6038 peer_unref(peer);
6041 static int expire_registry(const void *data)
6043 #ifdef SCHED_MULTITHREADED
6044 if (schedule_action(__expire_registry, data))
6045 #endif
6046 __expire_registry(data);
6047 return 0;
6050 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
6052 static void reg_source_db(struct iax2_peer *p)
6054 char data[80];
6055 struct in_addr in;
6056 char *c, *d;
6057 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
6058 c = strchr(data, ':');
6059 if (c) {
6060 *c = '\0';
6061 c++;
6062 if (inet_aton(data, &in)) {
6063 d = strchr(c, ':');
6064 if (d) {
6065 *d = '\0';
6066 d++;
6067 if (option_verbose > 2)
6068 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
6069 ast_inet_ntoa(in), atoi(c), atoi(d));
6070 iax2_poke_peer(p, 0);
6071 p->expiry = atoi(d);
6072 memset(&p->addr, 0, sizeof(p->addr));
6073 p->addr.sin_family = AF_INET;
6074 p->addr.sin_addr = in;
6075 p->addr.sin_port = htons(atoi(c));
6076 if (p->expire > -1) {
6077 if (!ast_sched_del(sched, p->expire)) {
6078 p->expire = -1;
6079 peer_unref(p);
6082 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6083 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6084 if (p->expire == -1)
6085 peer_unref(p);
6086 if (iax2_regfunk)
6087 iax2_regfunk(p->name, 1);
6088 register_peer_exten(p, 1);
6097 * \pre iaxsl[callno] is locked
6099 * \note Since this function calls send_command_final(), the pvt struct for
6100 * the given call number may disappear while executing this function.
6102 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
6104 /* Called from IAX thread only, with proper iaxsl lock */
6105 struct iax_ie_data ied;
6106 struct iax2_peer *p;
6107 int msgcount;
6108 char data[80];
6109 int version;
6110 const char *peer_name;
6111 int res = -1;
6113 memset(&ied, 0, sizeof(ied));
6115 peer_name = ast_strdupa(iaxs[callno]->peer);
6117 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6118 ast_mutex_unlock(&iaxsl[callno]);
6119 if (!(p = find_peer(peer_name, 1))) {
6120 ast_mutex_lock(&iaxsl[callno]);
6121 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6122 return -1;
6124 ast_mutex_lock(&iaxsl[callno]);
6125 if (!iaxs[callno])
6126 goto return_unref;
6128 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6129 if (sin->sin_addr.s_addr) {
6130 time_t nowtime;
6131 time(&nowtime);
6132 realtime_update_peer(peer_name, sin, nowtime);
6133 } else {
6134 realtime_update_peer(peer_name, sin, 0);
6137 if (inaddrcmp(&p->addr, sin)) {
6138 if (iax2_regfunk)
6139 iax2_regfunk(p->name, 1);
6140 /* Stash the IP address from which they registered */
6141 memcpy(&p->addr, sin, sizeof(p->addr));
6142 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
6143 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
6144 ast_db_put("IAX/Registry", p->name, data);
6145 if (option_verbose > 2)
6146 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
6147 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
6148 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
6149 register_peer_exten(p, 1);
6150 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6151 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
6152 if (option_verbose > 2)
6153 ast_verbose(VERBOSE_PREFIX_3 "Unregistered IAX2 '%s' (%s)\n", p->name,
6154 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6155 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
6156 register_peer_exten(p, 0);
6157 ast_db_del("IAX/Registry", p->name);
6158 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6160 /* Update the host */
6161 /* Verify that the host is really there */
6162 iax2_poke_peer(p, callno);
6165 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6166 if (!iaxs[callno]) {
6167 res = 0;
6168 goto return_unref;
6171 /* Store socket fd */
6172 p->sockfd = fd;
6173 /* Setup the expiry */
6174 if (p->expire > -1) {
6175 if (!ast_sched_del(sched, p->expire)) {
6176 p->expire = -1;
6177 peer_unref(p);
6180 /* treat an unspecified refresh interval as the minimum */
6181 if (!refresh)
6182 refresh = min_reg_expire;
6183 if (refresh > max_reg_expire) {
6184 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6185 p->name, max_reg_expire, refresh);
6186 p->expiry = max_reg_expire;
6187 } else if (refresh < min_reg_expire) {
6188 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6189 p->name, min_reg_expire, refresh);
6190 p->expiry = min_reg_expire;
6191 } else {
6192 p->expiry = refresh;
6194 if (p->expiry && sin->sin_addr.s_addr) {
6195 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6196 if (p->expire == -1)
6197 peer_unref(p);
6199 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
6200 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
6201 if (sin->sin_addr.s_addr) {
6202 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
6203 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
6204 if (!ast_strlen_zero(p->mailbox)) {
6205 int new, old;
6206 ast_app_inboxcount(p->mailbox, &new, &old);
6207 if (new > 255)
6208 new = 255;
6209 if (old > 255)
6210 old = 255;
6211 msgcount = (old << 8) | new;
6212 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
6214 if (ast_test_flag(p, IAX_HASCALLERID)) {
6215 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
6216 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
6219 version = iax_check_version(devtype);
6220 if (version)
6221 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
6223 res = 0;
6225 return_unref:
6226 peer_unref(p);
6228 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
6231 static int registry_authrequest(int callno)
6233 struct iax_ie_data ied;
6234 struct iax2_peer *p;
6235 char challenge[10];
6236 const char *peer_name;
6237 int res = -1;
6239 peer_name = ast_strdupa(iaxs[callno]->peer);
6241 /* SLD: third call to find_peer in registration */
6242 ast_mutex_unlock(&iaxsl[callno]);
6243 p = find_peer(peer_name, 1);
6244 ast_mutex_lock(&iaxsl[callno]);
6245 if (!iaxs[callno])
6246 goto return_unref;
6247 if (!p) {
6248 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6249 goto return_unref;
6252 memset(&ied, 0, sizeof(ied));
6253 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
6254 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
6255 /* Build the challenge */
6256 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
6257 ast_string_field_set(iaxs[callno], challenge, challenge);
6258 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
6260 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
6262 res = 0;
6264 return_unref:
6265 peer_unref(p);
6267 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
6270 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
6272 struct iax2_registry *reg;
6273 /* Start pessimistic */
6274 struct iax_ie_data ied;
6275 char peer[256] = "";
6276 char challenge[256] = "";
6277 int res;
6278 int authmethods = 0;
6279 if (ies->authmethods)
6280 authmethods = ies->authmethods;
6281 if (ies->username)
6282 ast_copy_string(peer, ies->username, sizeof(peer));
6283 if (ies->challenge)
6284 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
6285 memset(&ied, 0, sizeof(ied));
6286 reg = iaxs[callno]->reg;
6287 if (reg) {
6288 if (inaddrcmp(&reg->addr, sin)) {
6289 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6290 return -1;
6292 if (ast_strlen_zero(reg->secret)) {
6293 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
6294 reg->regstate = REG_STATE_NOAUTH;
6295 return -1;
6297 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
6298 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
6299 if (reg->secret[0] == '[') {
6300 char tmpkey[256];
6301 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
6302 tmpkey[strlen(tmpkey) - 1] = '\0';
6303 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
6304 } else
6305 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
6306 if (!res) {
6307 reg->regstate = REG_STATE_AUTHSENT;
6308 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
6309 } else
6310 return -1;
6311 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
6312 } else
6313 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
6314 return -1;
6317 static void stop_stuff(int callno)
6319 iax2_destroy_helper(iaxs[callno]);
6322 static void __auth_reject(const void *nothing)
6324 /* Called from IAX thread only, without iaxs lock */
6325 int callno = (int)(long)(nothing);
6326 struct iax_ie_data ied;
6327 ast_mutex_lock(&iaxsl[callno]);
6328 if (iaxs[callno]) {
6329 memset(&ied, 0, sizeof(ied));
6330 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
6331 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
6332 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
6333 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
6334 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
6335 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
6337 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
6339 ast_mutex_unlock(&iaxsl[callno]);
6342 static int auth_reject(const void *data)
6344 int callno = (int)(long)(data);
6345 ast_mutex_lock(&iaxsl[callno]);
6346 if (iaxs[callno])
6347 iaxs[callno]->authid = -1;
6348 ast_mutex_unlock(&iaxsl[callno]);
6349 #ifdef SCHED_MULTITHREADED
6350 if (schedule_action(__auth_reject, data))
6351 #endif
6352 __auth_reject(data);
6353 return 0;
6356 static int auth_fail(int callno, int failcode)
6358 /* Schedule sending the authentication failure in one second, to prevent
6359 guessing */
6360 if (iaxs[callno]) {
6361 iaxs[callno]->authfail = failcode;
6362 if (delayreject) {
6363 AST_SCHED_DEL(sched, iaxs[callno]->authid);
6364 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
6365 } else
6366 auth_reject((void *)(long)callno);
6368 return 0;
6371 static void __auto_hangup(const void *nothing)
6373 /* Called from IAX thread only, without iaxs lock */
6374 int callno = (int)(long)(nothing);
6375 struct iax_ie_data ied;
6376 ast_mutex_lock(&iaxsl[callno]);
6377 if (iaxs[callno]) {
6378 memset(&ied, 0, sizeof(ied));
6379 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
6380 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
6381 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
6383 ast_mutex_unlock(&iaxsl[callno]);
6386 static int auto_hangup(const void *data)
6388 int callno = (int)(long)(data);
6389 ast_mutex_lock(&iaxsl[callno]);
6390 if (iaxs[callno]) {
6391 iaxs[callno]->autoid = -1;
6393 ast_mutex_unlock(&iaxsl[callno]);
6394 #ifdef SCHED_MULTITHREADED
6395 if (schedule_action(__auto_hangup, data))
6396 #endif
6397 __auto_hangup(data);
6398 return 0;
6401 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
6403 struct iax_ie_data ied;
6404 /* Auto-hangup with 30 seconds of inactivity */
6405 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
6406 iaxs[callno]->autoid = iax2_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
6407 memset(&ied, 0, sizeof(ied));
6408 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
6409 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
6410 dp->flags |= CACHE_FLAG_TRANSMITTED;
6413 static int iax2_vnak(int callno)
6415 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
6418 static void vnak_retransmit(int callno, int last)
6420 struct iax_frame *f;
6422 AST_LIST_LOCK(&iaxq.queue);
6423 AST_LIST_TRAVERSE(&iaxq.queue, f, list) {
6424 /* Send a copy immediately */
6425 if ((f->callno == callno) && iaxs[f->callno] &&
6426 ((unsigned char ) (f->oseqno - last) < 128) &&
6427 (f->retries >= 0)) {
6428 send_packet(f);
6431 AST_LIST_UNLOCK(&iaxq.queue);
6434 static void __iax2_poke_peer_s(const void *data)
6436 struct iax2_peer *peer = (struct iax2_peer *)data;
6437 iax2_poke_peer(peer, 0);
6438 peer_unref(peer);
6441 static int iax2_poke_peer_s(const void *data)
6443 struct iax2_peer *peer = (struct iax2_peer *)data;
6444 peer->pokeexpire = -1;
6445 #ifdef SCHED_MULTITHREADED
6446 if (schedule_action(__iax2_poke_peer_s, data))
6447 #endif
6448 __iax2_poke_peer_s(data);
6449 return 0;
6452 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
6454 int res = 0;
6455 struct iax_frame *fr;
6456 struct ast_iax2_meta_hdr *meta;
6457 struct ast_iax2_meta_trunk_hdr *mth;
6458 int calls = 0;
6460 /* Point to frame */
6461 fr = (struct iax_frame *)tpeer->trunkdata;
6462 /* Point to meta data */
6463 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
6464 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
6465 if (tpeer->trunkdatalen) {
6466 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6467 meta->zeros = 0;
6468 meta->metacmd = IAX_META_TRUNK;
6469 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
6470 meta->cmddata = IAX_META_TRUNK_MINI;
6471 else
6472 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
6473 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
6474 /* And the rest of the ast_iax2 header */
6475 fr->direction = DIRECTION_OUTGRESS;
6476 fr->retrans = -1;
6477 fr->transfer = 0;
6478 /* Any appropriate call will do */
6479 fr->data = fr->afdata;
6480 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
6481 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
6482 calls = tpeer->calls;
6483 #if 0
6484 if (option_debug)
6485 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));
6486 #endif
6487 /* Reset transmit trunk side data */
6488 tpeer->trunkdatalen = 0;
6489 tpeer->calls = 0;
6491 if (res < 0)
6492 return res;
6493 return calls;
6496 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
6498 /* Drop when trunk is about 5 seconds idle */
6499 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
6500 return 1;
6501 return 0;
6504 static int timing_read(int *id, int fd, short events, void *cbdata)
6506 char buf[1024];
6507 int res;
6508 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
6509 int processed = 0;
6510 int totalcalls = 0;
6511 #ifdef ZT_TIMERACK
6512 int x = 1;
6513 #endif
6514 struct timeval now;
6515 if (iaxtrunkdebug)
6516 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA);
6517 gettimeofday(&now, NULL);
6518 if (events & AST_IO_PRI) {
6519 #ifdef ZT_TIMERACK
6520 /* Great, this is a timing interface, just call the ioctl */
6521 if (ioctl(fd, ZT_TIMERACK, &x)) {
6522 ast_log(LOG_WARNING, "Unable to acknowledge zap timer. IAX trunking will fail!\n");
6523 usleep(1);
6524 return -1;
6526 #endif
6527 } else {
6528 /* Read and ignore from the pseudo channel for timing */
6529 res = read(fd, buf, sizeof(buf));
6530 if (res < 1) {
6531 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
6532 return 1;
6535 /* For each peer that supports trunking... */
6536 ast_mutex_lock(&tpeerlock);
6537 tpeer = tpeers;
6538 while(tpeer) {
6539 processed++;
6540 res = 0;
6541 ast_mutex_lock(&tpeer->lock);
6542 /* We can drop a single tpeer per pass. That makes all this logic
6543 substantially easier */
6544 if (!drop && iax2_trunk_expired(tpeer, &now)) {
6545 /* Take it out of the list, but don't free it yet, because it
6546 could be in use */
6547 if (prev)
6548 prev->next = tpeer->next;
6549 else
6550 tpeers = tpeer->next;
6551 drop = tpeer;
6552 } else {
6553 res = send_trunk(tpeer, &now);
6554 if (iaxtrunkdebug)
6555 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);
6557 totalcalls += res;
6558 res = 0;
6559 ast_mutex_unlock(&tpeer->lock);
6560 prev = tpeer;
6561 tpeer = tpeer->next;
6563 ast_mutex_unlock(&tpeerlock);
6564 if (drop) {
6565 ast_mutex_lock(&drop->lock);
6566 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6567 because by the time they could get tpeerlock, we've already grabbed it */
6568 if (option_debug)
6569 ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
6570 if (drop->trunkdata) {
6571 free(drop->trunkdata);
6572 drop->trunkdata = NULL;
6574 ast_mutex_unlock(&drop->lock);
6575 ast_mutex_destroy(&drop->lock);
6576 free(drop);
6579 if (iaxtrunkdebug)
6580 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
6581 iaxtrunkdebug =0;
6582 return 1;
6585 struct dpreq_data {
6586 int callno;
6587 char context[AST_MAX_EXTENSION];
6588 char callednum[AST_MAX_EXTENSION];
6589 char *callerid;
6592 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
6594 unsigned short dpstatus = 0;
6595 struct iax_ie_data ied1;
6596 int mm;
6598 memset(&ied1, 0, sizeof(ied1));
6599 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
6600 /* Must be started */
6601 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
6602 dpstatus = IAX_DPSTATUS_EXISTS;
6603 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
6604 dpstatus = IAX_DPSTATUS_CANEXIST;
6605 } else {
6606 dpstatus = IAX_DPSTATUS_NONEXISTENT;
6608 if (ast_ignore_pattern(context, callednum))
6609 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
6610 if (mm)
6611 dpstatus |= IAX_DPSTATUS_MATCHMORE;
6612 if (!skiplock)
6613 ast_mutex_lock(&iaxsl[callno]);
6614 if (iaxs[callno]) {
6615 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
6616 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
6617 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
6618 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
6620 if (!skiplock)
6621 ast_mutex_unlock(&iaxsl[callno]);
6624 static void *dp_lookup_thread(void *data)
6626 /* Look up for dpreq */
6627 struct dpreq_data *dpr = data;
6628 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
6629 if (dpr->callerid)
6630 free(dpr->callerid);
6631 free(dpr);
6632 return NULL;
6635 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
6637 pthread_t newthread;
6638 struct dpreq_data *dpr;
6639 pthread_attr_t attr;
6641 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
6642 return;
6644 pthread_attr_init(&attr);
6645 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6647 dpr->callno = callno;
6648 ast_copy_string(dpr->context, context, sizeof(dpr->context));
6649 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
6650 if (callerid)
6651 dpr->callerid = ast_strdup(callerid);
6652 if (ast_pthread_create(&newthread, &attr, dp_lookup_thread, dpr)) {
6653 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
6656 pthread_attr_destroy(&attr);
6659 struct iax_dual {
6660 struct ast_channel *chan1;
6661 struct ast_channel *chan2;
6664 static void *iax_park_thread(void *stuff)
6666 struct ast_channel *chan1, *chan2;
6667 struct iax_dual *d;
6668 struct ast_frame *f;
6669 int ext;
6670 int res;
6671 d = stuff;
6672 chan1 = d->chan1;
6673 chan2 = d->chan2;
6674 free(d);
6675 f = ast_read(chan1);
6676 if (f)
6677 ast_frfree(f);
6678 res = ast_park_call(chan1, chan2, 0, &ext);
6679 ast_hangup(chan2);
6680 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
6681 return NULL;
6684 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
6686 struct iax_dual *d;
6687 struct ast_channel *chan1m, *chan2m;
6688 pthread_t th;
6689 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
6690 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
6691 if (chan2m && chan1m) {
6692 /* Make formats okay */
6693 chan1m->readformat = chan1->readformat;
6694 chan1m->writeformat = chan1->writeformat;
6695 ast_channel_masquerade(chan1m, chan1);
6696 /* Setup the extensions and such */
6697 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
6698 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
6699 chan1m->priority = chan1->priority;
6701 /* We make a clone of the peer channel too, so we can play
6702 back the announcement */
6703 /* Make formats okay */
6704 chan2m->readformat = chan2->readformat;
6705 chan2m->writeformat = chan2->writeformat;
6706 ast_channel_masquerade(chan2m, chan2);
6707 /* Setup the extensions and such */
6708 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
6709 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
6710 chan2m->priority = chan2->priority;
6711 if (ast_do_masquerade(chan2m)) {
6712 ast_log(LOG_WARNING, "Masquerade failed :(\n");
6713 ast_hangup(chan2m);
6714 return -1;
6716 } else {
6717 if (chan1m)
6718 ast_hangup(chan1m);
6719 if (chan2m)
6720 ast_hangup(chan2m);
6721 return -1;
6723 if ((d = ast_calloc(1, sizeof(*d)))) {
6724 pthread_attr_t attr;
6726 pthread_attr_init(&attr);
6727 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6729 d->chan1 = chan1m;
6730 d->chan2 = chan2m;
6731 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
6732 pthread_attr_destroy(&attr);
6733 return 0;
6735 pthread_attr_destroy(&attr);
6736 free(d);
6738 return -1;
6742 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
6744 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
6746 unsigned int ourver;
6747 char rsi[80];
6748 snprintf(rsi, sizeof(rsi), "si-%s", si);
6749 if (iax_provision_version(&ourver, rsi, 1))
6750 return 0;
6751 if (option_debug)
6752 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
6753 if (ourver != ver)
6754 iax2_provision(sin, sockfd, NULL, rsi, 1);
6755 return 0;
6758 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
6760 jb_info stats;
6761 jb_getinfo(pvt->jb, &stats);
6763 memset(iep, 0, sizeof(*iep));
6765 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
6766 if(stats.frames_in == 0) stats.frames_in = 1;
6767 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
6768 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
6769 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
6770 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
6771 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
6774 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
6776 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
6777 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
6778 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
6779 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
6780 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
6781 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
6782 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
6785 static int socket_process(struct iax2_thread *thread);
6788 * \brief Handle any deferred full frames for this thread
6790 static void handle_deferred_full_frames(struct iax2_thread *thread)
6792 struct iax2_pkt_buf *pkt_buf;
6794 ast_mutex_lock(&thread->lock);
6796 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
6797 ast_mutex_unlock(&thread->lock);
6799 thread->buf = pkt_buf->buf;
6800 thread->buf_len = pkt_buf->len;
6801 thread->buf_size = pkt_buf->len + 1;
6803 socket_process(thread);
6805 thread->buf = NULL;
6806 ast_free(pkt_buf);
6808 ast_mutex_lock(&thread->lock);
6811 ast_mutex_unlock(&thread->lock);
6815 * \brief Queue the last read full frame for processing by a certain thread
6817 * If there are already any full frames queued, they are sorted
6818 * by sequence number.
6820 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
6822 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
6823 struct ast_iax2_full_hdr *fh, *cur_fh;
6825 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
6826 return;
6828 pkt_buf->len = from_here->buf_len;
6829 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
6831 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
6832 ast_mutex_lock(&to_here->lock);
6833 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
6834 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
6835 if (fh->oseqno < cur_fh->oseqno) {
6836 AST_LIST_INSERT_BEFORE_CURRENT(&to_here->full_frames, pkt_buf, entry);
6837 break;
6840 AST_LIST_TRAVERSE_SAFE_END
6842 if (!cur_pkt_buf)
6843 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
6845 ast_mutex_unlock(&to_here->lock);
6848 static int socket_read(int *id, int fd, short events, void *cbdata)
6850 struct iax2_thread *thread;
6851 socklen_t len;
6852 time_t t;
6853 static time_t last_errtime = 0;
6854 struct ast_iax2_full_hdr *fh;
6856 if (!(thread = find_idle_thread())) {
6857 time(&t);
6858 if (t != last_errtime && option_debug)
6859 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
6860 last_errtime = t;
6861 usleep(1);
6862 return 1;
6865 len = sizeof(thread->iosin);
6866 thread->iofd = fd;
6867 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
6868 thread->buf_size = sizeof(thread->readbuf);
6869 thread->buf = thread->readbuf;
6870 if (thread->buf_len < 0) {
6871 if (errno != ECONNREFUSED && errno != EAGAIN)
6872 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
6873 handle_error();
6874 thread->iostate = IAX_IOSTATE_IDLE;
6875 signal_condition(&thread->lock, &thread->cond);
6876 return 1;
6878 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
6879 thread->iostate = IAX_IOSTATE_IDLE;
6880 signal_condition(&thread->lock, &thread->cond);
6881 return 1;
6884 /* Determine if this frame is a full frame; if so, and any thread is currently
6885 processing a full frame for the same callno from this peer, then drop this
6886 frame (and the peer will retransmit it) */
6887 fh = (struct ast_iax2_full_hdr *) thread->buf;
6888 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6889 struct iax2_thread *cur = NULL;
6890 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
6892 AST_LIST_LOCK(&active_list);
6893 AST_LIST_TRAVERSE(&active_list, cur, list) {
6894 if ((cur->ffinfo.callno == callno) &&
6895 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
6896 break;
6898 if (cur) {
6899 /* we found another thread processing a full frame for this call,
6900 so queue it up for processing later. */
6901 defer_full_frame(thread, cur);
6902 AST_LIST_UNLOCK(&active_list);
6903 thread->iostate = IAX_IOSTATE_IDLE;
6904 signal_condition(&thread->lock, &thread->cond);
6905 return 1;
6906 } else {
6907 /* this thread is going to process this frame, so mark it */
6908 thread->ffinfo.callno = callno;
6909 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
6910 thread->ffinfo.type = fh->type;
6911 thread->ffinfo.csub = fh->csub;
6913 AST_LIST_UNLOCK(&active_list);
6916 /* Mark as ready and send on its way */
6917 thread->iostate = IAX_IOSTATE_READY;
6918 #ifdef DEBUG_SCHED_MULTITHREAD
6919 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
6920 #endif
6921 signal_condition(&thread->lock, &thread->cond);
6923 return 1;
6926 static int socket_process(struct iax2_thread *thread)
6928 struct sockaddr_in sin;
6929 int res;
6930 int updatehistory=1;
6931 int new = NEW_PREVENT;
6932 void *ptr;
6933 int dcallno = 0;
6934 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
6935 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
6936 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
6937 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
6938 struct ast_iax2_meta_trunk_hdr *mth;
6939 struct ast_iax2_meta_trunk_entry *mte;
6940 struct ast_iax2_meta_trunk_mini *mtm;
6941 struct iax_frame *fr;
6942 struct iax_frame *cur;
6943 struct ast_frame f = { 0, };
6944 struct ast_channel *c;
6945 struct iax2_dpcache *dp;
6946 struct iax2_peer *peer;
6947 struct iax2_trunk_peer *tpeer;
6948 struct timeval rxtrunktime;
6949 struct iax_ies ies;
6950 struct iax_ie_data ied0, ied1;
6951 int format;
6952 int fd;
6953 int exists;
6954 int minivid = 0;
6955 unsigned int ts;
6956 char empty[32]=""; /* Safety measure */
6957 struct iax_frame *duped_fr;
6958 char host_pref_buf[128];
6959 char caller_pref_buf[128];
6960 struct ast_codec_pref pref;
6961 char *using_prefs = "mine";
6963 /* allocate an iax_frame with 4096 bytes of data buffer */
6964 fr = alloca(sizeof(*fr) + 4096);
6965 fr->callno = 0;
6966 fr->afdatalen = 4096; /* From alloca() above */
6968 /* Copy frequently used parameters to the stack */
6969 res = thread->buf_len;
6970 fd = thread->iofd;
6971 memcpy(&sin, &thread->iosin, sizeof(sin));
6973 if (res < sizeof(*mh)) {
6974 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*mh));
6975 return 1;
6977 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
6978 if (res < sizeof(*vh)) {
6979 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));
6980 return 1;
6983 /* This is a video frame, get call number */
6984 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
6985 minivid = 1;
6986 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
6987 unsigned char metatype;
6989 if (res < sizeof(*meta)) {
6990 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));
6991 return 1;
6994 /* This is a meta header */
6995 switch(meta->metacmd) {
6996 case IAX_META_TRUNK:
6997 if (res < (sizeof(*meta) + sizeof(*mth))) {
6998 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %zd min)\n", res,
6999 sizeof(*meta) + sizeof(*mth));
7000 return 1;
7002 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
7003 ts = ntohl(mth->ts);
7004 metatype = meta->cmddata;
7005 res -= (sizeof(*meta) + sizeof(*mth));
7006 ptr = mth->data;
7007 tpeer = find_tpeer(&sin, fd);
7008 if (!tpeer) {
7009 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));
7010 return 1;
7012 tpeer->trunkact = ast_tvnow();
7013 if (!ts || ast_tvzero(tpeer->rxtrunktime))
7014 tpeer->rxtrunktime = tpeer->trunkact;
7015 rxtrunktime = tpeer->rxtrunktime;
7016 ast_mutex_unlock(&tpeer->lock);
7017 while(res >= sizeof(*mte)) {
7018 /* Process channels */
7019 unsigned short callno, trunked_ts, len;
7021 if (metatype == IAX_META_TRUNK_MINI) {
7022 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
7023 ptr += sizeof(*mtm);
7024 res -= sizeof(*mtm);
7025 len = ntohs(mtm->len);
7026 callno = ntohs(mtm->mini.callno);
7027 trunked_ts = ntohs(mtm->mini.ts);
7028 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
7029 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
7030 ptr += sizeof(*mte);
7031 res -= sizeof(*mte);
7032 len = ntohs(mte->len);
7033 callno = ntohs(mte->callno);
7034 trunked_ts = 0;
7035 } else {
7036 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7037 break;
7039 /* Stop if we don't have enough data */
7040 if (len > res)
7041 break;
7042 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd, 0);
7043 if (fr->callno) {
7044 /* If it's a valid call, deliver the contents. If not, we
7045 drop it, since we don't have a scallno to use for an INVAL */
7046 /* Process as a mini frame */
7047 memset(&f, 0, sizeof(f));
7048 f.frametype = AST_FRAME_VOICE;
7049 if (iaxs[fr->callno]) {
7050 if (iaxs[fr->callno]->voiceformat > 0) {
7051 f.subclass = iaxs[fr->callno]->voiceformat;
7052 f.datalen = len;
7053 if (f.datalen >= 0) {
7054 if (f.datalen)
7055 f.data = ptr;
7056 if(trunked_ts) {
7057 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
7058 } else
7059 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
7060 /* Don't pass any packets until we're started */
7061 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7062 /* Common things */
7063 f.src = "IAX2";
7064 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
7065 f.samples = ast_codec_get_samples(&f);
7066 iax_frame_wrap(fr, &f);
7067 duped_fr = iaxfrdup2(fr);
7068 if (duped_fr) {
7069 schedule_delivery(duped_fr, updatehistory, 1, &fr->ts);
7071 /* It is possible for the pvt structure to go away after we call schedule_delivery */
7072 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
7073 iaxs[fr->callno]->last = fr->ts;
7074 #if 1
7075 if (option_debug && iaxdebug)
7076 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7077 #endif
7080 } else {
7081 ast_log(LOG_WARNING, "Datalen < 0?\n");
7083 } else {
7084 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n ");
7085 iax2_vnak(fr->callno);
7088 ast_mutex_unlock(&iaxsl[fr->callno]);
7090 ptr += len;
7091 res -= len;
7095 return 1;
7098 #ifdef DEBUG_SUPPORT
7099 if (iaxdebug && (res >= sizeof(*fh)))
7100 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
7101 #endif
7102 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7103 if (res < sizeof(*fh)) {
7104 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));
7105 return 1;
7108 /* Get the destination call number */
7109 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
7110 /* Retrieve the type and subclass */
7111 f.frametype = fh->type;
7112 if (f.frametype == AST_FRAME_VIDEO) {
7113 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
7114 } else {
7115 f.subclass = uncompress_subclass(fh->csub);
7117 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
7118 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
7119 (f.subclass == IAX_COMMAND_REGREL)))
7120 new = NEW_ALLOW;
7121 } else {
7122 /* Don't know anything about it yet */
7123 f.frametype = AST_FRAME_NULL;
7124 f.subclass = 0;
7127 if (!fr->callno)
7128 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, ntohs(mh->callno) & IAX_FLAG_FULL);
7130 if (fr->callno > 0)
7131 ast_mutex_lock(&iaxsl[fr->callno]);
7133 if (!fr->callno || !iaxs[fr->callno]) {
7134 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7135 frame, reply with an inval */
7136 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7137 /* We can only raw hangup control frames */
7138 if (((f.subclass != IAX_COMMAND_INVAL) &&
7139 (f.subclass != IAX_COMMAND_TXCNT) &&
7140 (f.subclass != IAX_COMMAND_TXACC) &&
7141 (f.subclass != IAX_COMMAND_FWDOWNL))||
7142 (f.frametype != AST_FRAME_IAX))
7143 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
7144 fd);
7146 if (fr->callno > 0)
7147 ast_mutex_unlock(&iaxsl[fr->callno]);
7148 return 1;
7150 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
7151 if (decrypt_frame(fr->callno, fh, &f, &res)) {
7152 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
7153 ast_mutex_unlock(&iaxsl[fr->callno]);
7154 return 1;
7156 #ifdef DEBUG_SUPPORT
7157 else if (iaxdebug)
7158 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
7159 #endif
7162 /* count this frame */
7163 iaxs[fr->callno]->frames_received++;
7165 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
7166 f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
7167 f.subclass != IAX_COMMAND_TXACC) { /* for attended transfer */
7168 unsigned short new_peercallno;
7170 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
7171 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
7172 if (iaxs[fr->callno]->peercallno) {
7173 remove_by_peercallno(iaxs[fr->callno]);
7175 iaxs[fr->callno]->peercallno = new_peercallno;
7176 store_by_peercallno(iaxs[fr->callno]);
7179 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7180 if (option_debug && iaxdebug)
7181 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
7182 /* Check if it's out of order (and not an ACK or INVAL) */
7183 fr->oseqno = fh->oseqno;
7184 fr->iseqno = fh->iseqno;
7185 fr->ts = ntohl(fh->ts);
7186 #ifdef IAXTESTS
7187 if (test_resync) {
7188 if (option_debug)
7189 ast_log(LOG_DEBUG, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
7190 fr->ts += test_resync;
7192 #endif /* IAXTESTS */
7193 #if 0
7194 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
7195 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
7196 (f.subclass == IAX_COMMAND_NEW ||
7197 f.subclass == IAX_COMMAND_AUTHREQ ||
7198 f.subclass == IAX_COMMAND_ACCEPT ||
7199 f.subclass == IAX_COMMAND_REJECT)) ) )
7200 #endif
7201 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
7202 updatehistory = 0;
7203 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
7204 (iaxs[fr->callno]->iseqno ||
7205 ((f.subclass != IAX_COMMAND_TXCNT) &&
7206 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7207 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7208 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7209 (f.subclass != IAX_COMMAND_TXACC)) ||
7210 (f.frametype != AST_FRAME_IAX))) {
7211 if (
7212 ((f.subclass != IAX_COMMAND_ACK) &&
7213 (f.subclass != IAX_COMMAND_INVAL) &&
7214 (f.subclass != IAX_COMMAND_TXCNT) &&
7215 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7216 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7217 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7218 (f.subclass != IAX_COMMAND_TXACC) &&
7219 (f.subclass != IAX_COMMAND_VNAK)) ||
7220 (f.frametype != AST_FRAME_IAX)) {
7221 /* If it's not an ACK packet, it's out of order. */
7222 if (option_debug)
7223 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7224 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
7225 /* Check to see if we need to request retransmission,
7226 * and take sequence number wraparound into account */
7227 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
7228 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7229 if ((f.frametype != AST_FRAME_IAX) ||
7230 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
7231 if (option_debug)
7232 ast_log(LOG_DEBUG, "Acking anyway\n");
7233 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7234 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7235 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7237 } else {
7238 /* Send a VNAK requesting retransmission */
7239 iax2_vnak(fr->callno);
7241 ast_mutex_unlock(&iaxsl[fr->callno]);
7242 return 1;
7244 } else {
7245 /* Increment unless it's an ACK or VNAK */
7246 if (((f.subclass != IAX_COMMAND_ACK) &&
7247 (f.subclass != IAX_COMMAND_INVAL) &&
7248 (f.subclass != IAX_COMMAND_TXCNT) &&
7249 (f.subclass != IAX_COMMAND_TXACC) &&
7250 (f.subclass != IAX_COMMAND_VNAK)) ||
7251 (f.frametype != AST_FRAME_IAX))
7252 iaxs[fr->callno]->iseqno++;
7254 /* A full frame */
7255 if (res < sizeof(*fh)) {
7256 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*fh));
7257 ast_mutex_unlock(&iaxsl[fr->callno]);
7258 return 1;
7260 /* Ensure text frames are NULL-terminated */
7261 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
7262 if (res < thread->buf_size)
7263 thread->buf[res++] = '\0';
7264 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7265 thread->buf[res - 1] = '\0';
7267 f.datalen = res - sizeof(*fh);
7269 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7270 from the real peer, not the transfer peer */
7271 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7272 ((f.subclass != IAX_COMMAND_INVAL) ||
7273 (f.frametype != AST_FRAME_IAX))) {
7274 unsigned char x;
7275 int call_to_destroy;
7276 /* XXX This code is not very efficient. Surely there is a better way which still
7277 properly handles boundary conditions? XXX */
7278 /* First we have to qualify that the ACKed value is within our window */
7279 for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
7280 if (fr->iseqno == x)
7281 break;
7282 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
7283 /* The acknowledgement is within our window. Time to acknowledge everything
7284 that it says to */
7285 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
7286 /* Ack the packet with the given timestamp */
7287 if (option_debug && iaxdebug)
7288 ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
7289 call_to_destroy = 0;
7290 AST_LIST_LOCK(&iaxq.queue);
7291 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7292 /* If it's our call, and our timestamp, mark -1 retries */
7293 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
7294 cur->retries = -1;
7295 /* Destroy call if this is the end */
7296 if (cur->final)
7297 call_to_destroy = fr->callno;
7300 AST_LIST_UNLOCK(&iaxq.queue);
7301 if (call_to_destroy) {
7302 if (iaxdebug && option_debug)
7303 ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", call_to_destroy);
7304 ast_mutex_lock(&iaxsl[call_to_destroy]);
7305 iax2_destroy(call_to_destroy);
7306 ast_mutex_unlock(&iaxsl[call_to_destroy]);
7309 /* Note how much we've received acknowledgement for */
7310 if (iaxs[fr->callno])
7311 iaxs[fr->callno]->rseqno = fr->iseqno;
7312 else {
7313 /* Stop processing now */
7314 ast_mutex_unlock(&iaxsl[fr->callno]);
7315 return 1;
7317 } else if (option_debug)
7318 ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
7320 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7321 ((f.frametype != AST_FRAME_IAX) ||
7322 ((f.subclass != IAX_COMMAND_TXACC) &&
7323 (f.subclass != IAX_COMMAND_TXCNT)))) {
7324 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7325 ast_mutex_unlock(&iaxsl[fr->callno]);
7326 return 1;
7329 if (f.datalen) {
7330 if (f.frametype == AST_FRAME_IAX) {
7331 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
7332 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
7333 ast_mutex_unlock(&iaxsl[fr->callno]);
7334 return 1;
7336 f.data = NULL;
7337 f.datalen = 0;
7338 } else
7339 f.data = thread->buf + sizeof(*fh);
7340 } else {
7341 if (f.frametype == AST_FRAME_IAX)
7342 f.data = NULL;
7343 else
7344 f.data = empty;
7345 memset(&ies, 0, sizeof(ies));
7348 /* when we receive the first full frame for a new incoming channel,
7349 it is safe to start the PBX on the channel because we have now
7350 completed a 3-way handshake with the peer */
7351 if ((f.frametype == AST_FRAME_VOICE) ||
7352 (f.frametype == AST_FRAME_VIDEO) ||
7353 (f.frametype == AST_FRAME_IAX)) {
7354 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
7355 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7356 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
7357 ast_mutex_unlock(&iaxsl[fr->callno]);
7358 return 1;
7363 if (f.frametype == AST_FRAME_VOICE) {
7364 if (f.subclass != iaxs[fr->callno]->voiceformat) {
7365 iaxs[fr->callno]->voiceformat = f.subclass;
7366 if (option_debug)
7367 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
7368 if (iaxs[fr->callno]->owner) {
7369 int orignative;
7370 retryowner:
7371 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7372 ast_mutex_unlock(&iaxsl[fr->callno]);
7373 usleep(1);
7374 ast_mutex_lock(&iaxsl[fr->callno]);
7375 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
7377 if (iaxs[fr->callno]) {
7378 if (iaxs[fr->callno]->owner) {
7379 orignative = iaxs[fr->callno]->owner->nativeformats;
7380 iaxs[fr->callno]->owner->nativeformats = f.subclass;
7381 if (iaxs[fr->callno]->owner->readformat)
7382 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7383 iaxs[fr->callno]->owner->nativeformats = orignative;
7384 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7386 } else {
7387 if (option_debug)
7388 ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
7389 ast_mutex_unlock(&iaxsl[fr->callno]);
7390 return 1;
7395 if (f.frametype == AST_FRAME_VIDEO) {
7396 if (f.subclass != iaxs[fr->callno]->videoformat) {
7397 if (option_debug)
7398 ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
7399 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
7402 if (f.frametype == AST_FRAME_IAX) {
7403 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
7404 /* Handle the IAX pseudo frame itself */
7405 if (option_debug && iaxdebug)
7406 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
7408 /* Update last ts unless the frame's timestamp originated with us. */
7409 if (iaxs[fr->callno]->last < fr->ts &&
7410 f.subclass != IAX_COMMAND_ACK &&
7411 f.subclass != IAX_COMMAND_PONG &&
7412 f.subclass != IAX_COMMAND_LAGRP) {
7413 iaxs[fr->callno]->last = fr->ts;
7414 if (option_debug && iaxdebug)
7415 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7418 switch(f.subclass) {
7419 case IAX_COMMAND_ACK:
7420 /* Do nothing */
7421 break;
7422 case IAX_COMMAND_QUELCH:
7423 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7424 /* Generate Manager Hold event, if necessary*/
7425 if (iaxs[fr->callno]->owner) {
7426 manager_event(EVENT_FLAG_CALL, "Hold",
7427 "Channel: %s\r\n"
7428 "Uniqueid: %s\r\n",
7429 iaxs[fr->callno]->owner->name,
7430 iaxs[fr->callno]->owner->uniqueid);
7433 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
7434 if (ies.musiconhold) {
7435 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7436 const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
7437 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
7438 S_OR(mohsuggest, NULL),
7439 !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
7440 if (!iaxs[fr->callno]) {
7441 ast_mutex_unlock(&iaxsl[fr->callno]);
7442 return 1;
7447 break;
7448 case IAX_COMMAND_UNQUELCH:
7449 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7450 /* Generate Manager Unhold event, if necessary*/
7451 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
7452 manager_event(EVENT_FLAG_CALL, "Unhold",
7453 "Channel: %s\r\n"
7454 "Uniqueid: %s\r\n",
7455 iaxs[fr->callno]->owner->name,
7456 iaxs[fr->callno]->owner->uniqueid);
7459 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
7460 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7461 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
7462 if (!iaxs[fr->callno]) {
7463 ast_mutex_unlock(&iaxsl[fr->callno]);
7464 return 1;
7468 break;
7469 case IAX_COMMAND_TXACC:
7470 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
7471 /* Ack the packet with the given timestamp */
7472 AST_LIST_LOCK(&iaxq.queue);
7473 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7474 /* Cancel any outstanding txcnt's */
7475 if ((fr->callno == cur->callno) && (cur->transfer))
7476 cur->retries = -1;
7478 AST_LIST_UNLOCK(&iaxq.queue);
7479 memset(&ied1, 0, sizeof(ied1));
7480 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
7481 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
7482 iaxs[fr->callno]->transferring = TRANSFER_READY;
7484 break;
7485 case IAX_COMMAND_NEW:
7486 /* Ignore if it's already up */
7487 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
7488 break;
7489 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
7490 ast_mutex_unlock(&iaxsl[fr->callno]);
7491 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
7492 ast_mutex_lock(&iaxsl[fr->callno]);
7493 if (!iaxs[fr->callno]) {
7494 ast_mutex_unlock(&iaxsl[fr->callno]);
7495 return 1;
7498 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7499 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
7500 int new_callno;
7501 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
7502 fr->callno = new_callno;
7504 /* For security, always ack immediately */
7505 if (delayreject)
7506 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7507 if (check_access(fr->callno, &sin, &ies)) {
7508 /* They're not allowed on */
7509 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7510 if (authdebug)
7511 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);
7512 break;
7514 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7515 const char *context, *exten, *cid_num;
7517 context = ast_strdupa(iaxs[fr->callno]->context);
7518 exten = ast_strdupa(iaxs[fr->callno]->exten);
7519 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
7521 /* This might re-enter the IAX code and need the lock */
7522 ast_mutex_unlock(&iaxsl[fr->callno]);
7523 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
7524 ast_mutex_lock(&iaxsl[fr->callno]);
7526 if (!iaxs[fr->callno]) {
7527 ast_mutex_unlock(&iaxsl[fr->callno]);
7528 return 1;
7530 } else
7531 exists = 0;
7532 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
7533 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7534 memset(&ied0, 0, sizeof(ied0));
7535 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7536 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7537 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7538 if (!iaxs[fr->callno]) {
7539 ast_mutex_unlock(&iaxsl[fr->callno]);
7540 return 1;
7542 if (authdebug)
7543 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);
7544 } else {
7545 /* Select an appropriate format */
7547 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7548 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7549 using_prefs = "reqonly";
7550 } else {
7551 using_prefs = "disabled";
7553 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7554 memset(&pref, 0, sizeof(pref));
7555 strcpy(caller_pref_buf, "disabled");
7556 strcpy(host_pref_buf, "disabled");
7557 } else {
7558 using_prefs = "mine";
7559 /* If the information elements are in here... use them */
7560 if (ies.codec_prefs)
7561 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7562 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7563 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7564 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7565 pref = iaxs[fr->callno]->rprefs;
7566 using_prefs = "caller";
7567 } else {
7568 pref = iaxs[fr->callno]->prefs;
7570 } else
7571 pref = iaxs[fr->callno]->prefs;
7573 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7574 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7575 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7577 if (!format) {
7578 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7579 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7580 if (!format) {
7581 memset(&ied0, 0, sizeof(ied0));
7582 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7583 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7584 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7585 if (!iaxs[fr->callno]) {
7586 ast_mutex_unlock(&iaxsl[fr->callno]);
7587 return 1;
7589 if (authdebug) {
7590 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7591 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);
7592 else
7593 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);
7595 } else {
7596 /* Pick one... */
7597 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7598 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7599 format = 0;
7600 } else {
7601 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7602 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7603 memset(&pref, 0, sizeof(pref));
7604 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7605 strcpy(caller_pref_buf,"disabled");
7606 strcpy(host_pref_buf,"disabled");
7607 } else {
7608 using_prefs = "mine";
7609 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7610 /* Do the opposite of what we tried above. */
7611 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7612 pref = iaxs[fr->callno]->prefs;
7613 } else {
7614 pref = iaxs[fr->callno]->rprefs;
7615 using_prefs = "caller";
7617 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7619 } else /* if no codec_prefs IE do it the old way */
7620 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7624 if (!format) {
7625 memset(&ied0, 0, sizeof(ied0));
7626 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7627 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7628 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7629 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7630 if (!iaxs[fr->callno]) {
7631 ast_mutex_unlock(&iaxsl[fr->callno]);
7632 return 1;
7634 if (authdebug)
7635 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);
7636 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7637 break;
7641 if (format) {
7642 /* No authentication required, let them in */
7643 memset(&ied1, 0, sizeof(ied1));
7644 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7645 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7646 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7647 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7648 if (option_verbose > 2)
7649 ast_verbose(VERBOSE_PREFIX_3 "Accepting UNAUTHENTICATED call from %s:\n"
7650 "%srequested format = %s,\n"
7651 "%srequested prefs = %s,\n"
7652 "%sactual format = %s,\n"
7653 "%shost prefs = %s,\n"
7654 "%spriority = %s\n",
7655 ast_inet_ntoa(sin.sin_addr),
7656 VERBOSE_PREFIX_4,
7657 ast_getformatname(iaxs[fr->callno]->peerformat),
7658 VERBOSE_PREFIX_4,
7659 caller_pref_buf,
7660 VERBOSE_PREFIX_4,
7661 ast_getformatname(format),
7662 VERBOSE_PREFIX_4,
7663 host_pref_buf,
7664 VERBOSE_PREFIX_4,
7665 using_prefs);
7667 iaxs[fr->callno]->chosenformat = format;
7668 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7669 } else {
7670 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7671 /* If this is a TBD call, we're ready but now what... */
7672 if (option_verbose > 2)
7673 ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
7677 break;
7679 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
7680 merge_encryption(iaxs[fr->callno],ies.encmethods);
7681 else
7682 iaxs[fr->callno]->encmethods = 0;
7683 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
7684 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
7685 if (!iaxs[fr->callno]) {
7686 ast_mutex_unlock(&iaxsl[fr->callno]);
7687 return 1;
7689 break;
7690 case IAX_COMMAND_DPREQ:
7691 /* Request status in the dialplan */
7692 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
7693 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
7694 if (iaxcompat) {
7695 /* Spawn a thread for the lookup */
7696 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
7697 } else {
7698 /* Just look it up */
7699 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
7702 break;
7703 case IAX_COMMAND_HANGUP:
7704 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7705 if (option_debug)
7706 ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr->callno);
7707 /* Set hangup cause according to remote */
7708 if (ies.causecode && iaxs[fr->callno]->owner)
7709 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7710 /* Send ack immediately, before we destroy */
7711 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7712 iax2_destroy(fr->callno);
7713 break;
7714 case IAX_COMMAND_REJECT:
7715 /* Set hangup cause according to remote */
7716 if (ies.causecode && iaxs[fr->callno]->owner)
7717 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7719 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7720 if (iaxs[fr->callno]->owner && authdebug)
7721 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
7722 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
7723 ies.cause ? ies.cause : "<Unknown>");
7724 if (option_debug)
7725 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
7726 fr->callno);
7728 /* Send ack immediately, before we destroy */
7729 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
7730 fr->ts, NULL, 0, fr->iseqno);
7731 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
7732 iaxs[fr->callno]->error = EPERM;
7733 iax2_destroy(fr->callno);
7734 break;
7735 case IAX_COMMAND_TRANSFER:
7737 struct ast_channel *bridged_chan;
7739 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
7740 /* Set BLINDTRANSFER channel variables */
7742 ast_mutex_unlock(&iaxsl[fr->callno]);
7743 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
7744 ast_mutex_lock(&iaxsl[fr->callno]);
7745 if (!iaxs[fr->callno]) {
7746 ast_mutex_unlock(&iaxsl[fr->callno]);
7747 return 1;
7750 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
7751 if (!strcmp(ies.called_number, ast_parking_ext())) {
7752 if (iax_park(bridged_chan, iaxs[fr->callno]->owner)) {
7753 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
7754 } else {
7755 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
7757 } else {
7758 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
7759 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
7760 ies.called_number, iaxs[fr->callno]->context);
7761 else
7762 ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
7763 ies.called_number, iaxs[fr->callno]->context);
7765 } else
7766 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
7768 break;
7770 case IAX_COMMAND_ACCEPT:
7771 /* Ignore if call is already up or needs authentication or is a TBD */
7772 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
7773 break;
7774 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7775 /* Send ack immediately, before we destroy */
7776 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7777 iax2_destroy(fr->callno);
7778 break;
7780 if (ies.format) {
7781 iaxs[fr->callno]->peerformat = ies.format;
7782 } else {
7783 if (iaxs[fr->callno]->owner)
7784 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
7785 else
7786 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
7788 if (option_verbose > 2)
7789 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));
7790 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
7791 memset(&ied0, 0, sizeof(ied0));
7792 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7793 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7794 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7795 if (!iaxs[fr->callno]) {
7796 ast_mutex_unlock(&iaxsl[fr->callno]);
7797 return 1;
7799 if (authdebug)
7800 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);
7801 } else {
7802 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7803 if (iaxs[fr->callno]->owner) {
7804 /* Switch us to use a compatible format */
7805 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
7806 if (option_verbose > 2)
7807 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
7808 retryowner2:
7809 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7810 ast_mutex_unlock(&iaxsl[fr->callno]);
7811 usleep(1);
7812 ast_mutex_lock(&iaxsl[fr->callno]);
7813 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
7816 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
7817 /* Setup read/write formats properly. */
7818 if (iaxs[fr->callno]->owner->writeformat)
7819 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
7820 if (iaxs[fr->callno]->owner->readformat)
7821 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7822 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7826 if (iaxs[fr->callno]) {
7827 ast_mutex_lock(&dpcache_lock);
7828 dp = iaxs[fr->callno]->dpentries;
7829 while(dp) {
7830 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
7831 iax2_dprequest(dp, fr->callno);
7833 dp = dp->peer;
7835 ast_mutex_unlock(&dpcache_lock);
7837 break;
7838 case IAX_COMMAND_POKE:
7839 /* Send back a pong packet with the original timestamp */
7840 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
7841 if (!iaxs[fr->callno]) {
7842 ast_mutex_unlock(&iaxsl[fr->callno]);
7843 return 1;
7845 break;
7846 case IAX_COMMAND_PING:
7848 struct iax_ie_data pingied;
7849 construct_rr(iaxs[fr->callno], &pingied);
7850 /* Send back a pong packet with the original timestamp */
7851 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
7853 break;
7854 case IAX_COMMAND_PONG:
7855 /* Calculate ping time */
7856 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
7857 /* save RR info */
7858 save_rr(fr, &ies);
7860 if (iaxs[fr->callno]->peerpoke) {
7861 peer = iaxs[fr->callno]->peerpoke;
7862 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
7863 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
7864 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
7865 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7866 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7868 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
7869 if (iaxs[fr->callno]->pingtime > peer->maxms) {
7870 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
7871 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7872 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7875 peer->lastms = iaxs[fr->callno]->pingtime;
7876 if (peer->smoothing && (peer->lastms > -1))
7877 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
7878 else if (peer->smoothing && peer->lastms < 0)
7879 peer->historicms = (0 + peer->historicms) / 2;
7880 else
7881 peer->historicms = iaxs[fr->callno]->pingtime;
7883 /* Remove scheduled iax2_poke_noanswer */
7884 if (peer->pokeexpire > -1) {
7885 if (!ast_sched_del(sched, peer->pokeexpire)) {
7886 peer_unref(peer);
7887 peer->pokeexpire = -1;
7890 /* Schedule the next cycle */
7891 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
7892 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
7893 else
7894 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
7895 if (peer->pokeexpire == -1)
7896 peer_unref(peer);
7897 /* and finally send the ack */
7898 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7899 /* And wrap up the qualify call */
7900 iax2_destroy(fr->callno);
7901 peer->callno = 0;
7902 if (option_debug)
7903 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
7905 break;
7906 case IAX_COMMAND_LAGRQ:
7907 case IAX_COMMAND_LAGRP:
7908 f.src = "LAGRQ";
7909 f.mallocd = 0;
7910 f.offset = 0;
7911 f.samples = 0;
7912 iax_frame_wrap(fr, &f);
7913 if(f.subclass == IAX_COMMAND_LAGRQ) {
7914 /* Received a LAGRQ - echo back a LAGRP */
7915 fr->af.subclass = IAX_COMMAND_LAGRP;
7916 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
7917 } else {
7918 /* Received LAGRP in response to our LAGRQ */
7919 unsigned int ts;
7920 /* This is a reply we've been given, actually measure the difference */
7921 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
7922 iaxs[fr->callno]->lag = ts - fr->ts;
7923 if (option_debug && iaxdebug)
7924 ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
7925 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
7927 break;
7928 case IAX_COMMAND_AUTHREQ:
7929 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7930 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>");
7931 break;
7933 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
7934 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
7935 .subclass = AST_CONTROL_HANGUP,
7937 ast_log(LOG_WARNING,
7938 "I don't know how to authenticate %s to %s\n",
7939 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
7940 iax2_queue_frame(fr->callno, &hangup_fr);
7942 if (!iaxs[fr->callno]) {
7943 ast_mutex_unlock(&iaxsl[fr->callno]);
7944 return 1;
7946 break;
7947 case IAX_COMMAND_AUTHREP:
7948 /* For security, always ack immediately */
7949 if (delayreject)
7950 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7951 /* Ignore once we've started */
7952 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7953 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>");
7954 break;
7956 if (authenticate_verify(iaxs[fr->callno], &ies)) {
7957 if (authdebug)
7958 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);
7959 memset(&ied0, 0, sizeof(ied0));
7960 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7961 break;
7963 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7964 /* This might re-enter the IAX code and need the lock */
7965 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
7966 } else
7967 exists = 0;
7968 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7969 if (authdebug)
7970 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);
7971 memset(&ied0, 0, sizeof(ied0));
7972 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7973 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7974 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7975 if (!iaxs[fr->callno]) {
7976 ast_mutex_unlock(&iaxsl[fr->callno]);
7977 return 1;
7979 } else {
7980 /* Select an appropriate format */
7981 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7982 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7983 using_prefs = "reqonly";
7984 } else {
7985 using_prefs = "disabled";
7987 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7988 memset(&pref, 0, sizeof(pref));
7989 strcpy(caller_pref_buf, "disabled");
7990 strcpy(host_pref_buf, "disabled");
7991 } else {
7992 using_prefs = "mine";
7993 if (ies.codec_prefs)
7994 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7995 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7996 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7997 pref = iaxs[fr->callno]->rprefs;
7998 using_prefs = "caller";
7999 } else {
8000 pref = iaxs[fr->callno]->prefs;
8002 } else /* if no codec_prefs IE do it the old way */
8003 pref = iaxs[fr->callno]->prefs;
8005 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
8006 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
8007 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
8009 if (!format) {
8010 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8011 if (option_debug)
8012 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);
8013 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
8015 if (!format) {
8016 if (authdebug) {
8017 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8018 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);
8019 else
8020 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);
8022 memset(&ied0, 0, sizeof(ied0));
8023 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8024 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8025 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8026 if (!iaxs[fr->callno]) {
8027 ast_mutex_unlock(&iaxsl[fr->callno]);
8028 return 1;
8030 } else {
8031 /* Pick one... */
8032 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8033 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
8034 format = 0;
8035 } else {
8036 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
8037 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
8038 memset(&pref, 0, sizeof(pref));
8039 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
8040 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8041 strcpy(caller_pref_buf,"disabled");
8042 strcpy(host_pref_buf,"disabled");
8043 } else {
8044 using_prefs = "mine";
8045 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
8046 /* Do the opposite of what we tried above. */
8047 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
8048 pref = iaxs[fr->callno]->prefs;
8049 } else {
8050 pref = iaxs[fr->callno]->rprefs;
8051 using_prefs = "caller";
8053 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
8054 } else /* if no codec_prefs IE do it the old way */
8055 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8058 if (!format) {
8059 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8060 if (authdebug) {
8061 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8062 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);
8063 else
8064 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);
8066 memset(&ied0, 0, sizeof(ied0));
8067 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8068 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8069 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8070 if (!iaxs[fr->callno]) {
8071 ast_mutex_unlock(&iaxsl[fr->callno]);
8072 return 1;
8077 if (format) {
8078 /* Authentication received */
8079 memset(&ied1, 0, sizeof(ied1));
8080 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
8081 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
8082 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
8083 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8084 if (option_verbose > 2)
8085 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s:\n"
8086 "%srequested format = %s,\n"
8087 "%srequested prefs = %s,\n"
8088 "%sactual format = %s,\n"
8089 "%shost prefs = %s,\n"
8090 "%spriority = %s\n",
8091 ast_inet_ntoa(sin.sin_addr),
8092 VERBOSE_PREFIX_4,
8093 ast_getformatname(iaxs[fr->callno]->peerformat),
8094 VERBOSE_PREFIX_4,
8095 caller_pref_buf,
8096 VERBOSE_PREFIX_4,
8097 ast_getformatname(format),
8098 VERBOSE_PREFIX_4,
8099 host_pref_buf,
8100 VERBOSE_PREFIX_4,
8101 using_prefs);
8103 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8104 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
8105 iax2_destroy(fr->callno);
8106 } else {
8107 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8108 /* If this is a TBD call, we're ready but now what... */
8109 if (option_verbose > 2)
8110 ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
8114 break;
8115 case IAX_COMMAND_DIAL:
8116 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
8117 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8118 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
8119 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
8120 if (authdebug)
8121 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);
8122 memset(&ied0, 0, sizeof(ied0));
8123 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
8124 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
8125 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8126 if (!iaxs[fr->callno]) {
8127 ast_mutex_unlock(&iaxsl[fr->callno]);
8128 return 1;
8130 } else {
8131 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8132 if (option_verbose > 2)
8133 ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
8134 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8135 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
8136 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
8137 iax2_destroy(fr->callno);
8140 break;
8141 case IAX_COMMAND_INVAL:
8142 iaxs[fr->callno]->error = ENOTCONN;
8143 if (option_debug)
8144 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
8145 iax2_destroy(fr->callno);
8146 if (option_debug)
8147 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
8148 break;
8149 case IAX_COMMAND_VNAK:
8150 if (option_debug)
8151 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
8152 /* Force retransmission */
8153 vnak_retransmit(fr->callno, fr->iseqno);
8154 break;
8155 case IAX_COMMAND_REGREQ:
8156 case IAX_COMMAND_REGREL:
8157 /* For security, always ack immediately */
8158 if (delayreject)
8159 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8160 if (register_verify(fr->callno, &sin, &ies)) {
8161 if (!iaxs[fr->callno]) {
8162 ast_mutex_unlock(&iaxsl[fr->callno]);
8163 return 1;
8165 /* Send delayed failure */
8166 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
8167 break;
8169 if (!iaxs[fr->callno]) {
8170 ast_mutex_unlock(&iaxsl[fr->callno]);
8171 return 1;
8173 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
8174 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
8175 if (f.subclass == IAX_COMMAND_REGREL)
8176 memset(&sin, 0, sizeof(sin));
8177 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
8178 ast_log(LOG_WARNING, "Registry error\n");
8179 if (!iaxs[fr->callno]) {
8180 ast_mutex_unlock(&iaxsl[fr->callno]);
8181 return 1;
8183 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
8184 ast_mutex_unlock(&iaxsl[fr->callno]);
8185 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
8186 ast_mutex_lock(&iaxsl[fr->callno]);
8187 if (!iaxs[fr->callno]) {
8188 ast_mutex_unlock(&iaxsl[fr->callno]);
8189 return 1;
8192 break;
8194 registry_authrequest(fr->callno);
8195 if (!iaxs[fr->callno]) {
8196 ast_mutex_unlock(&iaxsl[fr->callno]);
8197 return 1;
8199 break;
8200 case IAX_COMMAND_REGACK:
8201 if (iax2_ack_registry(&ies, &sin, fr->callno))
8202 ast_log(LOG_WARNING, "Registration failure\n");
8203 /* Send ack immediately, before we destroy */
8204 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8205 iax2_destroy(fr->callno);
8206 break;
8207 case IAX_COMMAND_REGREJ:
8208 if (iaxs[fr->callno]->reg) {
8209 if (authdebug) {
8210 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));
8211 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>");
8213 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
8215 /* Send ack immediately, before we destroy */
8216 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8217 iax2_destroy(fr->callno);
8218 break;
8219 case IAX_COMMAND_REGAUTH:
8220 /* Authentication request */
8221 if (registry_rerequest(&ies, fr->callno, &sin)) {
8222 memset(&ied0, 0, sizeof(ied0));
8223 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
8224 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
8225 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8226 if (!iaxs[fr->callno]) {
8227 ast_mutex_unlock(&iaxsl[fr->callno]);
8228 return 1;
8231 break;
8232 case IAX_COMMAND_TXREJ:
8233 iaxs[fr->callno]->transferring = 0;
8234 if (option_verbose > 2)
8235 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8236 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
8237 if (iaxs[fr->callno]->bridgecallno) {
8238 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
8239 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
8240 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
8243 break;
8244 case IAX_COMMAND_TXREADY:
8245 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
8246 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
8247 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
8248 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
8249 else
8250 iaxs[fr->callno]->transferring = TRANSFER_READY;
8251 if (option_verbose > 2)
8252 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8253 if (iaxs[fr->callno]->bridgecallno) {
8254 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
8255 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
8256 /* They're both ready, now release them. */
8257 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
8258 if (option_verbose > 2)
8259 ast_verbose(VERBOSE_PREFIX_3 "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8260 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8262 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
8263 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
8265 memset(&ied0, 0, sizeof(ied0));
8266 memset(&ied1, 0, sizeof(ied1));
8267 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8268 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8269 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
8270 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
8271 } else {
8272 if (option_verbose > 2)
8273 ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8274 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8276 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
8277 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
8278 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
8279 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8281 /* Stop doing lag & ping requests */
8282 stop_stuff(fr->callno);
8283 stop_stuff(iaxs[fr->callno]->bridgecallno);
8285 memset(&ied0, 0, sizeof(ied0));
8286 memset(&ied1, 0, sizeof(ied1));
8287 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8288 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8289 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
8290 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
8296 break;
8297 case IAX_COMMAND_TXREQ:
8298 try_transfer(iaxs[fr->callno], &ies);
8299 break;
8300 case IAX_COMMAND_TXCNT:
8301 if (iaxs[fr->callno]->transferring)
8302 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
8303 break;
8304 case IAX_COMMAND_TXREL:
8305 /* Send ack immediately, rather than waiting until we've changed addresses */
8306 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8307 complete_transfer(fr->callno, &ies);
8308 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
8309 break;
8310 case IAX_COMMAND_TXMEDIA:
8311 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
8312 AST_LIST_LOCK(&iaxq.queue);
8313 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
8314 /* Cancel any outstanding frames and start anew */
8315 if ((fr->callno == cur->callno) && (cur->transfer)) {
8316 cur->retries = -1;
8319 AST_LIST_UNLOCK(&iaxq.queue);
8320 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8321 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
8323 break;
8324 case IAX_COMMAND_DPREP:
8325 complete_dpreply(iaxs[fr->callno], &ies);
8326 break;
8327 case IAX_COMMAND_UNSUPPORT:
8328 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
8329 break;
8330 case IAX_COMMAND_FWDOWNL:
8331 /* Firmware download */
8332 memset(&ied0, 0, sizeof(ied0));
8333 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
8334 if (res < 0)
8335 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8336 else if (res > 0)
8337 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8338 else
8339 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8340 if (!iaxs[fr->callno]) {
8341 ast_mutex_unlock(&iaxsl[fr->callno]);
8342 return 1;
8344 break;
8345 default:
8346 if (option_debug)
8347 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
8348 memset(&ied0, 0, sizeof(ied0));
8349 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
8350 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
8352 /* Don't actually pass these frames along */
8353 if ((f.subclass != IAX_COMMAND_ACK) &&
8354 (f.subclass != IAX_COMMAND_TXCNT) &&
8355 (f.subclass != IAX_COMMAND_TXACC) &&
8356 (f.subclass != IAX_COMMAND_INVAL) &&
8357 (f.subclass != IAX_COMMAND_VNAK)) {
8358 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8359 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8361 ast_mutex_unlock(&iaxsl[fr->callno]);
8362 return 1;
8364 /* Unless this is an ACK or INVAL frame, ack it */
8365 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8366 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8367 } else if (minivid) {
8368 f.frametype = AST_FRAME_VIDEO;
8369 if (iaxs[fr->callno]->videoformat > 0)
8370 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
8371 else {
8372 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n ");
8373 iax2_vnak(fr->callno);
8374 ast_mutex_unlock(&iaxsl[fr->callno]);
8375 return 1;
8377 f.datalen = res - sizeof(*vh);
8378 if (f.datalen)
8379 f.data = thread->buf + sizeof(*vh);
8380 else
8381 f.data = NULL;
8382 #ifdef IAXTESTS
8383 if (test_resync) {
8384 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
8385 } else
8386 #endif /* IAXTESTS */
8387 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
8388 } else {
8389 /* A mini frame */
8390 f.frametype = AST_FRAME_VOICE;
8391 if (iaxs[fr->callno]->voiceformat > 0)
8392 f.subclass = iaxs[fr->callno]->voiceformat;
8393 else {
8394 if (option_debug)
8395 ast_log(LOG_DEBUG, "Received mini frame before first full voice frame\n");
8396 iax2_vnak(fr->callno);
8397 ast_mutex_unlock(&iaxsl[fr->callno]);
8398 return 1;
8400 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
8401 if (f.datalen < 0) {
8402 ast_log(LOG_WARNING, "Datalen < 0?\n");
8403 ast_mutex_unlock(&iaxsl[fr->callno]);
8404 return 1;
8406 if (f.datalen)
8407 f.data = thread->buf + sizeof(*mh);
8408 else
8409 f.data = NULL;
8410 #ifdef IAXTESTS
8411 if (test_resync) {
8412 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
8413 } else
8414 #endif /* IAXTESTS */
8415 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
8416 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8418 /* Don't pass any packets until we're started */
8419 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8420 ast_mutex_unlock(&iaxsl[fr->callno]);
8421 return 1;
8423 /* Common things */
8424 f.src = "IAX2";
8425 f.mallocd = 0;
8426 f.offset = 0;
8427 f.len = 0;
8428 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
8429 f.samples = ast_codec_get_samples(&f);
8430 /* We need to byteswap incoming slinear samples from network byte order */
8431 if (f.subclass == AST_FORMAT_SLINEAR)
8432 ast_frame_byteswap_be(&f);
8433 } else
8434 f.samples = 0;
8435 iax_frame_wrap(fr, &f);
8437 /* If this is our most recent packet, use it as our basis for timestamping */
8438 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8439 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8440 fr->outoforder = 0;
8441 } else {
8442 if (option_debug && iaxdebug && iaxs[fr->callno])
8443 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);
8444 fr->outoforder = -1;
8446 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
8447 duped_fr = iaxfrdup2(fr);
8448 if (duped_fr) {
8449 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
8451 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8452 iaxs[fr->callno]->last = fr->ts;
8453 #if 1
8454 if (option_debug && iaxdebug)
8455 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8456 #endif
8459 /* Always run again */
8460 ast_mutex_unlock(&iaxsl[fr->callno]);
8461 return 1;
8464 /* Function to clean up process thread if it is cancelled */
8465 static void iax2_process_thread_cleanup(void *data)
8467 struct iax2_thread *thread = data;
8468 ast_mutex_destroy(&thread->lock);
8469 ast_cond_destroy(&thread->cond);
8470 free(thread);
8471 ast_atomic_dec_and_test(&iaxactivethreadcount);
8474 static void *iax2_process_thread(void *data)
8476 struct iax2_thread *thread = data;
8477 struct timeval tv;
8478 struct timespec ts;
8479 int put_into_idle = 0;
8481 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
8482 pthread_cleanup_push(iax2_process_thread_cleanup, data);
8483 for(;;) {
8484 /* Wait for something to signal us to be awake */
8485 ast_mutex_lock(&thread->lock);
8487 /* Flag that we're ready to accept signals */
8488 thread->ready_for_signal = 1;
8490 /* Put into idle list if applicable */
8491 if (put_into_idle)
8492 insert_idle_thread(thread);
8494 if (thread->type == IAX_TYPE_DYNAMIC) {
8495 struct iax2_thread *t = NULL;
8496 /* Wait to be signalled or time out */
8497 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8498 ts.tv_sec = tv.tv_sec;
8499 ts.tv_nsec = tv.tv_usec * 1000;
8500 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
8501 /* This thread was never put back into the available dynamic
8502 * thread list, so just go away. */
8503 if (!put_into_idle) {
8504 ast_mutex_unlock(&thread->lock);
8505 break;
8507 AST_LIST_LOCK(&dynamic_list);
8508 /* Account for the case where this thread is acquired *right* after a timeout */
8509 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
8510 iaxdynamicthreadcount--;
8511 AST_LIST_UNLOCK(&dynamic_list);
8512 if (t) {
8513 /* This dynamic thread timed out waiting for a task and was
8514 * not acquired immediately after the timeout,
8515 * so it's time to go away. */
8516 ast_mutex_unlock(&thread->lock);
8517 break;
8519 /* Someone grabbed our thread *right* after we timed out.
8520 * Wait for them to set us up with something to do and signal
8521 * us to continue. */
8522 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8523 ts.tv_sec = tv.tv_sec;
8524 ts.tv_nsec = tv.tv_usec * 1000;
8525 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
8527 ast_mutex_unlock(&thread->lock);
8528 break;
8531 } else {
8532 ast_cond_wait(&thread->cond, &thread->lock);
8535 /* Go back into our respective list */
8536 put_into_idle = 1;
8538 ast_mutex_unlock(&thread->lock);
8540 if (thread->iostate == IAX_IOSTATE_IDLE)
8541 continue;
8543 /* Add ourselves to the active list now */
8544 AST_LIST_LOCK(&active_list);
8545 AST_LIST_INSERT_HEAD(&active_list, thread, list);
8546 AST_LIST_UNLOCK(&active_list);
8548 /* See what we need to do */
8549 switch(thread->iostate) {
8550 case IAX_IOSTATE_READY:
8551 thread->actions++;
8552 thread->iostate = IAX_IOSTATE_PROCESSING;
8553 socket_process(thread);
8554 handle_deferred_full_frames(thread);
8555 break;
8556 case IAX_IOSTATE_SCHEDREADY:
8557 thread->actions++;
8558 thread->iostate = IAX_IOSTATE_PROCESSING;
8559 #ifdef SCHED_MULTITHREADED
8560 thread->schedfunc(thread->scheddata);
8561 #endif
8562 break;
8564 time(&thread->checktime);
8565 thread->iostate = IAX_IOSTATE_IDLE;
8566 #ifdef DEBUG_SCHED_MULTITHREAD
8567 thread->curfunc[0]='\0';
8568 #endif
8570 /* Now... remove ourselves from the active list, and return to the idle list */
8571 AST_LIST_LOCK(&active_list);
8572 AST_LIST_REMOVE(&active_list, thread, list);
8573 AST_LIST_UNLOCK(&active_list);
8575 /* Make sure another frame didn't sneak in there after we thought we were done. */
8576 handle_deferred_full_frames(thread);
8579 /*!\note For some reason, idle threads are exiting without being removed
8580 * from an idle list, which is causing memory corruption. Forcibly remove
8581 * it from the list, if it's there.
8583 AST_LIST_LOCK(&idle_list);
8584 AST_LIST_REMOVE(&idle_list, thread, list);
8585 AST_LIST_UNLOCK(&idle_list);
8587 AST_LIST_LOCK(&dynamic_list);
8588 AST_LIST_REMOVE(&dynamic_list, thread, list);
8589 AST_LIST_UNLOCK(&dynamic_list);
8591 /* I am exiting here on my own volition, I need to clean up my own data structures
8592 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8594 pthread_cleanup_pop(1);
8596 return NULL;
8599 static int iax2_do_register(struct iax2_registry *reg)
8601 struct iax_ie_data ied;
8602 if (option_debug && iaxdebug)
8603 ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
8605 if (reg->dnsmgr &&
8606 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
8607 /* Maybe the IP has changed, force DNS refresh */
8608 ast_dnsmgr_refresh(reg->dnsmgr);
8612 * if IP has Changed, free allocated call to create a new one with new IP
8613 * call has the pointer to IP and must be updated to the new one
8615 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
8616 ast_mutex_lock(&iaxsl[reg->callno]);
8617 iax2_destroy(reg->callno);
8618 ast_mutex_unlock(&iaxsl[reg->callno]);
8619 reg->callno = 0;
8621 if (!reg->addr.sin_addr.s_addr) {
8622 if (option_debug && iaxdebug)
8623 ast_log(LOG_DEBUG, "Unable to send registration request for '%s' without IP address\n", reg->username);
8624 /* Setup the next registration attempt */
8625 AST_SCHED_DEL(sched, reg->expire);
8626 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8627 return -1;
8630 if (!reg->callno) {
8631 if (option_debug)
8632 ast_log(LOG_DEBUG, "Allocate call number\n");
8633 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
8634 if (reg->callno < 1) {
8635 ast_log(LOG_WARNING, "Unable to create call for registration\n");
8636 return -1;
8637 } else if (option_debug)
8638 ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
8639 iaxs[reg->callno]->reg = reg;
8640 ast_mutex_unlock(&iaxsl[reg->callno]);
8642 /* Schedule the next registration attempt */
8643 AST_SCHED_DEL(sched, reg->expire);
8644 /* Setup the next registration a little early */
8645 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8646 /* Send the request */
8647 memset(&ied, 0, sizeof(ied));
8648 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
8649 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
8650 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
8651 reg->regstate = REG_STATE_REGSENT;
8652 return 0;
8655 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
8657 if (pos != 3)
8658 return NULL;
8659 return iax_prov_complete_template(line, word, pos, state);
8662 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
8664 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8665 is found for template */
8666 struct iax_ie_data provdata;
8667 struct iax_ie_data ied;
8668 unsigned int sig;
8669 struct sockaddr_in sin;
8670 int callno;
8671 struct create_addr_info cai;
8673 memset(&cai, 0, sizeof(cai));
8675 if (option_debug)
8676 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
8678 if (iax_provision_build(&provdata, &sig, template, force)) {
8679 if (option_debug)
8680 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
8681 return 0;
8684 if (end) {
8685 memcpy(&sin, end, sizeof(sin));
8686 cai.sockfd = sockfd;
8687 } else if (create_addr(dest, NULL, &sin, &cai))
8688 return -1;
8690 /* Build the rest of the message */
8691 memset(&ied, 0, sizeof(ied));
8692 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
8694 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8695 if (!callno)
8696 return -1;
8698 if (iaxs[callno]) {
8699 /* Schedule autodestruct in case they don't ever give us anything back */
8700 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
8701 iaxs[callno]->autoid = iax2_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
8702 ast_set_flag(iaxs[callno], IAX_PROVISION);
8703 /* Got a call number now, so go ahead and send the provisioning information */
8704 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
8706 ast_mutex_unlock(&iaxsl[callno]);
8708 return 1;
8711 static char *papp = "IAX2Provision";
8712 static char *psyn = "Provision a calling IAXy with a given template";
8713 static char *pdescrip =
8714 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8715 "the calling entity is in fact an IAXy) with the given template or\n"
8716 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8718 /*! iax2provision
8719 \ingroup applications
8721 static int iax2_prov_app(struct ast_channel *chan, void *data)
8723 int res;
8724 char *sdata;
8725 char *opts;
8726 int force =0;
8727 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
8728 if (ast_strlen_zero(data))
8729 data = "default";
8730 sdata = ast_strdupa(data);
8731 opts = strchr(sdata, '|');
8732 if (opts)
8733 *opts='\0';
8735 if (chan->tech != &iax2_tech) {
8736 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
8737 return -1;
8739 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
8740 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
8741 return -1;
8743 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
8744 if (option_verbose > 2)
8745 ast_verbose(VERBOSE_PREFIX_3 "Provisioned IAXY at '%s' with '%s'= %d\n",
8746 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
8747 sdata, res);
8748 return res;
8752 static int iax2_prov_cmd(int fd, int argc, char *argv[])
8754 int force = 0;
8755 int res;
8756 if (argc < 4)
8757 return RESULT_SHOWUSAGE;
8758 if ((argc > 4)) {
8759 if (!strcasecmp(argv[4], "forced"))
8760 force = 1;
8761 else
8762 return RESULT_SHOWUSAGE;
8764 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
8765 if (res < 0)
8766 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
8767 else if (res < 1)
8768 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
8769 else
8770 ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
8771 return RESULT_SUCCESS;
8774 static void __iax2_poke_noanswer(const void *data)
8776 struct iax2_peer *peer = (struct iax2_peer *)data;
8777 if (peer->lastms > -1) {
8778 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
8779 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
8780 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
8782 if (peer->callno > 0) {
8783 ast_mutex_lock(&iaxsl[peer->callno]);
8784 iax2_destroy(peer->callno);
8785 ast_mutex_unlock(&iaxsl[peer->callno]);
8787 peer->callno = 0;
8788 peer->lastms = -1;
8789 /* Try again quickly */
8790 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
8791 if (peer->pokeexpire == -1)
8792 peer_unref(peer);
8795 static int iax2_poke_noanswer(const void *data)
8797 struct iax2_peer *peer = (struct iax2_peer *)data;
8798 peer->pokeexpire = -1;
8799 #ifdef SCHED_MULTITHREADED
8800 if (schedule_action(__iax2_poke_noanswer, data))
8801 #endif
8802 __iax2_poke_noanswer(data);
8803 peer_unref(peer);
8804 return 0;
8807 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
8809 struct iax2_peer *peer = obj;
8811 iax2_poke_peer(peer, 0);
8813 return 0;
8816 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
8818 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
8819 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8820 immediately after clearing things out */
8821 peer->lastms = 0;
8822 peer->historicms = 0;
8823 peer->pokeexpire = -1;
8824 peer->callno = 0;
8825 return 0;
8827 if (peer->callno > 0) {
8828 ast_log(LOG_NOTICE, "Still have a callno...\n");
8829 ast_mutex_lock(&iaxsl[peer->callno]);
8830 iax2_destroy(peer->callno);
8831 ast_mutex_unlock(&iaxsl[peer->callno]);
8833 if (heldcall)
8834 ast_mutex_unlock(&iaxsl[heldcall]);
8835 peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
8836 if (heldcall)
8837 ast_mutex_lock(&iaxsl[heldcall]);
8838 if (peer->callno < 1) {
8839 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
8840 return -1;
8843 /* Speed up retransmission times for this qualify call */
8844 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
8845 iaxs[peer->callno]->peerpoke = peer;
8847 /* Remove any pending pokeexpire task */
8848 if (peer->pokeexpire > -1) {
8849 if (!ast_sched_del(sched, peer->pokeexpire)) {
8850 peer->pokeexpire = -1;
8851 peer_unref(peer);
8855 /* Queue up a new task to handle no reply */
8856 /* If the host is already unreachable then use the unreachable interval instead */
8857 if (peer->lastms < 0) {
8858 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
8859 } else
8860 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
8862 if (peer->pokeexpire == -1)
8863 peer_unref(peer);
8865 /* And send the poke */
8866 send_command(iaxs[peer->callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
8868 return 0;
8871 static void free_context(struct iax2_context *con)
8873 struct iax2_context *conl;
8874 while(con) {
8875 conl = con;
8876 con = con->next;
8877 free(conl);
8881 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
8883 int callno;
8884 int res;
8885 int fmt, native;
8886 struct sockaddr_in sin;
8887 struct ast_channel *c;
8888 struct parsed_dial_string pds;
8889 struct create_addr_info cai;
8890 char *tmpstr;
8892 memset(&pds, 0, sizeof(pds));
8893 tmpstr = ast_strdupa(data);
8894 parse_dial_string(tmpstr, &pds);
8896 if (ast_strlen_zero(pds.peer)) {
8897 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
8898 return NULL;
8901 memset(&cai, 0, sizeof(cai));
8902 cai.capability = iax2_capability;
8904 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8906 /* Populate our address from the given */
8907 if (create_addr(pds.peer, NULL, &sin, &cai)) {
8908 *cause = AST_CAUSE_UNREGISTERED;
8909 return NULL;
8912 if (pds.port)
8913 sin.sin_port = htons(atoi(pds.port));
8915 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
8916 if (callno < 1) {
8917 ast_log(LOG_WARNING, "Unable to create call\n");
8918 *cause = AST_CAUSE_CONGESTION;
8919 return NULL;
8922 /* If this is a trunk, update it now */
8923 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8924 if (ast_test_flag(&cai, IAX_TRUNK)) {
8925 int new_callno;
8926 if ((new_callno = make_trunk(callno, 1)) != -1)
8927 callno = new_callno;
8929 iaxs[callno]->maxtime = cai.maxtime;
8930 if (cai.found)
8931 ast_string_field_set(iaxs[callno], host, pds.peer);
8933 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
8935 ast_mutex_unlock(&iaxsl[callno]);
8937 if (c) {
8938 /* Choose a format we can live with */
8939 if (c->nativeformats & format)
8940 c->nativeformats &= format;
8941 else {
8942 native = c->nativeformats;
8943 fmt = format;
8944 res = ast_translator_best_choice(&fmt, &native);
8945 if (res < 0) {
8946 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
8947 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
8948 ast_hangup(c);
8949 return NULL;
8951 c->nativeformats = native;
8953 c->readformat = ast_best_codec(c->nativeformats);
8954 c->writeformat = c->readformat;
8957 return c;
8960 static void *sched_thread(void *ignore)
8962 int count;
8963 int res;
8964 struct timeval tv;
8965 struct timespec ts;
8967 for (;;) {
8968 res = ast_sched_wait(sched);
8969 if ((res > 1000) || (res < 0))
8970 res = 1000;
8971 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
8972 ts.tv_sec = tv.tv_sec;
8973 ts.tv_nsec = tv.tv_usec * 1000;
8975 pthread_testcancel();
8976 ast_mutex_lock(&sched_lock);
8977 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
8978 ast_mutex_unlock(&sched_lock);
8979 pthread_testcancel();
8981 count = ast_sched_runq(sched);
8982 if (option_debug && count >= 20)
8983 ast_log(LOG_DEBUG, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
8985 return NULL;
8988 static void *network_thread(void *ignore)
8990 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
8991 from the network, and queue them for delivery to the channels */
8992 int res, count, wakeup;
8993 struct iax_frame *f;
8995 if (timingfd > -1)
8996 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
8998 for(;;) {
8999 pthread_testcancel();
9001 /* Go through the queue, sending messages which have not yet been
9002 sent, and scheduling retransmissions if appropriate */
9003 AST_LIST_LOCK(&iaxq.queue);
9004 count = 0;
9005 wakeup = -1;
9006 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
9007 if (f->sentyet)
9008 continue;
9010 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
9011 if (ast_mutex_trylock(&iaxsl[f->callno])) {
9012 wakeup = 1;
9013 continue;
9016 f->sentyet++;
9018 if (iaxs[f->callno]) {
9019 send_packet(f);
9020 count++;
9023 ast_mutex_unlock(&iaxsl[f->callno]);
9025 if (f->retries < 0) {
9026 /* This is not supposed to be retransmitted */
9027 AST_LIST_REMOVE_CURRENT(&iaxq.queue, list);
9028 iaxq.count--;
9029 /* Free the iax frame */
9030 iax_frame_free(f);
9031 } else {
9032 /* We need reliable delivery. Schedule a retransmission */
9033 f->retries++;
9034 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
9037 AST_LIST_TRAVERSE_SAFE_END
9038 AST_LIST_UNLOCK(&iaxq.queue);
9040 pthread_testcancel();
9042 if (option_debug && count >= 20)
9043 ast_log(LOG_DEBUG, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
9045 /* Now do the IO, and run scheduled tasks */
9046 res = ast_io_wait(io, wakeup);
9047 if (res >= 0) {
9048 if (option_debug && res >= 20)
9049 ast_log(LOG_DEBUG, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
9052 return NULL;
9055 static int start_network_thread(void)
9057 pthread_attr_t attr;
9058 int threadcount = 0;
9059 int x;
9060 for (x = 0; x < iaxthreadcount; x++) {
9061 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
9062 if (thread) {
9063 thread->type = IAX_TYPE_POOL;
9064 thread->threadnum = ++threadcount;
9065 ast_mutex_init(&thread->lock);
9066 ast_cond_init(&thread->cond, NULL);
9067 pthread_attr_init(&attr);
9068 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
9069 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
9070 ast_log(LOG_WARNING, "Failed to create new thread!\n");
9071 free(thread);
9072 thread = NULL;
9074 AST_LIST_LOCK(&idle_list);
9075 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
9076 AST_LIST_UNLOCK(&idle_list);
9079 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
9080 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
9081 if (option_verbose > 1)
9082 ast_verbose(VERBOSE_PREFIX_2 "%d helper threaads started\n", threadcount);
9083 return 0;
9086 static struct iax2_context *build_context(char *context)
9088 struct iax2_context *con;
9090 if ((con = ast_calloc(1, sizeof(*con))))
9091 ast_copy_string(con->context, context, sizeof(con->context));
9093 return con;
9096 static int get_auth_methods(char *value)
9098 int methods = 0;
9099 if (strstr(value, "rsa"))
9100 methods |= IAX_AUTH_RSA;
9101 if (strstr(value, "md5"))
9102 methods |= IAX_AUTH_MD5;
9103 if (strstr(value, "plaintext"))
9104 methods |= IAX_AUTH_PLAINTEXT;
9105 return methods;
9109 /*! \brief Check if address can be used as packet source.
9110 \return 0 address available, 1 address unavailable, -1 error
9112 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
9114 int sd;
9115 int res;
9117 sd = socket(AF_INET, SOCK_DGRAM, 0);
9118 if (sd < 0) {
9119 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
9120 return -1;
9123 res = bind(sd, sa, salen);
9124 if (res < 0) {
9125 if (option_debug)
9126 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
9127 close(sd);
9128 return 1;
9131 close(sd);
9132 return 0;
9135 /*! \brief Parse the "sourceaddress" value,
9136 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9137 not found. */
9138 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
9140 struct sockaddr_in sin;
9141 int nonlocal = 1;
9142 int port = IAX_DEFAULT_PORTNO;
9143 int sockfd = defaultsockfd;
9144 char *tmp;
9145 char *addr;
9146 char *portstr;
9148 if (!(tmp = ast_strdupa(srcaddr)))
9149 return -1;
9151 addr = strsep(&tmp, ":");
9152 portstr = tmp;
9154 if (portstr) {
9155 port = atoi(portstr);
9156 if (port < 1)
9157 port = IAX_DEFAULT_PORTNO;
9160 if (!ast_get_ip(&sin, addr)) {
9161 struct ast_netsock *sock;
9162 int res;
9164 sin.sin_port = 0;
9165 sin.sin_family = AF_INET;
9166 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
9167 if (res == 0) {
9168 /* ip address valid. */
9169 sin.sin_port = htons(port);
9170 if (!(sock = ast_netsock_find(netsock, &sin)))
9171 sock = ast_netsock_find(outsock, &sin);
9172 if (sock) {
9173 sockfd = ast_netsock_sockfd(sock);
9174 nonlocal = 0;
9175 } else {
9176 unsigned int orig_saddr = sin.sin_addr.s_addr;
9177 /* INADDR_ANY matches anyway! */
9178 sin.sin_addr.s_addr = INADDR_ANY;
9179 if (ast_netsock_find(netsock, &sin)) {
9180 sin.sin_addr.s_addr = orig_saddr;
9181 sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, socket_read, NULL);
9182 if (sock) {
9183 sockfd = ast_netsock_sockfd(sock);
9184 ast_netsock_unref(sock);
9185 nonlocal = 0;
9186 } else {
9187 nonlocal = 2;
9194 peer->sockfd = sockfd;
9196 if (nonlocal == 1) {
9197 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9198 srcaddr, peer->name);
9199 return -1;
9200 } else if (nonlocal == 2) {
9201 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9202 srcaddr, peer->name);
9203 return -1;
9204 } else {
9205 if (option_debug)
9206 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
9207 return 0;
9211 static void peer_destructor(void *obj)
9213 struct iax2_peer *peer = obj;
9215 ast_free_ha(peer->ha);
9217 if (peer->callno > 0) {
9218 ast_mutex_lock(&iaxsl[peer->callno]);
9219 iax2_destroy(peer->callno);
9220 ast_mutex_unlock(&iaxsl[peer->callno]);
9223 register_peer_exten(peer, 0);
9225 if (peer->dnsmgr)
9226 ast_dnsmgr_release(peer->dnsmgr);
9228 ast_string_field_free_memory(peer);
9231 /*! \brief Create peer structure based on configuration */
9232 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9234 struct iax2_peer *peer = NULL;
9235 struct ast_ha *oldha = NULL;
9236 int maskfound=0;
9237 int found=0;
9238 int firstpass=1;
9239 struct iax2_peer tmp_peer = {
9240 .name = name,
9243 if (!temponly) {
9244 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
9245 if (peer && !ast_test_flag(peer, IAX_DELME))
9246 firstpass = 0;
9249 if (peer) {
9250 found++;
9251 if (firstpass) {
9252 oldha = peer->ha;
9253 peer->ha = NULL;
9255 unlink_peer(peer);
9256 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
9257 peer->expire = -1;
9258 peer->pokeexpire = -1;
9259 peer->sockfd = defaultsockfd;
9260 if (ast_string_field_init(peer, 32))
9261 peer = peer_unref(peer);
9264 if (peer) {
9265 if (firstpass) {
9266 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
9267 peer->encmethods = iax2_encryption;
9268 peer->adsi = adsi;
9269 ast_string_field_set(peer,secret,"");
9270 if (!found) {
9271 ast_string_field_set(peer, name, name);
9272 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9273 peer->expiry = min_reg_expire;
9275 peer->prefs = prefs;
9276 peer->capability = iax2_capability;
9277 peer->smoothing = 0;
9278 peer->pokefreqok = DEFAULT_FREQ_OK;
9279 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
9280 ast_string_field_set(peer,context,"");
9281 ast_string_field_set(peer,peercontext,"");
9282 ast_clear_flag(peer, IAX_HASCALLERID);
9283 ast_string_field_set(peer, cid_name, "");
9284 ast_string_field_set(peer, cid_num, "");
9287 if (!v) {
9288 v = alt;
9289 alt = NULL;
9291 while(v) {
9292 if (!strcasecmp(v->name, "secret")) {
9293 ast_string_field_set(peer, secret, v->value);
9294 } else if (!strcasecmp(v->name, "mailbox")) {
9295 ast_string_field_set(peer, mailbox, v->value);
9296 } else if (!strcasecmp(v->name, "mohinterpret")) {
9297 ast_string_field_set(peer, mohinterpret, v->value);
9298 } else if (!strcasecmp(v->name, "mohsuggest")) {
9299 ast_string_field_set(peer, mohsuggest, v->value);
9300 } else if (!strcasecmp(v->name, "dbsecret")) {
9301 ast_string_field_set(peer, dbsecret, v->value);
9302 } else if (!strcasecmp(v->name, "trunk")) {
9303 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
9304 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
9305 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without zaptel timing\n", peer->name);
9306 ast_clear_flag(peer, IAX_TRUNK);
9308 } else if (!strcasecmp(v->name, "auth")) {
9309 peer->authmethods = get_auth_methods(v->value);
9310 } else if (!strcasecmp(v->name, "encryption")) {
9311 peer->encmethods = get_encrypt_methods(v->value);
9312 } else if (!strcasecmp(v->name, "notransfer")) {
9313 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9314 ast_clear_flag(peer, IAX_TRANSFERMEDIA);
9315 ast_set2_flag(peer, ast_true(v->value), IAX_NOTRANSFER);
9316 } else if (!strcasecmp(v->name, "transfer")) {
9317 if (!strcasecmp(v->value, "mediaonly")) {
9318 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9319 } else if (ast_true(v->value)) {
9320 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9321 } else
9322 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9323 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9324 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
9325 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9326 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
9327 } else if (!strcasecmp(v->name, "host")) {
9328 if (!strcasecmp(v->value, "dynamic")) {
9329 /* They'll register with us */
9330 ast_set_flag(peer, IAX_DYNAMIC);
9331 if (!found) {
9332 /* Initialize stuff iff we're not found, otherwise
9333 we keep going with what we had */
9334 memset(&peer->addr.sin_addr, 0, 4);
9335 if (peer->addr.sin_port) {
9336 /* If we've already got a port, make it the default rather than absolute */
9337 peer->defaddr.sin_port = peer->addr.sin_port;
9338 peer->addr.sin_port = 0;
9341 } else {
9342 /* Non-dynamic. Make sure we become that way if we're not */
9343 AST_SCHED_DEL(sched, peer->expire);
9344 ast_clear_flag(peer, IAX_DYNAMIC);
9345 if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
9346 return peer_unref(peer);
9347 if (!peer->addr.sin_port)
9348 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9350 if (!maskfound)
9351 inet_aton("255.255.255.255", &peer->mask);
9352 } else if (!strcasecmp(v->name, "defaultip")) {
9353 if (ast_get_ip(&peer->defaddr, v->value))
9354 return peer_unref(peer);
9355 } else if (!strcasecmp(v->name, "sourceaddress")) {
9356 peer_set_srcaddr(peer, v->value);
9357 } else if (!strcasecmp(v->name, "permit") ||
9358 !strcasecmp(v->name, "deny")) {
9359 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
9360 } else if (!strcasecmp(v->name, "mask")) {
9361 maskfound++;
9362 inet_aton(v->value, &peer->mask);
9363 } else if (!strcasecmp(v->name, "context")) {
9364 ast_string_field_set(peer, context, v->value);
9365 } else if (!strcasecmp(v->name, "regexten")) {
9366 ast_string_field_set(peer, regexten, v->value);
9367 } else if (!strcasecmp(v->name, "peercontext")) {
9368 ast_string_field_set(peer, peercontext, v->value);
9369 } else if (!strcasecmp(v->name, "port")) {
9370 if (ast_test_flag(peer, IAX_DYNAMIC))
9371 peer->defaddr.sin_port = htons(atoi(v->value));
9372 else
9373 peer->addr.sin_port = htons(atoi(v->value));
9374 } else if (!strcasecmp(v->name, "username")) {
9375 ast_string_field_set(peer, username, v->value);
9376 } else if (!strcasecmp(v->name, "allow")) {
9377 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
9378 } else if (!strcasecmp(v->name, "disallow")) {
9379 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
9380 } else if (!strcasecmp(v->name, "callerid")) {
9381 if (!ast_strlen_zero(v->value)) {
9382 char name2[80];
9383 char num2[80];
9384 ast_callerid_split(v->value, name2, 80, num2, 80);
9385 ast_string_field_set(peer, cid_name, name2);
9386 ast_string_field_set(peer, cid_num, num2);
9387 ast_set_flag(peer, IAX_HASCALLERID);
9388 } else {
9389 ast_clear_flag(peer, IAX_HASCALLERID);
9390 ast_string_field_set(peer, cid_name, "");
9391 ast_string_field_set(peer, cid_num, "");
9393 } else if (!strcasecmp(v->name, "fullname")) {
9394 if (!ast_strlen_zero(v->value)) {
9395 ast_string_field_set(peer, cid_name, v->value);
9396 ast_set_flag(peer, IAX_HASCALLERID);
9397 } else {
9398 ast_string_field_set(peer, cid_name, "");
9399 if (ast_strlen_zero(peer->cid_num))
9400 ast_clear_flag(peer, IAX_HASCALLERID);
9402 } else if (!strcasecmp(v->name, "cid_number")) {
9403 if (!ast_strlen_zero(v->value)) {
9404 ast_string_field_set(peer, cid_num, v->value);
9405 ast_set_flag(peer, IAX_HASCALLERID);
9406 } else {
9407 ast_string_field_set(peer, cid_num, "");
9408 if (ast_strlen_zero(peer->cid_name))
9409 ast_clear_flag(peer, IAX_HASCALLERID);
9411 } else if (!strcasecmp(v->name, "sendani")) {
9412 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
9413 } else if (!strcasecmp(v->name, "inkeys")) {
9414 ast_string_field_set(peer, inkeys, v->value);
9415 } else if (!strcasecmp(v->name, "outkey")) {
9416 ast_string_field_set(peer, outkey, v->value);
9417 } else if (!strcasecmp(v->name, "qualify")) {
9418 if (!strcasecmp(v->value, "no")) {
9419 peer->maxms = 0;
9420 } else if (!strcasecmp(v->value, "yes")) {
9421 peer->maxms = DEFAULT_MAXMS;
9422 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
9423 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);
9424 peer->maxms = 0;
9426 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
9427 peer->smoothing = ast_true(v->value);
9428 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
9429 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
9430 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);
9432 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
9433 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
9434 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);
9435 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
9436 } else if (!strcasecmp(v->name, "timezone")) {
9437 ast_string_field_set(peer, zonetag, v->value);
9438 } else if (!strcasecmp(v->name, "adsi")) {
9439 peer->adsi = ast_true(v->value);
9440 }/* else if (strcasecmp(v->name,"type")) */
9441 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9442 v = v->next;
9443 if (!v) {
9444 v = alt;
9445 alt = NULL;
9448 if (!peer->authmethods)
9449 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9450 ast_clear_flag(peer, IAX_DELME);
9451 /* Make sure these are IPv4 addresses */
9452 peer->addr.sin_family = AF_INET;
9454 if (oldha)
9455 ast_free_ha(oldha);
9456 return peer;
9459 static void user_destructor(void *obj)
9461 struct iax2_user *user = obj;
9463 ast_free_ha(user->ha);
9464 free_context(user->contexts);
9465 if(user->vars) {
9466 ast_variables_destroy(user->vars);
9467 user->vars = NULL;
9469 ast_string_field_free_memory(user);
9472 /*! \brief Create in-memory user structure from configuration */
9473 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9475 struct iax2_user *user = NULL;
9476 struct iax2_context *con, *conl = NULL;
9477 struct ast_ha *oldha = NULL;
9478 struct iax2_context *oldcon = NULL;
9479 int format;
9480 int firstpass=1;
9481 int oldcurauthreq = 0;
9482 char *varname = NULL, *varval = NULL;
9483 struct ast_variable *tmpvar = NULL;
9484 struct iax2_user tmp_user = {
9485 .name = name,
9488 if (!temponly) {
9489 user = ao2_find(users, &tmp_user, OBJ_POINTER);
9490 if (user && !ast_test_flag(user, IAX_DELME))
9491 firstpass = 0;
9494 if (user) {
9495 if (firstpass) {
9496 oldcurauthreq = user->curauthreq;
9497 oldha = user->ha;
9498 oldcon = user->contexts;
9499 user->ha = NULL;
9500 user->contexts = NULL;
9502 /* Already in the list, remove it and it will be added back (or FREE'd) */
9503 ao2_unlink(users, user);
9504 } else {
9505 user = ao2_alloc(sizeof(*user), user_destructor);
9508 if (user) {
9509 if (firstpass) {
9510 ast_string_field_free_memory(user);
9511 memset(user, 0, sizeof(struct iax2_user));
9512 if (ast_string_field_init(user, 32)) {
9513 user = user_unref(user);
9514 goto cleanup;
9516 user->maxauthreq = maxauthreq;
9517 user->curauthreq = oldcurauthreq;
9518 user->prefs = prefs;
9519 user->capability = iax2_capability;
9520 user->encmethods = iax2_encryption;
9521 user->adsi = adsi;
9522 ast_string_field_set(user, name, name);
9523 ast_string_field_set(user, language, language);
9524 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
9525 ast_clear_flag(user, IAX_HASCALLERID);
9526 ast_string_field_set(user, cid_name, "");
9527 ast_string_field_set(user, cid_num, "");
9529 if (!v) {
9530 v = alt;
9531 alt = NULL;
9533 while(v) {
9534 if (!strcasecmp(v->name, "context")) {
9535 con = build_context(v->value);
9536 if (con) {
9537 if (conl)
9538 conl->next = con;
9539 else
9540 user->contexts = con;
9541 conl = con;
9543 } else if (!strcasecmp(v->name, "permit") ||
9544 !strcasecmp(v->name, "deny")) {
9545 user->ha = ast_append_ha(v->name, v->value, user->ha);
9546 } else if (!strcasecmp(v->name, "setvar")) {
9547 varname = ast_strdupa(v->value);
9548 if (varname && (varval = strchr(varname,'='))) {
9549 *varval = '\0';
9550 varval++;
9551 if((tmpvar = ast_variable_new(varname, varval))) {
9552 tmpvar->next = user->vars;
9553 user->vars = tmpvar;
9556 } else if (!strcasecmp(v->name, "allow")) {
9557 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
9558 } else if (!strcasecmp(v->name, "disallow")) {
9559 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
9560 } else if (!strcasecmp(v->name, "trunk")) {
9561 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
9562 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
9563 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without zaptel timing\n", user->name);
9564 ast_clear_flag(user, IAX_TRUNK);
9566 } else if (!strcasecmp(v->name, "auth")) {
9567 user->authmethods = get_auth_methods(v->value);
9568 } else if (!strcasecmp(v->name, "encryption")) {
9569 user->encmethods = get_encrypt_methods(v->value);
9570 } else if (!strcasecmp(v->name, "notransfer")) {
9571 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9572 ast_clear_flag(user, IAX_TRANSFERMEDIA);
9573 ast_set2_flag(user, ast_true(v->value), IAX_NOTRANSFER);
9574 } else if (!strcasecmp(v->name, "transfer")) {
9575 if (!strcasecmp(v->value, "mediaonly")) {
9576 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9577 } else if (ast_true(v->value)) {
9578 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9579 } else
9580 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9581 } else if (!strcasecmp(v->name, "codecpriority")) {
9582 if(!strcasecmp(v->value, "caller"))
9583 ast_set_flag(user, IAX_CODEC_USER_FIRST);
9584 else if(!strcasecmp(v->value, "disabled"))
9585 ast_set_flag(user, IAX_CODEC_NOPREFS);
9586 else if(!strcasecmp(v->value, "reqonly")) {
9587 ast_set_flag(user, IAX_CODEC_NOCAP);
9588 ast_set_flag(user, IAX_CODEC_NOPREFS);
9590 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9591 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
9592 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9593 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
9594 } else if (!strcasecmp(v->name, "dbsecret")) {
9595 ast_string_field_set(user, dbsecret, v->value);
9596 } else if (!strcasecmp(v->name, "secret")) {
9597 if (!ast_strlen_zero(user->secret)) {
9598 char *old = ast_strdupa(user->secret);
9600 ast_string_field_build(user, secret, "%s;%s", old, v->value);
9601 } else
9602 ast_string_field_set(user, secret, v->value);
9603 } else if (!strcasecmp(v->name, "callerid")) {
9604 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
9605 char name2[80];
9606 char num2[80];
9607 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
9608 ast_string_field_set(user, cid_name, name2);
9609 ast_string_field_set(user, cid_num, num2);
9610 ast_set_flag(user, IAX_HASCALLERID);
9611 } else {
9612 ast_clear_flag(user, IAX_HASCALLERID);
9613 ast_string_field_set(user, cid_name, "");
9614 ast_string_field_set(user, cid_num, "");
9616 } else if (!strcasecmp(v->name, "fullname")) {
9617 if (!ast_strlen_zero(v->value)) {
9618 ast_string_field_set(user, cid_name, v->value);
9619 ast_set_flag(user, IAX_HASCALLERID);
9620 } else {
9621 ast_string_field_set(user, cid_name, "");
9622 if (ast_strlen_zero(user->cid_num))
9623 ast_clear_flag(user, IAX_HASCALLERID);
9625 } else if (!strcasecmp(v->name, "cid_number")) {
9626 if (!ast_strlen_zero(v->value)) {
9627 ast_string_field_set(user, cid_num, v->value);
9628 ast_set_flag(user, IAX_HASCALLERID);
9629 } else {
9630 ast_string_field_set(user, cid_num, "");
9631 if (ast_strlen_zero(user->cid_name))
9632 ast_clear_flag(user, IAX_HASCALLERID);
9634 } else if (!strcasecmp(v->name, "accountcode")) {
9635 ast_string_field_set(user, accountcode, v->value);
9636 } else if (!strcasecmp(v->name, "mohinterpret")) {
9637 ast_string_field_set(user, mohinterpret, v->value);
9638 } else if (!strcasecmp(v->name, "mohsuggest")) {
9639 ast_string_field_set(user, mohsuggest, v->value);
9640 } else if (!strcasecmp(v->name, "language")) {
9641 ast_string_field_set(user, language, v->value);
9642 } else if (!strcasecmp(v->name, "amaflags")) {
9643 format = ast_cdr_amaflags2int(v->value);
9644 if (format < 0) {
9645 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9646 } else {
9647 user->amaflags = format;
9649 } else if (!strcasecmp(v->name, "inkeys")) {
9650 ast_string_field_set(user, inkeys, v->value);
9651 } else if (!strcasecmp(v->name, "maxauthreq")) {
9652 user->maxauthreq = atoi(v->value);
9653 if (user->maxauthreq < 0)
9654 user->maxauthreq = 0;
9655 } else if (!strcasecmp(v->name, "adsi")) {
9656 user->adsi = ast_true(v->value);
9657 }/* else if (strcasecmp(v->name,"type")) */
9658 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9659 v = v->next;
9660 if (!v) {
9661 v = alt;
9662 alt = NULL;
9665 if (!user->authmethods) {
9666 if (!ast_strlen_zero(user->secret)) {
9667 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9668 if (!ast_strlen_zero(user->inkeys))
9669 user->authmethods |= IAX_AUTH_RSA;
9670 } else if (!ast_strlen_zero(user->inkeys)) {
9671 user->authmethods = IAX_AUTH_RSA;
9672 } else {
9673 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9676 ast_clear_flag(user, IAX_DELME);
9678 cleanup:
9679 if (oldha)
9680 ast_free_ha(oldha);
9681 if (oldcon)
9682 free_context(oldcon);
9683 return user;
9686 static int peer_delme_cb(void *obj, void *arg, int flags)
9688 struct iax2_peer *peer = obj;
9690 ast_set_flag(peer, IAX_DELME);
9692 return 0;
9695 static int user_delme_cb(void *obj, void *arg, int flags)
9697 struct iax2_user *user = obj;
9699 ast_set_flag(user, IAX_DELME);
9701 return 0;
9704 static void delete_users(void)
9706 struct iax2_registry *reg;
9708 ao2_callback(users, 0, user_delme_cb, NULL);
9710 AST_LIST_LOCK(&registrations);
9711 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
9712 ast_sched_del(sched, reg->expire);
9713 if (reg->callno) {
9714 ast_mutex_lock(&iaxsl[reg->callno]);
9715 if (iaxs[reg->callno]) {
9716 iaxs[reg->callno]->reg = NULL;
9717 iax2_destroy(reg->callno);
9719 ast_mutex_unlock(&iaxsl[reg->callno]);
9721 if (reg->dnsmgr)
9722 ast_dnsmgr_release(reg->dnsmgr);
9723 free(reg);
9725 AST_LIST_UNLOCK(&registrations);
9727 ao2_callback(peers, 0, peer_delme_cb, NULL);
9730 static void prune_users(void)
9732 struct iax2_user *user;
9733 struct ao2_iterator i;
9735 i = ao2_iterator_init(users, 0);
9736 while ((user = ao2_iterator_next(&i))) {
9737 if (ast_test_flag(user, IAX_DELME))
9738 ao2_unlink(users, user);
9739 user_unref(user);
9743 /* Prune peers who still are supposed to be deleted */
9744 static void prune_peers(void)
9746 struct iax2_peer *peer;
9747 struct ao2_iterator i;
9749 i = ao2_iterator_init(peers, 0);
9750 while ((peer = ao2_iterator_next(&i))) {
9751 if (ast_test_flag(peer, IAX_DELME))
9752 unlink_peer(peer);
9753 peer_unref(peer);
9757 static void set_timing(void)
9759 #ifdef HAVE_ZAPTEL
9760 int bs = trunkfreq * 8;
9761 if (timingfd > -1) {
9762 if (
9763 #ifdef ZT_TIMERACK
9764 ioctl(timingfd, ZT_TIMERCONFIG, &bs) &&
9765 #endif
9766 ioctl(timingfd, ZT_SET_BLOCKSIZE, &bs))
9767 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
9769 #endif
9772 static void set_config_destroy(void)
9774 strcpy(accountcode, "");
9775 strcpy(language, "");
9776 strcpy(mohinterpret, "default");
9777 strcpy(mohsuggest, "");
9778 amaflags = 0;
9779 delayreject = 0;
9780 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
9781 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9782 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
9783 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
9784 delete_users();
9787 /*! \brief Load configuration */
9788 static int set_config(char *config_file, int reload)
9790 struct ast_config *cfg, *ucfg;
9791 int capability=iax2_capability;
9792 struct ast_variable *v;
9793 char *cat;
9794 const char *utype;
9795 const char *tosval;
9796 int format;
9797 int portno = IAX_DEFAULT_PORTNO;
9798 int x;
9799 struct iax2_user *user;
9800 struct iax2_peer *peer;
9801 struct ast_netsock *ns;
9802 #if 0
9803 static unsigned short int last_port=0;
9804 #endif
9806 cfg = ast_config_load(config_file);
9808 if (!cfg) {
9809 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
9810 return -1;
9813 if (reload) {
9814 set_config_destroy();
9817 /* Reset global codec prefs */
9818 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
9820 /* Reset Global Flags */
9821 memset(&globalflags, 0, sizeof(globalflags));
9822 ast_set_flag(&globalflags, IAX_RTUPDATE);
9824 #ifdef SO_NO_CHECK
9825 nochecksums = 0;
9826 #endif
9828 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9829 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9831 maxauthreq = 3;
9833 v = ast_variable_browse(cfg, "general");
9835 /* Seed initial tos value */
9836 tosval = ast_variable_retrieve(cfg, "general", "tos");
9837 if (tosval) {
9838 if (ast_str2tos(tosval, &tos))
9839 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9841 while(v) {
9842 if (!strcasecmp(v->name, "bindport")){
9843 if (reload)
9844 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
9845 else
9846 portno = atoi(v->value);
9847 } else if (!strcasecmp(v->name, "pingtime"))
9848 ping_time = atoi(v->value);
9849 else if (!strcasecmp(v->name, "iaxthreadcount")) {
9850 if (reload) {
9851 if (atoi(v->value) != iaxthreadcount)
9852 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
9853 } else {
9854 iaxthreadcount = atoi(v->value);
9855 if (iaxthreadcount < 1) {
9856 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
9857 iaxthreadcount = 1;
9858 } else if (iaxthreadcount > 256) {
9859 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
9860 iaxthreadcount = 256;
9863 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
9864 if (reload) {
9865 AST_LIST_LOCK(&dynamic_list);
9866 iaxmaxthreadcount = atoi(v->value);
9867 AST_LIST_UNLOCK(&dynamic_list);
9868 } else {
9869 iaxmaxthreadcount = atoi(v->value);
9870 if (iaxmaxthreadcount < 0) {
9871 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
9872 iaxmaxthreadcount = 0;
9873 } else if (iaxmaxthreadcount > 256) {
9874 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
9875 iaxmaxthreadcount = 256;
9878 } else if (!strcasecmp(v->name, "nochecksums")) {
9879 #ifdef SO_NO_CHECK
9880 if (ast_true(v->value))
9881 nochecksums = 1;
9882 else
9883 nochecksums = 0;
9884 #else
9885 if (ast_true(v->value))
9886 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
9887 #endif
9889 else if (!strcasecmp(v->name, "maxjitterbuffer"))
9890 maxjitterbuffer = atoi(v->value);
9891 else if (!strcasecmp(v->name, "resyncthreshold"))
9892 resyncthreshold = atoi(v->value);
9893 else if (!strcasecmp(v->name, "maxjitterinterps"))
9894 maxjitterinterps = atoi(v->value);
9895 else if (!strcasecmp(v->name, "lagrqtime"))
9896 lagrq_time = atoi(v->value);
9897 else if (!strcasecmp(v->name, "maxregexpire"))
9898 max_reg_expire = atoi(v->value);
9899 else if (!strcasecmp(v->name, "minregexpire"))
9900 min_reg_expire = atoi(v->value);
9901 else if (!strcasecmp(v->name, "bindaddr")) {
9902 if (reload) {
9903 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
9904 } else {
9905 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, socket_read, NULL))) {
9906 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
9907 } else {
9908 if (option_verbose > 1) {
9909 if (strchr(v->value, ':'))
9910 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
9911 else
9912 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s:%d'\n", v->value, portno);
9914 if (defaultsockfd < 0)
9915 defaultsockfd = ast_netsock_sockfd(ns);
9916 ast_netsock_unref(ns);
9919 } else if (!strcasecmp(v->name, "authdebug"))
9920 authdebug = ast_true(v->value);
9921 else if (!strcasecmp(v->name, "encryption"))
9922 iax2_encryption = get_encrypt_methods(v->value);
9923 else if (!strcasecmp(v->name, "notransfer")) {
9924 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9925 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9926 ast_set2_flag((&globalflags), ast_true(v->value), IAX_NOTRANSFER);
9927 } else if (!strcasecmp(v->name, "transfer")) {
9928 if (!strcasecmp(v->value, "mediaonly")) {
9929 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9930 } else if (ast_true(v->value)) {
9931 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9932 } else
9933 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9934 } else if (!strcasecmp(v->name, "codecpriority")) {
9935 if(!strcasecmp(v->value, "caller"))
9936 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
9937 else if(!strcasecmp(v->value, "disabled"))
9938 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9939 else if(!strcasecmp(v->value, "reqonly")) {
9940 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
9941 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9943 } else if (!strcasecmp(v->name, "jitterbuffer"))
9944 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
9945 else if (!strcasecmp(v->name, "forcejitterbuffer"))
9946 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
9947 else if (!strcasecmp(v->name, "delayreject"))
9948 delayreject = ast_true(v->value);
9949 else if (!strcasecmp(v->name, "rtcachefriends"))
9950 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
9951 else if (!strcasecmp(v->name, "rtignoreregexpire"))
9952 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
9953 else if (!strcasecmp(v->name, "rtupdate"))
9954 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
9955 else if (!strcasecmp(v->name, "trunktimestamps"))
9956 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
9957 else if (!strcasecmp(v->name, "rtautoclear")) {
9958 int i = atoi(v->value);
9959 if(i > 0)
9960 global_rtautoclear = i;
9961 else
9962 i = 0;
9963 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
9964 } else if (!strcasecmp(v->name, "trunkfreq")) {
9965 trunkfreq = atoi(v->value);
9966 if (trunkfreq < 10)
9967 trunkfreq = 10;
9968 } else if (!strcasecmp(v->name, "autokill")) {
9969 if (sscanf(v->value, "%d", &x) == 1) {
9970 if (x >= 0)
9971 autokill = x;
9972 else
9973 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
9974 } else if (ast_true(v->value)) {
9975 autokill = DEFAULT_MAXMS;
9976 } else {
9977 autokill = 0;
9979 } else if (!strcasecmp(v->name, "bandwidth")) {
9980 if (!strcasecmp(v->value, "low")) {
9981 capability = IAX_CAPABILITY_LOWBANDWIDTH;
9982 } else if (!strcasecmp(v->value, "medium")) {
9983 capability = IAX_CAPABILITY_MEDBANDWIDTH;
9984 } else if (!strcasecmp(v->value, "high")) {
9985 capability = IAX_CAPABILITY_FULLBANDWIDTH;
9986 } else
9987 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
9988 } else if (!strcasecmp(v->name, "allow")) {
9989 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
9990 } else if (!strcasecmp(v->name, "disallow")) {
9991 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
9992 } else if (!strcasecmp(v->name, "register")) {
9993 iax2_register(v->value, v->lineno);
9994 } else if (!strcasecmp(v->name, "iaxcompat")) {
9995 iaxcompat = ast_true(v->value);
9996 } else if (!strcasecmp(v->name, "regcontext")) {
9997 ast_copy_string(regcontext, v->value, sizeof(regcontext));
9998 /* Create context if it doesn't exist already */
9999 if (!ast_context_find(regcontext))
10000 ast_context_create(NULL, regcontext, "IAX2");
10001 } else if (!strcasecmp(v->name, "tos")) {
10002 if (ast_str2tos(v->value, &tos))
10003 ast_log(LOG_WARNING, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v->lineno);
10004 } else if (!strcasecmp(v->name, "accountcode")) {
10005 ast_copy_string(accountcode, v->value, sizeof(accountcode));
10006 } else if (!strcasecmp(v->name, "mohinterpret")) {
10007 ast_copy_string(mohinterpret, v->value, sizeof(user->mohinterpret));
10008 } else if (!strcasecmp(v->name, "mohsuggest")) {
10009 ast_copy_string(mohsuggest, v->value, sizeof(user->mohsuggest));
10010 } else if (!strcasecmp(v->name, "amaflags")) {
10011 format = ast_cdr_amaflags2int(v->value);
10012 if (format < 0) {
10013 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
10014 } else {
10015 amaflags = format;
10017 } else if (!strcasecmp(v->name, "language")) {
10018 ast_copy_string(language, v->value, sizeof(language));
10019 } else if (!strcasecmp(v->name, "maxauthreq")) {
10020 maxauthreq = atoi(v->value);
10021 if (maxauthreq < 0)
10022 maxauthreq = 0;
10023 } else if (!strcasecmp(v->name, "adsi")) {
10024 adsi = ast_true(v->value);
10025 } /*else if (strcasecmp(v->name,"type")) */
10026 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10027 v = v->next;
10030 if (defaultsockfd < 0) {
10031 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, socket_read, NULL))) {
10032 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
10033 } else {
10034 if (option_verbose > 1)
10035 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
10036 defaultsockfd = ast_netsock_sockfd(ns);
10037 ast_netsock_unref(ns);
10040 if (reload) {
10041 ast_netsock_release(outsock);
10042 outsock = ast_netsock_list_alloc();
10043 if (!outsock) {
10044 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10045 return -1;
10047 ast_netsock_init(outsock);
10050 if (min_reg_expire > max_reg_expire) {
10051 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
10052 min_reg_expire, max_reg_expire, max_reg_expire);
10053 min_reg_expire = max_reg_expire;
10055 iax2_capability = capability;
10057 ucfg = ast_config_load("users.conf");
10058 if (ucfg) {
10059 struct ast_variable *gen;
10060 int genhasiax;
10061 int genregisteriax;
10062 const char *hasiax, *registeriax;
10064 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
10065 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
10066 gen = ast_variable_browse(ucfg, "general");
10067 cat = ast_category_browse(ucfg, NULL);
10068 while (cat) {
10069 if (strcasecmp(cat, "general")) {
10070 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
10071 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
10072 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
10073 /* Start with general parameters, then specific parameters, user and peer */
10074 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
10075 if (user) {
10076 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10077 user = user_unref(user);
10079 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
10080 if (peer) {
10081 if (ast_test_flag(peer, IAX_DYNAMIC))
10082 reg_source_db(peer);
10083 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10084 peer = peer_unref(peer);
10087 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
10088 char tmp[256];
10089 const char *host = ast_variable_retrieve(ucfg, cat, "host");
10090 const char *username = ast_variable_retrieve(ucfg, cat, "username");
10091 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
10092 if (!host)
10093 host = ast_variable_retrieve(ucfg, "general", "host");
10094 if (!username)
10095 username = ast_variable_retrieve(ucfg, "general", "username");
10096 if (!secret)
10097 secret = ast_variable_retrieve(ucfg, "general", "secret");
10098 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
10099 if (!ast_strlen_zero(secret))
10100 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
10101 else
10102 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
10103 iax2_register(tmp, 0);
10107 cat = ast_category_browse(ucfg, cat);
10109 ast_config_destroy(ucfg);
10112 cat = ast_category_browse(cfg, NULL);
10113 while(cat) {
10114 if (strcasecmp(cat, "general")) {
10115 utype = ast_variable_retrieve(cfg, cat, "type");
10116 if (utype) {
10117 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
10118 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
10119 if (user) {
10120 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10121 user = user_unref(user);
10124 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
10125 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
10126 if (peer) {
10127 if (ast_test_flag(peer, IAX_DYNAMIC))
10128 reg_source_db(peer);
10129 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10130 peer = peer_unref(peer);
10132 } else if (strcasecmp(utype, "user")) {
10133 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
10135 } else
10136 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10138 cat = ast_category_browse(cfg, cat);
10140 ast_config_destroy(cfg);
10141 set_timing();
10142 return 1;
10145 static void poke_all_peers(void)
10147 struct ao2_iterator i;
10148 struct iax2_peer *peer;
10150 i = ao2_iterator_init(peers, 0);
10151 while ((peer = ao2_iterator_next(&i))) {
10152 iax2_poke_peer(peer, 0);
10153 peer_unref(peer);
10156 static int reload_config(void)
10158 char *config = "iax.conf";
10159 struct iax2_registry *reg;
10161 if (set_config(config, 1) > 0) {
10162 prune_peers();
10163 prune_users();
10164 AST_LIST_LOCK(&registrations);
10165 AST_LIST_TRAVERSE(&registrations, reg, entry)
10166 iax2_do_register(reg);
10167 AST_LIST_UNLOCK(&registrations);
10168 /* Qualify hosts, too */
10169 poke_all_peers();
10171 reload_firmware(0);
10172 iax_provision_reload();
10174 return 0;
10177 static int iax2_reload(int fd, int argc, char *argv[])
10179 return reload_config();
10182 static int reload(void)
10184 return reload_config();
10187 static int cache_get_callno_locked(const char *data)
10189 struct sockaddr_in sin;
10190 int x;
10191 int callno;
10192 struct iax_ie_data ied;
10193 struct create_addr_info cai;
10194 struct parsed_dial_string pds;
10195 char *tmpstr;
10197 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10198 /* Look for an *exact match* call. Once a call is negotiated, it can only
10199 look up entries for a single context */
10200 if (!ast_mutex_trylock(&iaxsl[x])) {
10201 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
10202 return x;
10203 ast_mutex_unlock(&iaxsl[x]);
10207 /* No match found, we need to create a new one */
10209 memset(&cai, 0, sizeof(cai));
10210 memset(&ied, 0, sizeof(ied));
10211 memset(&pds, 0, sizeof(pds));
10213 tmpstr = ast_strdupa(data);
10214 parse_dial_string(tmpstr, &pds);
10216 if (ast_strlen_zero(pds.peer)) {
10217 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
10218 return -1;
10221 /* Populate our address from the given */
10222 if (create_addr(pds.peer, NULL, &sin, &cai))
10223 return -1;
10225 if (option_debug)
10226 ast_log(LOG_DEBUG, "peer: %s, username: %s, password: %s, context: %s\n",
10227 pds.peer, pds.username, pds.password, pds.context);
10229 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
10230 if (callno < 1) {
10231 ast_log(LOG_WARNING, "Unable to create call\n");
10232 return -1;
10235 ast_string_field_set(iaxs[callno], dproot, data);
10236 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
10238 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
10239 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
10240 /* the string format is slightly different from a standard dial string,
10241 because the context appears in the 'exten' position
10243 if (pds.exten)
10244 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10245 if (pds.username)
10246 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
10247 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
10248 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
10249 /* Keep password handy */
10250 if (pds.password)
10251 ast_string_field_set(iaxs[callno], secret, pds.password);
10252 if (pds.key)
10253 ast_string_field_set(iaxs[callno], outkey, pds.key);
10254 /* Start the call going */
10255 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
10257 return callno;
10260 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
10262 struct iax2_dpcache *dp, *prev = NULL, *next;
10263 struct timeval tv;
10264 int x;
10265 int com[2];
10266 int timeout;
10267 int old=0;
10268 int outfd;
10269 int abort;
10270 int callno;
10271 struct ast_channel *c;
10272 struct ast_frame *f;
10273 gettimeofday(&tv, NULL);
10274 dp = dpcache;
10275 while(dp) {
10276 next = dp->next;
10277 /* Expire old caches */
10278 if (ast_tvcmp(tv, dp->expiry) > 0) {
10279 /* It's expired, let it disappear */
10280 if (prev)
10281 prev->next = dp->next;
10282 else
10283 dpcache = dp->next;
10284 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10285 /* Free memory and go again */
10286 free(dp);
10287 } else {
10288 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);
10290 dp = next;
10291 continue;
10293 /* We found an entry that matches us! */
10294 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10295 break;
10296 prev = dp;
10297 dp = next;
10299 if (!dp) {
10300 /* No matching entry. Create a new one. */
10301 /* First, can we make a callno? */
10302 callno = cache_get_callno_locked(data);
10303 if (callno < 0) {
10304 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10305 return NULL;
10307 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10308 ast_mutex_unlock(&iaxsl[callno]);
10309 return NULL;
10311 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
10312 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
10313 gettimeofday(&dp->expiry, NULL);
10314 dp->orig = dp->expiry;
10315 /* Expires in 30 mins by default */
10316 dp->expiry.tv_sec += iaxdefaultdpcache;
10317 dp->next = dpcache;
10318 dp->flags = CACHE_FLAG_PENDING;
10319 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10320 dp->waiters[x] = -1;
10321 dpcache = dp;
10322 dp->peer = iaxs[callno]->dpentries;
10323 iaxs[callno]->dpentries = dp;
10324 /* Send the request if we're already up */
10325 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
10326 iax2_dprequest(dp, callno);
10327 ast_mutex_unlock(&iaxsl[callno]);
10329 /* By here we must have a dp */
10330 if (dp->flags & CACHE_FLAG_PENDING) {
10331 /* Okay, here it starts to get nasty. We need a pipe now to wait
10332 for a reply to come back so long as it's pending */
10333 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
10334 /* Find an empty slot */
10335 if (dp->waiters[x] < 0)
10336 break;
10338 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10339 ast_log(LOG_WARNING, "No more waiter positions available\n");
10340 return NULL;
10342 if (pipe(com)) {
10343 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10344 return NULL;
10346 dp->waiters[x] = com[1];
10347 /* Okay, now we wait */
10348 timeout = iaxdefaulttimeout * 1000;
10349 /* Temporarily unlock */
10350 ast_mutex_unlock(&dpcache_lock);
10351 /* Defer any dtmf */
10352 if (chan)
10353 old = ast_channel_defer_dtmf(chan);
10354 abort = 0;
10355 while(timeout) {
10356 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10357 if (outfd > -1) {
10358 break;
10360 if (c) {
10361 f = ast_read(c);
10362 if (f)
10363 ast_frfree(f);
10364 else {
10365 /* Got hung up on, abort! */
10366 break;
10367 abort = 1;
10371 if (!timeout) {
10372 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
10374 ast_mutex_lock(&dpcache_lock);
10375 dp->waiters[x] = -1;
10376 close(com[1]);
10377 close(com[0]);
10378 if (abort) {
10379 /* Don't interpret anything, just abort. Not sure what th epoint
10380 of undeferring dtmf on a hung up channel is but hey whatever */
10381 if (!old && chan)
10382 ast_channel_undefer_dtmf(chan);
10383 return NULL;
10385 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
10386 /* Now to do non-independent analysis the results of our wait */
10387 if (dp->flags & CACHE_FLAG_PENDING) {
10388 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10389 pending. Don't let it take as long to timeout. */
10390 dp->flags &= ~CACHE_FLAG_PENDING;
10391 dp->flags |= CACHE_FLAG_TIMEOUT;
10392 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10393 systems without leaving it unavailable once the server comes back online */
10394 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
10395 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10396 if (dp->waiters[x] > -1)
10397 write(dp->waiters[x], "asdf", 4);
10400 /* Our caller will obtain the rest */
10401 if (!old && chan)
10402 ast_channel_undefer_dtmf(chan);
10404 return dp;
10407 /*! \brief Part of the IAX2 switch interface */
10408 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10410 struct iax2_dpcache *dp;
10411 int res = 0;
10412 #if 0
10413 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10414 #endif
10415 if ((priority != 1) && (priority != 2))
10416 return 0;
10417 ast_mutex_lock(&dpcache_lock);
10418 dp = find_cache(chan, data, context, exten, priority);
10419 if (dp) {
10420 if (dp->flags & CACHE_FLAG_EXISTS)
10421 res= 1;
10423 ast_mutex_unlock(&dpcache_lock);
10424 if (!dp) {
10425 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10427 return res;
10430 /*! \brief part of the IAX2 dial plan switch interface */
10431 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10433 int res = 0;
10434 struct iax2_dpcache *dp;
10435 #if 0
10436 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10437 #endif
10438 if ((priority != 1) && (priority != 2))
10439 return 0;
10440 ast_mutex_lock(&dpcache_lock);
10441 dp = find_cache(chan, data, context, exten, priority);
10442 if (dp) {
10443 if (dp->flags & CACHE_FLAG_CANEXIST)
10444 res= 1;
10446 ast_mutex_unlock(&dpcache_lock);
10447 if (!dp) {
10448 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10450 return res;
10453 /*! \brief Part of the IAX2 Switch interface */
10454 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10456 int res = 0;
10457 struct iax2_dpcache *dp;
10458 #if 0
10459 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10460 #endif
10461 if ((priority != 1) && (priority != 2))
10462 return 0;
10463 ast_mutex_lock(&dpcache_lock);
10464 dp = find_cache(chan, data, context, exten, priority);
10465 if (dp) {
10466 if (dp->flags & CACHE_FLAG_MATCHMORE)
10467 res= 1;
10469 ast_mutex_unlock(&dpcache_lock);
10470 if (!dp) {
10471 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10473 return res;
10476 /*! \brief Execute IAX2 dialplan switch */
10477 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10479 char odata[256];
10480 char req[256];
10481 char *ncontext;
10482 struct iax2_dpcache *dp;
10483 struct ast_app *dial;
10484 #if 0
10485 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);
10486 #endif
10487 if (priority == 2) {
10488 /* Indicate status, can be overridden in dialplan */
10489 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10490 if (dialstatus) {
10491 dial = pbx_findapp(dialstatus);
10492 if (dial)
10493 pbx_exec(chan, dial, "");
10495 return -1;
10496 } else if (priority != 1)
10497 return -1;
10498 ast_mutex_lock(&dpcache_lock);
10499 dp = find_cache(chan, data, context, exten, priority);
10500 if (dp) {
10501 if (dp->flags & CACHE_FLAG_EXISTS) {
10502 ast_copy_string(odata, data, sizeof(odata));
10503 ncontext = strchr(odata, '/');
10504 if (ncontext) {
10505 *ncontext = '\0';
10506 ncontext++;
10507 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10508 } else {
10509 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
10511 if (option_verbose > 2)
10512 ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
10513 } else {
10514 ast_mutex_unlock(&dpcache_lock);
10515 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
10516 return -1;
10519 ast_mutex_unlock(&dpcache_lock);
10520 dial = pbx_findapp("Dial");
10521 if (dial) {
10522 return pbx_exec(chan, dial, req);
10523 } else {
10524 ast_log(LOG_WARNING, "No dial application registered\n");
10526 return -1;
10529 static int function_iaxpeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10531 struct iax2_peer *peer;
10532 char *peername, *colname;
10534 peername = ast_strdupa(data);
10536 /* if our channel, return the IP address of the endpoint of current channel */
10537 if (!strcmp(peername,"CURRENTCHANNEL")) {
10538 unsigned short callno;
10539 if (chan->tech != &iax2_tech)
10540 return -1;
10541 callno = PTR_TO_CALLNO(chan->tech_pvt);
10542 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
10543 return 0;
10546 if ((colname = strchr(peername, ':'))) /*! \todo : will be removed after the 1.4 relese */
10547 *colname++ = '\0';
10548 else if ((colname = strchr(peername, '|')))
10549 *colname++ = '\0';
10550 else
10551 colname = "ip";
10553 if (!(peer = find_peer(peername, 1)))
10554 return -1;
10556 if (!strcasecmp(colname, "ip")) {
10557 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10558 } else if (!strcasecmp(colname, "status")) {
10559 peer_status(peer, buf, len);
10560 } else if (!strcasecmp(colname, "mailbox")) {
10561 ast_copy_string(buf, peer->mailbox, len);
10562 } else if (!strcasecmp(colname, "context")) {
10563 ast_copy_string(buf, peer->context, len);
10564 } else if (!strcasecmp(colname, "expire")) {
10565 snprintf(buf, len, "%d", peer->expire);
10566 } else if (!strcasecmp(colname, "dynamic")) {
10567 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
10568 } else if (!strcasecmp(colname, "callerid_name")) {
10569 ast_copy_string(buf, peer->cid_name, len);
10570 } else if (!strcasecmp(colname, "callerid_num")) {
10571 ast_copy_string(buf, peer->cid_num, len);
10572 } else if (!strcasecmp(colname, "codecs")) {
10573 ast_getformatname_multiple(buf, len -1, peer->capability);
10574 } else if (!strncasecmp(colname, "codec[", 6)) {
10575 char *codecnum, *ptr;
10576 int index = 0, codec = 0;
10578 codecnum = strchr(colname, '[');
10579 *codecnum = '\0';
10580 codecnum++;
10581 if ((ptr = strchr(codecnum, ']'))) {
10582 *ptr = '\0';
10584 index = atoi(codecnum);
10585 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10586 ast_copy_string(buf, ast_getformatname(codec), len);
10590 peer_unref(peer);
10592 return 0;
10595 struct ast_custom_function iaxpeer_function = {
10596 .name = "IAXPEER",
10597 .synopsis = "Gets IAX peer information",
10598 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10599 .read = function_iaxpeer,
10600 .desc = "If peername specified, valid items are:\n"
10601 "- ip (default) The IP address.\n"
10602 "- status The peer's status (if qualify=yes)\n"
10603 "- mailbox The configured mailbox.\n"
10604 "- context The configured context.\n"
10605 "- expire The epoch time of the next expire.\n"
10606 "- dynamic Is it dynamic? (yes/no).\n"
10607 "- callerid_name The configured Caller ID name.\n"
10608 "- callerid_num The configured Caller ID number.\n"
10609 "- codecs The configured codecs.\n"
10610 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10611 "\n"
10612 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10613 "\n"
10617 /*! \brief Part of the device state notification system ---*/
10618 static int iax2_devicestate(void *data)
10620 struct parsed_dial_string pds;
10621 char *tmp = ast_strdupa(data);
10622 struct iax2_peer *p;
10623 int res = AST_DEVICE_INVALID;
10625 memset(&pds, 0, sizeof(pds));
10626 parse_dial_string(tmp, &pds);
10628 if (ast_strlen_zero(pds.peer)) {
10629 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10630 return res;
10633 if (option_debug > 2)
10634 ast_log(LOG_DEBUG, "Checking device state for device %s\n", pds.peer);
10636 /* SLD: FIXME: second call to find_peer during registration */
10637 if (!(p = find_peer(pds.peer, 1)))
10638 return res;
10640 res = AST_DEVICE_UNAVAILABLE;
10641 if (option_debug > 2)
10642 ast_log(LOG_DEBUG, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10643 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
10645 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
10646 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
10647 /* Peer is registered, or have default IP address
10648 and a valid registration */
10649 if (p->historicms == 0 || p->historicms <= p->maxms)
10650 /* let the core figure out whether it is in use or not */
10651 res = AST_DEVICE_UNKNOWN;
10654 peer_unref(p);
10656 return res;
10659 static struct ast_switch iax2_switch =
10661 name: "IAX2",
10662 description: "IAX Remote Dialplan Switch",
10663 exists: iax2_exists,
10664 canmatch: iax2_canmatch,
10665 exec: iax2_exec,
10666 matchmore: iax2_matchmore,
10669 static char show_stats_usage[] =
10670 "Usage: iax2 show stats\n"
10671 " Display statistics on IAX channel driver.\n";
10673 static char show_cache_usage[] =
10674 "Usage: iax2 show cache\n"
10675 " Display currently cached IAX Dialplan results.\n";
10677 static char show_peer_usage[] =
10678 "Usage: iax2 show peer <name>\n"
10679 " Display details on specific IAX peer\n";
10681 static char prune_realtime_usage[] =
10682 "Usage: iax2 prune realtime [<peername>|all]\n"
10683 " Prunes object(s) from the cache\n";
10685 static char iax2_reload_usage[] =
10686 "Usage: iax2 reload\n"
10687 " Reloads IAX configuration from iax.conf\n";
10689 static char show_prov_usage[] =
10690 "Usage: iax2 provision <host> <template> [forced]\n"
10691 " Provisions the given peer or IP address using a template\n"
10692 " matching either 'template' or '*' if the template is not\n"
10693 " found. If 'forced' is specified, even empty provisioning\n"
10694 " fields will be provisioned as empty fields.\n";
10696 static char show_users_usage[] =
10697 "Usage: iax2 show users [like <pattern>]\n"
10698 " Lists all known IAX2 users.\n"
10699 " Optional regular expression pattern is used to filter the user list.\n";
10701 static char show_channels_usage[] =
10702 "Usage: iax2 show channels\n"
10703 " Lists all currently active IAX channels.\n";
10705 static char show_netstats_usage[] =
10706 "Usage: iax2 show netstats\n"
10707 " Lists network status for all currently active IAX channels.\n";
10709 static char show_threads_usage[] =
10710 "Usage: iax2 show threads\n"
10711 " Lists status of IAX helper threads\n";
10713 static char show_peers_usage[] =
10714 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10715 " Lists all known IAX2 peers.\n"
10716 " Optional 'registered' argument lists only peers with known addresses.\n"
10717 " Optional regular expression pattern is used to filter the peer list.\n";
10719 static char show_firmware_usage[] =
10720 "Usage: iax2 show firmware\n"
10721 " Lists all known IAX firmware images.\n";
10723 static char show_reg_usage[] =
10724 "Usage: iax2 show registry\n"
10725 " Lists all registration requests and status.\n";
10727 static char debug_usage[] =
10728 "Usage: iax2 set debug\n"
10729 " Enables dumping of IAX packets for debugging purposes\n";
10731 static char no_debug_usage[] =
10732 "Usage: iax2 set debug off\n"
10733 " Disables dumping of IAX packets for debugging purposes\n";
10735 static char debug_trunk_usage[] =
10736 "Usage: iax2 set debug trunk\n"
10737 " Requests current status of IAX trunking\n";
10739 static char no_debug_trunk_usage[] =
10740 "Usage: iax2 set debug trunk off\n"
10741 " Requests current status of IAX trunking\n";
10743 static char debug_jb_usage[] =
10744 "Usage: iax2 set debug jb\n"
10745 " Enables jitterbuffer debugging information\n";
10747 static char no_debug_jb_usage[] =
10748 "Usage: iax2 set debug jb off\n"
10749 " Disables jitterbuffer debugging information\n";
10751 static char iax2_test_losspct_usage[] =
10752 "Usage: iax2 test losspct <percentage>\n"
10753 " For testing, throws away <percentage> percent of incoming packets\n";
10755 #ifdef IAXTESTS
10756 static char iax2_test_late_usage[] =
10757 "Usage: iax2 test late <ms>\n"
10758 " For testing, count the next frame as <ms> ms late\n";
10760 static char iax2_test_resync_usage[] =
10761 "Usage: iax2 test resync <ms>\n"
10762 " For testing, adjust all future frames by <ms> ms\n";
10764 static char iax2_test_jitter_usage[] =
10765 "Usage: iax2 test jitter <ms> <pct>\n"
10766 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10767 #endif /* IAXTESTS */
10769 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated = {
10770 { "iax2", "trunk", "debug", NULL },
10771 iax2_do_trunk_debug, NULL,
10772 NULL };
10774 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10775 { "iax2", "jb", "debug", NULL },
10776 iax2_do_jb_debug, NULL,
10777 NULL };
10779 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10780 { "iax2", "no", "debug", NULL },
10781 iax2_no_debug, NULL,
10782 NULL };
10784 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated = {
10785 { "iax2", "no", "trunk", "debug", NULL },
10786 iax2_no_trunk_debug, NULL,
10787 NULL };
10789 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated = {
10790 { "iax2", "no", "jb", "debug", NULL },
10791 iax2_no_jb_debug, NULL,
10792 NULL };
10794 static struct ast_cli_entry cli_iax2[] = {
10795 { { "iax2", "show", "cache", NULL },
10796 iax2_show_cache, "Display IAX cached dialplan",
10797 show_cache_usage, NULL, },
10799 { { "iax2", "show", "channels", NULL },
10800 iax2_show_channels, "List active IAX channels",
10801 show_channels_usage, NULL, },
10803 { { "iax2", "show", "firmware", NULL },
10804 iax2_show_firmware, "List available IAX firmwares",
10805 show_firmware_usage, NULL, },
10807 { { "iax2", "show", "netstats", NULL },
10808 iax2_show_netstats, "List active IAX channel netstats",
10809 show_netstats_usage, NULL, },
10811 { { "iax2", "show", "peers", NULL },
10812 iax2_show_peers, "List defined IAX peers",
10813 show_peers_usage, NULL, },
10815 { { "iax2", "show", "registry", NULL },
10816 iax2_show_registry, "Display IAX registration status",
10817 show_reg_usage, NULL, },
10819 { { "iax2", "show", "stats", NULL },
10820 iax2_show_stats, "Display IAX statistics",
10821 show_stats_usage, NULL, },
10823 { { "iax2", "show", "threads", NULL },
10824 iax2_show_threads, "Display IAX helper thread info",
10825 show_threads_usage, NULL, },
10827 { { "iax2", "show", "users", NULL },
10828 iax2_show_users, "List defined IAX users",
10829 show_users_usage, NULL, },
10831 { { "iax2", "prune", "realtime", NULL },
10832 iax2_prune_realtime, "Prune a cached realtime lookup",
10833 prune_realtime_usage, complete_iax2_show_peer },
10835 { { "iax2", "reload", NULL },
10836 iax2_reload, "Reload IAX configuration",
10837 iax2_reload_usage },
10839 { { "iax2", "show", "peer", NULL },
10840 iax2_show_peer, "Show details on specific IAX peer",
10841 show_peer_usage, complete_iax2_show_peer },
10843 { { "iax2", "set", "debug", NULL },
10844 iax2_do_debug, "Enable IAX debugging",
10845 debug_usage },
10847 { { "iax2", "set", "debug", "trunk", NULL },
10848 iax2_do_trunk_debug, "Enable IAX trunk debugging",
10849 debug_trunk_usage, NULL, &cli_iax2_trunk_debug_deprecated },
10851 { { "iax2", "set", "debug", "jb", NULL },
10852 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
10853 debug_jb_usage, NULL, &cli_iax2_jb_debug_deprecated },
10855 { { "iax2", "set", "debug", "off", NULL },
10856 iax2_no_debug, "Disable IAX debugging",
10857 no_debug_usage, NULL, &cli_iax2_no_debug_deprecated },
10859 { { "iax2", "set", "debug", "trunk", "off", NULL },
10860 iax2_no_trunk_debug, "Disable IAX trunk debugging",
10861 no_debug_trunk_usage, NULL, &cli_iax2_no_trunk_debug_deprecated },
10863 { { "iax2", "set", "debug", "jb", "off", NULL },
10864 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
10865 no_debug_jb_usage, NULL, &cli_iax2_no_jb_debug_deprecated },
10867 { { "iax2", "test", "losspct", NULL },
10868 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
10869 iax2_test_losspct_usage },
10871 { { "iax2", "provision", NULL },
10872 iax2_prov_cmd, "Provision an IAX device",
10873 show_prov_usage, iax2_prov_complete_template_3rd },
10875 #ifdef IAXTESTS
10876 { { "iax2", "test", "late", NULL },
10877 iax2_test_late, "Test the receipt of a late frame",
10878 iax2_test_late_usage },
10880 { { "iax2", "test", "resync", NULL },
10881 iax2_test_resync, "Test a resync in received timestamps",
10882 iax2_test_resync_usage },
10884 { { "iax2", "test", "jitter", NULL },
10885 iax2_test_jitter, "Simulates jitter for testing",
10886 iax2_test_jitter_usage },
10887 #endif /* IAXTESTS */
10890 static int __unload_module(void)
10892 struct iax2_thread *thread = NULL;
10893 int x;
10895 /* Make sure threads do not hold shared resources when they are canceled */
10897 /* Grab the sched lock resource to keep it away from threads about to die */
10898 /* Cancel the network thread, close the net socket */
10899 if (netthreadid != AST_PTHREADT_NULL) {
10900 AST_LIST_LOCK(&iaxq.queue);
10901 ast_mutex_lock(&sched_lock);
10902 pthread_cancel(netthreadid);
10903 ast_cond_signal(&sched_cond);
10904 ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
10905 AST_LIST_UNLOCK(&iaxq.queue);
10906 pthread_join(netthreadid, NULL);
10908 if (schedthreadid != AST_PTHREADT_NULL) {
10909 ast_mutex_lock(&sched_lock);
10910 pthread_cancel(schedthreadid);
10911 ast_cond_signal(&sched_cond);
10912 ast_mutex_unlock(&sched_lock);
10913 pthread_join(schedthreadid, NULL);
10916 /* Call for all threads to halt */
10917 AST_LIST_LOCK(&idle_list);
10918 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list, thread, list) {
10919 AST_LIST_REMOVE_CURRENT(&idle_list, list);
10920 pthread_cancel(thread->threadid);
10922 AST_LIST_TRAVERSE_SAFE_END
10923 AST_LIST_UNLOCK(&idle_list);
10925 AST_LIST_LOCK(&active_list);
10926 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list, thread, list) {
10927 AST_LIST_REMOVE_CURRENT(&active_list, list);
10928 pthread_cancel(thread->threadid);
10930 AST_LIST_TRAVERSE_SAFE_END
10931 AST_LIST_UNLOCK(&active_list);
10933 AST_LIST_LOCK(&dynamic_list);
10934 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list, thread, list) {
10935 AST_LIST_REMOVE_CURRENT(&dynamic_list, list);
10936 pthread_cancel(thread->threadid);
10938 AST_LIST_TRAVERSE_SAFE_END
10939 AST_LIST_UNLOCK(&dynamic_list);
10941 AST_LIST_HEAD_DESTROY(&iaxq.queue);
10943 /* Wait for threads to exit */
10944 while(0 < iaxactivethreadcount)
10945 usleep(10000);
10947 ast_netsock_release(netsock);
10948 ast_netsock_release(outsock);
10949 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10950 if (iaxs[x]) {
10951 iax2_destroy(x);
10954 ast_manager_unregister( "IAXpeers" );
10955 ast_manager_unregister( "IAXnetstats" );
10956 ast_unregister_application(papp);
10957 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10958 ast_unregister_switch(&iax2_switch);
10959 ast_channel_unregister(&iax2_tech);
10960 delete_users();
10961 iax_provision_unload();
10962 sched_context_destroy(sched);
10963 reload_firmware(1);
10965 ast_mutex_destroy(&waresl.lock);
10967 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
10968 ast_mutex_destroy(&iaxsl[x]);
10971 ao2_ref(peers, -1);
10972 ao2_ref(users, -1);
10973 ao2_ref(iax_peercallno_pvts, -1);
10975 return 0;
10978 static int unload_module(void)
10980 ast_custom_function_unregister(&iaxpeer_function);
10981 return __unload_module();
10984 static int peer_set_sock_cb(void *obj, void *arg, int flags)
10986 struct iax2_peer *peer = obj;
10988 if (peer->sockfd < 0)
10989 peer->sockfd = defaultsockfd;
10991 return 0;
10994 static int pvt_hash_cb(const void *obj, const int flags)
10996 const struct chan_iax2_pvt *pvt = obj;
10998 return pvt->peercallno;
11001 static int pvt_cmp_cb(void *obj, void *arg, int flags)
11003 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
11005 /* The frames_received field is used to hold whether we're matching
11006 * against a full frame or not ... */
11008 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
11009 pvt2->frames_received) ? CMP_MATCH : 0;
11012 /*! \brief Load IAX2 module, load configuraiton ---*/
11013 static int load_module(void)
11015 char *config = "iax.conf";
11016 int res = 0;
11017 int x;
11018 struct iax2_registry *reg = NULL;
11020 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
11021 if (!peers)
11022 return AST_MODULE_LOAD_FAILURE;
11023 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
11024 if (!users) {
11025 ao2_ref(peers, -1);
11026 return AST_MODULE_LOAD_FAILURE;
11028 iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb);
11029 if (!iax_peercallno_pvts) {
11030 ao2_ref(peers, -1);
11031 ao2_ref(users, -1);
11032 return AST_MODULE_LOAD_FAILURE;
11035 ast_custom_function_register(&iaxpeer_function);
11037 iax_set_output(iax_debug_output);
11038 iax_set_error(iax_error_output);
11039 jb_setoutput(jb_error_output, jb_warning_output, NULL);
11041 #ifdef HAVE_ZAPTEL
11042 #ifdef ZT_TIMERACK
11043 timingfd = open("/dev/zap/timer", O_RDWR);
11044 if (timingfd < 0)
11045 #endif
11046 timingfd = open("/dev/zap/pseudo", O_RDWR);
11047 if (timingfd < 0)
11048 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
11049 #endif
11051 memset(iaxs, 0, sizeof(iaxs));
11053 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
11054 ast_mutex_init(&iaxsl[x]);
11057 ast_cond_init(&sched_cond, NULL);
11059 io = io_context_create();
11060 sched = sched_context_create();
11062 if (!io || !sched) {
11063 ast_log(LOG_ERROR, "Out of memory\n");
11064 return -1;
11067 netsock = ast_netsock_list_alloc();
11068 if (!netsock) {
11069 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
11070 return -1;
11072 ast_netsock_init(netsock);
11074 outsock = ast_netsock_list_alloc();
11075 if (!outsock) {
11076 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
11077 return -1;
11079 ast_netsock_init(outsock);
11081 ast_mutex_init(&waresl.lock);
11083 AST_LIST_HEAD_INIT(&iaxq.queue);
11085 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
11087 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
11089 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
11090 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats, "Show IAX Netstats" );
11092 if(set_config(config, 0) == -1)
11093 return AST_MODULE_LOAD_DECLINE;
11095 if (ast_channel_register(&iax2_tech)) {
11096 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
11097 __unload_module();
11098 return -1;
11101 if (ast_register_switch(&iax2_switch))
11102 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
11104 res = start_network_thread();
11105 if (!res) {
11106 if (option_verbose > 1)
11107 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
11108 } else {
11109 ast_log(LOG_ERROR, "Unable to start network thread\n");
11110 ast_netsock_release(netsock);
11111 ast_netsock_release(outsock);
11114 AST_LIST_LOCK(&registrations);
11115 AST_LIST_TRAVERSE(&registrations, reg, entry)
11116 iax2_do_register(reg);
11117 AST_LIST_UNLOCK(&registrations);
11119 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
11120 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
11122 reload_firmware(0);
11123 iax_provision_reload();
11124 return res;
11127 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
11128 .load = load_module,
11129 .unload = unload_module,
11130 .reload = reload,