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.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
34 <depend>res_features</depend>
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/zapata.h"
58 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
60 #include "asterisk/lock.h"
61 #include "asterisk/frame.h"
62 #include "asterisk/channel.h"
63 #include "asterisk/module.h"
64 #include "asterisk/pbx.h"
65 #include "asterisk/sched.h"
66 #include "asterisk/io.h"
67 #include "asterisk/config.h"
68 #include "asterisk/cli.h"
69 #include "asterisk/translate.h"
70 #include "asterisk/md5.h"
71 #include "asterisk/cdr.h"
72 #include "asterisk/crypto.h"
73 #include "asterisk/acl.h"
74 #include "asterisk/manager.h"
75 #include "asterisk/callerid.h"
76 #include "asterisk/app.h"
77 #include "asterisk/astdb.h"
78 #include "asterisk/musiconhold.h"
79 #include "asterisk/features.h"
80 #include "asterisk/utils.h"
81 #include "asterisk/causes.h"
82 #include "asterisk/localtime.h"
83 #include "asterisk/aes.h"
84 #include "asterisk/dnsmgr.h"
85 #include "asterisk/devicestate.h"
86 #include "asterisk/netsock.h"
87 #include "asterisk/stringfields.h"
88 #include "asterisk/linkedlists.h"
89 #include "asterisk/event.h"
90 #include "asterisk/astobj2.h"
93 #include "iax2-parser.h"
94 #include "iax2-provision.h"
95 #include "jitterbuf.h"
97 /* Define SCHED_MULTITHREADED to run the scheduler in a special
98 multithreaded mode. */
99 #define SCHED_MULTITHREADED
101 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
102 thread is actually doing. */
103 #define DEBUG_SCHED_MULTITHREAD
107 static int nochecksums = 0;
111 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
112 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
114 #define DEFAULT_THREAD_COUNT 10
115 #define DEFAULT_MAX_THREAD_COUNT 100
116 #define DEFAULT_RETRY_TIME 1000
117 #define MEMORY_SIZE 100
118 #define DEFAULT_DROP 3
119 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
120 but keeps the division between trunked and non-trunked better. */
121 #define TRUNK_CALL_START 0x4000
123 #define DEBUG_SUPPORT
125 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
127 /* Sample over last 100 units to determine historic jitter */
130 static struct ast_codec_pref prefs;
132 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
135 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
136 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
137 #define MAX_TRUNK_MTU 1240
139 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
140 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
143 static char context[80] = "default";
145 static char language[MAX_LANGUAGE] = "";
146 static char regcontext[AST_MAX_CONTEXT] = "";
148 static int maxauthreq = 3;
149 static int max_retries = 4;
150 static int ping_time = 21;
151 static int lagrq_time = 10;
152 static int maxtrunkcall = TRUNK_CALL_START;
153 static int maxnontrunkcall = 1;
154 static int maxjitterbuffer=1000;
155 static int resyncthreshold=1000;
156 static int maxjitterinterps=10;
157 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
159 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
161 static int trunkfreq = 20;
162 static int trunkmaxsize = MAX_TRUNKDATA;
164 static int authdebug = 1;
165 static int autokill = 0;
166 static int iaxcompat = 0;
168 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
170 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
172 static unsigned int tos = 0;
174 static unsigned int cos = 0;
176 static int min_reg_expire;
177 static int max_reg_expire;
179 static int srvlookup = 0;
181 static int timingfd = -1; /* Timing file descriptor */
183 static struct ast_netsock_list *netsock;
184 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
185 static int defaultsockfd = -1;
187 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
190 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
192 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
193 ~AST_FORMAT_SLINEAR & \
198 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
200 ~AST_FORMAT_G726_AAL2 & \
203 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
207 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
208 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
209 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
211 static struct io_context *io;
212 static struct sched_context *sched;
214 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
216 static int iaxdebug = 0;
218 static int iaxtrunkdebug = 0;
220 static int test_losspct = 0;
222 static int test_late = 0;
223 static int test_resync = 0;
224 static int test_jit = 0;
225 static int test_jitpct = 0;
226 #endif /* IAXTESTS */
228 static char accountcode[AST_MAX_ACCOUNT_CODE];
229 static char mohinterpret[MAX_MUSICCLASS];
230 static char mohsuggest[MAX_MUSICCLASS];
231 static int amaflags = 0;
233 static int delayreject = 0;
234 static int iax2_encryption = 0;
236 static struct ast_flags globalflags = { 0 };
238 static pthread_t netthreadid = AST_PTHREADT_NULL;
239 static pthread_t schedthreadid = AST_PTHREADT_NULL;
240 AST_MUTEX_DEFINE_STATIC(sched_lock);
241 static ast_cond_t sched_cond;
244 IAX_STATE_STARTED = (1 << 0),
245 IAX_STATE_AUTHENTICATED = (1 << 1),
246 IAX_STATE_TBD = (1 << 2),
247 IAX_STATE_UNCHANGED = (1 << 3),
250 struct iax2_context {
251 char context[AST_MAX_CONTEXT];
252 struct iax2_context *next;
256 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
257 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
258 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
259 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
260 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
261 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
262 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
263 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
264 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
265 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
266 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
267 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
268 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
269 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
270 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
271 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
272 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
273 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
274 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
275 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
276 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
277 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
278 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
279 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
280 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
281 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
282 response, so that we've achieved a three-way handshake with
283 them before sending voice or anything else*/
286 static int global_rtautoclear = 120;
288 static int reload_config(void);
291 AST_DECLARE_STRING_FIELDS(
292 AST_STRING_FIELD(name);
293 AST_STRING_FIELD(secret);
294 AST_STRING_FIELD(dbsecret);
295 AST_STRING_FIELD(accountcode);
296 AST_STRING_FIELD(mohinterpret);
297 AST_STRING_FIELD(mohsuggest);
298 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
299 AST_STRING_FIELD(language);
300 AST_STRING_FIELD(cid_num);
301 AST_STRING_FIELD(cid_name);
310 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
311 int curauthreq; /*!< Current number of outstanding AUTHREQs */
312 struct ast_codec_pref prefs;
314 struct iax2_context *contexts;
315 struct ast_variable *vars;
319 AST_DECLARE_STRING_FIELDS(
320 AST_STRING_FIELD(name);
321 AST_STRING_FIELD(username);
322 AST_STRING_FIELD(secret);
323 AST_STRING_FIELD(dbsecret);
324 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
326 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
327 AST_STRING_FIELD(context); /*!< For transfers only */
328 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
329 AST_STRING_FIELD(mailbox); /*!< Mailbox */
330 AST_STRING_FIELD(mohinterpret);
331 AST_STRING_FIELD(mohsuggest);
332 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
333 /* Suggested caller id if registering */
334 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
335 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
336 AST_STRING_FIELD(zonetag); /*!< Time Zone */
338 struct ast_codec_pref prefs;
339 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
340 struct sockaddr_in addr;
342 int sockfd; /*!< Socket to use for transmission */
347 /* Dynamic Registration fields */
348 struct sockaddr_in defaddr; /*!< Default address if there is one */
349 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
350 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
352 int expire; /*!< Schedule entry for expiry */
353 int expiry; /*!< How soon to expire */
354 int capability; /*!< Capability */
357 int callno; /*!< Call number of POKE request */
358 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
359 int lastms; /*!< How long last response took (in ms), or -1 for no response */
360 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
362 int pokefreqok; /*!< How often to check if the host is up */
363 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
364 int historicms; /*!< How long recent average responses took */
365 int smoothing; /*!< Sample over how many units to determine historic ms */
367 struct ast_event_sub *mwi_event_sub;
372 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
374 struct iax2_trunk_peer {
377 struct sockaddr_in addr;
378 struct timeval txtrunktime; /*!< Transmit trunktime */
379 struct timeval rxtrunktime; /*!< Receive trunktime */
380 struct timeval lasttxtime; /*!< Last transmitted trunktime */
381 struct timeval trunkact; /*!< Last trunk activity */
382 unsigned int lastsent; /*!< Last sent time */
383 /* Trunk data and length */
384 unsigned char *trunkdata;
385 unsigned int trunkdatalen;
386 unsigned int trunkdataalloc;
390 AST_LIST_ENTRY(iax2_trunk_peer) list;
393 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
395 struct iax_firmware {
396 AST_LIST_ENTRY(iax_firmware) list;
400 struct ast_iax2_firmware_header *fwh;
405 REG_STATE_UNREGISTERED = 0,
408 REG_STATE_REGISTERED,
414 enum iax_transfer_state {
419 TRANSFER_PASSTHROUGH,
423 TRANSFER_MPASSTHROUGH,
428 struct iax2_registry {
429 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
431 char secret[80]; /*!< Password or key name in []'s */
432 int expire; /*!< Sched ID of expiration */
433 int refresh; /*!< How often to refresh */
434 enum iax_reg_state regstate;
435 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
436 int callno; /*!< Associated call number if applicable */
437 struct sockaddr_in us; /*!< Who the server thinks we are */
438 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
439 AST_LIST_ENTRY(iax2_registry) entry;
442 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
444 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
445 #define MIN_RETRY_TIME 100
446 #define MAX_RETRY_TIME 10000
448 #define MAX_JITTER_BUFFER 50
449 #define MIN_JITTER_BUFFER 10
451 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
453 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
455 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
456 #define TS_GAP_FOR_JB_RESYNC 5000
458 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
459 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
460 static int iaxdynamicthreadcount = 0;
461 static int iaxactivethreadcount = 0;
475 struct chan_iax2_pvt {
476 /*! Socket to send/receive on for this call */
478 /*! Last received voice format */
480 /*! Last received video format */
482 /*! Last sent voice format */
484 /*! Last sent video format */
486 /*! What we are capable of sending */
488 /*! Last received timestamp */
490 /*! Last sent timestamp - never send the same timestamp twice in a single call */
491 unsigned int lastsent;
492 /*! Next outgoing timestamp if everything is good */
493 unsigned int nextpred;
494 /*! True if the last voice we transmitted was not silence/CNG */
495 unsigned int notsilenttx:1;
497 unsigned int pingtime;
498 /*! Max time for initial response */
501 struct sockaddr_in addr;
502 /*! Actual used codec preferences */
503 struct ast_codec_pref prefs;
504 /*! Requested codec preferences */
505 struct ast_codec_pref rprefs;
506 /*! Our call number */
507 unsigned short callno;
509 unsigned short peercallno;
510 /*! Negotiated format, this is only used to remember what format was
511 chosen for an unauthenticated call so that the channel can get
512 created later using the right format */
514 /*! Peer selected format */
516 /*! Peer capability */
518 /*! timeval that we base our transmission on */
519 struct timeval offset;
520 /*! timeval that we base our delivery on */
521 struct timeval rxcore;
522 /*! The jitterbuffer */
524 /*! active jb read scheduler id */
528 /*! Error, as discovered by the manager */
530 /*! Owner if we have one */
531 struct ast_channel *owner;
532 /*! What's our state? */
533 struct ast_flags state;
534 /*! Expiry (optional) */
536 /*! Next outgoing sequence number */
537 unsigned char oseqno;
538 /*! Next sequence number they have not yet acknowledged */
539 unsigned char rseqno;
540 /*! Next incoming sequence number */
541 unsigned char iseqno;
542 /*! Last incoming sequence number we have acknowledged */
543 unsigned char aseqno;
545 AST_DECLARE_STRING_FIELDS(
547 AST_STRING_FIELD(peer);
548 /*! Default Context */
549 AST_STRING_FIELD(context);
550 /*! Caller ID if available */
551 AST_STRING_FIELD(cid_num);
552 AST_STRING_FIELD(cid_name);
553 /*! Hidden Caller ID (i.e. ANI) if appropriate */
554 AST_STRING_FIELD(ani);
556 AST_STRING_FIELD(dnid);
558 AST_STRING_FIELD(rdnis);
559 /*! Requested Extension */
560 AST_STRING_FIELD(exten);
561 /*! Expected Username */
562 AST_STRING_FIELD(username);
563 /*! Expected Secret */
564 AST_STRING_FIELD(secret);
566 AST_STRING_FIELD(challenge);
567 /*! Public keys permitted keys for incoming authentication */
568 AST_STRING_FIELD(inkeys);
569 /*! Private key for outgoing authentication */
570 AST_STRING_FIELD(outkey);
571 /*! Preferred language */
572 AST_STRING_FIELD(language);
573 /*! Hostname/peername for naming purposes */
574 AST_STRING_FIELD(host);
576 AST_STRING_FIELD(dproot);
577 AST_STRING_FIELD(accountcode);
578 AST_STRING_FIELD(mohinterpret);
579 AST_STRING_FIELD(mohsuggest);
580 /*! received OSP token */
581 AST_STRING_FIELD(osptoken);
584 /*! permitted authentication methods */
586 /*! permitted encryption methods */
588 /*! Encryption AES-128 Key */
589 ast_aes_encrypt_key ecx;
590 /*! Decryption AES-128 Key */
591 ast_aes_decrypt_key dcx;
592 /*! 32 bytes of semi-random data */
593 unsigned char semirand[32];
594 /*! Associated registry */
595 struct iax2_registry *reg;
596 /*! Associated peer for poking */
597 struct iax2_peer *peerpoke;
602 /*! Transferring status */
603 enum iax_transfer_state transferring;
604 /*! Transfer identifier */
606 /*! Who we are IAX transferring to */
607 struct sockaddr_in transfer;
608 /*! What's the new call number for the transfer */
609 unsigned short transfercallno;
610 /*! Transfer encrypt AES-128 Key */
611 ast_aes_encrypt_key tdcx;
613 /*! Status of knowledge of peer ADSI capability */
616 /*! Who we are bridged to */
617 unsigned short bridgecallno;
619 int pingid; /*!< Transmit PING request */
620 int lagid; /*!< Retransmit lag request */
621 int autoid; /*!< Auto hangup for Dialplan requestor */
622 int authid; /*!< Authentication rejection ID */
623 int authfail; /*!< Reason to report failure */
624 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
629 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
630 struct ast_variable *vars;
631 /*! last received remote rr */
632 struct iax_rr remote_rr;
633 /*! Current base time: (just for stats) */
635 /*! Dropped frame count: (just for stats) */
637 /*! received frame count: (just for stats) */
642 * \brief a list of frames that may need to be retransmitted
644 * \note The contents of this list do not need to be explicitly destroyed
645 * on module unload. This is because all active calls are destroyed, and
646 * all frames in this queue will get destroyed as a part of that process.
648 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
651 * This module will get much higher performance when doing a lot of
652 * user and peer lookups if the number of buckets is increased from 1.
653 * However, to maintain old behavior for Asterisk 1.4, these are set to
654 * 1 by default. When using multiple buckets, search order through these
655 * containers is considered random, so you will not be able to depend on
656 * the order the entires are specified in iax.conf for matching order. */
658 #define MAX_PEER_BUCKETS 17
660 #define MAX_PEER_BUCKETS 563
662 static struct ao2_container *peers;
664 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
665 static struct ao2_container *users;
667 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
670 /*! Extension exists */
671 CACHE_FLAG_EXISTS = (1 << 0),
672 /*! Extension is nonexistent */
673 CACHE_FLAG_NONEXISTENT = (1 << 1),
674 /*! Extension can exist */
675 CACHE_FLAG_CANEXIST = (1 << 2),
676 /*! Waiting to hear back response */
677 CACHE_FLAG_PENDING = (1 << 3),
679 CACHE_FLAG_TIMEOUT = (1 << 4),
680 /*! Request transmitted */
681 CACHE_FLAG_TRANSMITTED = (1 << 5),
683 CACHE_FLAG_UNKNOWN = (1 << 6),
685 CACHE_FLAG_MATCHMORE = (1 << 7),
688 struct iax2_dpcache {
689 char peercontext[AST_MAX_CONTEXT];
690 char exten[AST_MAX_EXTENSION];
692 struct timeval expiry;
694 unsigned short callno;
696 AST_LIST_ENTRY(iax2_dpcache) cache_list;
697 AST_LIST_ENTRY(iax2_dpcache) peer_list;
700 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
702 static void reg_source_db(struct iax2_peer *p);
703 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
705 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
706 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
707 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
709 enum iax2_thread_iostate {
712 IAX_IOSTATE_PROCESSING,
713 IAX_IOSTATE_SCHEDREADY,
716 enum iax2_thread_type {
717 IAX_THREAD_TYPE_POOL,
718 IAX_THREAD_TYPE_DYNAMIC,
721 struct iax2_pkt_buf {
722 AST_LIST_ENTRY(iax2_pkt_buf) entry;
724 unsigned char buf[1];
728 AST_LIST_ENTRY(iax2_thread) list;
729 enum iax2_thread_type type;
730 enum iax2_thread_iostate iostate;
731 #ifdef SCHED_MULTITHREADED
732 void (*schedfunc)(const void *);
733 const void *scheddata;
735 #ifdef DEBUG_SCHED_MULTITHREAD
741 struct sockaddr_in iosin;
742 unsigned char readbuf[4096];
750 unsigned int ready_for_signal:1;
751 /*! if this thread is processing a full frame,
752 some information about that frame will be stored
753 here, so we can avoid dispatching any more full
754 frames for that callno to other threads */
756 unsigned short callno;
757 struct sockaddr_in sin;
761 /*! Queued up full frames for processing. If more full frames arrive for
762 * a call which this thread is already processing a full frame for, they
763 * are queued up here. */
764 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
768 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
769 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
770 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
772 static void *iax2_process_thread(void *data);
774 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
776 ast_mutex_lock(lock);
777 ast_cond_signal(cond);
778 ast_mutex_unlock(lock);
781 static void iax_debug_output(const char *data)
784 ast_verbose("%s", data);
787 static void iax_error_output(const char *data)
789 ast_log(LOG_WARNING, "%s", data);
792 static void jb_error_output(const char *fmt, ...)
798 vsnprintf(buf, sizeof(buf), fmt, args);
801 ast_log(LOG_ERROR, buf);
804 static void jb_warning_output(const char *fmt, ...)
810 vsnprintf(buf, sizeof(buf), fmt, args);
813 ast_log(LOG_WARNING, buf);
816 static void jb_debug_output(const char *fmt, ...)
822 vsnprintf(buf, sizeof(buf), fmt, args);
829 * \brief an array of iax2 pvt structures
831 * The container for active chan_iax2_pvt structures is implemented as an
832 * array for extremely quick direct access to the correct pvt structure
833 * based on the local call number. The local call number is used as the
834 * index into the array where the associated pvt structure is stored.
836 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
838 * \brief chan_iax2_pvt structure locks
840 * These locks are used when accessing a pvt structure in the iaxs array.
841 * The index used here is the same as used in the iaxs array. It is the
842 * local call number for the associated pvt struct.
844 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
846 * \brief The last time a call number was used
848 * It is important to know the last time that a call number was used locally so
849 * that it is not used again too soon. The reason for this is the same as the
850 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
852 * For example, say that a call is up. Then, the remote side sends a HANGUP,
853 * which we respond to with an ACK. However, there is no way to know whether
854 * the ACK made it there successfully. If it were to get lost, the remote
855 * side may retransmit the HANGUP. If in the meantime, this call number has
856 * been reused locally, given the right set of circumstances, this retransmitted
857 * HANGUP could potentially improperly hang up the new session. So, to avoid
858 * this potential issue, we must wait a specified timeout period before reusing
859 * a local call number.
861 * The specified time that we must wait before reusing a local call number is
862 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
864 static struct timeval lastused[IAX_MAX_CALLS];
866 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);
867 static int expire_registry(const void *data);
868 static int iax2_answer(struct ast_channel *c);
869 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
870 static int iax2_devicestate(void *data);
871 static int iax2_digit_begin(struct ast_channel *c, char digit);
872 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
873 static int iax2_do_register(struct iax2_registry *reg);
874 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
875 static int iax2_hangup(struct ast_channel *c);
876 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
877 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
878 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
879 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
880 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
881 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
882 static int iax2_sendtext(struct ast_channel *c, const char *text);
883 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
884 static int iax2_transfer(struct ast_channel *c, const char *dest);
885 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
886 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
887 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
888 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
889 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
890 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
891 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
892 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
893 static struct ast_frame *iax2_read(struct ast_channel *c);
894 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
895 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
896 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
897 static void prune_peers(void);
898 static void *iax2_dup_variable_datastore(void *);
899 static void iax2_free_variable_datastore(void *);
901 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
902 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
904 static const struct ast_channel_tech iax2_tech = {
906 .description = tdesc,
907 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
908 .properties = AST_CHAN_TP_WANTSJITTER,
909 .requester = iax2_request,
910 .devicestate = iax2_devicestate,
911 .send_digit_begin = iax2_digit_begin,
912 .send_digit_end = iax2_digit_end,
913 .send_text = iax2_sendtext,
914 .send_image = iax2_sendimage,
915 .send_html = iax2_sendhtml,
917 .hangup = iax2_hangup,
918 .answer = iax2_answer,
921 .write_video = iax2_write,
922 .indicate = iax2_indicate,
923 .setoption = iax2_setoption,
924 .bridge = iax2_bridge,
925 .transfer = iax2_transfer,
927 .func_channel_read = acf_channel_read,
928 .func_channel_write = acf_channel_write,
931 static void mwi_event_cb(const struct ast_event *event, void *userdata)
933 /* The MWI subscriptions exist just so the core knows we care about those
934 * mailboxes. However, we just grab the events out of the cache when it
935 * is time to send MWI, since it is only sent with a REGACK. */
938 /*! \brief Send manager event at call setup to link between Asterisk channel name
939 and IAX2 call identifiers */
940 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
942 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
943 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
944 pvt->owner ? pvt->owner->name : "",
945 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
949 static struct ast_datastore_info iax2_variable_datastore_info = {
950 .type = "IAX2_VARIABLE",
951 .duplicate = iax2_dup_variable_datastore,
952 .destroy = iax2_free_variable_datastore,
955 static void *iax2_dup_variable_datastore(void *old)
957 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
958 struct ast_var_t *oldvar, *newvar;
960 newlist = ast_calloc(sizeof(*newlist), 1);
962 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
966 AST_LIST_HEAD_INIT(newlist);
967 AST_LIST_LOCK(oldlist);
968 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
969 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
971 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
973 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
975 AST_LIST_UNLOCK(oldlist);
979 static void iax2_free_variable_datastore(void *old)
981 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
982 struct ast_var_t *oldvar;
984 AST_LIST_LOCK(oldlist);
985 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
988 AST_LIST_UNLOCK(oldlist);
989 AST_LIST_HEAD_DESTROY(oldlist);
994 /* WARNING: insert_idle_thread should only ever be called within the
995 * context of an iax2_process_thread() thread.
997 static void insert_idle_thread(struct iax2_thread *thread)
999 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1000 AST_LIST_LOCK(&dynamic_list);
1001 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1002 AST_LIST_UNLOCK(&dynamic_list);
1004 AST_LIST_LOCK(&idle_list);
1005 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1006 AST_LIST_UNLOCK(&idle_list);
1012 static struct iax2_thread *find_idle_thread(void)
1014 struct iax2_thread *thread = NULL;
1016 /* Pop the head of the idle list off */
1017 AST_LIST_LOCK(&idle_list);
1018 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1019 AST_LIST_UNLOCK(&idle_list);
1021 /* If we popped a thread off the idle list, just return it */
1023 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1027 /* Pop the head of the dynamic list off */
1028 AST_LIST_LOCK(&dynamic_list);
1029 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1030 AST_LIST_UNLOCK(&dynamic_list);
1032 /* If we popped a thread off the dynamic list, just return it */
1034 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1038 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1039 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1042 /* Set default values */
1043 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1044 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1046 /* Initialize lock and condition */
1047 ast_mutex_init(&thread->lock);
1048 ast_cond_init(&thread->cond, NULL);
1050 /* Create thread and send it on it's way */
1051 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1052 ast_cond_destroy(&thread->cond);
1053 ast_mutex_destroy(&thread->lock);
1058 /* this thread is not processing a full frame (since it is idle),
1059 so ensure that the field for the full frame call number is empty */
1060 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1062 /* Wait for the thread to be ready before returning it to the caller */
1063 while (!thread->ready_for_signal)
1069 #ifdef SCHED_MULTITHREADED
1070 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1072 struct iax2_thread *thread = NULL;
1073 static time_t lasterror;
1076 thread = find_idle_thread();
1078 if (thread != NULL) {
1079 thread->schedfunc = func;
1080 thread->scheddata = data;
1081 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1082 #ifdef DEBUG_SCHED_MULTITHREAD
1083 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1085 signal_condition(&thread->lock, &thread->cond);
1090 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
1095 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1098 static int iax2_sched_replace(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1102 res = ast_sched_replace(old_id, con, when, callback, data);
1103 signal_condition(&sched_lock, &sched_cond);
1108 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1112 res = ast_sched_add(con, when, callback, data);
1113 signal_condition(&sched_lock, &sched_cond);
1118 static int send_ping(const void *data);
1120 static void __send_ping(const void *data)
1122 int callno = (long)data;
1123 ast_mutex_lock(&iaxsl[callno]);
1124 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
1125 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1126 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1128 ast_mutex_unlock(&iaxsl[callno]);
1131 static int send_ping(const void *data)
1133 #ifdef SCHED_MULTITHREADED
1134 if (schedule_action(__send_ping, data))
1140 static int get_encrypt_methods(const char *s)
1143 if (!strcasecmp(s, "aes128"))
1144 e = IAX_ENCRYPT_AES128;
1145 else if (ast_true(s))
1146 e = IAX_ENCRYPT_AES128;
1152 static int send_lagrq(const void *data);
1154 static void __send_lagrq(const void *data)
1156 int callno = (long)data;
1157 /* Ping only if it's real not if it's bridged */
1158 ast_mutex_lock(&iaxsl[callno]);
1159 if (iaxs[callno] && iaxs[callno]->lagid != -1) {
1160 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1161 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1163 ast_mutex_unlock(&iaxsl[callno]);
1166 static int send_lagrq(const void *data)
1168 #ifdef SCHED_MULTITHREADED
1169 if (schedule_action(__send_lagrq, data))
1175 static unsigned char compress_subclass(int subclass)
1179 /* If it's 128 or smaller, just return it */
1180 if (subclass < IAX_FLAG_SC_LOG)
1182 /* Otherwise find its power */
1183 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1184 if (subclass & (1 << x)) {
1186 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1192 return power | IAX_FLAG_SC_LOG;
1195 static int uncompress_subclass(unsigned char csub)
1197 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1198 if (csub & IAX_FLAG_SC_LOG) {
1199 /* special case for 'compressed' -1 */
1203 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1210 * \note The only member of the peer passed here guaranteed to be set is the name field
1212 static int peer_hash_cb(const void *obj, const int flags)
1214 const struct iax2_peer *peer = obj;
1216 return ast_str_hash(peer->name);
1220 * \note The only member of the peer passed here guaranteed to be set is the name field
1222 static int peer_cmp_cb(void *obj, void *arg, int flags)
1224 struct iax2_peer *peer = obj, *peer2 = arg;
1226 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1230 * \note The only member of the user passed here guaranteed to be set is the name field
1232 static int user_hash_cb(const void *obj, const int flags)
1234 const struct iax2_user *user = obj;
1236 return ast_str_hash(user->name);
1240 * \note The only member of the user passed here guaranteed to be set is the name field
1242 static int user_cmp_cb(void *obj, void *arg, int flags)
1244 struct iax2_user *user = obj, *user2 = arg;
1246 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1250 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1251 * so do not call it with a pvt lock held.
1253 static struct iax2_peer *find_peer(const char *name, int realtime)
1255 struct iax2_peer *peer = NULL;
1256 struct iax2_peer tmp_peer = {
1260 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1262 /* Now go for realtime if applicable */
1263 if(!peer && realtime)
1264 peer = realtime_peer(name, NULL);
1269 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1275 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1281 static inline struct iax2_user *user_ref(struct iax2_user *user)
1287 static inline struct iax2_user *user_unref(struct iax2_user *user)
1293 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1295 struct iax2_peer *peer = NULL;
1297 struct ao2_iterator i;
1299 i = ao2_iterator_init(peers, 0);
1300 while ((peer = ao2_iterator_next(&i))) {
1301 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1302 (peer->addr.sin_port == sin.sin_port)) {
1303 ast_copy_string(host, peer->name, len);
1312 peer = realtime_peer(NULL, &sin);
1314 ast_copy_string(host, peer->name, len);
1323 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1325 struct chan_iax2_pvt *tmp;
1328 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1331 if (ast_string_field_init(tmp, 32)) {
1344 ast_string_field_set(tmp,exten, "s");
1345 ast_string_field_set(tmp,host, host);
1349 jbconf.max_jitterbuf = maxjitterbuffer;
1350 jbconf.resync_threshold = resyncthreshold;
1351 jbconf.max_contig_interp = maxjitterinterps;
1352 jbconf.target_extra = jittertargetextra;
1353 jb_setconf(tmp->jb,&jbconf);
1355 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1360 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1362 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1364 size_t afdatalen = new->afdatalen;
1365 memcpy(new, fr, sizeof(*new));
1366 iax_frame_wrap(new, &fr->af);
1367 new->afdatalen = afdatalen;
1370 new->direction = DIRECTION_INGRESS;
1376 #define NEW_PREVENT 0
1380 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur)
1382 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1383 (cur->addr.sin_port == sin->sin_port)) {
1384 /* This is the main host */
1385 if ((cur->peercallno == callno) ||
1386 ((dcallno == cur->callno) && !cur->peercallno)) {
1387 /* That's us. Be sure we keep track of the peer call number */
1391 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1392 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1393 /* We're transferring */
1394 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1400 static void update_max_trunk(void)
1402 int max = TRUNK_CALL_START;
1404 /* XXX Prolly don't need locks here XXX */
1405 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1411 ast_debug(1, "New max trunk callno is %d\n", max);
1414 static void update_max_nontrunk(void)
1418 /* XXX Prolly don't need locks here XXX */
1419 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1423 maxnontrunkcall = max;
1425 ast_debug(1, "New max nontrunk callno is %d\n", max);
1428 static int make_trunk(unsigned short callno, int locked)
1432 struct timeval now = ast_tvnow();
1433 if (iaxs[callno]->oseqno) {
1434 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1437 if (callno & TRUNK_CALL_START) {
1438 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1441 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1442 ast_mutex_lock(&iaxsl[x]);
1443 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1444 iaxs[x] = iaxs[callno];
1445 iaxs[x]->callno = x;
1446 iaxs[callno] = NULL;
1447 /* Update the two timers that should have been started */
1448 iaxs[x]->pingid = iax2_sched_replace(iaxs[x]->pingid, sched,
1449 ping_time * 1000, send_ping, (void *)(long)x);
1450 iaxs[x]->lagid = iax2_sched_replace(iaxs[x]->lagid, sched,
1451 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1453 ast_mutex_unlock(&iaxsl[callno]);
1456 ast_mutex_unlock(&iaxsl[x]);
1459 ast_mutex_unlock(&iaxsl[x]);
1461 if (x >= IAX_MAX_CALLS - 1) {
1462 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1465 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1466 /* We move this call from a non-trunked to a trunked call */
1468 update_max_nontrunk();
1473 * \todo XXX Note that this function contains a very expensive operation that
1474 * happens for *every* incoming media frame. It iterates through every
1475 * possible call number, locking and unlocking each one, to try to match the
1476 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1477 * So, for a call with a local call number of 20000, every incoming audio
1478 * frame would require 20000 mutex lock and unlock operations. Ouch.
1480 * It's a shame that IAX2 media frames carry the source call number instead of
1481 * the destination call number. If they did, this lookup wouldn't be needed.
1482 * However, it's too late to change that now. Instead, we need to come up with
1483 * a better way of indexing active calls so that these frequent lookups are not
1486 * \note Calling this function while holding another pvt lock can cause a deadlock.
1488 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd)
1495 if (new <= NEW_ALLOW) {
1496 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1497 ast_mutex_lock(&iaxsl[x]);
1499 /* Look for an exact match */
1500 if (match(sin, callno, dcallno, iaxs[x])) {
1504 ast_mutex_unlock(&iaxsl[x]);
1506 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1507 ast_mutex_lock(&iaxsl[x]);
1509 /* Look for an exact match */
1510 if (match(sin, callno, dcallno, iaxs[x])) {
1514 ast_mutex_unlock(&iaxsl[x]);
1517 if ((res < 1) && (new >= NEW_ALLOW)) {
1518 /* It may seem odd that we look through the peer list for a name for
1519 * this *incoming* call. Well, it is weird. However, users don't
1520 * have an IP address/port number that we can match against. So,
1521 * this is just checking for a peer that has that IP/port and
1522 * assuming that we have a user of the same name. This isn't always
1523 * correct, but it will be changed if needed after authentication. */
1524 if (!iax2_getpeername(*sin, host, sizeof(host)))
1525 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1527 for (x=1;x<TRUNK_CALL_START;x++) {
1528 /* Find first unused call number that hasn't been used in a while */
1529 ast_mutex_lock(&iaxsl[x]);
1530 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1531 ast_mutex_unlock(&iaxsl[x]);
1533 /* We've still got lock held if we found a spot */
1534 if (x >= TRUNK_CALL_START) {
1535 ast_log(LOG_WARNING, "No more space\n");
1538 iaxs[x] = new_iax(sin, host);
1539 update_max_nontrunk();
1542 ast_debug(1, "Creating new call structure %d\n", x);
1543 iaxs[x]->sockfd = sockfd;
1544 iaxs[x]->addr.sin_port = sin->sin_port;
1545 iaxs[x]->addr.sin_family = sin->sin_family;
1546 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1547 iaxs[x]->peercallno = callno;
1548 iaxs[x]->callno = x;
1549 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1550 iaxs[x]->expiry = min_reg_expire;
1551 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1552 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1553 iaxs[x]->amaflags = amaflags;
1554 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1556 ast_string_field_set(iaxs[x], accountcode, accountcode);
1557 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1558 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1560 ast_log(LOG_WARNING, "Out of resources\n");
1561 ast_mutex_unlock(&iaxsl[x]);
1564 ast_mutex_unlock(&iaxsl[x]);
1570 static void iax2_frame_free(struct iax_frame *fr)
1572 if (fr->retrans > -1)
1573 ast_sched_del(sched, fr->retrans);
1578 * \brief Queue a frame to a call's owning asterisk channel
1580 * \pre This function assumes that iaxsl[callno] is locked when called.
1582 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1583 * was valid before calling it, it may no longer be valid after calling it.
1584 * This function may unlock and lock the mutex associated with this callno,
1585 * meaning that another thread may grab it and destroy the call.
1587 static int iax2_queue_frame(int callno, struct ast_frame *f)
1590 if (iaxs[callno] && iaxs[callno]->owner) {
1591 if (ast_channel_trylock(iaxs[callno]->owner)) {
1592 /* Avoid deadlock by pausing and trying again */
1593 ast_mutex_unlock(&iaxsl[callno]);
1595 ast_mutex_lock(&iaxsl[callno]);
1597 ast_queue_frame(iaxs[callno]->owner, f);
1598 ast_channel_unlock(iaxs[callno]->owner);
1608 * \brief Queue a hangup frame on the ast_channel owner
1610 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1611 * is active for the given call number.
1613 * \pre Assumes lock for callno is already held.
1615 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1616 * was valid before calling it, it may no longer be valid after calling it.
1617 * This function may unlock and lock the mutex associated with this callno,
1618 * meaning that another thread may grab it and destroy the call.
1620 static int iax2_queue_hangup(int callno)
1623 if (iaxs[callno] && iaxs[callno]->owner) {
1624 if (ast_channel_trylock(iaxs[callno]->owner)) {
1625 /* Avoid deadlock by pausing and trying again */
1626 ast_mutex_unlock(&iaxsl[callno]);
1628 ast_mutex_lock(&iaxsl[callno]);
1630 ast_queue_hangup(iaxs[callno]->owner);
1631 ast_channel_unlock(iaxs[callno]->owner);
1641 * \brief Queue a control frame on the ast_channel owner
1643 * This function queues a control frame on the owner of the IAX2 pvt struct that
1644 * is active for the given call number.
1646 * \pre Assumes lock for callno is already held.
1648 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1649 * was valid before calling it, it may no longer be valid after calling it.
1650 * This function may unlock and lock the mutex associated with this callno,
1651 * meaning that another thread may grab it and destroy the call.
1653 static int iax2_queue_control_data(int callno,
1654 enum ast_control_frame_type control, const void *data, size_t datalen)
1657 if (iaxs[callno] && iaxs[callno]->owner) {
1658 if (ast_channel_trylock(iaxs[callno]->owner)) {
1659 /* Avoid deadlock by pausing and trying again */
1660 ast_mutex_unlock(&iaxsl[callno]);
1662 ast_mutex_lock(&iaxsl[callno]);
1664 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1665 ast_channel_unlock(iaxs[callno]->owner);
1673 static void destroy_firmware(struct iax_firmware *cur)
1675 /* Close firmware */
1677 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1683 static int try_firmware(char *s)
1686 struct iax_firmware *cur = NULL;
1687 int ifd, fd, res, len, chunk;
1688 struct ast_iax2_firmware_header *fwh, fwh2;
1689 struct MD5Context md5;
1690 unsigned char sum[16], buf[1024];
1693 if (!(s2 = alloca(strlen(s) + 100))) {
1694 ast_log(LOG_WARNING, "Alloca failed!\n");
1698 last = strrchr(s, '/');
1704 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1706 if ((res = stat(s, &stbuf) < 0)) {
1707 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1711 /* Make sure it's not a directory */
1712 if (S_ISDIR(stbuf.st_mode))
1714 ifd = open(s, O_RDONLY);
1716 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1719 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1721 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1725 /* Unlink our newly created file */
1728 /* Now copy the firmware into it */
1729 len = stbuf.st_size;
1732 if (chunk > sizeof(buf))
1733 chunk = sizeof(buf);
1734 res = read(ifd, buf, chunk);
1736 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1741 res = write(fd, buf, chunk);
1743 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1751 /* Return to the beginning */
1752 lseek(fd, 0, SEEK_SET);
1753 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1754 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1758 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1759 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1763 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1764 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1768 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1769 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1773 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1774 if (fwh == (void *) -1) {
1775 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1780 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1781 MD5Final(sum, &md5);
1782 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1783 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1784 munmap((void*)fwh, stbuf.st_size);
1789 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1790 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1791 /* Found a candidate */
1792 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1793 /* The version we have on loaded is older, load this one instead */
1795 /* This version is no newer than what we have. Don't worry about it.
1796 We'll consider it a proper load anyhow though */
1797 munmap((void*)fwh, stbuf.st_size);
1803 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1805 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1810 munmap((void*)cur->fwh, cur->mmaplen);
1815 cur->mmaplen = stbuf.st_size;
1822 static int iax_check_version(char *dev)
1825 struct iax_firmware *cur = NULL;
1827 if (ast_strlen_zero(dev))
1830 AST_LIST_LOCK(&firmwares);
1831 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1832 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1833 res = ntohs(cur->fwh->version);
1837 AST_LIST_UNLOCK(&firmwares);
1842 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1845 unsigned int bs = desc & 0xff;
1846 unsigned int start = (desc >> 8) & 0xffffff;
1848 struct iax_firmware *cur;
1850 if (ast_strlen_zero((char *)dev) || !bs)
1855 AST_LIST_LOCK(&firmwares);
1856 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1857 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1859 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1860 if (start < ntohl(cur->fwh->datalen)) {
1861 bytes = ntohl(cur->fwh->datalen) - start;
1864 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1867 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1875 AST_LIST_UNLOCK(&firmwares);
1881 static void reload_firmware(int unload)
1883 struct iax_firmware *cur = NULL;
1886 char dir[256], fn[256];
1888 AST_LIST_LOCK(&firmwares);
1890 /* Mark all as dead */
1891 AST_LIST_TRAVERSE(&firmwares, cur, list)
1894 /* Now that we have marked them dead... load new ones */
1896 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
1899 while((de = readdir(fwd))) {
1900 if (de->d_name[0] != '.') {
1901 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1902 if (!try_firmware(fn)) {
1903 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
1909 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1912 /* Clean up leftovers */
1913 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1916 AST_LIST_REMOVE_CURRENT(list);
1917 destroy_firmware(cur);
1919 AST_LIST_TRAVERSE_SAFE_END;
1921 AST_LIST_UNLOCK(&firmwares);
1925 * \note This function assumes that iaxsl[callno] is locked when called.
1927 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1928 * was valid before calling it, it may no longer be valid after calling it.
1929 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1930 * associated with this callno, meaning that another thread may grab it and destroy the call.
1932 static int __do_deliver(void *data)
1934 /* Just deliver the packet by using queueing. This is called by
1935 the IAX thread with the iaxsl lock held. */
1936 struct iax_frame *fr = data;
1938 fr->af.has_timing_info = 0;
1939 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1940 iax2_queue_frame(fr->callno, &fr->af);
1941 /* Free our iax frame */
1942 iax2_frame_free(fr);
1943 /* And don't run again */
1947 static int handle_error(void)
1949 /* XXX Ideally we should figure out why an error occurred and then abort those
1950 rather than continuing to try. Unfortunately, the published interface does
1951 not seem to work XXX */
1953 struct sockaddr_in *sin;
1956 struct sock_extended_err e;
1961 m.msg_controllen = sizeof(e);
1963 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1965 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1967 if (m.msg_controllen) {
1968 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1970 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1972 ast_log(LOG_WARNING, "No address detected??\n");
1974 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1981 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1984 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1987 ast_debug(1, "Received error: %s\n", strerror(errno));
1994 static int send_packet(struct iax_frame *f)
1997 int callno = f->callno;
1999 /* Don't send if there was an error, but return error instead */
2000 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2003 /* Called with iaxsl held */
2005 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
2008 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2009 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
2010 sizeof(iaxs[callno]->transfer));
2013 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2014 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
2015 sizeof(iaxs[callno]->addr));
2019 ast_debug(1, "Received error: %s\n", strerror(errno));
2026 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2028 /* Decrement AUTHREQ count if needed */
2029 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
2030 struct iax2_user *user;
2031 struct iax2_user tmp_user = {
2032 .name = pvt->username,
2035 user = ao2_find(users, &tmp_user, OBJ_POINTER);
2037 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2041 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
2043 /* No more pings or lagrq's */
2044 if (pvt->pingid > -1)
2045 ast_sched_del(sched, pvt->pingid);
2047 if (pvt->lagid > -1)
2048 ast_sched_del(sched, pvt->lagid);
2050 if (pvt->autoid > -1)
2051 ast_sched_del(sched, pvt->autoid);
2053 if (pvt->authid > -1)
2054 ast_sched_del(sched, pvt->authid);
2056 if (pvt->initid > -1)
2057 ast_sched_del(sched, pvt->initid);
2060 ast_sched_del(sched, pvt->jbid);
2065 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2066 * for the given call number may disappear during its execution.
2068 static int iax2_predestroy(int callno)
2070 struct ast_channel *c = NULL;
2071 struct chan_iax2_pvt *pvt = iaxs[callno];
2076 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2077 iax2_destroy_helper(pvt);
2078 ast_set_flag(pvt, IAX_ALREADYGONE);
2081 if ((c = pvt->owner)) {
2083 iax2_queue_hangup(callno);
2085 ast_module_unref(ast_module_info->self);
2091 static void iax2_destroy(int callno)
2093 struct chan_iax2_pvt *pvt = NULL;
2094 struct iax_frame *cur = NULL;
2095 struct ast_channel *owner = NULL;
2099 lastused[callno] = ast_tvnow();
2101 owner = pvt ? pvt->owner : NULL;
2104 if (ast_channel_trylock(owner)) {
2105 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
2106 ast_mutex_unlock(&iaxsl[callno]);
2108 ast_mutex_lock(&iaxsl[callno]);
2113 iaxs[callno] = NULL;
2117 iax2_destroy_helper(pvt);
2120 ast_set_flag(pvt, IAX_ALREADYGONE);
2123 /* If there's an owner, prod it to give up */
2124 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2125 * because we already hold the owner channel lock. */
2126 ast_queue_hangup(owner);
2129 AST_LIST_LOCK(&frame_queue);
2130 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2131 /* Cancel any pending transmissions */
2132 if (cur->callno == pvt->callno)
2135 AST_LIST_UNLOCK(&frame_queue);
2138 pvt->reg->callno = 0;
2142 ast_variables_destroy(pvt->vars);
2146 while (jb_getall(pvt->jb, &frame) == JB_OK)
2147 iax2_frame_free(frame.data);
2148 jb_destroy(pvt->jb);
2149 /* gotta free up the stringfields */
2150 ast_string_field_free_memory(pvt);
2155 ast_channel_unlock(owner);
2157 if (callno & 0x4000)
2161 static int update_packet(struct iax_frame *f)
2163 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2164 struct ast_iax2_full_hdr *fh = f->data;
2165 /* Mark this as a retransmission */
2166 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2168 f->iseqno = iaxs[f->callno]->iseqno;
2169 fh->iseqno = f->iseqno;
2173 static int attempt_transmit(const void *data);
2174 static void __attempt_transmit(const void *data)
2176 /* Attempt to transmit the frame to the remote peer...
2177 Called without iaxsl held. */
2178 struct iax_frame *f = (struct iax_frame *)data;
2180 int callno = f->callno;
2181 /* Make sure this call is still active */
2183 ast_mutex_lock(&iaxsl[callno]);
2184 if (callno && iaxs[callno]) {
2185 if ((f->retries < 0) /* Already ACK'd */ ||
2186 (f->retries >= max_retries) /* Too many attempts */) {
2187 /* Record an error if we've transmitted too many times */
2188 if (f->retries >= max_retries) {
2190 /* Transfer timeout */
2191 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2192 } else if (f->final) {
2194 iax2_destroy(callno);
2196 if (iaxs[callno]->owner)
2197 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);
2198 iaxs[callno]->error = ETIMEDOUT;
2199 if (iaxs[callno]->owner) {
2200 struct ast_frame fr = { 0, };
2202 fr.frametype = AST_FRAME_CONTROL;
2203 fr.subclass = AST_CONTROL_HANGUP;
2204 iax2_queue_frame(callno, &fr); /* XXX */
2205 /* Remember, owner could disappear */
2206 if (iaxs[callno] && iaxs[callno]->owner)
2207 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2209 if (iaxs[callno]->reg) {
2210 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2211 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2212 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2214 iax2_destroy(callno);
2221 /* Update it if it needs it */
2223 /* Attempt transmission */
2226 /* Try again later after 10 times as long */
2228 if (f->retrytime > MAX_RETRY_TIME)
2229 f->retrytime = MAX_RETRY_TIME;
2230 /* Transfer messages max out at one second */
2231 if (f->transfer && (f->retrytime > 1000))
2232 f->retrytime = 1000;
2233 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2236 /* Make sure it gets freed */
2241 ast_mutex_unlock(&iaxsl[callno]);
2242 /* Do not try again */
2244 /* Don't attempt delivery, just remove it from the queue */
2245 AST_LIST_LOCK(&frame_queue);
2246 AST_LIST_REMOVE(&frame_queue, f, list);
2247 AST_LIST_UNLOCK(&frame_queue);
2249 /* Free the IAX frame */
2254 static int attempt_transmit(const void *data)
2256 #ifdef SCHED_MULTITHREADED
2257 if (schedule_action(__attempt_transmit, data))
2259 __attempt_transmit(data);
2263 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2265 struct iax2_peer *peer;
2269 e->command = "iax2 prune realtime";
2271 "Usage: iax2 prune realtime [<peername>|all]\n"
2272 " Prunes object(s) from the cache\n";
2275 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2279 return CLI_SHOWUSAGE;
2280 if (!strcmp(a->argv[3], "all")) {
2282 ast_cli(a->fd, "Cache flushed successfully.\n");
2283 } else if ((peer = find_peer(a->argv[3], 0))) {
2284 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2285 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2286 expire_registry(peer_ref(peer));
2287 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2289 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2293 ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2299 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2303 e->command = "iax2 test losspct";
2305 "Usage: iax2 test losspct <percentage>\n"
2306 " For testing, throws away <percentage> percent of incoming packets\n";
2312 return CLI_SHOWUSAGE;
2314 test_losspct = atoi(a->argv[3]);
2320 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2324 e->command = "iax2 test late";
2326 "Usage: iax2 test late <ms>\n"
2327 " For testing, count the next frame as <ms> ms late\n";
2334 return CLI_SHOWUSAGE;
2336 test_late = atoi(a->argv[3]);
2341 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2345 e->command = "iax2 test resync";
2347 "Usage: iax2 test resync <ms>\n"
2348 " For testing, adjust all future frames by <ms> ms\n";
2355 return CLI_SHOWUSAGE;
2357 test_resync = atoi(a->argv[3]);
2362 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2366 e->command = "iax2 test jitter";
2368 "Usage: iax2 test jitter <ms> <pct>\n"
2369 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2370 " percentage of packets. If <pct> is not specified, adds\n"
2371 " jitter to all packets.\n";
2377 if (a->argc < 4 || a->argc > 5)
2378 return CLI_SHOWUSAGE;
2380 test_jit = atoi(a->argv[3]);
2382 test_jitpct = atoi(a->argv[4]);
2386 #endif /* IAXTESTS */
2388 /*! \brief peer_status: Report Peer status in character string */
2389 /* returns 1 if peer is online, -1 if unmonitored */
2390 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2394 if (peer->lastms < 0) {
2395 ast_copy_string(status, "UNREACHABLE", statuslen);
2396 } else if (peer->lastms > peer->maxms) {
2397 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2399 } else if (peer->lastms) {
2400 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2403 ast_copy_string(status, "UNKNOWN", statuslen);
2406 ast_copy_string(status, "Unmonitored", statuslen);
2412 /*! \brief Show one peer in detail */
2413 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2417 struct iax2_peer *peer;
2418 char codec_buf[512];
2419 int x = 0, codec = 0, load_realtime = 0;
2423 e->command = "iax2 show peer";
2425 "Usage: iax2 show peer <name>\n"
2426 " Display details on specific IAX peer\n";
2429 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2433 return CLI_SHOWUSAGE;
2435 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2437 peer = find_peer(a->argv[3], load_realtime);
2439 ast_cli(a->fd, "\n\n");
2440 ast_cli(a->fd, " * Name : %s\n", peer->name);
2441 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2442 ast_cli(a->fd, " Context : %s\n", peer->context);
2443 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
2444 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2445 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2446 ast_cli(a->fd, " Expire : %d\n", peer->expire);
2447 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
2448 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2449 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2450 ast_cli(a->fd, " Username : %s\n", peer->username);
2451 ast_cli(a->fd, " Codecs : ");
2452 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2453 ast_cli(a->fd, "%s\n", codec_buf);
2455 ast_cli(a->fd, " Codec Order : (");
2456 for(x = 0; x < 32 ; x++) {
2457 codec = ast_codec_pref_index(&peer->prefs,x);
2460 ast_cli(a->fd, "%s", ast_getformatname(codec));
2461 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2462 ast_cli(a->fd, "|");
2466 ast_cli(a->fd, "none");
2467 ast_cli(a->fd, ")\n");
2469 ast_cli(a->fd, " Status : ");
2470 peer_status(peer, status, sizeof(status));
2471 ast_cli(a->fd, "%s\n",status);
2472 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2473 ast_cli(a->fd, "\n");
2476 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2477 ast_cli(a->fd, "\n");
2483 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2486 struct iax2_peer *peer;
2488 int wordlen = strlen(word);
2489 struct ao2_iterator i;
2491 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2495 i = ao2_iterator_init(peers, 0);
2496 while ((peer = ao2_iterator_next(&i))) {
2497 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2498 res = ast_strdup(peer->name);
2508 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2510 struct iax_frame *cur;
2511 int cnt = 0, dead = 0, final = 0;
2515 e->command = "iax2 show stats";
2517 "Usage: iax2 show stats\n"
2518 " Display statistics on IAX channel driver.\n";
2525 return CLI_SHOWUSAGE;
2527 AST_LIST_LOCK(&frame_queue);
2528 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2529 if (cur->retries < 0)
2535 AST_LIST_UNLOCK(&frame_queue);
2537 ast_cli(a->fd, " IAX Statistics\n");
2538 ast_cli(a->fd, "---------------------\n");
2539 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2540 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2541 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2542 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2544 trunk_timed = trunk_untimed = 0;
2545 if (trunk_maxmtu > trunk_nmaxmtu)
2546 trunk_nmaxmtu = trunk_maxmtu;
2551 /*! \brief Set trunk MTU from CLI */
2552 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2558 e->command = "iax2 set mtu";
2560 "Usage: iax2 set mtu <value>\n"
2561 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2562 " zero to disable. Disabling means that the operating system\n"
2563 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2564 " packet exceeds the UDP payload size. This is substantially\n"
2565 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2566 " greater for G.711 samples.\n";
2573 return CLI_SHOWUSAGE;
2574 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2575 mtuv = MAX_TRUNK_MTU;
2577 mtuv = atoi(a->argv[3]);
2580 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2581 global_max_trunk_mtu = 0;
2584 if (mtuv < 172 || mtuv > 4000) {
2585 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
2586 return CLI_SHOWUSAGE;
2588 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2589 global_max_trunk_mtu = mtuv;
2593 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2595 struct iax2_dpcache *dp = NULL;
2596 char tmp[1024], *pc = NULL;
2598 struct timeval tv = ast_tvnow();
2602 e->command = "iax2 show cache";
2604 "Usage: iax2 show cache\n"
2605 " Display currently cached IAX Dialplan results.\n";
2611 AST_LIST_LOCK(&dpcache);
2613 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2615 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2616 s = dp->expiry.tv_sec - tv.tv_sec;
2618 if (dp->flags & CACHE_FLAG_EXISTS)
2619 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2620 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2621 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2622 if (dp->flags & CACHE_FLAG_CANEXIST)
2623 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2624 if (dp->flags & CACHE_FLAG_PENDING)
2625 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2626 if (dp->flags & CACHE_FLAG_TIMEOUT)
2627 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2628 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2629 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2630 if (dp->flags & CACHE_FLAG_MATCHMORE)
2631 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2632 if (dp->flags & CACHE_FLAG_UNKNOWN)
2633 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2634 /* Trim trailing pipe */
2635 if (!ast_strlen_zero(tmp))
2636 tmp[strlen(tmp) - 1] = '\0';
2638 ast_copy_string(tmp, "(none)", sizeof(tmp));
2640 pc = strchr(dp->peercontext, '@');
2642 pc = dp->peercontext;
2645 for (x = 0; x < sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2646 if (dp->waiters[x] > -1)
2649 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2651 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2654 AST_LIST_LOCK(&dpcache);
2659 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2661 static void unwrap_timestamp(struct iax_frame *fr)
2665 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2666 x = fr->ts - iaxs[fr->callno]->last;
2668 /* Sudden big jump backwards in timestamp:
2669 What likely happened here is that miniframe timestamp has circled but we haven't
2670 gotten the update from the main packet. We'll just pretend that we did, and
2671 update the timestamp appropriately. */
2672 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2674 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2677 /* Sudden apparent big jump forwards in timestamp:
2678 What's likely happened is this is an old miniframe belonging to the previous
2679 top-16-bit timestamp that has turned up out of order.
2680 Adjust the timestamp appropriately. */
2681 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2683 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2688 static int get_from_jb(const void *p);
2690 static void update_jbsched(struct chan_iax2_pvt *pvt)
2694 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2696 when = jb_next(pvt->jb) - when;
2699 /* XXX should really just empty until when > 0.. */
2703 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
2704 CALLNO_TO_PTR(pvt->callno));
2707 static void __get_from_jb(const void *p)
2709 int callno = PTR_TO_CALLNO(p);
2710 struct chan_iax2_pvt *pvt = NULL;
2711 struct iax_frame *fr;
2716 struct timeval tv = ast_tvnow();
2718 /* Make sure we have a valid private structure before going on */
2719 ast_mutex_lock(&iaxsl[callno]);
2723 ast_mutex_unlock(&iaxsl[callno]);
2729 /* round up a millisecond since ast_sched_runq does; */
2730 /* prevents us from spinning while waiting for our now */
2731 /* to catch up with runq's now */
2734 now = ast_tvdiff_ms(tv, pvt->rxcore);
2736 if(now >= (next = jb_next(pvt->jb))) {
2737 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2742 /* __do_deliver() can cause the call to disappear */
2747 struct ast_frame af = { 0, };
2749 /* create an interpolation frame */
2750 af.frametype = AST_FRAME_VOICE;
2751 af.subclass = pvt->voiceformat;
2752 af.samples = frame.ms * 8;
2753 af.src = "IAX2 JB interpolation";
2754 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2755 af.offset = AST_FRIENDLY_OFFSET;
2757 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2758 * which we'd need to malloc, and then it would free it. That seems like a drag */
2759 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2760 iax2_queue_frame(callno, &af);
2761 /* iax2_queue_frame() could cause the call to disappear */
2767 iax2_frame_free(frame.data);
2774 /* shouldn't happen */
2779 update_jbsched(pvt);
2780 ast_mutex_unlock(&iaxsl[callno]);
2783 static int get_from_jb(const void *data)
2785 #ifdef SCHED_MULTITHREADED
2786 if (schedule_action(__get_from_jb, data))
2788 __get_from_jb(data);
2793 * \note This function assumes fr->callno is locked
2795 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2796 * was valid before calling it, it may no longer be valid after calling it.
2798 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2804 /* Attempt to recover wrapped timestamps */
2805 unwrap_timestamp(fr);
2807 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2808 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2809 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2812 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2814 fr->af.delivery = ast_tv(0,0);
2817 type = JB_TYPE_CONTROL;
2820 if(fr->af.frametype == AST_FRAME_VOICE) {
2821 type = JB_TYPE_VOICE;
2822 len = ast_codec_get_samples(&fr->af) / 8;
2823 } else if(fr->af.frametype == AST_FRAME_CNG) {
2824 type = JB_TYPE_SILENCE;
2827 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2834 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2835 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2836 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2837 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2838 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2841 /* deliver any frames in the jb */
2842 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2843 __do_deliver(frame.data);
2844 /* __do_deliver() can make the call disappear */
2845 if (!iaxs[fr->callno])
2849 jb_reset(iaxs[fr->callno]->jb);
2851 if (iaxs[fr->callno]->jbid > -1)
2852 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2854 iaxs[fr->callno]->jbid = -1;
2856 /* deliver this frame now */
2863 /* insert into jitterbuffer */
2864 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2865 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2866 calc_rxstamp(iaxs[fr->callno],fr->ts));
2867 if (ret == JB_DROP) {
2869 } else if (ret == JB_SCHED) {
2870 update_jbsched(iaxs[fr->callno]);
2875 /* Free our iax frame */
2876 iax2_frame_free(fr);
2882 static int iax2_transmit(struct iax_frame *fr)
2884 /* Lock the queue and place this packet at the end */
2885 /* By setting this to 0, the network thread will send it for us, and
2886 queue retransmission if necessary */
2888 AST_LIST_LOCK(&frame_queue);
2889 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
2890 AST_LIST_UNLOCK(&frame_queue);
2891 /* Wake up the network and scheduler thread */
2892 if (netthreadid != AST_PTHREADT_NULL)
2893 pthread_kill(netthreadid, SIGURG);
2894 signal_condition(&sched_lock, &sched_cond);
2900 static int iax2_digit_begin(struct ast_channel *c, char digit)
2902 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2905 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2907 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2910 static int iax2_sendtext(struct ast_channel *c, const char *text)
2913 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2914 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2917 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2919 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2922 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2924 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2927 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2929 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2930 ast_mutex_lock(&iaxsl[callno]);
2932 iaxs[callno]->owner = newchan;
2934 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2935 ast_mutex_unlock(&iaxsl[callno]);
2940 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2941 * so do not call this with a pvt lock held.
2943 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2945 struct ast_variable *var = NULL;
2946 struct ast_variable *tmp;
2947 struct iax2_peer *peer=NULL;
2948 time_t regseconds = 0, nowtime;
2952 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
2954 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr));
2957 sprintf(porta, "%d", ntohs(sin->sin_port));
2958 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2960 /* We'll need the peer name in order to build the structure! */
2961 for (tmp = var; tmp; tmp = tmp->next) {
2962 if (!strcasecmp(tmp->name, "name"))
2963 peername = tmp->value;
2967 if (!var && peername) { /* Last ditch effort */
2968 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2970 * If this one loaded something, then we need to ensure that the host
2971 * field matched. The only reason why we can't have this as a criteria
2972 * is because we only have the IP address and the host field might be
2973 * set as a name (and the reverse PTR might not match).
2976 for (tmp = var; tmp; tmp = tmp->next) {
2977 if (!strcasecmp(tmp->name, "host")) {
2978 struct in_addr sin2 = { 0, };
2979 struct ast_dnsmgr_entry *dnsmgr = NULL;
2980 if ((ast_dnsmgr_lookup(tmp->value, &sin2, &dnsmgr) < 0) || (memcmp(&sin2, &sin->sin_addr, sizeof(sin2)) != 0)) {
2982 ast_variables_destroy(var);
2993 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2996 ast_variables_destroy(var);
3000 for (tmp = var; tmp; tmp = tmp->next) {
3001 /* Make sure it's not a user only... */
3002 if (!strcasecmp(tmp->name, "type")) {
3003 if (strcasecmp(tmp->value, "friend") &&
3004 strcasecmp(tmp->value, "peer")) {
3005 /* Whoops, we weren't supposed to exist! */
3006 peer = peer_unref(peer);
3009 } else if (!strcasecmp(tmp->name, "regseconds")) {
3010 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
3011 } else if (!strcasecmp(tmp->name, "ipaddr")) {
3012 inet_aton(tmp->value, &(peer->addr.sin_addr));
3013 } else if (!strcasecmp(tmp->name, "port")) {
3014 peer->addr.sin_port = htons(atoi(tmp->value));
3015 } else if (!strcasecmp(tmp->name, "host")) {
3016 if (!strcasecmp(tmp->value, "dynamic"))
3021 ast_variables_destroy(var);
3026 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3027 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3028 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3029 if (peer->expire > -1) {
3030 if (!ast_sched_del(sched, peer->expire)) {
3035 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3036 if (peer->expire == -1)
3039 ao2_link(peers, peer);
3040 if (ast_test_flag(peer, IAX_DYNAMIC))
3041 reg_source_db(peer);
3043 ast_set_flag(peer, IAX_TEMPONLY);
3046 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3048 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3049 memset(&peer->addr, 0, sizeof(peer->addr));
3050 realtime_update_peer(peer->name, &peer->addr, 0);
3051 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3052 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3055 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3056 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3063 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
3065 struct ast_variable *var;
3066 struct ast_variable *tmp;
3067 struct iax2_user *user=NULL;
3069 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
3071 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr));
3074 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
3075 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3077 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
3079 if (!var) { /* Last ditch effort */
3080 var = ast_load_realtime("iaxusers", "name", username, NULL);
3082 * If this one loaded something, then we need to ensure that the host
3083 * field matched. The only reason why we can't have this as a criteria
3084 * is because we only have the IP address and the host field might be
3085 * set as a name (and the reverse PTR might not match).
3088 for (tmp = var; tmp; tmp = tmp->next) {
3089 if (!strcasecmp(tmp->name, "host")) {
3090 struct in_addr sin2 = { 0, };
3091 struct ast_dnsmgr_entry *dnsmgr = NULL;
3092 if ((ast_dnsmgr_lookup(tmp->value, &sin2, &dnsmgr) < 0) || (memcmp(&sin2, &sin->sin_addr, sizeof(sin2)) != 0)) {
3094 ast_variables_destroy(var);
3107 /* Make sure it's not a peer only... */
3108 if (!strcasecmp(tmp->name, "type")) {
3109 if (strcasecmp(tmp->value, "friend") &&
3110 strcasecmp(tmp->value, "user")) {
3117 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3119 ast_variables_destroy(var);
3124 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3125 ast_set_flag(user, IAX_RTCACHEFRIENDS);
3126 ao2_link(users, user);
3128 ast_set_flag(user, IAX_TEMPONLY);
3134 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3137 char regseconds[20];
3139 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3140 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3141 ast_update_realtime("iaxpeers", "name", peername,
3142 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
3143 "regseconds", regseconds, NULL);
3146 struct create_addr_info {
3159 char context[AST_MAX_CONTEXT];
3160 char peercontext[AST_MAX_CONTEXT];
3161 char mohinterpret[MAX_MUSICCLASS];
3162 char mohsuggest[MAX_MUSICCLASS];
3165 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
3167 struct iax2_peer *peer;
3170 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3171 cai->sockfd = defaultsockfd;
3173 sin->sin_family = AF_INET;