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>
62 #include <sys/ioctl.h>
63 #include <zaptel/zaptel.h>
66 #include "asterisk/lock.h"
67 #include "asterisk/frame.h"
68 #include "asterisk/channel.h"
69 #include "asterisk/logger.h"
70 #include "asterisk/module.h"
71 #include "asterisk/pbx.h"
72 #include "asterisk/sched.h"
73 #include "asterisk/io.h"
74 #include "asterisk/config.h"
75 #include "asterisk/options.h"
76 #include "asterisk/cli.h"
77 #include "asterisk/translate.h"
78 #include "asterisk/md5.h"
79 #include "asterisk/cdr.h"
80 #include "asterisk/crypto.h"
81 #include "asterisk/acl.h"
82 #include "asterisk/manager.h"
83 #include "asterisk/callerid.h"
84 #include "asterisk/app.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/musiconhold.h"
87 #include "asterisk/features.h"
88 #include "asterisk/utils.h"
89 #include "asterisk/causes.h"
90 #include "asterisk/localtime.h"
91 #include "asterisk/aes.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
99 #include "iax2-parser.h"
100 #include "iax2-provision.h"
101 #include "jitterbuf.h"
103 /* Define SCHED_MULTITHREADED to run the scheduler in a special
104 multithreaded mode. */
105 #define SCHED_MULTITHREADED
107 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
108 thread is actually doing. */
109 #define DEBUG_SCHED_MULTITHREAD
111 #ifndef IPTOS_MINCOST
112 #define IPTOS_MINCOST 0x02
116 static int nochecksums = 0;
120 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
121 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
123 #define DEFAULT_THREAD_COUNT 10
124 #define DEFAULT_MAX_THREAD_COUNT 100
125 #define DEFAULT_RETRY_TIME 1000
126 #define MEMORY_SIZE 100
127 #define DEFAULT_DROP 3
128 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
129 but keeps the division between trunked and non-trunked better. */
130 #define TRUNK_CALL_START 0x4000
132 #define DEBUG_SUPPORT
134 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
136 /* Sample over last 100 units to determine historic jitter */
139 static struct ast_codec_pref prefs;
141 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
144 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
145 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
146 #define MAX_TRUNK_MTU 1240
148 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
149 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
152 static char context[80] = "default";
154 static char language[MAX_LANGUAGE] = "";
155 static char regcontext[AST_MAX_CONTEXT] = "";
157 static int maxauthreq = 3;
158 static int max_retries = 4;
159 static int ping_time = 20;
160 static int lagrq_time = 10;
161 static int maxtrunkcall = TRUNK_CALL_START;
162 static int maxnontrunkcall = 1;
163 static int maxjitterbuffer=1000;
164 static int resyncthreshold=1000;
165 static int maxjitterinterps=10;
166 static int trunkfreq = 20;
167 static int authdebug = 1;
168 static int autokill = 0;
169 static int iaxcompat = 0;
171 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
173 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
175 static unsigned int tos = 0;
177 static int min_reg_expire;
178 static int max_reg_expire;
180 static int timingfd = -1; /* Timing file descriptor */
182 static struct ast_netsock_list *netsock;
183 static int defaultsockfd = -1;
185 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
188 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
190 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
191 ~AST_FORMAT_SLINEAR & \
196 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
198 ~AST_FORMAT_G726_AAL2 & \
201 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
205 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
206 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
207 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
209 static struct io_context *io;
210 static struct sched_context *sched;
212 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
214 static int iaxdebug = 0;
216 static int iaxtrunkdebug = 0;
218 static int test_losspct = 0;
220 static int test_late = 0;
221 static int test_resync = 0;
222 static int test_jit = 0;
223 static int test_jitpct = 0;
224 #endif /* IAXTESTS */
226 static char accountcode[AST_MAX_ACCOUNT_CODE];
227 static char mohinterpret[MAX_MUSICCLASS];
228 static char mohsuggest[MAX_MUSICCLASS];
229 static int amaflags = 0;
231 static int delayreject = 0;
232 static int iax2_encryption = 0;
234 static struct ast_flags globalflags = { 0 };
236 static pthread_t netthreadid = AST_PTHREADT_NULL;
237 static pthread_t schedthreadid = AST_PTHREADT_NULL;
238 AST_MUTEX_DEFINE_STATIC(sched_lock);
239 static ast_cond_t sched_cond;
242 IAX_STATE_STARTED = (1 << 0),
243 IAX_STATE_AUTHENTICATED = (1 << 1),
244 IAX_STATE_TBD = (1 << 2),
245 IAX_STATE_UNCHANGED = (1 << 3),
248 struct iax2_context {
249 char context[AST_MAX_CONTEXT];
250 struct iax2_context *next;
254 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
255 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
256 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
257 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
258 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
259 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
260 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
261 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
262 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
263 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
264 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
265 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
266 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
267 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
268 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
269 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
270 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
271 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
272 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
273 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
274 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
275 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
276 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
277 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
278 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
281 static int global_rtautoclear = 120;
283 static int reload_config(void);
284 static int iax2_reload(int fd, int argc, char *argv[]);
288 AST_DECLARE_STRING_FIELDS(
289 AST_STRING_FIELD(name);
290 AST_STRING_FIELD(secret);
291 AST_STRING_FIELD(dbsecret);
292 AST_STRING_FIELD(accountcode);
293 AST_STRING_FIELD(mohinterpret);
294 AST_STRING_FIELD(mohsuggest);
295 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
296 AST_STRING_FIELD(language);
297 AST_STRING_FIELD(cid_num);
298 AST_STRING_FIELD(cid_name);
307 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
308 int curauthreq; /*!< Current number of outstanding AUTHREQs */
309 struct ast_codec_pref prefs;
311 struct iax2_context *contexts;
312 struct ast_variable *vars;
313 AST_LIST_ENTRY(iax2_user) entry;
317 AST_DECLARE_STRING_FIELDS(
318 AST_STRING_FIELD(name);
319 AST_STRING_FIELD(username);
320 AST_STRING_FIELD(secret);
321 AST_STRING_FIELD(dbsecret);
322 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
324 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
325 AST_STRING_FIELD(context); /*!< For transfers only */
326 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
327 AST_STRING_FIELD(mailbox); /*!< Mailbox */
328 AST_STRING_FIELD(mohinterpret);
329 AST_STRING_FIELD(mohsuggest);
330 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
331 /* Suggested caller id if registering */
332 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
333 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
334 AST_STRING_FIELD(zonetag); /*!< Time Zone */
336 struct ast_codec_pref prefs;
337 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
338 struct sockaddr_in addr;
340 int sockfd; /*!< Socket to use for transmission */
345 /* Dynamic Registration fields */
346 struct sockaddr_in defaddr; /*!< Default address if there is one */
347 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
348 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
350 int expire; /*!< Schedule entry for expiry */
351 int expiry; /*!< How soon to expire */
352 int capability; /*!< Capability */
355 int callno; /*!< Call number of POKE request */
356 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
357 int lastms; /*!< How long last response took (in ms), or -1 for no response */
358 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
360 int pokefreqok; /*!< How often to check if the host is up */
361 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
362 int historicms; /*!< How long recent average responses took */
363 int smoothing; /*!< Sample over how many units to determine historic ms */
366 AST_LIST_ENTRY(iax2_peer) entry;
369 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
371 struct iax2_trunk_peer {
374 struct sockaddr_in addr;
375 struct timeval txtrunktime; /*!< Transmit trunktime */
376 struct timeval rxtrunktime; /*!< Receive trunktime */
377 struct timeval lasttxtime; /*!< Last transmitted trunktime */
378 struct timeval trunkact; /*!< Last trunk activity */
379 unsigned int lastsent; /*!< Last sent time */
380 /* Trunk data and length */
381 unsigned char *trunkdata;
382 unsigned int trunkdatalen;
383 unsigned int trunkdataalloc;
387 AST_LIST_ENTRY(iax2_trunk_peer) list;
390 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
392 struct iax_firmware {
393 AST_LIST_ENTRY(iax_firmware) list;
397 struct ast_iax2_firmware_header *fwh;
402 REG_STATE_UNREGISTERED = 0,
405 REG_STATE_REGISTERED,
411 enum iax_transfer_state {
416 TRANSFER_PASSTHROUGH,
420 TRANSFER_MPASSTHROUGH,
425 struct iax2_registry {
426 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
428 char secret[80]; /*!< Password or key name in []'s */
430 int expire; /*!< Sched ID of expiration */
431 int refresh; /*!< How often to refresh */
432 enum iax_reg_state regstate;
433 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
434 int callno; /*!< Associated call number if applicable */
435 struct sockaddr_in us; /*!< Who the server thinks we are */
436 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
437 AST_LIST_ENTRY(iax2_registry) entry;
440 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
442 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
443 #define MIN_RETRY_TIME 100
444 #define MAX_RETRY_TIME 10000
446 #define MAX_JITTER_BUFFER 50
447 #define MIN_JITTER_BUFFER 10
449 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
450 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
452 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
454 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
455 #define TS_GAP_FOR_JB_RESYNC 5000
457 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
458 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
459 static int iaxdynamicthreadcount = 0;
471 struct chan_iax2_pvt {
472 /*! Socket to send/receive on for this call */
474 /*! Last received voice format */
476 /*! Last received video format */
478 /*! Last sent voice format */
480 /*! Last sent video format */
482 /*! What we are capable of sending */
484 /*! Last received timestamp */
486 /*! Last sent timestamp - never send the same timestamp twice in a single call */
487 unsigned int lastsent;
488 /*! Next outgoing timestamp if everything is good */
489 unsigned int nextpred;
490 /*! True if the last voice we transmitted was not silence/CNG */
491 unsigned int notsilenttx:1;
493 unsigned int pingtime;
494 /*! Max time for initial response */
497 struct sockaddr_in addr;
498 /*! Actual used codec preferences */
499 struct ast_codec_pref prefs;
500 /*! Requested codec preferences */
501 struct ast_codec_pref rprefs;
502 /*! Our call number */
503 unsigned short callno;
505 unsigned short peercallno;
506 /*! Peer selected format */
508 /*! Peer capability */
510 /*! timeval that we base our transmission on */
511 struct timeval offset;
512 /*! timeval that we base our delivery on */
513 struct timeval rxcore;
514 /*! The jitterbuffer */
516 /*! active jb read scheduler id */
520 /*! Error, as discovered by the manager */
522 /*! Owner if we have one */
523 struct ast_channel *owner;
524 /*! What's our state? */
525 struct ast_flags state;
526 /*! Expiry (optional) */
528 /*! Next outgoing sequence number */
529 unsigned char oseqno;
530 /*! Next sequence number they have not yet acknowledged */
531 unsigned char rseqno;
532 /*! Next incoming sequence number */
533 unsigned char iseqno;
534 /*! Last incoming sequence number we have acknowledged */
535 unsigned char aseqno;
537 AST_DECLARE_STRING_FIELDS(
539 AST_STRING_FIELD(peer);
540 /*! Default Context */
541 AST_STRING_FIELD(context);
542 /*! Caller ID if available */
543 AST_STRING_FIELD(cid_num);
544 AST_STRING_FIELD(cid_name);
545 /*! Hidden Caller ID (i.e. ANI) if appropriate */
546 AST_STRING_FIELD(ani);
548 AST_STRING_FIELD(dnid);
550 AST_STRING_FIELD(rdnis);
551 /*! Requested Extension */
552 AST_STRING_FIELD(exten);
553 /*! Expected Username */
554 AST_STRING_FIELD(username);
555 /*! Expected Secret */
556 AST_STRING_FIELD(secret);
558 AST_STRING_FIELD(challenge);
559 /*! Public keys permitted keys for incoming authentication */
560 AST_STRING_FIELD(inkeys);
561 /*! Private key for outgoing authentication */
562 AST_STRING_FIELD(outkey);
563 /*! Preferred language */
564 AST_STRING_FIELD(language);
565 /*! Hostname/peername for naming purposes */
566 AST_STRING_FIELD(host);
568 AST_STRING_FIELD(dproot);
569 AST_STRING_FIELD(accountcode);
570 AST_STRING_FIELD(mohinterpret);
571 AST_STRING_FIELD(mohsuggest);
574 /*! permitted authentication methods */
576 /*! permitted encryption methods */
578 /*! Encryption AES-128 Key */
580 /*! Decryption AES-128 Key */
582 /*! 32 bytes of semi-random data */
583 unsigned char semirand[32];
584 /*! Associated registry */
585 struct iax2_registry *reg;
586 /*! Associated peer for poking */
587 struct iax2_peer *peerpoke;
592 /*! Transferring status */
593 enum iax_transfer_state transferring;
594 /*! Transfer identifier */
596 /*! Who we are IAX transferring to */
597 struct sockaddr_in transfer;
598 /*! What's the new call number for the transfer */
599 unsigned short transfercallno;
600 /*! Transfer decrypt AES-128 Key */
601 aes_encrypt_ctx tdcx;
603 /*! Status of knowledge of peer ADSI capability */
606 /*! Who we are bridged to */
607 unsigned short bridgecallno;
609 int pingid; /*!< Transmit PING request */
610 int lagid; /*!< Retransmit lag request */
611 int autoid; /*!< Auto hangup for Dialplan requestor */
612 int authid; /*!< Authentication rejection ID */
613 int authfail; /*!< Reason to report failure */
614 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
619 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
620 struct ast_variable *vars;
621 /*! last received remote rr */
622 struct iax_rr remote_rr;
623 /*! Current base time: (just for stats) */
625 /*! Dropped frame count: (just for stats) */
627 /*! received frame count: (just for stats) */
631 static struct ast_iax2_queue {
632 AST_LIST_HEAD(, iax_frame) queue;
635 .queue = AST_LIST_HEAD_INIT_VALUE
638 static AST_LIST_HEAD_STATIC(users, iax2_user);
640 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
642 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
644 /*! Extension exists */
645 #define CACHE_FLAG_EXISTS (1 << 0)
646 /*! Extension is nonexistent */
647 #define CACHE_FLAG_NONEXISTENT (1 << 1)
648 /*! Extension can exist */
649 #define CACHE_FLAG_CANEXIST (1 << 2)
650 /*! Waiting to hear back response */
651 #define CACHE_FLAG_PENDING (1 << 3)
653 #define CACHE_FLAG_TIMEOUT (1 << 4)
654 /*! Request transmitted */
655 #define CACHE_FLAG_TRANSMITTED (1 << 5)
657 #define CACHE_FLAG_UNKNOWN (1 << 6)
659 #define CACHE_FLAG_MATCHMORE (1 << 7)
661 struct iax2_dpcache {
662 char peercontext[AST_MAX_CONTEXT];
663 char exten[AST_MAX_EXTENSION];
665 struct timeval expiry;
667 unsigned short callno;
669 AST_LIST_ENTRY(iax2_dpcache) cache_list;
670 AST_LIST_ENTRY(iax2_dpcache) peer_list;
673 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
675 static void reg_source_db(struct iax2_peer *p);
676 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
678 static void destroy_peer(struct iax2_peer *peer);
679 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
681 enum iax2_thread_iostate {
684 IAX_IOSTATE_PROCESSING,
685 IAX_IOSTATE_SCHEDREADY,
688 enum iax2_thread_type {
689 IAX_THREAD_TYPE_POOL,
690 IAX_THREAD_TYPE_DYNAMIC,
694 AST_LIST_ENTRY(iax2_thread) list;
695 enum iax2_thread_type type;
696 enum iax2_thread_iostate iostate;
697 #ifdef SCHED_MULTITHREADED
698 void (*schedfunc)(void *);
701 #ifdef DEBUG_SCHED_MULTITHREAD
707 struct sockaddr_in iosin;
708 unsigned char buf[4096];
717 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
718 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
719 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
721 static void *iax2_process_thread(void *data);
723 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
725 ast_mutex_lock(lock);
726 ast_cond_signal(cond);
727 ast_mutex_unlock(lock);
730 static void iax_debug_output(const char *data)
733 ast_verbose("%s", data);
736 static void iax_error_output(const char *data)
738 ast_log(LOG_WARNING, "%s", data);
741 static void jb_error_output(const char *fmt, ...)
747 vsnprintf(buf, sizeof(buf), fmt, args);
750 ast_log(LOG_ERROR, buf);
753 static void jb_warning_output(const char *fmt, ...)
759 vsnprintf(buf, sizeof(buf), fmt, args);
762 ast_log(LOG_WARNING, buf);
765 static void jb_debug_output(const char *fmt, ...)
771 vsnprintf(buf, sizeof(buf), fmt, args);
778 * \brief an array of iax2 pvt structures
780 * The container for active chan_iax2_pvt structures is implemented as an
781 * array for extremely quick direct access to the correct pvt structure
782 * based on the local call number. The local call number is used as the
783 * index into the array where the associated pvt structure is stored.
785 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
787 * \brief chan_iax2_pvt structure locks
789 * These locks are used when accessing a pvt structure in the iaxs array.
790 * The index used here is the same as used in the iaxs array. It is the
791 * local call number for the associated pvt struct.
793 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
795 * \brief The last time a call number was used
797 * It is important to know the last time that a call number was used locally so
798 * that it is not used again too soon. The reason for this is the same as the
799 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
801 * For example, say that a call is up. Then, the remote side sends a HANGUP,
802 * which we respond to with an ACK. However, there is no way to know whether
803 * the ACK made it there successfully. If it were to get lost, the remote
804 * side may retransmit the HANGUP. If in the meantime, this call number has
805 * been reused locally, given the right set of circumstances, this retransmitted
806 * HANGUP could potentially improperly hang up the new session. So, to avoid
807 * this potential issue, we must wait a specified timeout period before reusing
808 * a local call number.
810 * The specified time that we must wait before reusing a local call number is
811 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
813 static struct timeval lastused[IAX_MAX_CALLS];
815 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);
816 static int expire_registry(void *data);
817 static int iax2_answer(struct ast_channel *c);
818 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
819 static int iax2_devicestate(void *data);
820 static int iax2_digit_begin(struct ast_channel *c, char digit);
821 static int iax2_digit_end(struct ast_channel *c, char digit);
822 static int iax2_do_register(struct iax2_registry *reg);
823 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
824 static int iax2_hangup(struct ast_channel *c);
825 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
826 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
827 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
828 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
829 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
830 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
831 static int iax2_sendtext(struct ast_channel *c, const char *text);
832 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
833 static int iax2_transfer(struct ast_channel *c, const char *dest);
834 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
835 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
836 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
837 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
838 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
839 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
840 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
841 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
842 static struct ast_frame *iax2_read(struct ast_channel *c);
843 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
844 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
845 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
846 static void destroy_user(struct iax2_user *user);
847 static void prune_peers(void);
849 static const struct ast_channel_tech iax2_tech = {
851 .description = tdesc,
852 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
853 .properties = AST_CHAN_TP_WANTSJITTER,
854 .requester = iax2_request,
855 .devicestate = iax2_devicestate,
856 .send_digit_begin = iax2_digit_begin,
857 .send_digit_end = iax2_digit_end,
858 .send_text = iax2_sendtext,
859 .send_image = iax2_sendimage,
860 .send_html = iax2_sendhtml,
862 .hangup = iax2_hangup,
863 .answer = iax2_answer,
866 .write_video = iax2_write,
867 .indicate = iax2_indicate,
868 .setoption = iax2_setoption,
869 .bridge = iax2_bridge,
870 .transfer = iax2_transfer,
874 static struct iax2_thread *find_idle_thread(void)
876 struct iax2_thread *thread = NULL;
878 /* Pop the head of the list off */
879 AST_LIST_LOCK(&idle_list);
880 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
881 AST_LIST_UNLOCK(&idle_list);
883 /* If no idle thread is available from the regular list, try dynamic */
884 if (thread == NULL) {
885 AST_LIST_LOCK(&dynamic_list);
886 thread = AST_LIST_FIRST(&dynamic_list);
887 if (thread != NULL) {
888 AST_LIST_REMOVE(&dynamic_list, thread, list);
890 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
891 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
892 /* We need to MAKE a thread! */
893 thread = ast_calloc(1, sizeof(*thread));
894 if (thread != NULL) {
895 thread->threadnum = iaxdynamicthreadcount;
896 thread->type = IAX_THREAD_TYPE_DYNAMIC;
897 ast_mutex_init(&thread->lock);
898 ast_cond_init(&thread->cond, NULL);
899 if (ast_pthread_create(&thread->threadid, NULL, iax2_process_thread, thread)) {
903 /* All went well and the thread is up, so increment our count */
904 iaxdynamicthreadcount++;
908 AST_LIST_UNLOCK(&dynamic_list);
914 #ifdef SCHED_MULTITHREADED
915 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
917 struct iax2_thread *thread = NULL;
918 static time_t lasterror;
921 thread = find_idle_thread();
923 if (thread != NULL) {
924 thread->schedfunc = func;
925 thread->scheddata = data;
926 thread->iostate = IAX_IOSTATE_SCHEDREADY;
927 #ifdef DEBUG_SCHED_MULTITHREAD
928 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
930 signal_condition(&thread->lock, &thread->cond);
935 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
940 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
943 static void __send_ping(void *data)
945 int callno = (long)data;
946 send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
949 static int send_ping(void *data)
951 int callno = (long)data;
953 #ifdef SCHED_MULTITHREADED
954 if (schedule_action(__send_ping, data))
963 static int get_encrypt_methods(const char *s)
966 if (!strcasecmp(s, "aes128"))
967 e = IAX_ENCRYPT_AES128;
968 else if (ast_true(s))
969 e = IAX_ENCRYPT_AES128;
975 static void __send_lagrq(void *data)
977 int callno = (long)data;
978 /* Ping only if it's real not if it's bridged */
979 send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
982 static int send_lagrq(void *data)
984 int callno = (long)data;
986 #ifdef SCHED_MULTITHREADED
987 if (schedule_action(__send_lagrq, data))
996 static unsigned char compress_subclass(int subclass)
1000 /* If it's 128 or smaller, just return it */
1001 if (subclass < IAX_FLAG_SC_LOG)
1003 /* Otherwise find its power */
1004 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1005 if (subclass & (1 << x)) {
1007 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1013 return power | IAX_FLAG_SC_LOG;
1016 static int uncompress_subclass(unsigned char csub)
1018 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1019 if (csub & IAX_FLAG_SC_LOG) {
1020 /* special case for 'compressed' -1 */
1024 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1030 static struct iax2_peer *find_peer(const char *name, int realtime)
1032 struct iax2_peer *peer = NULL;
1034 /* Grab peer from linked list */
1035 AST_LIST_LOCK(&peers);
1036 AST_LIST_TRAVERSE(&peers, peer, entry) {
1037 if (!strcasecmp(peer->name, name)) {
1041 AST_LIST_UNLOCK(&peers);
1043 /* Now go for realtime if applicable */
1044 if(!peer && realtime)
1045 peer = realtime_peer(name, NULL);
1049 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1051 struct iax2_peer *peer = NULL;
1055 AST_LIST_LOCK(&peers);
1056 AST_LIST_TRAVERSE(&peers, peer, entry) {
1057 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1058 (peer->addr.sin_port == sin.sin_port)) {
1059 ast_copy_string(host, peer->name, len);
1065 AST_LIST_UNLOCK(&peers);
1067 peer = realtime_peer(NULL, &sin);
1069 ast_copy_string(host, peer->name, len);
1070 if (ast_test_flag(peer, IAX_TEMPONLY))
1079 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1081 struct chan_iax2_pvt *tmp;
1084 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1087 if (ast_string_field_init(tmp, 32)) {
1100 ast_string_field_set(tmp,exten, "s");
1101 ast_string_field_set(tmp,host, host);
1105 jbconf.max_jitterbuf = maxjitterbuffer;
1106 jbconf.resync_threshold = resyncthreshold;
1107 jbconf.max_contig_interp = maxjitterinterps;
1108 jb_setconf(tmp->jb,&jbconf);
1110 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1115 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1117 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1119 size_t mallocd_datalen = new->mallocd_datalen;
1120 memcpy(new, fr, sizeof(*new));
1121 iax_frame_wrap(new, &fr->af);
1122 new->mallocd_datalen = mallocd_datalen;
1125 new->direction = DIRECTION_INGRESS;
1131 #define NEW_PREVENT 0
1135 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1137 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1138 (cur->addr.sin_port == sin->sin_port)) {
1139 /* This is the main host */
1140 if ((cur->peercallno == callno) ||
1141 ((dcallno == cur->callno) && !cur->peercallno)) {
1142 /* That's us. Be sure we keep track of the peer call number */
1146 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1147 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1148 /* We're transferring */
1149 if (dcallno == cur->callno)
1155 static void update_max_trunk(void)
1157 int max = TRUNK_CALL_START;
1159 /* XXX Prolly don't need locks here XXX */
1160 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1165 if (option_debug && iaxdebug)
1166 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1169 static void update_max_nontrunk(void)
1173 /* XXX Prolly don't need locks here XXX */
1174 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1178 maxnontrunkcall = max;
1179 if (option_debug && iaxdebug)
1180 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1183 static int make_trunk(unsigned short callno, int locked)
1188 if (iaxs[callno]->oseqno) {
1189 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1192 if (callno & TRUNK_CALL_START) {
1193 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1196 gettimeofday(&now, NULL);
1197 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1198 ast_mutex_lock(&iaxsl[x]);
1199 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1200 iaxs[x] = iaxs[callno];
1201 iaxs[x]->callno = x;
1202 iaxs[callno] = NULL;
1203 /* Update the two timers that should have been started */
1204 if (iaxs[x]->pingid > -1)
1205 ast_sched_del(sched, iaxs[x]->pingid);
1206 if (iaxs[x]->lagid > -1)
1207 ast_sched_del(sched, iaxs[x]->lagid);
1208 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1209 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1211 ast_mutex_unlock(&iaxsl[callno]);
1214 ast_mutex_unlock(&iaxsl[x]);
1217 ast_mutex_unlock(&iaxsl[x]);
1219 if (x >= IAX_MAX_CALLS - 1) {
1220 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1224 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1225 /* We move this call from a non-trunked to a trunked call */
1227 update_max_nontrunk();
1232 * \todo XXX Note that this function contains a very expensive operation that
1233 * happens for *every* incoming media frame. It iterates through every
1234 * possible call number, locking and unlocking each one, to try to match the
1235 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1236 * So, for an call with a local call number of 20000, every incoming audio
1237 * frame would require 20000 mutex lock and unlock operations. Ouch.
1239 * It's a shame that IAX2 media frames carry the source call number instead of
1240 * the destination call number. If they did, this lookup wouldn't be needed.
1241 * However, it's too late to change that now. Instead, we need to come up with
1242 * a better way of indexing active calls so that these frequent lookups are not
1245 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1251 if (new <= NEW_ALLOW) {
1252 /* Look for an existing connection first */
1253 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1254 ast_mutex_lock(&iaxsl[x]);
1256 /* Look for an exact match */
1257 if (match(sin, callno, dcallno, iaxs[x])) {
1261 ast_mutex_unlock(&iaxsl[x]);
1263 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1264 ast_mutex_lock(&iaxsl[x]);
1266 /* Look for an exact match */
1267 if (match(sin, callno, dcallno, iaxs[x])) {
1271 ast_mutex_unlock(&iaxsl[x]);
1274 if ((res < 1) && (new >= NEW_ALLOW)) {
1275 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1276 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1277 gettimeofday(&now, NULL);
1278 for (x=1;x<TRUNK_CALL_START;x++) {
1279 /* Find first unused call number that hasn't been used in a while */
1280 ast_mutex_lock(&iaxsl[x]);
1281 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1282 ast_mutex_unlock(&iaxsl[x]);
1284 /* We've still got lock held if we found a spot */
1285 if (x >= TRUNK_CALL_START) {
1286 ast_log(LOG_WARNING, "No more space\n");
1289 iaxs[x] = new_iax(sin, lockpeer, host);
1290 update_max_nontrunk();
1292 if (option_debug && iaxdebug)
1293 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1294 iaxs[x]->sockfd = sockfd;
1295 iaxs[x]->addr.sin_port = sin->sin_port;
1296 iaxs[x]->addr.sin_family = sin->sin_family;
1297 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1298 iaxs[x]->peercallno = callno;
1299 iaxs[x]->callno = x;
1300 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1301 iaxs[x]->expiry = min_reg_expire;
1302 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1303 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1304 iaxs[x]->amaflags = amaflags;
1305 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1307 ast_string_field_set(iaxs[x], accountcode, accountcode);
1308 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1309 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1311 ast_log(LOG_WARNING, "Out of resources\n");
1312 ast_mutex_unlock(&iaxsl[x]);
1315 ast_mutex_unlock(&iaxsl[x]);
1321 static void iax2_frame_free(struct iax_frame *fr)
1323 if (fr->retrans > -1)
1324 ast_sched_del(sched, fr->retrans);
1328 static int iax2_queue_frame(int callno, struct ast_frame *f)
1330 /* Assumes lock for callno is already held... */
1332 if (iaxs[callno] && iaxs[callno]->owner) {
1333 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1334 /* Avoid deadlock by pausing and trying again */
1335 ast_mutex_unlock(&iaxsl[callno]);
1337 ast_mutex_lock(&iaxsl[callno]);
1339 ast_queue_frame(iaxs[callno]->owner, f);
1340 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1349 static void destroy_firmware(struct iax_firmware *cur)
1351 /* Close firmware */
1353 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1359 static int try_firmware(char *s)
1362 struct iax_firmware *cur = NULL;
1363 int ifd, fd, res, len, chunk;
1364 struct ast_iax2_firmware_header *fwh, fwh2;
1365 struct MD5Context md5;
1366 unsigned char sum[16], buf[1024];
1369 if (!(s2 = alloca(strlen(s) + 100))) {
1370 ast_log(LOG_WARNING, "Alloca failed!\n");
1374 last = strrchr(s, '/');
1380 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1382 if ((res = stat(s, &stbuf) < 0)) {
1383 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1387 /* Make sure it's not a directory */
1388 if (S_ISDIR(stbuf.st_mode))
1390 ifd = open(s, O_RDONLY);
1392 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1395 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1397 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1401 /* Unlink our newly created file */
1404 /* Now copy the firmware into it */
1405 len = stbuf.st_size;
1408 if (chunk > sizeof(buf))
1409 chunk = sizeof(buf);
1410 res = read(ifd, buf, chunk);
1412 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1417 res = write(fd, buf, chunk);
1419 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1427 /* Return to the beginning */
1428 lseek(fd, 0, SEEK_SET);
1429 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1430 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1434 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1435 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1439 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1440 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1444 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1445 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1449 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1451 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1456 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1457 MD5Final(sum, &md5);
1458 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1459 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1460 munmap(fwh, stbuf.st_size);
1465 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1466 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1467 /* Found a candidate */
1468 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1469 /* The version we have on loaded is older, load this one instead */
1471 /* This version is no newer than what we have. Don't worry about it.
1472 We'll consider it a proper load anyhow though */
1473 munmap(fwh, stbuf.st_size);
1479 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1481 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1486 munmap(cur->fwh, cur->mmaplen);
1491 cur->mmaplen = stbuf.st_size;
1498 static int iax_check_version(char *dev)
1501 struct iax_firmware *cur = NULL;
1503 if (ast_strlen_zero(dev))
1506 AST_LIST_LOCK(&firmwares);
1507 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1508 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1509 res = ntohs(cur->fwh->version);
1513 AST_LIST_UNLOCK(&firmwares);
1518 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1521 unsigned int bs = desc & 0xff;
1522 unsigned int start = (desc >> 8) & 0xffffff;
1524 struct iax_firmware *cur;
1526 if (ast_strlen_zero((char *)dev) || !bs)
1531 AST_LIST_LOCK(&firmwares);
1532 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1533 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1535 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1536 if (start < ntohl(cur->fwh->datalen)) {
1537 bytes = ntohl(cur->fwh->datalen) - start;
1540 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1543 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1551 AST_LIST_UNLOCK(&firmwares);
1557 static void reload_firmware(void)
1559 struct iax_firmware *cur = NULL;
1562 char dir[256], fn[256];
1564 AST_LIST_LOCK(&firmwares);
1566 /* Mark all as dead */
1567 AST_LIST_TRAVERSE(&firmwares, cur, list)
1570 /* Now that we have marked them dead... load new ones */
1571 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1574 while((de = readdir(fwd))) {
1575 if (de->d_name[0] != '.') {
1576 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1577 if (!try_firmware(fn)) {
1578 if (option_verbose > 1)
1579 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1585 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1587 /* Clean up leftovers */
1588 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1591 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1592 destroy_firmware(cur);
1594 AST_LIST_TRAVERSE_SAFE_END
1596 AST_LIST_UNLOCK(&firmwares);
1599 static int __do_deliver(void *data)
1601 /* Just deliver the packet by using queueing. This is called by
1602 the IAX thread with the iaxsl lock held. */
1603 struct iax_frame *fr = data;
1605 fr->af.has_timing_info = 0;
1606 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1607 iax2_queue_frame(fr->callno, &fr->af);
1608 /* Free our iax frame */
1609 iax2_frame_free(fr);
1610 /* And don't run again */
1614 static int handle_error(void)
1616 /* XXX Ideally we should figure out why an error occurred and then abort those
1617 rather than continuing to try. Unfortunately, the published interface does
1618 not seem to work XXX */
1620 struct sockaddr_in *sin;
1623 struct sock_extended_err e;
1628 m.msg_controllen = sizeof(e);
1630 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1632 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1634 if (m.msg_controllen) {
1635 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1637 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1639 ast_log(LOG_WARNING, "No address detected??\n");
1641 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1648 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1651 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1655 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1662 static int send_packet(struct iax_frame *f)
1665 int callno = f->callno;
1667 /* Don't send if there was an error, but return error instead */
1668 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1671 /* Called with iaxsl held */
1672 if (option_debug > 2 && iaxdebug)
1673 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));
1676 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1677 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1678 sizeof(iaxs[callno]->transfer));
1681 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1682 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1683 sizeof(iaxs[callno]->addr));
1686 if (option_debug && iaxdebug)
1687 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1694 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1696 struct iax2_user *user = NULL;
1698 /* Decrement AUTHREQ count if needed */
1699 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1700 AST_LIST_LOCK(&users);
1701 AST_LIST_TRAVERSE(&users, user, entry) {
1702 if (!strcmp(user->name, pvt->username)) {
1707 AST_LIST_UNLOCK(&users);
1708 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1710 /* No more pings or lagrq's */
1711 if (pvt->pingid > -1)
1712 ast_sched_del(sched, pvt->pingid);
1714 if (pvt->lagid > -1)
1715 ast_sched_del(sched, pvt->lagid);
1717 if (pvt->autoid > -1)
1718 ast_sched_del(sched, pvt->autoid);
1720 if (pvt->authid > -1)
1721 ast_sched_del(sched, pvt->authid);
1723 if (pvt->initid > -1)
1724 ast_sched_del(sched, pvt->initid);
1727 ast_sched_del(sched, pvt->jbid);
1731 static int iax2_predestroy(int callno)
1733 struct ast_channel *c = NULL;
1734 struct chan_iax2_pvt *pvt = iaxs[callno];
1739 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1740 iax2_destroy_helper(pvt);
1741 ast_set_flag(pvt, IAX_ALREADYGONE);
1744 if ((c = pvt->owner)) {
1745 c->_softhangup |= AST_SOFTHANGUP_DEV;
1747 ast_queue_hangup(c);
1754 static void iax2_destroy(int callno)
1756 struct chan_iax2_pvt *pvt = NULL;
1757 struct iax_frame *cur = NULL;
1758 struct ast_channel *owner = NULL;
1762 gettimeofday(&lastused[callno], NULL);
1764 owner = pvt ? pvt->owner : NULL;
1767 if (ast_mutex_trylock(&owner->lock)) {
1768 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1769 ast_mutex_unlock(&iaxsl[callno]);
1771 ast_mutex_lock(&iaxsl[callno]);
1776 iaxs[callno] = NULL;
1780 iax2_destroy_helper(pvt);
1783 ast_set_flag(pvt, IAX_ALREADYGONE);
1786 /* If there's an owner, prod it to give up */
1787 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1788 ast_queue_hangup(owner);
1791 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1792 /* Cancel any pending transmissions */
1793 if (cur->callno == pvt->callno)
1797 pvt->reg->callno = 0;
1801 ast_variables_destroy(pvt->vars);
1805 while (jb_getall(pvt->jb, &frame) == JB_OK)
1806 iax2_frame_free(frame.data);
1807 jb_destroy(pvt->jb);
1808 /* gotta free up the stringfields */
1809 ast_string_field_free_pools(pvt);
1814 ast_mutex_unlock(&owner->lock);
1816 if (callno & 0x4000)
1820 static int update_packet(struct iax_frame *f)
1822 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1823 struct ast_iax2_full_hdr *fh = f->data;
1824 /* Mark this as a retransmission */
1825 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1827 f->iseqno = iaxs[f->callno]->iseqno;
1828 fh->iseqno = f->iseqno;
1832 static int attempt_transmit(void *data);
1833 static void __attempt_transmit(void *data)
1835 /* Attempt to transmit the frame to the remote peer...
1836 Called without iaxsl held. */
1837 struct iax_frame *f = data;
1839 int callno = f->callno;
1840 /* Make sure this call is still active */
1842 ast_mutex_lock(&iaxsl[callno]);
1843 if (callno && iaxs[callno]) {
1844 if ((f->retries < 0) /* Already ACK'd */ ||
1845 (f->retries >= max_retries) /* Too many attempts */) {
1846 /* Record an error if we've transmitted too many times */
1847 if (f->retries >= max_retries) {
1849 /* Transfer timeout */
1850 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1851 } else if (f->final) {
1853 iax2_destroy(callno);
1855 if (iaxs[callno]->owner)
1856 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);
1857 iaxs[callno]->error = ETIMEDOUT;
1858 if (iaxs[callno]->owner) {
1859 struct ast_frame fr = { 0, };
1861 fr.frametype = AST_FRAME_CONTROL;
1862 fr.subclass = AST_CONTROL_HANGUP;
1863 iax2_queue_frame(callno, &fr);
1864 /* Remember, owner could disappear */
1865 if (iaxs[callno]->owner)
1866 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1868 if (iaxs[callno]->reg) {
1869 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1870 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1871 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1873 iax2_destroy(callno);
1880 /* Update it if it needs it */
1882 /* Attempt transmission */
1885 /* Try again later after 10 times as long */
1887 if (f->retrytime > MAX_RETRY_TIME)
1888 f->retrytime = MAX_RETRY_TIME;
1889 /* Transfer messages max out at one second */
1890 if (f->transfer && (f->retrytime > 1000))
1891 f->retrytime = 1000;
1892 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1895 /* Make sure it gets freed */
1900 ast_mutex_unlock(&iaxsl[callno]);
1901 /* Do not try again */
1903 /* Don't attempt delivery, just remove it from the queue */
1904 AST_LIST_LOCK(&iaxq.queue);
1905 AST_LIST_REMOVE(&iaxq.queue, f, list);
1907 AST_LIST_UNLOCK(&iaxq.queue);
1909 /* Free the IAX frame */
1914 static int attempt_transmit(void *data)
1916 #ifdef SCHED_MULTITHREADED
1917 if (schedule_action(__attempt_transmit, data))
1919 __attempt_transmit(data);
1923 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1925 struct iax2_peer *peer;
1928 return RESULT_SHOWUSAGE;
1929 if (!strcmp(argv[3],"all")) {
1931 ast_cli(fd, "OK cache is flushed.\n");
1932 } else if ((peer = find_peer(argv[3], 0))) {
1933 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1934 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1935 expire_registry((void*)peer->name);
1936 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1938 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1941 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1944 return RESULT_SUCCESS;
1947 static int iax2_test_losspct(int fd, int argc, char *argv[])
1950 return RESULT_SHOWUSAGE;
1952 test_losspct = atoi(argv[3]);
1954 return RESULT_SUCCESS;
1958 static int iax2_test_late(int fd, int argc, char *argv[])
1961 return RESULT_SHOWUSAGE;
1963 test_late = atoi(argv[3]);
1965 return RESULT_SUCCESS;
1968 static int iax2_test_resync(int fd, int argc, char *argv[])
1971 return RESULT_SHOWUSAGE;
1973 test_resync = atoi(argv[3]);
1975 return RESULT_SUCCESS;
1978 static int iax2_test_jitter(int fd, int argc, char *argv[])
1980 if (argc < 4 || argc > 5)
1981 return RESULT_SHOWUSAGE;
1983 test_jit = atoi(argv[3]);
1985 test_jitpct = atoi(argv[4]);
1987 return RESULT_SUCCESS;
1989 #endif /* IAXTESTS */
1991 /*! \brief peer_status: Report Peer status in character string */
1992 /* returns 1 if peer is online, -1 if unmonitored */
1993 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1997 if (peer->lastms < 0) {
1998 ast_copy_string(status, "UNREACHABLE", statuslen);
1999 } else if (peer->lastms > peer->maxms) {
2000 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2002 } else if (peer->lastms) {
2003 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2006 ast_copy_string(status, "UNKNOWN", statuslen);
2009 ast_copy_string(status, "Unmonitored", statuslen);
2015 /*! \brief Show one peer in detail */
2016 static int iax2_show_peer(int fd, int argc, char *argv[])
2020 struct iax2_peer *peer;
2021 char codec_buf[512];
2022 int x = 0, codec = 0, load_realtime = 0;
2025 return RESULT_SHOWUSAGE;
2027 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2029 peer = find_peer(argv[3], load_realtime);
2032 ast_cli(fd, " * Name : %s\n", peer->name);
2033 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2034 ast_cli(fd, " Context : %s\n", peer->context);
2035 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2036 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2037 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2038 ast_cli(fd, " Expire : %d\n", peer->expire);
2039 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2040 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));
2041 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2042 ast_cli(fd, " Username : %s\n", peer->username);
2043 ast_cli(fd, " Codecs : ");
2044 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2045 ast_cli(fd, "%s\n", codec_buf);
2047 ast_cli(fd, " Codec Order : (");
2048 for(x = 0; x < 32 ; x++) {
2049 codec = ast_codec_pref_index(&peer->prefs,x);
2052 ast_cli(fd, "%s", ast_getformatname(codec));
2053 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2058 ast_cli(fd, "none");
2061 ast_cli(fd, " Status : ");
2062 peer_status(peer, status, sizeof(status));
2063 ast_cli(fd, "%s\n",status);
2064 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2066 if (ast_test_flag(peer, IAX_TEMPONLY))
2069 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2073 return RESULT_SUCCESS;
2076 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2079 struct iax2_peer *p = NULL;
2081 int wordlen = strlen(word);
2083 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2085 AST_LIST_LOCK(&peers);
2086 AST_LIST_TRAVERSE(&peers, p, entry) {
2087 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2088 res = ast_strdup(p->name);
2092 AST_LIST_UNLOCK(&peers);
2098 static int iax2_show_stats(int fd, int argc, char *argv[])
2100 struct iax_frame *cur;
2101 int cnt = 0, dead=0, final=0;
2103 return RESULT_SHOWUSAGE;
2104 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2105 if (cur->retries < 0)
2111 ast_cli(fd, " IAX Statistics\n");
2112 ast_cli(fd, "---------------------\n");
2113 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2114 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2115 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2117 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2119 trunk_timed = trunk_untimed = 0;
2120 if (trunk_maxmtu > trunk_nmaxmtu)
2121 trunk_nmaxmtu = trunk_maxmtu;
2123 return RESULT_SUCCESS;
2126 /*! \brief Set trunk MTU from CLI */
2127 static int iax2_set_mtu(int fd, int argc, char *argv[])
2132 return RESULT_SHOWUSAGE;
2133 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0)
2134 mtuv = MAX_TRUNK_MTU;
2136 mtuv = atoi(argv[3]);
2139 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2140 global_max_trunk_mtu = 0;
2141 return RESULT_SUCCESS;
2143 if (mtuv < 172 || mtuv > 4000) {
2144 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n");
2145 return RESULT_SHOWUSAGE;
2147 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2148 global_max_trunk_mtu = mtuv;
2149 return RESULT_SUCCESS;
2152 static int iax2_show_cache(int fd, int argc, char *argv[])
2154 struct iax2_dpcache *dp = NULL;
2155 char tmp[1024], *pc = NULL;
2159 gettimeofday(&tv, NULL);
2161 AST_LIST_LOCK(&dpcache);
2163 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2165 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2166 s = dp->expiry.tv_sec - tv.tv_sec;
2168 if (dp->flags & CACHE_FLAG_EXISTS)
2169 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2170 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2171 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2172 if (dp->flags & CACHE_FLAG_CANEXIST)
2173 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2174 if (dp->flags & CACHE_FLAG_PENDING)
2175 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2176 if (dp->flags & CACHE_FLAG_TIMEOUT)
2177 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2178 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2179 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2180 if (dp->flags & CACHE_FLAG_MATCHMORE)
2181 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2182 if (dp->flags & CACHE_FLAG_UNKNOWN)
2183 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2184 /* Trim trailing pipe */
2185 if (!ast_strlen_zero(tmp))
2186 tmp[strlen(tmp) - 1] = '\0';
2188 ast_copy_string(tmp, "(none)", sizeof(tmp));
2190 pc = strchr(dp->peercontext, '@');
2192 pc = dp->peercontext;
2195 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2196 if (dp->waiters[x] > -1)
2199 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2201 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2204 AST_LIST_LOCK(&dpcache);
2206 return RESULT_SUCCESS;
2209 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2211 static void unwrap_timestamp(struct iax_frame *fr)
2215 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2216 x = fr->ts - iaxs[fr->callno]->last;
2218 /* Sudden big jump backwards in timestamp:
2219 What likely happened here is that miniframe timestamp has circled but we haven't
2220 gotten the update from the main packet. We'll just pretend that we did, and
2221 update the timestamp appropriately. */
2222 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2223 if (option_debug && iaxdebug)
2224 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2227 /* Sudden apparent big jump forwards in timestamp:
2228 What's likely happened is this is an old miniframe belonging to the previous
2229 top-16-bit timestamp that has turned up out of order.
2230 Adjust the timestamp appropriately. */
2231 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2232 if (option_debug && iaxdebug)
2233 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2238 static int get_from_jb(void *p);
2240 static void update_jbsched(struct chan_iax2_pvt *pvt)
2244 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2246 when = jb_next(pvt->jb) - when;
2248 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2251 /* XXX should really just empty until when > 0.. */
2255 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2257 /* Signal scheduler thread */
2258 signal_condition(&sched_lock, &sched_cond);
2261 static void __get_from_jb(void *p)
2263 int callno = PTR_TO_CALLNO(p);
2264 struct chan_iax2_pvt *pvt = NULL;
2265 struct iax_frame *fr;
2272 /* Make sure we have a valid private structure before going on */
2273 ast_mutex_lock(&iaxsl[callno]);
2277 ast_mutex_unlock(&iaxsl[callno]);
2283 gettimeofday(&tv,NULL);
2284 /* round up a millisecond since ast_sched_runq does; */
2285 /* prevents us from spinning while waiting for our now */
2286 /* to catch up with runq's now */
2289 now = ast_tvdiff_ms(tv, pvt->rxcore);
2291 if(now >= (next = jb_next(pvt->jb))) {
2292 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2300 struct ast_frame af;
2302 /* create an interpolation frame */
2303 af.frametype = AST_FRAME_VOICE;
2304 af.subclass = pvt->voiceformat;
2306 af.samples = frame.ms * 8;
2308 af.src = "IAX2 JB interpolation";
2310 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2311 af.offset=AST_FRIENDLY_OFFSET;
2313 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2314 * which we'd need to malloc, and then it would free it. That seems like a drag */
2315 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2316 iax2_queue_frame(callno, &af);
2320 iax2_frame_free(frame.data);
2327 /* shouldn't happen */
2331 update_jbsched(pvt);
2332 ast_mutex_unlock(&iaxsl[callno]);
2335 static int get_from_jb(void *data)
2337 #ifdef SCHED_MULTITHREADED
2338 if (schedule_action(__get_from_jb, data))
2340 __get_from_jb(data);
2344 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2350 /* Attempt to recover wrapped timestamps */
2351 unwrap_timestamp(fr);
2354 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2355 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2356 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2360 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2362 fr->af.delivery = ast_tv(0,0);
2365 type = JB_TYPE_CONTROL;
2368 if(fr->af.frametype == AST_FRAME_VOICE) {
2369 type = JB_TYPE_VOICE;
2370 len = ast_codec_get_samples(&fr->af) / 8;
2371 } else if(fr->af.frametype == AST_FRAME_CNG) {
2372 type = JB_TYPE_SILENCE;
2375 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2382 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2383 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2384 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2385 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2386 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2389 /* deliver any frames in the jb */
2390 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2391 __do_deliver(frame.data);
2393 jb_reset(iaxs[fr->callno]->jb);
2395 if (iaxs[fr->callno]->jbid > -1)
2396 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2398 iaxs[fr->callno]->jbid = -1;
2400 /* deliver this frame now */
2407 /* insert into jitterbuffer */
2408 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2409 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2410 calc_rxstamp(iaxs[fr->callno],fr->ts));
2411 if (ret == JB_DROP) {
2413 } else if (ret == JB_SCHED) {
2414 update_jbsched(iaxs[fr->callno]);
2419 /* Free our iax frame */
2420 iax2_frame_free(fr);
2426 static int iax2_transmit(struct iax_frame *fr)
2428 /* Lock the queue and place this packet at the end */
2429 /* By setting this to 0, the network thread will send it for us, and
2430 queue retransmission if necessary */
2432 AST_LIST_LOCK(&iaxq.queue);
2433 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2435 AST_LIST_UNLOCK(&iaxq.queue);
2436 /* Wake up the network and scheduler thread */
2437 pthread_kill(netthreadid, SIGURG);
2438 signal_condition(&sched_lock, &sched_cond);
2444 static int iax2_digit_begin(struct ast_channel *c, char digit)
2446 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2449 static int iax2_digit_end(struct ast_channel *c, char digit)
2451 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2454 static int iax2_sendtext(struct ast_channel *c, const char *text)
2457 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2458 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2461 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2463 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2466 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2468 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2471 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2473 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2474 ast_mutex_lock(&iaxsl[callno]);
2476 iaxs[callno]->owner = newchan;
2478 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2479 ast_mutex_unlock(&iaxsl[callno]);
2483 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2485 struct ast_variable *var;
2486 struct ast_variable *tmp;
2487 struct iax2_peer *peer=NULL;
2488 time_t regseconds = 0, nowtime;
2492 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2495 sprintf(porta, "%d", ntohs(sin->sin_port));
2496 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2498 /* We'll need the peer name in order to build the structure! */
2499 for (tmp = var; tmp; tmp = tmp->next) {
2500 if (!strcasecmp(tmp->name, "name"))
2501 peername = tmp->value;
2508 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2513 for (tmp = var; tmp; tmp = tmp->next) {
2514 /* Make sure it's not a user only... */
2515 if (!strcasecmp(tmp->name, "type")) {
2516 if (strcasecmp(tmp->value, "friend") &&
2517 strcasecmp(tmp->value, "peer")) {
2518 /* Whoops, we weren't supposed to exist! */
2523 } else if (!strcasecmp(tmp->name, "regseconds")) {
2524 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2525 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2526 inet_aton(tmp->value, &(peer->addr.sin_addr));
2527 } else if (!strcasecmp(tmp->name, "port")) {
2528 peer->addr.sin_port = htons(atoi(tmp->value));
2529 } else if (!strcasecmp(tmp->name, "host")) {
2530 if (!strcasecmp(tmp->value, "dynamic"))
2537 ast_variables_destroy(var);
2539 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2540 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2541 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2542 if (peer->expire > -1)
2543 ast_sched_del(sched, peer->expire);
2544 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2546 AST_LIST_LOCK(&peers);
2547 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2548 AST_LIST_UNLOCK(&peers);
2549 if (ast_test_flag(peer, IAX_DYNAMIC))
2550 reg_source_db(peer);
2552 ast_set_flag(peer, IAX_TEMPONLY);
2555 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2557 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2558 memset(&peer->addr, 0, sizeof(peer->addr));
2559 realtime_update_peer(peer->name, &peer->addr, 0);
2561 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2562 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2566 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2567 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2574 static struct iax2_user *realtime_user(const char *username)
2576 struct ast_variable *var;
2577 struct ast_variable *tmp;
2578 struct iax2_user *user=NULL;
2580 var = ast_load_realtime("iaxusers", "name", username, NULL);
2586 /* Make sure it's not a peer only... */
2587 if (!strcasecmp(tmp->name, "type")) {
2588 if (strcasecmp(tmp->value, "friend") &&
2589 strcasecmp(tmp->value, "user")) {
2596 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2600 ast_variables_destroy(var);
2602 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2603 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2604 AST_LIST_LOCK(&users);
2605 AST_LIST_INSERT_HEAD(&users, user, entry);
2606 AST_LIST_UNLOCK(&users);
2608 ast_set_flag(user, IAX_TEMPONLY);
2614 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2617 char regseconds[20];
2619 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2620 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2621 ast_update_realtime("iaxpeers", "name", peername,
2622 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2623 "regseconds", regseconds, NULL);
2626 struct create_addr_info {
2639 char context[AST_MAX_CONTEXT];
2640 char peercontext[AST_MAX_CONTEXT];
2641 char mohinterpret[MAX_MUSICCLASS];
2642 char mohsuggest[MAX_MUSICCLASS];
2645 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2647 struct ast_hostent ahp;
2649 struct iax2_peer *peer;
2651 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2652 cai->sockfd = defaultsockfd;
2654 sin->sin_family = AF_INET;
2656 if (!(peer = find_peer(peername, 1))) {
2659 hp = ast_gethostbyname(peername, &ahp);
2661 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2662 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2663 /* use global iax prefs for unknown peer/user */
2664 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2667 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2674 /* if the peer has no address (current or default), return failure */
2675 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2676 if (ast_test_flag(peer, IAX_TEMPONLY))
2681 /* if the peer is being monitored and is currently unreachable, return failure */
2682 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2683 if (ast_test_flag(peer, IAX_TEMPONLY))
2688 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2689 cai->maxtime = peer->maxms;
2690 cai->capability = peer->capability;
2691 cai->encmethods = peer->encmethods;
2692 cai->sockfd = peer->sockfd;
2693 cai->adsi = peer->adsi;
2694 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2695 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2696 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2697 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2698 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2699 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2700 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2701 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2702 if (ast_strlen_zero(peer->dbsecret)) {
2703 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2708 family = ast_strdupa(peer->dbsecret);
2709 key = strchr(family, '/');
2712 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2713 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2714 if (ast_test_flag(peer, IAX_TEMPONLY))
2720 if (peer->addr.sin_addr.s_addr) {
2721 sin->sin_addr = peer->addr.sin_addr;
2722 sin->sin_port = peer->addr.sin_port;
2724 sin->sin_addr = peer->defaddr.sin_addr;
2725 sin->sin_port = peer->defaddr.sin_port;
2728 if (ast_test_flag(peer, IAX_TEMPONLY))
2734 static void __auto_congest(void *nothing)
2736 int callno = PTR_TO_CALLNO(nothing);
2737 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2738 ast_mutex_lock(&iaxsl[callno]);
2740 iaxs[callno]->initid = -1;
2741 iax2_queue_frame(callno, &f);
2742 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2744 ast_mutex_unlock(&iaxsl[callno]);
2747 static int auto_congest(void *data)
2749 #ifdef SCHED_MULTITHREADED
2750 if (schedule_action(__auto_congest, data))
2752 __auto_congest(data);
2756 static unsigned int iax2_datetime(const char *tz)
2762 localtime_r(&t, &tm);
2763 if (!ast_strlen_zero(tz))
2764 ast_localtime(&t, &tm, tz);
2765 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2766 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2767 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2768 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2769 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2770 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2774 struct parsed_dial_string {
2786 * \brief Parses an IAX dial string into its component parts.
2787 * \param data the string to be parsed
2788 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2791 * This function parses the string and fills the structure
2792 * with pointers to its component parts. The input string
2795 * \note This function supports both plaintext passwords and RSA
2796 * key names; if the password string is formatted as '[keyname]',
2797 * then the keyname will be placed into the key field, and the
2798 * password field will be set to NULL.
2800 * \note The dial string format is:
2801 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2803 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2805 if (ast_strlen_zero(data))
2808 pds->peer = strsep(&data, "/");
2809 pds->exten = strsep(&data, "/");
2810 pds->options = data;
2814 pds->exten = strsep(&data, "@");
2815 pds->context = data;
2818 if (strchr(pds->peer, '@')) {
2820 pds->username = strsep(&data, "@");
2824 if (pds->username) {
2825 data = pds->username;
2826 pds->username = strsep(&data, ":");
2827 pds->password = data;
2831 pds->peer = strsep(&data, ":");
2834 /* check for a key name wrapped in [] in the secret position, if found,
2835 move it to the key field instead
2837 if (pds->password && (pds->password[0] == '[')) {
2838 pds->key = ast_strip_quoted(pds->password, "[", "]");
2839 pds->password = NULL;
2843 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2845 struct sockaddr_in sin;
2846 char *l=NULL, *n=NULL, *tmpstr;
2847 struct iax_ie_data ied;
2848 char *defaultrdest = "s";
2849 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2850 struct parsed_dial_string pds;
2851 struct create_addr_info cai;
2853 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2854 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2858 memset(&cai, 0, sizeof(cai));
2859 cai.encmethods = iax2_encryption;
2861 memset(&pds, 0, sizeof(pds));
2862 tmpstr = ast_strdupa(dest);
2863 parse_dial_string(tmpstr, &pds);
2866 pds.exten = defaultrdest;
2868 if (create_addr(pds.peer, &sin, &cai)) {
2869 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2873 if (!pds.username && !ast_strlen_zero(cai.username))
2874 pds.username = cai.username;
2875 if (!pds.password && !ast_strlen_zero(cai.secret))
2876 pds.password = cai.secret;
2877 if (!pds.key && !ast_strlen_zero(cai.outkey))
2878 pds.key = cai.outkey;
2879 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2880 pds.context = cai.peercontext;
2882 /* Keep track of the context for outgoing calls too */
2883 ast_copy_string(c->context, cai.context, sizeof(c->context));
2886 sin.sin_port = htons(atoi(pds.port));
2889 n = c->cid.cid_name;
2891 /* Now build request */
2892 memset(&ied, 0, sizeof(ied));
2894 /* On new call, first IE MUST be IAX version of caller */
2895 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2896 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2897 if (pds.options && strchr(pds.options, 'a')) {
2898 /* Request auto answer */
2899 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2902 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2905 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2906 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2909 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2911 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2914 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2915 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2918 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2919 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2920 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2922 if (!ast_strlen_zero(c->language))
2923 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2924 if (!ast_strlen_zero(c->cid.cid_dnid))
2925 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2926 if (!ast_strlen_zero(c->cid.cid_rdnis))
2927 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2930 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2933 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2936 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2938 ast_mutex_lock(&iaxsl[callno]);
2940 if (!ast_strlen_zero(c->context))
2941 ast_string_field_set(iaxs[callno], context, c->context);
2944 ast_string_field_set(iaxs[callno], username, pds.username);
2946 iaxs[callno]->encmethods = cai.encmethods;
2948 iaxs[callno]->adsi = cai.adsi;
2950 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
2951 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
2954 ast_string_field_set(iaxs[callno], outkey, pds.key);
2956 ast_string_field_set(iaxs[callno], secret, pds.password);
2958 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2959 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2960 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2961 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2963 if (iaxs[callno]->maxtime) {
2964 /* Initialize pingtime and auto-congest time */
2965 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2966 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2967 } else if (autokill) {
2968 iaxs[callno]->pingtime = autokill / 2;
2969 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2972 /* send the command using the appropriate socket for this peer */
2973 iaxs[callno]->sockfd = cai.sockfd;
2975 /* Transmit the string in a "NEW" request */
2976 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2978 ast_mutex_unlock(&iaxsl[callno]);
2979 ast_setstate(c, AST_STATE_RINGING);
2984 static int iax2_hangup(struct ast_channel *c)
2986 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2988 struct iax_ie_data ied;
2989 memset(&ied, 0, sizeof(ied));
2990 ast_mutex_lock(&iaxsl[callno]);
2991 if (callno && iaxs[callno]) {
2993 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2994 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2995 /* Send the hangup unless we have had a transmission error or are already gone */
2996 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2997 if (!iaxs[callno]->error && !alreadygone)
2998 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2999 /* Explicitly predestroy it */
3000 iax2_predestroy(callno);
3001 /* If we were already gone to begin with, destroy us now */
3004 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3005 iax2_destroy(callno);
3008 ast_mutex_unlock(&iaxsl[callno]);
3009 if (option_verbose > 2)
3010 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3014 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3016 struct ast_option_header *h;
3020 case AST_OPTION_TXGAIN:
3021 case AST_OPTION_RXGAIN:
3022 /* these two cannot be sent, because they require a result */
3026 if (!(h = ast_malloc(datalen + sizeof(*h))))
3029 h->flag = AST_OPTION_FLAG_REQUEST;
3030 h->option = htons(option);
3031 memcpy(h->data, data, datalen);
3032 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3033 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3034 datalen + sizeof(*h), -1);
3040 static struct ast_frame *iax2_read(struct ast_channel *c)
3042 ast_log(LOG_NOTICE, "I should never be called!\n");
3043 return &ast_null_frame;
3046 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3049 struct iax_ie_data ied0;
3050 struct iax_ie_data ied1;
3051 unsigned int transferid = (unsigned int)ast_random();
3052 memset(&ied0, 0, sizeof(ied0));
3053 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3054 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3055 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3057 memset(&ied1, 0, sizeof(ied1));
3058 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3059 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3060 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3062 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3065 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3068 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3069 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3073 static void lock_both(unsigned short callno0, unsigned short callno1)
3075 ast_mutex_lock(&iaxsl[callno0]);
3076 while (ast_mutex_trylock(&iaxsl[callno1])) {
3077 ast_mutex_unlock(&iaxsl[callno0]);
3079 ast_mutex_lock(&iaxsl[callno0]);
3083 static void unlock_both(unsigned short callno0, unsigned short callno1)
3085 ast_mutex_unlock(&iaxsl[callno1]);
3086 ast_mutex_unlock(&iaxsl[callno0]);
3089 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)
3091 struct ast_channel *cs[3];
3092 struct ast_channel *who, *other;
3095 int transferstarted=0;
3096 struct ast_frame *f;
3097 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3098 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3099 struct timeval waittimer = {0, 0}, tv;
3101 lock_both(callno0, callno1);
3102 /* Put them in native bridge mode */
3103 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3104 iaxs[callno0]->bridgecallno = callno1;
3105 iaxs[callno1]->bridgecallno = callno0;
3107 unlock_both(callno0, callno1);
3109 /* If not, try to bridge until we can execute a transfer, if we can */
3112 for (/* ever */;;) {
3113 /* Check in case we got masqueraded into */
3114 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3115 if (option_verbose > 2)
3116 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3117 /* Remove from native mode */
3118 if (c0->tech == &iax2_tech) {
3119 ast_mutex_lock(&iaxsl[callno0]);
3120 iaxs[callno0]->bridgecallno = 0;
3121 ast_mutex_unlock(&iaxsl[callno0]);
3123 if (c1->tech == &iax2_tech) {
3124 ast_mutex_lock(&iaxsl[callno1]);
3125 iaxs[callno1]->bridgecallno = 0;
3126 ast_mutex_unlock(&iaxsl[callno1]);
3128 return AST_BRIDGE_FAILED_NOWARN;
3130 if (c0->nativeformats != c1->nativeformats) {
3131 if (option_verbose > 2) {
3134 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3135 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3136 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3138 /* Remove from native mode */
3139 lock_both(callno0, callno1);
3140 iaxs[callno0]->bridgecallno = 0;
3141 iaxs[callno1]->bridgecallno = 0;
3142 unlock_both(callno0, callno1);
3143 return AST_BRIDGE_FAILED_NOWARN;
3145 /* check if transfered and if we really want native bridging */
3146 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3147 /* Try the transfer */
3148 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3149 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3150 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3151 transferstarted = 1;
3153 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3154 /* Call has been transferred. We're no longer involved */
3155 gettimeofday(&tv, NULL);
3156 if (ast_tvzero(waittimer)) {
3158 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3159 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3160 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3163 res = AST_BRIDGE_COMPLETE;
3168 who = ast_waitfor_n(cs, 2, &to);
3169 if (timeoutms > -1) {
3170 timeoutms -= (1000 - to);
<