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
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
50 #include <sys/signal.h>
61 #include "asterisk/zapata.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/frame.h"
65 #include "asterisk/channel.h"
66 #include "asterisk/logger.h"
67 #include "asterisk/module.h"
68 #include "asterisk/pbx.h"
69 #include "asterisk/sched.h"
70 #include "asterisk/io.h"
71 #include "asterisk/config.h"
72 #include "asterisk/options.h"
73 #include "asterisk/cli.h"
74 #include "asterisk/translate.h"
75 #include "asterisk/md5.h"
76 #include "asterisk/cdr.h"
77 #include "asterisk/crypto.h"
78 #include "asterisk/acl.h"
79 #include "asterisk/manager.h"
80 #include "asterisk/callerid.h"
81 #include "asterisk/app.h"
82 #include "asterisk/astdb.h"
83 #include "asterisk/musiconhold.h"
84 #include "asterisk/features.h"
85 #include "asterisk/utils.h"
86 #include "asterisk/causes.h"
87 #include "asterisk/localtime.h"
88 #include "asterisk/aes.h"
89 #include "asterisk/dnsmgr.h"
90 #include "asterisk/devicestate.h"
91 #include "asterisk/netsock.h"
92 #include "asterisk/stringfields.h"
93 #include "asterisk/linkedlists.h"
96 #include "iax2-parser.h"
97 #include "iax2-provision.h"
98 #include "jitterbuf.h"
100 /* Define SCHED_MULTITHREADED to run the scheduler in a special
101 multithreaded mode. */
102 #define SCHED_MULTITHREADED
104 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
105 thread is actually doing. */
106 #define DEBUG_SCHED_MULTITHREAD
108 #ifndef IPTOS_MINCOST
109 #define IPTOS_MINCOST 0x02
113 static int nochecksums = 0;
117 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
118 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
120 #define DEFAULT_THREAD_COUNT 10
121 #define DEFAULT_MAX_THREAD_COUNT 100
122 #define DEFAULT_RETRY_TIME 1000
123 #define MEMORY_SIZE 100
124 #define DEFAULT_DROP 3
125 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
126 but keeps the division between trunked and non-trunked better. */
127 #define TRUNK_CALL_START 0x4000
129 #define DEBUG_SUPPORT
131 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
133 /* Sample over last 100 units to determine historic jitter */
136 static struct ast_codec_pref prefs;
138 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
141 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
142 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
143 #define MAX_TRUNK_MTU 1240
145 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
146 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
149 static char context[80] = "default";
151 static char language[MAX_LANGUAGE] = "";
152 static char regcontext[AST_MAX_CONTEXT] = "";
154 static int maxauthreq = 3;
155 static int max_retries = 4;
156 static int ping_time = 20;
157 static int lagrq_time = 10;
158 static int maxtrunkcall = TRUNK_CALL_START;
159 static int maxnontrunkcall = 1;
160 static int maxjitterbuffer=1000;
161 static int resyncthreshold=1000;
162 static int maxjitterinterps=10;
163 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
165 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
167 static int trunkfreq = 20;
168 static int trunkmaxsize = MAX_TRUNKDATA;
170 static int authdebug = 1;
171 static int autokill = 0;
172 static int iaxcompat = 0;
174 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
176 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
178 static unsigned int tos = 0;
180 static int min_reg_expire;
181 static int max_reg_expire;
183 static int srvlookup = 0;
185 static int timingfd = -1; /* Timing file descriptor */
187 static struct ast_netsock_list *netsock;
188 static int defaultsockfd = -1;
190 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
193 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
195 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
196 ~AST_FORMAT_SLINEAR & \
201 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
203 ~AST_FORMAT_G726_AAL2 & \
206 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
210 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
211 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
212 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
214 static struct io_context *io;
215 static struct sched_context *sched;
217 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
219 static int iaxdebug = 0;
221 static int iaxtrunkdebug = 0;
223 static int test_losspct = 0;
225 static int test_late = 0;
226 static int test_resync = 0;
227 static int test_jit = 0;
228 static int test_jitpct = 0;
229 #endif /* IAXTESTS */
231 static char accountcode[AST_MAX_ACCOUNT_CODE];
232 static char mohinterpret[MAX_MUSICCLASS];
233 static char mohsuggest[MAX_MUSICCLASS];
234 static int amaflags = 0;
236 static int delayreject = 0;
237 static int iax2_encryption = 0;
239 static struct ast_flags globalflags = { 0 };
241 static pthread_t netthreadid = AST_PTHREADT_NULL;
242 static pthread_t schedthreadid = AST_PTHREADT_NULL;
243 AST_MUTEX_DEFINE_STATIC(sched_lock);
244 static ast_cond_t sched_cond;
247 IAX_STATE_STARTED = (1 << 0),
248 IAX_STATE_AUTHENTICATED = (1 << 1),
249 IAX_STATE_TBD = (1 << 2),
250 IAX_STATE_UNCHANGED = (1 << 3),
253 struct iax2_context {
254 char context[AST_MAX_CONTEXT];
255 struct iax2_context *next;
259 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
260 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
261 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
262 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
263 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
264 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
265 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
266 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
267 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
268 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
269 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
270 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
271 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
272 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
273 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
274 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
275 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
276 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
277 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
278 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
279 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
280 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
281 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
282 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
283 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
286 static int global_rtautoclear = 120;
288 static int reload_config(void);
289 static int iax2_reload(int fd, int argc, char *argv[]);
293 AST_DECLARE_STRING_FIELDS(
294 AST_STRING_FIELD(name);
295 AST_STRING_FIELD(secret);
296 AST_STRING_FIELD(dbsecret);
297 AST_STRING_FIELD(accountcode);
298 AST_STRING_FIELD(mohinterpret);
299 AST_STRING_FIELD(mohsuggest);
300 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
301 AST_STRING_FIELD(language);
302 AST_STRING_FIELD(cid_num);
303 AST_STRING_FIELD(cid_name);
312 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
313 int curauthreq; /*!< Current number of outstanding AUTHREQs */
314 struct ast_codec_pref prefs;
316 struct iax2_context *contexts;
317 struct ast_variable *vars;
318 AST_LIST_ENTRY(iax2_user) entry;
322 AST_DECLARE_STRING_FIELDS(
323 AST_STRING_FIELD(name);
324 AST_STRING_FIELD(username);
325 AST_STRING_FIELD(secret);
326 AST_STRING_FIELD(dbsecret);
327 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
329 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
330 AST_STRING_FIELD(context); /*!< For transfers only */
331 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
332 AST_STRING_FIELD(mailbox); /*!< Mailbox */
333 AST_STRING_FIELD(mohinterpret);
334 AST_STRING_FIELD(mohsuggest);
335 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
336 /* Suggested caller id if registering */
337 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
338 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
339 AST_STRING_FIELD(zonetag); /*!< Time Zone */
341 struct ast_codec_pref prefs;
342 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
343 struct sockaddr_in addr;
345 int sockfd; /*!< Socket to use for transmission */
350 /* Dynamic Registration fields */
351 struct sockaddr_in defaddr; /*!< Default address if there is one */
352 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
353 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
355 int expire; /*!< Schedule entry for expiry */
356 int expiry; /*!< How soon to expire */
357 int capability; /*!< Capability */
360 int callno; /*!< Call number of POKE request */
361 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
362 int lastms; /*!< How long last response took (in ms), or -1 for no response */
363 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
365 int pokefreqok; /*!< How often to check if the host is up */
366 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
367 int historicms; /*!< How long recent average responses took */
368 int smoothing; /*!< Sample over how many units to determine historic ms */
371 AST_LIST_ENTRY(iax2_peer) entry;
374 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
376 struct iax2_trunk_peer {
379 struct sockaddr_in addr;
380 struct timeval txtrunktime; /*!< Transmit trunktime */
381 struct timeval rxtrunktime; /*!< Receive trunktime */
382 struct timeval lasttxtime; /*!< Last transmitted trunktime */
383 struct timeval trunkact; /*!< Last trunk activity */
384 unsigned int lastsent; /*!< Last sent time */
385 /* Trunk data and length */
386 unsigned char *trunkdata;
387 unsigned int trunkdatalen;
388 unsigned int trunkdataalloc;
392 AST_LIST_ENTRY(iax2_trunk_peer) list;
395 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
397 struct iax_firmware {
398 AST_LIST_ENTRY(iax_firmware) list;
402 struct ast_iax2_firmware_header *fwh;
407 REG_STATE_UNREGISTERED = 0,
410 REG_STATE_REGISTERED,
416 enum iax_transfer_state {
421 TRANSFER_PASSTHROUGH,
425 TRANSFER_MPASSTHROUGH,
430 struct iax2_registry {
431 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
433 char secret[80]; /*!< Password or key name in []'s */
435 int expire; /*!< Sched ID of expiration */
436 int refresh; /*!< How often to refresh */
437 enum iax_reg_state regstate;
438 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
439 int callno; /*!< Associated call number if applicable */
440 struct sockaddr_in us; /*!< Who the server thinks we are */
441 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
442 AST_LIST_ENTRY(iax2_registry) entry;
445 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
447 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
448 #define MIN_RETRY_TIME 100
449 #define MAX_RETRY_TIME 10000
451 #define MAX_JITTER_BUFFER 50
452 #define MIN_JITTER_BUFFER 10
454 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
456 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
458 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
459 #define TS_GAP_FOR_JB_RESYNC 5000
461 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
462 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
463 static int iaxdynamicthreadcount = 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 /*! Peer selected format */
512 /*! Peer capability */
514 /*! timeval that we base our transmission on */
515 struct timeval offset;
516 /*! timeval that we base our delivery on */
517 struct timeval rxcore;
518 /*! The jitterbuffer */
520 /*! active jb read scheduler id */
524 /*! Error, as discovered by the manager */
526 /*! Owner if we have one */
527 struct ast_channel *owner;
528 /*! What's our state? */
529 struct ast_flags state;
530 /*! Expiry (optional) */
532 /*! Next outgoing sequence number */
533 unsigned char oseqno;
534 /*! Next sequence number they have not yet acknowledged */
535 unsigned char rseqno;
536 /*! Next incoming sequence number */
537 unsigned char iseqno;
538 /*! Last incoming sequence number we have acknowledged */
539 unsigned char aseqno;
541 AST_DECLARE_STRING_FIELDS(
543 AST_STRING_FIELD(peer);
544 /*! Default Context */
545 AST_STRING_FIELD(context);
546 /*! Caller ID if available */
547 AST_STRING_FIELD(cid_num);
548 AST_STRING_FIELD(cid_name);
549 /*! Hidden Caller ID (i.e. ANI) if appropriate */
550 AST_STRING_FIELD(ani);
552 AST_STRING_FIELD(dnid);
554 AST_STRING_FIELD(rdnis);
555 /*! Requested Extension */
556 AST_STRING_FIELD(exten);
557 /*! Expected Username */
558 AST_STRING_FIELD(username);
559 /*! Expected Secret */
560 AST_STRING_FIELD(secret);
562 AST_STRING_FIELD(challenge);
563 /*! Public keys permitted keys for incoming authentication */
564 AST_STRING_FIELD(inkeys);
565 /*! Private key for outgoing authentication */
566 AST_STRING_FIELD(outkey);
567 /*! Preferred language */
568 AST_STRING_FIELD(language);
569 /*! Hostname/peername for naming purposes */
570 AST_STRING_FIELD(host);
572 AST_STRING_FIELD(dproot);
573 AST_STRING_FIELD(accountcode);
574 AST_STRING_FIELD(mohinterpret);
575 AST_STRING_FIELD(mohsuggest);
578 /*! permitted authentication methods */
580 /*! permitted encryption methods */
582 /*! Encryption AES-128 Key */
584 /*! Decryption AES-128 Key */
586 /*! 32 bytes of semi-random data */
587 unsigned char semirand[32];
588 /*! Associated registry */
589 struct iax2_registry *reg;
590 /*! Associated peer for poking */
591 struct iax2_peer *peerpoke;
596 /*! Transferring status */
597 enum iax_transfer_state transferring;
598 /*! Transfer identifier */
600 /*! Who we are IAX transferring to */
601 struct sockaddr_in transfer;
602 /*! What's the new call number for the transfer */
603 unsigned short transfercallno;
604 /*! Transfer decrypt AES-128 Key */
605 aes_encrypt_ctx tdcx;
607 /*! Status of knowledge of peer ADSI capability */
610 /*! Who we are bridged to */
611 unsigned short bridgecallno;
613 int pingid; /*!< Transmit PING request */
614 int lagid; /*!< Retransmit lag request */
615 int autoid; /*!< Auto hangup for Dialplan requestor */
616 int authid; /*!< Authentication rejection ID */
617 int authfail; /*!< Reason to report failure */
618 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
623 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
624 struct ast_variable *vars;
625 /*! last received remote rr */
626 struct iax_rr remote_rr;
627 /*! Current base time: (just for stats) */
629 /*! Dropped frame count: (just for stats) */
631 /*! received frame count: (just for stats) */
635 static AST_LIST_HEAD_STATIC(queue, iax_frame);
637 static AST_LIST_HEAD_STATIC(users, iax2_user);
639 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
641 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
644 /*! Extension exists */
645 CACHE_FLAG_EXISTS = (1 << 0),
646 /*! Extension is nonexistent */
647 CACHE_FLAG_NONEXISTENT = (1 << 1),
648 /*! Extension can exist */
649 CACHE_FLAG_CANEXIST = (1 << 2),
650 /*! Waiting to hear back response */
651 CACHE_FLAG_PENDING = (1 << 3),
653 CACHE_FLAG_TIMEOUT = (1 << 4),
654 /*! Request transmitted */
655 CACHE_FLAG_TRANSMITTED = (1 << 5),
657 CACHE_FLAG_UNKNOWN = (1 << 6),
659 CACHE_FLAG_MATCHMORE = (1 << 7),
662 struct iax2_dpcache {
663 char peercontext[AST_MAX_CONTEXT];
664 char exten[AST_MAX_EXTENSION];
666 struct timeval expiry;
668 unsigned short callno;
670 AST_LIST_ENTRY(iax2_dpcache) cache_list;
671 AST_LIST_ENTRY(iax2_dpcache) peer_list;
674 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
676 static void reg_source_db(struct iax2_peer *p);
677 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
679 static void destroy_peer(struct iax2_peer *peer);
680 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
682 enum iax2_thread_iostate {
685 IAX_IOSTATE_PROCESSING,
686 IAX_IOSTATE_SCHEDREADY,
689 enum iax2_thread_type {
690 IAX_THREAD_TYPE_POOL,
691 IAX_THREAD_TYPE_DYNAMIC,
695 AST_LIST_ENTRY(iax2_thread) list;
696 enum iax2_thread_type type;
697 enum iax2_thread_iostate iostate;
698 #ifdef SCHED_MULTITHREADED
699 void (*schedfunc)(void *);
702 #ifdef DEBUG_SCHED_MULTITHREAD
708 struct sockaddr_in iosin;
709 unsigned char buf[4096];
718 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
719 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
720 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
722 static void *iax2_process_thread(void *data);
724 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
726 ast_mutex_lock(lock);
727 ast_cond_signal(cond);
728 ast_mutex_unlock(lock);
731 static void iax_debug_output(const char *data)
734 ast_verbose("%s", data);
737 static void iax_error_output(const char *data)
739 ast_log(LOG_WARNING, "%s", data);
742 static void jb_error_output(const char *fmt, ...)
748 vsnprintf(buf, sizeof(buf), fmt, args);
751 ast_log(LOG_ERROR, buf);
754 static void jb_warning_output(const char *fmt, ...)
760 vsnprintf(buf, sizeof(buf), fmt, args);
763 ast_log(LOG_WARNING, buf);
766 static void jb_debug_output(const char *fmt, ...)
772 vsnprintf(buf, sizeof(buf), fmt, args);
779 * \brief an array of iax2 pvt structures
781 * The container for active chan_iax2_pvt structures is implemented as an
782 * array for extremely quick direct access to the correct pvt structure
783 * based on the local call number. The local call number is used as the
784 * index into the array where the associated pvt structure is stored.
786 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
788 * \brief chan_iax2_pvt structure locks
790 * These locks are used when accessing a pvt structure in the iaxs array.
791 * The index used here is the same as used in the iaxs array. It is the
792 * local call number for the associated pvt struct.
794 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
796 * \brief The last time a call number was used
798 * It is important to know the last time that a call number was used locally so
799 * that it is not used again too soon. The reason for this is the same as the
800 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
802 * For example, say that a call is up. Then, the remote side sends a HANGUP,
803 * which we respond to with an ACK. However, there is no way to know whether
804 * the ACK made it there successfully. If it were to get lost, the remote
805 * side may retransmit the HANGUP. If in the meantime, this call number has
806 * been reused locally, given the right set of circumstances, this retransmitted
807 * HANGUP could potentially improperly hang up the new session. So, to avoid
808 * this potential issue, we must wait a specified timeout period before reusing
809 * a local call number.
811 * The specified time that we must wait before reusing a local call number is
812 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
814 static struct timeval lastused[IAX_MAX_CALLS];
816 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);
817 static int expire_registry(void *data);
818 static int iax2_answer(struct ast_channel *c);
819 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
820 static int iax2_devicestate(void *data);
821 static int iax2_digit_begin(struct ast_channel *c, char digit);
822 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
823 static int iax2_do_register(struct iax2_registry *reg);
824 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
825 static int iax2_hangup(struct ast_channel *c);
826 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
827 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
828 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
829 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
830 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
831 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
832 static int iax2_sendtext(struct ast_channel *c, const char *text);
833 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
834 static int iax2_transfer(struct ast_channel *c, const char *dest);
835 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
836 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
837 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
838 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
839 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
840 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
841 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
842 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
843 static struct ast_frame *iax2_read(struct ast_channel *c);
844 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
845 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
846 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
847 static void destroy_user(struct iax2_user *user);
848 static void prune_peers(void);
850 static const struct ast_channel_tech iax2_tech = {
852 .description = tdesc,
853 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
854 .properties = AST_CHAN_TP_WANTSJITTER,
855 .requester = iax2_request,
856 .devicestate = iax2_devicestate,
857 .send_digit_begin = iax2_digit_begin,
858 .send_digit_end = iax2_digit_end,
859 .send_text = iax2_sendtext,
860 .send_image = iax2_sendimage,
861 .send_html = iax2_sendhtml,
863 .hangup = iax2_hangup,
864 .answer = iax2_answer,
867 .write_video = iax2_write,
868 .indicate = iax2_indicate,
869 .setoption = iax2_setoption,
870 .bridge = iax2_bridge,
871 .transfer = iax2_transfer,
875 static void insert_idle_thread(struct iax2_thread *thread)
877 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
878 AST_LIST_LOCK(&dynamic_list);
879 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
880 AST_LIST_UNLOCK(&dynamic_list);
882 AST_LIST_LOCK(&idle_list);
883 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
884 AST_LIST_UNLOCK(&idle_list);
890 static struct iax2_thread *find_idle_thread(void)
892 struct iax2_thread *thread = NULL;
894 /* Pop the head of the idle list off */
895 AST_LIST_LOCK(&idle_list);
896 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
897 AST_LIST_UNLOCK(&idle_list);
899 /* If we popped a thread off the idle list, just return it */
903 /* Pop the head of the dynamic list off */
904 AST_LIST_LOCK(&dynamic_list);
905 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
906 AST_LIST_UNLOCK(&dynamic_list);
908 /* If we popped a thread off the dynamic list, just return it */
912 /* If we can't create a new dynamic thread for any reason, return no thread at all */
913 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
916 /* Set default values */
917 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
918 thread->type = IAX_THREAD_TYPE_DYNAMIC;
920 /* Initialize lock and condition */
921 ast_mutex_init(&thread->lock);
922 ast_cond_init(&thread->cond, NULL);
924 /* Create thread and send it on it's way */
925 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
926 ast_cond_destroy(&thread->cond);
927 ast_mutex_destroy(&thread->lock);
935 #ifdef SCHED_MULTITHREADED
936 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
938 struct iax2_thread *thread = NULL;
939 static time_t lasterror;
942 thread = find_idle_thread();
944 if (thread != NULL) {
945 thread->schedfunc = func;
946 thread->scheddata = data;
947 thread->iostate = IAX_IOSTATE_SCHEDREADY;
948 #ifdef DEBUG_SCHED_MULTITHREAD
949 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
951 signal_condition(&thread->lock, &thread->cond);
956 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
961 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
964 static int send_ping(void *data);
966 static void __send_ping(void *data)
968 int callno = (long)data;
969 ast_mutex_lock(&iaxsl[callno]);
970 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
971 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
972 iaxs[callno]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, data);
974 ast_mutex_unlock(&iaxsl[callno]);
977 static int send_ping(void *data)
979 #ifdef SCHED_MULTITHREADED
980 if (schedule_action(__send_ping, data))
986 static int get_encrypt_methods(const char *s)
989 if (!strcasecmp(s, "aes128"))
990 e = IAX_ENCRYPT_AES128;
991 else if (ast_true(s))
992 e = IAX_ENCRYPT_AES128;
998 static int send_lagrq(void *data);
1000 static void __send_lagrq(void *data)
1002 int callno = (long)data;
1003 /* Ping only if it's real not if it's bridged */
1004 ast_mutex_lock(&iaxsl[callno]);
1005 if (iaxs[callno] && iaxs[callno]->lagid != -1) {
1006 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1007 iaxs[callno]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1009 ast_mutex_unlock(&iaxsl[callno]);
1012 static int send_lagrq(void *data)
1014 #ifdef SCHED_MULTITHREADED
1015 if (schedule_action(__send_lagrq, data))
1021 static unsigned char compress_subclass(int subclass)
1025 /* If it's 128 or smaller, just return it */
1026 if (subclass < IAX_FLAG_SC_LOG)
1028 /* Otherwise find its power */
1029 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1030 if (subclass & (1 << x)) {
1032 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1038 return power | IAX_FLAG_SC_LOG;
1041 static int uncompress_subclass(unsigned char csub)
1043 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1044 if (csub & IAX_FLAG_SC_LOG) {
1045 /* special case for 'compressed' -1 */
1049 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1055 static struct iax2_peer *find_peer(const char *name, int realtime)
1057 struct iax2_peer *peer = NULL;
1059 /* Grab peer from linked list */
1060 AST_LIST_LOCK(&peers);
1061 AST_LIST_TRAVERSE(&peers, peer, entry) {
1062 if (!strcasecmp(peer->name, name)) {
1066 AST_LIST_UNLOCK(&peers);
1068 /* Now go for realtime if applicable */
1069 if(!peer && realtime)
1070 peer = realtime_peer(name, NULL);
1074 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1076 struct iax2_peer *peer = NULL;
1080 AST_LIST_LOCK(&peers);
1081 AST_LIST_TRAVERSE(&peers, peer, entry) {
1082 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1083 (peer->addr.sin_port == sin.sin_port)) {
1084 ast_copy_string(host, peer->name, len);
1090 AST_LIST_UNLOCK(&peers);
1092 peer = realtime_peer(NULL, &sin);
1094 ast_copy_string(host, peer->name, len);
1095 if (ast_test_flag(peer, IAX_TEMPONLY))
1104 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1106 struct chan_iax2_pvt *tmp;
1109 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1112 if (ast_string_field_init(tmp, 32)) {
1125 ast_string_field_set(tmp,exten, "s");
1126 ast_string_field_set(tmp,host, host);
1130 jbconf.max_jitterbuf = maxjitterbuffer;
1131 jbconf.resync_threshold = resyncthreshold;
1132 jbconf.max_contig_interp = maxjitterinterps;
1133 jbconf.target_extra = jittertargetextra;
1134 jb_setconf(tmp->jb,&jbconf);
1136 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1141 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1143 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1145 size_t mallocd_datalen = new->mallocd_datalen;
1146 memcpy(new, fr, sizeof(*new));
1147 iax_frame_wrap(new, &fr->af);
1148 new->mallocd_datalen = mallocd_datalen;
1151 new->direction = DIRECTION_INGRESS;
1157 #define NEW_PREVENT 0
1161 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1163 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1164 (cur->addr.sin_port == sin->sin_port)) {
1165 /* This is the main host */
1166 if ((cur->peercallno == callno) ||
1167 ((dcallno == cur->callno) && !cur->peercallno)) {
1168 /* That's us. Be sure we keep track of the peer call number */
1172 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1173 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1174 /* We're transferring */
1175 if (dcallno == cur->callno)
1181 static void update_max_trunk(void)
1183 int max = TRUNK_CALL_START;
1185 /* XXX Prolly don't need locks here XXX */
1186 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1191 if (option_debug && iaxdebug)
1192 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1195 static void update_max_nontrunk(void)
1199 /* XXX Prolly don't need locks here XXX */
1200 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1204 maxnontrunkcall = max;
1205 if (option_debug && iaxdebug)
1206 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1209 static int make_trunk(unsigned short callno, int locked)
1214 if (iaxs[callno]->oseqno) {
1215 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1218 if (callno & TRUNK_CALL_START) {
1219 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1222 gettimeofday(&now, NULL);
1223 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1224 ast_mutex_lock(&iaxsl[x]);
1225 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1226 iaxs[x] = iaxs[callno];
1227 iaxs[x]->callno = x;
1228 iaxs[callno] = NULL;
1229 /* Update the two timers that should have been started */
1230 if (iaxs[x]->pingid > -1)
1231 ast_sched_del(sched, iaxs[x]->pingid);
1232 if (iaxs[x]->lagid > -1)
1233 ast_sched_del(sched, iaxs[x]->lagid);
1234 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1235 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1237 ast_mutex_unlock(&iaxsl[callno]);
1240 ast_mutex_unlock(&iaxsl[x]);
1243 ast_mutex_unlock(&iaxsl[x]);
1245 if (x >= IAX_MAX_CALLS - 1) {
1246 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1250 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1251 /* We move this call from a non-trunked to a trunked call */
1253 update_max_nontrunk();
1258 * \todo XXX Note that this function contains a very expensive operation that
1259 * happens for *every* incoming media frame. It iterates through every
1260 * possible call number, locking and unlocking each one, to try to match the
1261 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1262 * So, for an call with a local call number of 20000, every incoming audio
1263 * frame would require 20000 mutex lock and unlock operations. Ouch.
1265 * It's a shame that IAX2 media frames carry the source call number instead of
1266 * the destination call number. If they did, this lookup wouldn't be needed.
1267 * However, it's too late to change that now. Instead, we need to come up with
1268 * a better way of indexing active calls so that these frequent lookups are not
1271 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1277 if (new <= NEW_ALLOW) {
1278 /* Look for an existing connection first */
1279 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1280 ast_mutex_lock(&iaxsl[x]);
1282 /* Look for an exact match */
1283 if (match(sin, callno, dcallno, iaxs[x])) {
1287 ast_mutex_unlock(&iaxsl[x]);
1289 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1290 ast_mutex_lock(&iaxsl[x]);
1292 /* Look for an exact match */
1293 if (match(sin, callno, dcallno, iaxs[x])) {
1297 ast_mutex_unlock(&iaxsl[x]);
1300 if ((res < 1) && (new >= NEW_ALLOW)) {
1301 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1302 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1303 gettimeofday(&now, NULL);
1304 for (x=1;x<TRUNK_CALL_START;x++) {
1305 /* Find first unused call number that hasn't been used in a while */
1306 ast_mutex_lock(&iaxsl[x]);
1307 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1308 ast_mutex_unlock(&iaxsl[x]);
1310 /* We've still got lock held if we found a spot */
1311 if (x >= TRUNK_CALL_START) {
1312 ast_log(LOG_WARNING, "No more space\n");
1315 iaxs[x] = new_iax(sin, lockpeer, host);
1316 update_max_nontrunk();
1318 if (option_debug && iaxdebug)
1319 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1320 iaxs[x]->sockfd = sockfd;
1321 iaxs[x]->addr.sin_port = sin->sin_port;
1322 iaxs[x]->addr.sin_family = sin->sin_family;
1323 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1324 iaxs[x]->peercallno = callno;
1325 iaxs[x]->callno = x;
1326 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1327 iaxs[x]->expiry = min_reg_expire;
1328 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1329 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1330 iaxs[x]->amaflags = amaflags;
1331 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1333 ast_string_field_set(iaxs[x], accountcode, accountcode);
1334 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1335 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1337 ast_log(LOG_WARNING, "Out of resources\n");
1338 ast_mutex_unlock(&iaxsl[x]);
1341 ast_mutex_unlock(&iaxsl[x]);
1347 static void iax2_frame_free(struct iax_frame *fr)
1349 if (fr->retrans > -1)
1350 ast_sched_del(sched, fr->retrans);
1354 static int iax2_queue_frame(int callno, struct ast_frame *f)
1356 /* Assumes lock for callno is already held... */
1358 if (iaxs[callno] && iaxs[callno]->owner) {
1359 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1360 /* Avoid deadlock by pausing and trying again */
1361 ast_mutex_unlock(&iaxsl[callno]);
1363 ast_mutex_lock(&iaxsl[callno]);
1365 ast_queue_frame(iaxs[callno]->owner, f);
1366 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1375 static void destroy_firmware(struct iax_firmware *cur)
1377 /* Close firmware */
1379 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1385 static int try_firmware(char *s)
1388 struct iax_firmware *cur = NULL;
1389 int ifd, fd, res, len, chunk;
1390 struct ast_iax2_firmware_header *fwh, fwh2;
1391 struct MD5Context md5;
1392 unsigned char sum[16], buf[1024];
1395 if (!(s2 = alloca(strlen(s) + 100))) {
1396 ast_log(LOG_WARNING, "Alloca failed!\n");
1400 last = strrchr(s, '/');
1406 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1408 if ((res = stat(s, &stbuf) < 0)) {
1409 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1413 /* Make sure it's not a directory */
1414 if (S_ISDIR(stbuf.st_mode))
1416 ifd = open(s, O_RDONLY);
1418 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1421 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1423 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1427 /* Unlink our newly created file */
1430 /* Now copy the firmware into it */
1431 len = stbuf.st_size;
1434 if (chunk > sizeof(buf))
1435 chunk = sizeof(buf);
1436 res = read(ifd, buf, chunk);
1438 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1443 res = write(fd, buf, chunk);
1445 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1453 /* Return to the beginning */
1454 lseek(fd, 0, SEEK_SET);
1455 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1456 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1460 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1461 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1465 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1466 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1470 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1471 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1475 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1476 if (fwh == (void *) -1) {
1477 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1482 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1483 MD5Final(sum, &md5);
1484 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1485 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1486 munmap(fwh, stbuf.st_size);
1491 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1492 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1493 /* Found a candidate */
1494 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1495 /* The version we have on loaded is older, load this one instead */
1497 /* This version is no newer than what we have. Don't worry about it.
1498 We'll consider it a proper load anyhow though */
1499 munmap(fwh, stbuf.st_size);
1505 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1507 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1512 munmap(cur->fwh, cur->mmaplen);
1517 cur->mmaplen = stbuf.st_size;
1524 static int iax_check_version(char *dev)
1527 struct iax_firmware *cur = NULL;
1529 if (ast_strlen_zero(dev))
1532 AST_LIST_LOCK(&firmwares);
1533 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1534 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1535 res = ntohs(cur->fwh->version);
1539 AST_LIST_UNLOCK(&firmwares);
1544 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1547 unsigned int bs = desc & 0xff;
1548 unsigned int start = (desc >> 8) & 0xffffff;
1550 struct iax_firmware *cur;
1552 if (ast_strlen_zero((char *)dev) || !bs)
1557 AST_LIST_LOCK(&firmwares);
1558 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1559 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1561 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1562 if (start < ntohl(cur->fwh->datalen)) {
1563 bytes = ntohl(cur->fwh->datalen) - start;
1566 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1569 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1577 AST_LIST_UNLOCK(&firmwares);
1583 static void reload_firmware(void)
1585 struct iax_firmware *cur = NULL;
1588 char dir[256], fn[256];
1590 AST_LIST_LOCK(&firmwares);
1592 /* Mark all as dead */
1593 AST_LIST_TRAVERSE(&firmwares, cur, list)
1596 /* Now that we have marked them dead... load new ones */
1597 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1600 while((de = readdir(fwd))) {
1601 if (de->d_name[0] != '.') {
1602 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1603 if (!try_firmware(fn)) {
1604 if (option_verbose > 1)
1605 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1611 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1613 /* Clean up leftovers */
1614 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1617 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1618 destroy_firmware(cur);
1620 AST_LIST_TRAVERSE_SAFE_END
1622 AST_LIST_UNLOCK(&firmwares);
1625 static int __do_deliver(void *data)
1627 /* Just deliver the packet by using queueing. This is called by
1628 the IAX thread with the iaxsl lock held. */
1629 struct iax_frame *fr = data;
1631 fr->af.has_timing_info = 0;
1632 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1633 iax2_queue_frame(fr->callno, &fr->af);
1634 /* Free our iax frame */
1635 iax2_frame_free(fr);
1636 /* And don't run again */
1640 static int handle_error(void)
1642 /* XXX Ideally we should figure out why an error occurred and then abort those
1643 rather than continuing to try. Unfortunately, the published interface does
1644 not seem to work XXX */
1646 struct sockaddr_in *sin;
1649 struct sock_extended_err e;
1654 m.msg_controllen = sizeof(e);
1656 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1658 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1660 if (m.msg_controllen) {
1661 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1663 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1665 ast_log(LOG_WARNING, "No address detected??\n");
1667 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1674 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1677 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1681 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1688 static int send_packet(struct iax_frame *f)
1691 int callno = f->callno;
1693 /* Don't send if there was an error, but return error instead */
1694 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1697 /* Called with iaxsl held */
1698 if (option_debug > 2 && iaxdebug)
1699 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));
1702 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1703 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1704 sizeof(iaxs[callno]->transfer));
1707 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1708 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1709 sizeof(iaxs[callno]->addr));
1712 if (option_debug && iaxdebug)
1713 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1720 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1722 struct iax2_user *user = NULL;
1724 /* Decrement AUTHREQ count if needed */
1725 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1726 AST_LIST_LOCK(&users);
1727 AST_LIST_TRAVERSE(&users, user, entry) {
1728 if (!strcmp(user->name, pvt->username)) {
1733 AST_LIST_UNLOCK(&users);
1734 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1736 /* No more pings or lagrq's */
1737 if (pvt->pingid > -1)
1738 ast_sched_del(sched, pvt->pingid);
1740 if (pvt->lagid > -1)
1741 ast_sched_del(sched, pvt->lagid);
1743 if (pvt->autoid > -1)
1744 ast_sched_del(sched, pvt->autoid);
1746 if (pvt->authid > -1)
1747 ast_sched_del(sched, pvt->authid);
1749 if (pvt->initid > -1)
1750 ast_sched_del(sched, pvt->initid);
1753 ast_sched_del(sched, pvt->jbid);
1757 static int iax2_predestroy(int callno)
1759 struct ast_channel *c = NULL;
1760 struct chan_iax2_pvt *pvt = iaxs[callno];
1765 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1766 iax2_destroy_helper(pvt);
1767 ast_set_flag(pvt, IAX_ALREADYGONE);
1770 if ((c = pvt->owner)) {
1771 c->_softhangup |= AST_SOFTHANGUP_DEV;
1773 ast_queue_hangup(c);
1775 ast_module_unref(ast_module_info->self);
1781 static void iax2_destroy(int callno)
1783 struct chan_iax2_pvt *pvt = NULL;
1784 struct iax_frame *cur = NULL;
1785 struct ast_channel *owner = NULL;
1789 gettimeofday(&lastused[callno], NULL);
1791 owner = pvt ? pvt->owner : NULL;
1794 if (ast_mutex_trylock(&owner->lock)) {
1795 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1796 ast_mutex_unlock(&iaxsl[callno]);
1798 ast_mutex_lock(&iaxsl[callno]);
1803 iaxs[callno] = NULL;
1807 iax2_destroy_helper(pvt);
1810 ast_set_flag(pvt, IAX_ALREADYGONE);
1813 /* If there's an owner, prod it to give up */
1814 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1815 ast_queue_hangup(owner);
1818 AST_LIST_LOCK(&queue);
1819 AST_LIST_TRAVERSE(&queue, cur, list) {
1820 /* Cancel any pending transmissions */
1821 if (cur->callno == pvt->callno)
1824 AST_LIST_UNLOCK(&queue);
1827 pvt->reg->callno = 0;
1831 ast_variables_destroy(pvt->vars);
1835 while (jb_getall(pvt->jb, &frame) == JB_OK)
1836 iax2_frame_free(frame.data);
1837 jb_destroy(pvt->jb);
1838 /* gotta free up the stringfields */
1839 ast_string_field_free_pools(pvt);
1844 ast_mutex_unlock(&owner->lock);
1846 if (callno & 0x4000)
1850 static int update_packet(struct iax_frame *f)
1852 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1853 struct ast_iax2_full_hdr *fh = f->data;
1854 /* Mark this as a retransmission */
1855 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1857 f->iseqno = iaxs[f->callno]->iseqno;
1858 fh->iseqno = f->iseqno;
1862 static int attempt_transmit(void *data);
1863 static void __attempt_transmit(void *data)
1865 /* Attempt to transmit the frame to the remote peer...
1866 Called without iaxsl held. */
1867 struct iax_frame *f = data;
1869 int callno = f->callno;
1870 /* Make sure this call is still active */
1872 ast_mutex_lock(&iaxsl[callno]);
1873 if (callno && iaxs[callno]) {
1874 if ((f->retries < 0) /* Already ACK'd */ ||
1875 (f->retries >= max_retries) /* Too many attempts */) {
1876 /* Record an error if we've transmitted too many times */
1877 if (f->retries >= max_retries) {
1879 /* Transfer timeout */
1880 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1881 } else if (f->final) {
1883 iax2_destroy(callno);
1885 if (iaxs[callno]->owner)
1886 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);
1887 iaxs[callno]->error = ETIMEDOUT;
1888 if (iaxs[callno]->owner) {
1889 struct ast_frame fr = { 0, };
1891 fr.frametype = AST_FRAME_CONTROL;
1892 fr.subclass = AST_CONTROL_HANGUP;
1893 iax2_queue_frame(callno, &fr);
1894 /* Remember, owner could disappear */
1895 if (iaxs[callno]->owner)
1896 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1898 if (iaxs[callno]->reg) {
1899 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1900 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1901 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1903 iax2_destroy(callno);
1910 /* Update it if it needs it */
1912 /* Attempt transmission */
1915 /* Try again later after 10 times as long */
1917 if (f->retrytime > MAX_RETRY_TIME)
1918 f->retrytime = MAX_RETRY_TIME;
1919 /* Transfer messages max out at one second */
1920 if (f->transfer && (f->retrytime > 1000))
1921 f->retrytime = 1000;
1922 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1925 /* Make sure it gets freed */
1930 ast_mutex_unlock(&iaxsl[callno]);
1931 /* Do not try again */
1933 /* Don't attempt delivery, just remove it from the queue */
1934 AST_LIST_LOCK(&queue);
1935 AST_LIST_REMOVE(&queue, f, list);
1936 AST_LIST_UNLOCK(&queue);
1938 /* Free the IAX frame */
1943 static int attempt_transmit(void *data)
1945 #ifdef SCHED_MULTITHREADED
1946 if (schedule_action(__attempt_transmit, data))
1948 __attempt_transmit(data);
1952 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1954 struct iax2_peer *peer;
1957 return RESULT_SHOWUSAGE;
1958 if (!strcmp(argv[3],"all")) {
1960 ast_cli(fd, "OK cache is flushed.\n");
1961 } else if ((peer = find_peer(argv[3], 0))) {
1962 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1963 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1964 expire_registry((void*)peer->name);
1965 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1967 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1970 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1973 return RESULT_SUCCESS;
1976 static int iax2_test_losspct(int fd, int argc, char *argv[])
1979 return RESULT_SHOWUSAGE;
1981 test_losspct = atoi(argv[3]);
1983 return RESULT_SUCCESS;
1987 static int iax2_test_late(int fd, int argc, char *argv[])
1990 return RESULT_SHOWUSAGE;
1992 test_late = atoi(argv[3]);
1994 return RESULT_SUCCESS;
1997 static int iax2_test_resync(int fd, int argc, char *argv[])
2000 return RESULT_SHOWUSAGE;
2002 test_resync = atoi(argv[3]);
2004 return RESULT_SUCCESS;
2007 static int iax2_test_jitter(int fd, int argc, char *argv[])
2009 if (argc < 4 || argc > 5)
2010 return RESULT_SHOWUSAGE;
2012 test_jit = atoi(argv[3]);
2014 test_jitpct = atoi(argv[4]);
2016 return RESULT_SUCCESS;
2018 #endif /* IAXTESTS */
2020 /*! \brief peer_status: Report Peer status in character string */
2021 /* returns 1 if peer is online, -1 if unmonitored */
2022 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2026 if (peer->lastms < 0) {
2027 ast_copy_string(status, "UNREACHABLE", statuslen);
2028 } else if (peer->lastms > peer->maxms) {
2029 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2031 } else if (peer->lastms) {
2032 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2035 ast_copy_string(status, "UNKNOWN", statuslen);
2038 ast_copy_string(status, "Unmonitored", statuslen);
2044 /*! \brief Show one peer in detail */
2045 static int iax2_show_peer(int fd, int argc, char *argv[])
2049 struct iax2_peer *peer;
2050 char codec_buf[512];
2051 int x = 0, codec = 0, load_realtime = 0;
2054 return RESULT_SHOWUSAGE;
2056 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2058 peer = find_peer(argv[3], load_realtime);
2061 ast_cli(fd, " * Name : %s\n", peer->name);
2062 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2063 ast_cli(fd, " Context : %s\n", peer->context);
2064 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2065 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2066 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2067 ast_cli(fd, " Expire : %d\n", peer->expire);
2068 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2069 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));
2070 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2071 ast_cli(fd, " Username : %s\n", peer->username);
2072 ast_cli(fd, " Codecs : ");
2073 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2074 ast_cli(fd, "%s\n", codec_buf);
2076 ast_cli(fd, " Codec Order : (");
2077 for(x = 0; x < 32 ; x++) {
2078 codec = ast_codec_pref_index(&peer->prefs,x);
2081 ast_cli(fd, "%s", ast_getformatname(codec));
2082 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2087 ast_cli(fd, "none");
2090 ast_cli(fd, " Status : ");
2091 peer_status(peer, status, sizeof(status));
2092 ast_cli(fd, "%s\n",status);
2093 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2095 if (ast_test_flag(peer, IAX_TEMPONLY))
2098 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2102 return RESULT_SUCCESS;
2105 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2108 struct iax2_peer *p = NULL;
2110 int wordlen = strlen(word);
2112 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2114 AST_LIST_LOCK(&peers);
2115 AST_LIST_TRAVERSE(&peers, p, entry) {
2116 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2117 res = ast_strdup(p->name);
2121 AST_LIST_UNLOCK(&peers);
2127 static int iax2_show_stats(int fd, int argc, char *argv[])
2129 struct iax_frame *cur;
2130 int cnt = 0, dead=0, final=0;
2133 return RESULT_SHOWUSAGE;
2135 AST_LIST_LOCK(&queue);
2136 AST_LIST_TRAVERSE(&queue, cur, list) {
2137 if (cur->retries < 0)
2143 AST_LIST_UNLOCK(&queue);
2145 ast_cli(fd, " IAX Statistics\n");
2146 ast_cli(fd, "---------------------\n");
2147 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2148 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2149 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2151 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2153 trunk_timed = trunk_untimed = 0;
2154 if (trunk_maxmtu > trunk_nmaxmtu)
2155 trunk_nmaxmtu = trunk_maxmtu;
2157 return RESULT_SUCCESS;
2160 /*! \brief Set trunk MTU from CLI */
2161 static int iax2_set_mtu(int fd, int argc, char *argv[])
2166 return RESULT_SHOWUSAGE;
2167 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0)
2168 mtuv = MAX_TRUNK_MTU;
2170 mtuv = atoi(argv[3]);
2173 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2174 global_max_trunk_mtu = 0;
2175 return RESULT_SUCCESS;
2177 if (mtuv < 172 || mtuv > 4000) {
2178 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n");
2179 return RESULT_SHOWUSAGE;
2181 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2182 global_max_trunk_mtu = mtuv;
2183 return RESULT_SUCCESS;
2186 static int iax2_show_cache(int fd, int argc, char *argv[])
2188 struct iax2_dpcache *dp = NULL;
2189 char tmp[1024], *pc = NULL;
2193 gettimeofday(&tv, NULL);
2195 AST_LIST_LOCK(&dpcache);
2197 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2199 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2200 s = dp->expiry.tv_sec - tv.tv_sec;
2202 if (dp->flags & CACHE_FLAG_EXISTS)
2203 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2204 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2205 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2206 if (dp->flags & CACHE_FLAG_CANEXIST)
2207 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2208 if (dp->flags & CACHE_FLAG_PENDING)
2209 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2210 if (dp->flags & CACHE_FLAG_TIMEOUT)
2211 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2212 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2213 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2214 if (dp->flags & CACHE_FLAG_MATCHMORE)
2215 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2216 if (dp->flags & CACHE_FLAG_UNKNOWN)
2217 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2218 /* Trim trailing pipe */
2219 if (!ast_strlen_zero(tmp))
2220 tmp[strlen(tmp) - 1] = '\0';
2222 ast_copy_string(tmp, "(none)", sizeof(tmp));
2224 pc = strchr(dp->peercontext, '@');
2226 pc = dp->peercontext;
2229 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2230 if (dp->waiters[x] > -1)
2233 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2235 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2238 AST_LIST_LOCK(&dpcache);
2240 return RESULT_SUCCESS;
2243 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2245 static void unwrap_timestamp(struct iax_frame *fr)
2249 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2250 x = fr->ts - iaxs[fr->callno]->last;
2252 /* Sudden big jump backwards in timestamp:
2253 What likely happened here is that miniframe timestamp has circled but we haven't
2254 gotten the update from the main packet. We'll just pretend that we did, and
2255 update the timestamp appropriately. */
2256 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2257 if (option_debug && iaxdebug)
2258 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2261 /* Sudden apparent big jump forwards in timestamp:
2262 What's likely happened is this is an old miniframe belonging to the previous
2263 top-16-bit timestamp that has turned up out of order.
2264 Adjust the timestamp appropriately. */
2265 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2266 if (option_debug && iaxdebug)
2267 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2272 static int get_from_jb(void *p);
2274 static void update_jbsched(struct chan_iax2_pvt *pvt)
2278 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2280 when = jb_next(pvt->jb) - when;
2282 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2285 /* XXX should really just empty until when > 0.. */
2289 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2291 /* Signal scheduler thread */
2292 signal_condition(&sched_lock, &sched_cond);
2295 static void __get_from_jb(void *p)
2297 int callno = PTR_TO_CALLNO(p);
2298 struct chan_iax2_pvt *pvt = NULL;
2299 struct iax_frame *fr;
2306 /* Make sure we have a valid private structure before going on */
2307 ast_mutex_lock(&iaxsl[callno]);
2311 ast_mutex_unlock(&iaxsl[callno]);
2317 gettimeofday(&tv,NULL);
2318 /* round up a millisecond since ast_sched_runq does; */
2319 /* prevents us from spinning while waiting for our now */
2320 /* to catch up with runq's now */
2323 now = ast_tvdiff_ms(tv, pvt->rxcore);
2325 if(now >= (next = jb_next(pvt->jb))) {
2326 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2334 struct ast_frame af;
2336 /* create an interpolation frame */
2337 af.frametype = AST_FRAME_VOICE;
2338 af.subclass = pvt->voiceformat;
2340 af.samples = frame.ms * 8;
2342 af.src = "IAX2 JB interpolation";
2344 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2345 af.offset=AST_FRIENDLY_OFFSET;
2347 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2348 * which we'd need to malloc, and then it would free it. That seems like a drag */
2349 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2350 iax2_queue_frame(callno, &af);
2354 iax2_frame_free(frame.data);
2361 /* shouldn't happen */
2365 update_jbsched(pvt);
2366 ast_mutex_unlock(&iaxsl[callno]);
2369 static int get_from_jb(void *data)
2371 #ifdef SCHED_MULTITHREADED
2372 if (schedule_action(__get_from_jb, data))
2374 __get_from_jb(data);
2378 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2384 /* Attempt to recover wrapped timestamps */
2385 unwrap_timestamp(fr);
2388 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2389 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2390 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2394 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2396 fr->af.delivery = ast_tv(0,0);
2399 type = JB_TYPE_CONTROL;
2402 if(fr->af.frametype == AST_FRAME_VOICE) {
2403 type = JB_TYPE_VOICE;
2404 len = ast_codec_get_samples(&fr->af) / 8;
2405 } else if(fr->af.frametype == AST_FRAME_CNG) {
2406 type = JB_TYPE_SILENCE;
2409 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2416 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2417 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2418 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2419 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2420 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2423 /* deliver any frames in the jb */
2424 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2425 __do_deliver(frame.data);
2427 jb_reset(iaxs[fr->callno]->jb);
2429 if (iaxs[fr->callno]->jbid > -1)
2430 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2432 iaxs[fr->callno]->jbid = -1;
2434 /* deliver this frame now */
2441 /* insert into jitterbuffer */
2442 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2443 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2444 calc_rxstamp(iaxs[fr->callno],fr->ts));
2445 if (ret == JB_DROP) {
2447 } else if (ret == JB_SCHED) {
2448 update_jbsched(iaxs[fr->callno]);
2453 /* Free our iax frame */
2454 iax2_frame_free(fr);
2460 static int iax2_transmit(struct iax_frame *fr)
2462 /* Lock the queue and place this packet at the end */
2463 /* By setting this to 0, the network thread will send it for us, and
2464 queue retransmission if necessary */
2466 AST_LIST_LOCK(&queue);
2467 AST_LIST_INSERT_TAIL(&queue, fr, list);
2468 AST_LIST_UNLOCK(&queue);
2469 /* Wake up the network and scheduler thread */
2470 pthread_kill(netthreadid, SIGURG);
2471 signal_condition(&sched_lock, &sched_cond);
2477 static int iax2_digit_begin(struct ast_channel *c, char digit)
2479 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2482 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2484 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2487 static int iax2_sendtext(struct ast_channel *c, const char *text)
2490 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2491 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2494 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2496 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2499 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2501 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2504 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2506 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2507 ast_mutex_lock(&iaxsl[callno]);
2509 iaxs[callno]->owner = newchan;
2511 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2512 ast_mutex_unlock(&iaxsl[callno]);
2516 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2518 struct ast_variable *var;
2519 struct ast_variable *tmp;
2520 struct iax2_peer *peer=NULL;
2521 time_t regseconds = 0, nowtime;
2525 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2528 sprintf(porta, "%d", ntohs(sin->sin_port));
2529 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2531 /* We'll need the peer name in order to build the structure! */
2532 for (tmp = var; tmp; tmp = tmp->next) {
2533 if (!strcasecmp(tmp->name, "name"))
2534 peername = tmp->value;
2541 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2546 for (tmp = var; tmp; tmp = tmp->next) {
2547 /* Make sure it's not a user only... */
2548 if (!strcasecmp(tmp->name, "type")) {
2549 if (strcasecmp(tmp->value, "friend") &&
2550 strcasecmp(tmp->value, "peer")) {
2551 /* Whoops, we weren't supposed to exist! */
2556 } else if (!strcasecmp(tmp->name, "regseconds")) {
2557 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2558 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2559 inet_aton(tmp->value, &(peer->addr.sin_addr));
2560 } else if (!strcasecmp(tmp->name, "port")) {
2561 peer->addr.sin_port = htons(atoi(tmp->value));
2562 } else if (!strcasecmp(tmp->name, "host")) {
2563 if (!strcasecmp(tmp->value, "dynamic"))
2570 ast_variables_destroy(var);
2572 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2573 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2574 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2575 if (peer->expire > -1)
2576 ast_sched_del(sched, peer->expire);
2577 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2579 AST_LIST_LOCK(&peers);
2580 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2581 AST_LIST_UNLOCK(&peers);
2582 if (ast_test_flag(peer, IAX_DYNAMIC))
2583 reg_source_db(peer);
2585 ast_set_flag(peer, IAX_TEMPONLY);
2588 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2590 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2591 memset(&peer->addr, 0, sizeof(peer->addr));
2592 realtime_update_peer(peer->name, &peer->addr, 0);
2594 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2595 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2599 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2600 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2607 static struct iax2_user *realtime_user(const char *username)
2609 struct ast_variable *var;
2610 struct ast_variable *tmp;
2611 struct iax2_user *user=NULL;
2613 var = ast_load_realtime("iaxusers", "name", username, NULL);
2619 /* Make sure it's not a peer only... */
2620 if (!strcasecmp(tmp->name, "type")) {
2621 if (strcasecmp(tmp->value, "friend") &&
2622 strcasecmp(tmp->value, "user")) {
2629 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2633 ast_variables_destroy(var);
2635 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2636 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2637 AST_LIST_LOCK(&users);
2638 AST_LIST_INSERT_HEAD(&users, user, entry);
2639 AST_LIST_UNLOCK(&users);
2641 ast_set_flag(user, IAX_TEMPONLY);
2647 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2650 char regseconds[20];
2652 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2653 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2654 ast_update_realtime("iaxpeers", "name", peername,
2655 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2656 "regseconds", regseconds, NULL);
2659 struct create_addr_info {
2672 char context[AST_MAX_CONTEXT];
2673 char peercontext[AST_MAX_CONTEXT];
2674 char mohinterpret[MAX_MUSICCLASS];
2675 char mohsuggest[MAX_MUSICCLASS];
2678 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2680 struct iax2_peer *peer;
2682 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2683 cai->sockfd = defaultsockfd;
2685 sin->sin_family = AF_INET;
2687 if (!(peer = find_peer(peername, 1))) {
2689 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
2690 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2693 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2694 /* use global iax prefs for unknown peer/user */
2695 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2701 /* if the peer has no address (current or default), return failure */
2702 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2703 if (ast_test_flag(peer, IAX_TEMPONLY))
2708 /* if the peer is being monitored and is currently unreachable, return failure */
2709 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2710 if (ast_test_flag(peer, IAX_TEMPONLY))
2715 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2716 cai->maxtime = peer->maxms;
2717 cai->capability = peer->capability;
2718 cai->encmethods = peer->encmethods;
2719 cai->sockfd = peer->sockfd;
2720 cai->adsi = peer->adsi;
2721 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2722 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2723 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2724 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2725 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2726 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2727 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2728 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2729 if (ast_strlen_zero(peer->dbsecret)) {
2730 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2735 family = ast_strdupa(peer->dbsecret);
2736 key = strchr(family, '/');
2739 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2740 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2741 if (ast_test_flag(peer, IAX_TEMPONLY))
2747 if (peer->addr.sin_addr.s_addr) {
2748 sin->sin_addr = peer->addr.sin_addr;
2749 sin->sin_port = peer->addr.sin_port;
2751 sin->sin_addr = peer->defaddr.sin_addr;
2752 sin->sin_port = peer->defaddr.sin_port;
2755 if (ast_test_flag(peer, IAX_TEMPONLY))
2761 static void __auto_congest(void *nothing)
2763 int callno = PTR_TO_CALLNO(nothing);
2764 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2765 ast_mutex_lock(&iaxsl[callno]);
2767 iaxs[callno]->initid = -1;
2768 iax2_queue_frame(callno, &f);
2769 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2771 ast_mutex_unlock(&iaxsl[callno]);
2774 static int auto_congest(void *data)
2776 #ifdef SCHED_MULTITHREADED
2777 if (schedule_action(__auto_congest, data))
2779 __auto_congest(data);
2783 static unsigned int iax2_datetime(const char *tz)
2789 localtime_r(&t, &tm);
2790 if (!ast_strlen_zero(tz))
2791 ast_localtime(&t, &tm, tz);
2792 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2793 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2794 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2795 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2796 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2797 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2801 struct parsed_dial_string {
2813 * \brief Parses an IAX dial string into its component parts.
2814 * \param data the string to be parsed
2815 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2818 * This function parses the string and fills the structure
2819 * with pointers to its component parts. The input string
2822 * \note This function supports both plaintext passwords and RSA
2823 * key names; if the password string is formatted as '[keyname]',
2824 * then the keyname will be placed into the key field, and the
2825 * password field will be set to NULL.
2827 * \note The dial string format is:
2828 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2830 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2832 if (ast_strlen_zero(data))
2835 pds->peer = strsep(&data, "/");
2836 pds->exten = strsep(&data, "/");
2837 pds->options = data;
2841 pds->exten = strsep(&data, "@");
2842 pds->context = data;
2845 if (strchr(pds->peer, '@')) {
2847 pds->username = strsep(&data, "@");
2851 if (pds->username) {
2852 data = pds->username;
2853 pds->username = strsep(&data, ":");
2854 pds->password = data;
2858 pds->peer = strsep(&data, ":");
2861 /* check for a key name wrapped in [] in the secret position, if found,
2862 move it to the key field instead
2864 if (pds->password && (pds->password[0] == '[')) {
2865 pds->key = ast_strip_quoted(pds->password, "[", "]");
2866 pds->password = NULL;
2870 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2872 struct sockaddr_in sin;
2873 char *l=NULL, *n=NULL, *tmpstr;
2874 struct iax_ie_data ied;
2875 char *defaultrdest = "s";
2876 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2877 struct parsed_dial_string pds;
2878 struct create_addr_info cai;
2879 struct ast_var_t *var;
2881 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2882 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2886 memset(&cai, 0, sizeof(cai));
2887 cai.encmethods = iax2_encryption;
2889 memset(&pds, 0, sizeof(pds));
2890 tmpstr = ast_strdupa(dest);
2891 parse_dial_string(tmpstr, &pds);
2894 pds.exten = defaultrdest;
2896 if (create_addr(pds.peer, &sin, &cai)) {
2897 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2901 if (!pds.username && !ast_strlen_zero(cai.username))
2902 pds.username = cai.username;
2903 if (!pds.password && !ast_strlen_zero(cai.secret))
2904 pds.password = cai.secret;
2905 if (!pds.key && !ast_strlen_zero(cai.outkey))
2906 pds.key = cai.outkey;
2907 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2908 pds.context = cai.peercontext;
2910 /* Keep track of the context for outgoing calls too */
2911 ast_copy_string(c->context, cai.context, sizeof(c->context));
2914 sin.sin_port = htons(atoi(pds.port));
2917 n = c->cid.cid_name;
2919 /* Now build request */
2920 memset(&ied, 0, sizeof(ied));
2922 /* On new call, first IE MUST be IAX version of caller */
2923 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2924 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2925 if (pds.options && strchr(pds.options, 'a')) {
2926 /* Request auto answer */
2927 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2930 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2933 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2934 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2937 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2939 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2942 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2943 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2946 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2947 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2948 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2950 if (!ast_strlen_zero(c->language))
2951 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2952 if (!ast_strlen_zero(c->cid.cid_dnid))
2953 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2954 if (!ast_strlen_zero(c->cid.cid_rdnis))
2955 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2958 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2961 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2964 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2966 ast_mutex_lock(&iaxsl[callno]);
2968 if (!ast_strlen_zero(c->context))
2969 ast_string_field_set(iaxs[callno], context, c->context);
2972 ast_string_field_set(iaxs[callno], username, pds.username);
2974 iaxs[callno]->encmethods = cai.encmethods;
2976 iaxs[callno]->adsi = cai.adsi;
2978 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
2979 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
2982 ast_string_field_set(iaxs[callno], outkey, pds.key);
2984 ast_string_field_set(iaxs[callno], secret, pds.password);
2986 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2987 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2988 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2989 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2991 if (iaxs[callno]->maxtime) {
2992 /* Initialize pingtime and auto-congest time */
2993 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2994 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2995 } else if (autokill) {
2996 iaxs[callno]->pingtime = autokill / 2;
2997 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3000 /* send the command using the appropriate socket for this peer */
3001 iaxs[callno]->sockfd = cai.sockfd;
3003 /* Add remote vars */
3004 AST_LIST_TRAVERSE(&c->varshead, var, entries) {
3005 if (!strncmp(ast_var_name(var), "~IAX2~", strlen("~IAX2~"))) {
3008 /* Automatically divide the value up into sized chunks */
3009 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) - strlen("~IAX2~") + 1)) {
3010 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var) + strlen("~IAX2~"), ast_var_value(var) + i);
3011 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3016 /* Transmit the string in a "NEW" request */
3017 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3019 ast_mutex_unlock(&iaxsl[callno]);
3020 ast_setstate(c, AST_STATE_RINGING);
3025 static int iax2_hangup(struct ast_channel *c)
3027 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3029 struct iax_ie_data ied;
3030 memset(&ied, 0, sizeof(ied));
3031 ast_mutex_lock(&iaxsl[callno]);
3032 if (callno && iaxs[callno]) {
3034 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3035 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3036 /* Send the hangup unless we have had a transmission error or are already gone */
3037 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3038 if (!iaxs[callno]->error && !alreadygone)
3039 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3040 /* Explicitly predestroy it */
3041 iax2_predestroy(callno);
3042 /* If we were already gone to begin with, destroy us now */
3045 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3046 iax2_destroy(callno);
3049 ast_mutex_unlock(&iaxsl[callno]);
3050 if (option_verbose > 2)
3051 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3055 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3057 struct ast_option_header *h;
3061 case AST_OPTION_TXGAIN:
3062 case AST_OPTION_RXGAIN:
3063 /* these two cannot be sent, because they require a result */
3067 if (!(h = ast_malloc(datalen + sizeof(*h))))
3070 h->flag = AST_OPTION_FLAG_REQUEST;
3071 h->option = htons(option);
3072 memcpy(h->data, data, datalen);
3073 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3074 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3075 datalen + sizeof(*h), -1);
3081 static struct ast_frame *iax2_read(struct ast_channel *c)
3083 ast_log(LOG_NOTICE, "I should never be called!\n");
3084 return &ast_null_frame;
3087 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3090 struct iax_ie_data ied0;
3091 struct iax_ie_data ied1;
3092 unsigned int transferid = (unsigned int)ast_random();
3093 memset(&ied0, 0, sizeof(ied0));
3094 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3095 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3096 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3098 memset(&ied1, 0, sizeof(ied1));
3099 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3100 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3101 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3103 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3106 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3109 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3110 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3114 static void lock_both(unsigned short callno0, unsigned short callno1)
3116 ast_mutex_lock(&iaxsl[callno0]);
3117 while (ast_mutex_trylock(&iaxsl[callno1])) {
3118 ast_mutex_unlock(&iaxsl[callno0]);
3120 ast_mutex_lock(&iaxsl[callno0]);
3124 static void unlock_both(unsigned short callno0, unsigned short callno1)
3126 ast_mutex_unlock(&iaxsl[callno1]);
3127 ast_mutex_unlock(&iaxsl[callno0]);
3130 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)
3132 struct ast_channel *cs[3];
3133 struct ast_channel *who, *other;
3136 int transferstarted=0;
3137 struct ast_frame *f;
3138 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3139 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3140 struct timeval waittimer = {0, 0}, tv;
3142 lock_both(callno0, callno1);
3143 /* Put them in native bridge mode */
3144 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3145 iaxs[callno0]->bridgecallno = callno1;
3146 iaxs[callno1]->bridgecallno = callno0;
3148 unlock_both(callno0, callno1);
3150 /* If not, try to bridge until we can execute a transfer, if we can */
3153 for (/* ever */;;) {
3154 /* Check in case we got masqueraded into */
3155 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3156 if (option_verbose > 2)
3157 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3158 /* Remove from native mode */
3159 if (c0->tech == &iax2_tech) {
3160 ast_mutex_lock(&iaxsl[callno0]);
3161 iaxs[callno0]->bridgecallno = 0;
3162 ast_mutex_unlock(&iaxsl[callno0]);
3164 if (c1->tech == &iax2_tech) {
3165 ast_mutex_lock(&iaxsl[callno1]);
3166 iaxs[callno1]->bridgecallno = 0;
3167 ast_mutex_unlock(&iaxsl[callno1]);
3169 return AST_BRIDGE_FAILED_NOWARN;
3171 if (c0->nativeformats != c1->nativeformats) {
3172 if (option_verbose > 2) {
3175 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3176 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3177 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3179 /* Remove from native mode */
3180 lock_both(callno0, callno1);
3181 iaxs[callno0]->bridgecallno = 0;
3182 iaxs[callno1]->bridgecallno = 0;
3183 unlock_both(callno0, callno1);
3184 return AST_BRIDGE_FAILED_NOWARN;
3186 /* check if transfered and if we really want native bridging */
3187 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3188 /* Try the transfer */