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
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
42 #include <sys/socket.h>
43 #include <netinet/in.h>
44 #include <arpa/inet.h>
45 #include <netinet/in_systm.h>
46 #include <netinet/ip.h>
48 #include <sys/signal.h>
56 #include "asterisk/zapata.h"
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
92 #include "iax2-parser.h"
93 #include "iax2-provision.h"
94 #include "jitterbuf.h"
96 /* Define SCHED_MULTITHREADED to run the scheduler in a special
97 multithreaded mode. */
98 #define SCHED_MULTITHREADED
100 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
101 thread is actually doing. */
102 #define DEBUG_SCHED_MULTITHREAD
106 static int nochecksums = 0;
110 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
111 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
113 #define DEFAULT_THREAD_COUNT 10
114 #define DEFAULT_MAX_THREAD_COUNT 100
115 #define DEFAULT_RETRY_TIME 1000
116 #define MEMORY_SIZE 100
117 #define DEFAULT_DROP 3
118 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
119 but keeps the division between trunked and non-trunked better. */
120 #define TRUNK_CALL_START 0x4000
122 #define DEBUG_SUPPORT
124 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
126 /* Sample over last 100 units to determine historic jitter */
129 static struct ast_codec_pref prefs;
131 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
134 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
135 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
136 #define MAX_TRUNK_MTU 1240
138 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
139 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
142 static char context[80] = "default";
144 static char language[MAX_LANGUAGE] = "";
145 static char regcontext[AST_MAX_CONTEXT] = "";
147 static int maxauthreq = 3;
148 static int max_retries = 4;
149 static int ping_time = 21;
150 static int lagrq_time = 10;
151 static int maxtrunkcall = TRUNK_CALL_START;
152 static int maxnontrunkcall = 1;
153 static int maxjitterbuffer=1000;
154 static int resyncthreshold=1000;
155 static int maxjitterinterps=10;
156 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
158 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
160 static int trunkfreq = 20;
161 static int trunkmaxsize = MAX_TRUNKDATA;
163 static int authdebug = 1;
164 static int autokill = 0;
165 static int iaxcompat = 0;
167 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
169 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
171 static unsigned int tos = 0;
173 static unsigned int cos = 0;
175 static int min_reg_expire;
176 static int max_reg_expire;
178 static int srvlookup = 0;
180 static int timingfd = -1; /* Timing file descriptor */
182 static struct ast_netsock_list *netsock;
183 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
184 static int defaultsockfd = -1;
186 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
189 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
191 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
192 ~AST_FORMAT_SLINEAR & \
197 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
199 ~AST_FORMAT_G726_AAL2 & \
202 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
206 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
207 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
208 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
210 static struct io_context *io;
211 static struct sched_context *sched;
213 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
215 static int iaxdebug = 0;
217 static int iaxtrunkdebug = 0;
219 static int test_losspct = 0;
221 static int test_late = 0;
222 static int test_resync = 0;
223 static int test_jit = 0;
224 static int test_jitpct = 0;
225 #endif /* IAXTESTS */
227 static char accountcode[AST_MAX_ACCOUNT_CODE];
228 static char mohinterpret[MAX_MUSICCLASS];
229 static char mohsuggest[MAX_MUSICCLASS];
230 static int amaflags = 0;
232 static int delayreject = 0;
233 static int iax2_encryption = 0;
235 static struct ast_flags globalflags = { 0 };
237 static pthread_t netthreadid = AST_PTHREADT_NULL;
238 static pthread_t schedthreadid = AST_PTHREADT_NULL;
239 AST_MUTEX_DEFINE_STATIC(sched_lock);
240 static ast_cond_t sched_cond;
243 IAX_STATE_STARTED = (1 << 0),
244 IAX_STATE_AUTHENTICATED = (1 << 1),
245 IAX_STATE_TBD = (1 << 2),
246 IAX_STATE_UNCHANGED = (1 << 3),
249 struct iax2_context {
250 char context[AST_MAX_CONTEXT];
251 struct iax2_context *next;
255 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
256 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
257 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
258 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
259 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
260 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
261 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
262 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
263 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
264 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
265 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
266 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
267 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
268 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
269 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
270 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
271 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
272 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
273 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
274 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
275 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
276 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
277 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
278 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
279 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
280 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
281 response, so that we've achieved a three-way handshake with
282 them before sending voice or anything else*/
285 static int global_rtautoclear = 120;
287 static int reload_config(void);
290 AST_DECLARE_STRING_FIELDS(
291 AST_STRING_FIELD(name);
292 AST_STRING_FIELD(secret);
293 AST_STRING_FIELD(dbsecret);
294 AST_STRING_FIELD(accountcode);
295 AST_STRING_FIELD(mohinterpret);
296 AST_STRING_FIELD(mohsuggest);
297 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
298 AST_STRING_FIELD(language);
299 AST_STRING_FIELD(cid_num);
300 AST_STRING_FIELD(cid_name);
309 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
310 int curauthreq; /*!< Current number of outstanding AUTHREQs */
311 struct ast_codec_pref prefs;
313 struct iax2_context *contexts;
314 struct ast_variable *vars;
318 AST_DECLARE_STRING_FIELDS(
319 AST_STRING_FIELD(name);
320 AST_STRING_FIELD(username);
321 AST_STRING_FIELD(secret);
322 AST_STRING_FIELD(dbsecret);
323 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
325 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
326 AST_STRING_FIELD(context); /*!< For transfers only */
327 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
328 AST_STRING_FIELD(mailbox); /*!< Mailbox */
329 AST_STRING_FIELD(mohinterpret);
330 AST_STRING_FIELD(mohsuggest);
331 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
332 /* Suggested caller id if registering */
333 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
334 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
335 AST_STRING_FIELD(zonetag); /*!< Time Zone */
337 struct ast_codec_pref prefs;
338 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
339 struct sockaddr_in addr;
341 int sockfd; /*!< Socket to use for transmission */
346 /* Dynamic Registration fields */
347 struct sockaddr_in defaddr; /*!< Default address if there is one */
348 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
349 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
351 int expire; /*!< Schedule entry for expiry */
352 int expiry; /*!< How soon to expire */
353 int capability; /*!< Capability */
356 int callno; /*!< Call number of POKE request */
357 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
358 int lastms; /*!< How long last response took (in ms), or -1 for no response */
359 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
361 int pokefreqok; /*!< How often to check if the host is up */
362 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
363 int historicms; /*!< How long recent average responses took */
364 int smoothing; /*!< Sample over how many units to determine historic ms */
366 struct ast_event_sub *mwi_event_sub;
371 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
373 struct iax2_trunk_peer {
376 struct sockaddr_in addr;
377 struct timeval txtrunktime; /*!< Transmit trunktime */
378 struct timeval rxtrunktime; /*!< Receive trunktime */
379 struct timeval lasttxtime; /*!< Last transmitted trunktime */
380 struct timeval trunkact; /*!< Last trunk activity */
381 unsigned int lastsent; /*!< Last sent time */
382 /* Trunk data and length */
383 unsigned char *trunkdata;
384 unsigned int trunkdatalen;
385 unsigned int trunkdataalloc;
389 AST_LIST_ENTRY(iax2_trunk_peer) list;
392 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
394 struct iax_firmware {
395 AST_LIST_ENTRY(iax_firmware) list;
399 struct ast_iax2_firmware_header *fwh;
404 REG_STATE_UNREGISTERED = 0,
407 REG_STATE_REGISTERED,
413 enum iax_transfer_state {
418 TRANSFER_PASSTHROUGH,
422 TRANSFER_MPASSTHROUGH,
427 struct iax2_registry {
428 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
430 char secret[80]; /*!< Password or key name in []'s */
431 int expire; /*!< Sched ID of expiration */
432 int refresh; /*!< How often to refresh */
433 enum iax_reg_state regstate;
434 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
435 int callno; /*!< Associated call number if applicable */
436 struct sockaddr_in us; /*!< Who the server thinks we are */
437 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
438 AST_LIST_ENTRY(iax2_registry) entry;
441 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
443 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
444 #define MIN_RETRY_TIME 100
445 #define MAX_RETRY_TIME 10000
447 #define MAX_JITTER_BUFFER 50
448 #define MIN_JITTER_BUFFER 10
450 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 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;
460 static int iaxactivethreadcount = 0;
474 struct chan_iax2_pvt {
475 /*! Socket to send/receive on for this call */
477 /*! Last received voice format */
479 /*! Last received video format */
481 /*! Last sent voice format */
483 /*! Last sent video format */
485 /*! What we are capable of sending */
487 /*! Last received timestamp */
489 /*! Last sent timestamp - never send the same timestamp twice in a single call */
490 unsigned int lastsent;
491 /*! Next outgoing timestamp if everything is good */
492 unsigned int nextpred;
493 /*! True if the last voice we transmitted was not silence/CNG */
494 unsigned int notsilenttx:1;
496 unsigned int pingtime;
497 /*! Max time for initial response */
500 struct sockaddr_in addr;
501 /*! Actual used codec preferences */
502 struct ast_codec_pref prefs;
503 /*! Requested codec preferences */
504 struct ast_codec_pref rprefs;
505 /*! Our call number */
506 unsigned short callno;
508 unsigned short peercallno;
509 /*! Negotiated format, this is only used to remember what format was
510 chosen for an unauthenticated call so that the channel can get
511 created later using the right format */
513 /*! Peer selected format */
515 /*! Peer capability */
517 /*! timeval that we base our transmission on */
518 struct timeval offset;
519 /*! timeval that we base our delivery on */
520 struct timeval rxcore;
521 /*! The jitterbuffer */
523 /*! active jb read scheduler id */
527 /*! Error, as discovered by the manager */
529 /*! Owner if we have one */
530 struct ast_channel *owner;
531 /*! What's our state? */
532 struct ast_flags state;
533 /*! Expiry (optional) */
535 /*! Next outgoing sequence number */
536 unsigned char oseqno;
537 /*! Next sequence number they have not yet acknowledged */
538 unsigned char rseqno;
539 /*! Next incoming sequence number */
540 unsigned char iseqno;
541 /*! Last incoming sequence number we have acknowledged */
542 unsigned char aseqno;
544 AST_DECLARE_STRING_FIELDS(
546 AST_STRING_FIELD(peer);
547 /*! Default Context */
548 AST_STRING_FIELD(context);
549 /*! Caller ID if available */
550 AST_STRING_FIELD(cid_num);
551 AST_STRING_FIELD(cid_name);
552 /*! Hidden Caller ID (i.e. ANI) if appropriate */
553 AST_STRING_FIELD(ani);
555 AST_STRING_FIELD(dnid);
557 AST_STRING_FIELD(rdnis);
558 /*! Requested Extension */
559 AST_STRING_FIELD(exten);
560 /*! Expected Username */
561 AST_STRING_FIELD(username);
562 /*! Expected Secret */
563 AST_STRING_FIELD(secret);
565 AST_STRING_FIELD(challenge);
566 /*! Public keys permitted keys for incoming authentication */
567 AST_STRING_FIELD(inkeys);
568 /*! Private key for outgoing authentication */
569 AST_STRING_FIELD(outkey);
570 /*! Preferred language */
571 AST_STRING_FIELD(language);
572 /*! Hostname/peername for naming purposes */
573 AST_STRING_FIELD(host);
575 AST_STRING_FIELD(dproot);
576 AST_STRING_FIELD(accountcode);
577 AST_STRING_FIELD(mohinterpret);
578 AST_STRING_FIELD(mohsuggest);
579 /*! received OSP token */
580 AST_STRING_FIELD(osptoken);
583 /*! permitted authentication methods */
585 /*! permitted encryption methods */
587 /*! Encryption AES-128 Key */
588 ast_aes_encrypt_key ecx;
589 /*! Decryption AES-128 Key */
590 ast_aes_decrypt_key dcx;
591 /*! 32 bytes of semi-random data */
592 unsigned char semirand[32];
593 /*! Associated registry */
594 struct iax2_registry *reg;
595 /*! Associated peer for poking */
596 struct iax2_peer *peerpoke;
601 /*! Transferring status */
602 enum iax_transfer_state transferring;
603 /*! Transfer identifier */
605 /*! Who we are IAX transferring to */
606 struct sockaddr_in transfer;
607 /*! What's the new call number for the transfer */
608 unsigned short transfercallno;
609 /*! Transfer encrypt AES-128 Key */
610 ast_aes_encrypt_key tdcx;
612 /*! Status of knowledge of peer ADSI capability */
615 /*! Who we are bridged to */
616 unsigned short bridgecallno;
618 int pingid; /*!< Transmit PING request */
619 int lagid; /*!< Retransmit lag request */
620 int autoid; /*!< Auto hangup for Dialplan requestor */
621 int authid; /*!< Authentication rejection ID */
622 int authfail; /*!< Reason to report failure */
623 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
628 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
629 struct ast_variable *vars;
630 /*! last received remote rr */
631 struct iax_rr remote_rr;
632 /*! Current base time: (just for stats) */
634 /*! Dropped frame count: (just for stats) */
636 /*! received frame count: (just for stats) */
641 * \brief a list of frames that may need to be retransmitted
643 * \note The contents of this list do not need to be explicitly destroyed
644 * on module unload. This is because all active calls are destroyed, and
645 * all frames in this queue will get destroyed as a part of that process.
647 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
650 * This module will get much higher performance when doing a lot of
651 * user and peer lookups if the number of buckets is increased from 1.
652 * However, to maintain old behavior for Asterisk 1.4, these are set to
653 * 1 by default. When using multiple buckets, search order through these
654 * containers is considered random, so you will not be able to depend on
655 * the order the entires are specified in iax.conf for matching order. */
657 #define MAX_PEER_BUCKETS 17
659 #define MAX_PEER_BUCKETS 563
661 static struct ao2_container *peers;
663 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
664 static struct ao2_container *users;
666 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
669 /*! Extension exists */
670 CACHE_FLAG_EXISTS = (1 << 0),
671 /*! Extension is nonexistent */
672 CACHE_FLAG_NONEXISTENT = (1 << 1),
673 /*! Extension can exist */
674 CACHE_FLAG_CANEXIST = (1 << 2),
675 /*! Waiting to hear back response */
676 CACHE_FLAG_PENDING = (1 << 3),
678 CACHE_FLAG_TIMEOUT = (1 << 4),
679 /*! Request transmitted */
680 CACHE_FLAG_TRANSMITTED = (1 << 5),
682 CACHE_FLAG_UNKNOWN = (1 << 6),
684 CACHE_FLAG_MATCHMORE = (1 << 7),
687 struct iax2_dpcache {
688 char peercontext[AST_MAX_CONTEXT];
689 char exten[AST_MAX_EXTENSION];
691 struct timeval expiry;
693 unsigned short callno;
695 AST_LIST_ENTRY(iax2_dpcache) cache_list;
696 AST_LIST_ENTRY(iax2_dpcache) peer_list;
699 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
701 static void reg_source_db(struct iax2_peer *p);
702 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
704 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
705 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
706 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
708 enum iax2_thread_iostate {
711 IAX_IOSTATE_PROCESSING,
712 IAX_IOSTATE_SCHEDREADY,
715 enum iax2_thread_type {
716 IAX_THREAD_TYPE_POOL,
717 IAX_THREAD_TYPE_DYNAMIC,
720 struct iax2_pkt_buf {
721 AST_LIST_ENTRY(iax2_pkt_buf) entry;
723 unsigned char buf[1];
727 AST_LIST_ENTRY(iax2_thread) list;
728 enum iax2_thread_type type;
729 enum iax2_thread_iostate iostate;
730 #ifdef SCHED_MULTITHREADED
731 void (*schedfunc)(const void *);
732 const void *scheddata;
734 #ifdef DEBUG_SCHED_MULTITHREAD
740 struct sockaddr_in iosin;
741 unsigned char readbuf[4096];
749 unsigned int ready_for_signal:1;
750 /*! if this thread is processing a full frame,
751 some information about that frame will be stored
752 here, so we can avoid dispatching any more full
753 frames for that callno to other threads */
755 unsigned short callno;
756 struct sockaddr_in sin;
760 /*! Queued up full frames for processing. If more full frames arrive for
761 * a call which this thread is already processing a full frame for, they
762 * are queued up here. */
763 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
767 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
768 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
769 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
771 static void *iax2_process_thread(void *data);
773 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
775 ast_mutex_lock(lock);
776 ast_cond_signal(cond);
777 ast_mutex_unlock(lock);
780 static void iax_debug_output(const char *data)
783 ast_verbose("%s", data);
786 static void iax_error_output(const char *data)
788 ast_log(LOG_WARNING, "%s", data);
791 static void jb_error_output(const char *fmt, ...)
797 vsnprintf(buf, sizeof(buf), fmt, args);
800 ast_log(LOG_ERROR, buf);
803 static void jb_warning_output(const char *fmt, ...)
809 vsnprintf(buf, sizeof(buf), fmt, args);
812 ast_log(LOG_WARNING, buf);
815 static void jb_debug_output(const char *fmt, ...)
821 vsnprintf(buf, sizeof(buf), fmt, args);
828 * \brief an array of iax2 pvt structures
830 * The container for active chan_iax2_pvt structures is implemented as an
831 * array for extremely quick direct access to the correct pvt structure
832 * based on the local call number. The local call number is used as the
833 * index into the array where the associated pvt structure is stored.
835 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
837 * \brief chan_iax2_pvt structure locks
839 * These locks are used when accessing a pvt structure in the iaxs array.
840 * The index used here is the same as used in the iaxs array. It is the
841 * local call number for the associated pvt struct.
843 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
845 * \brief The last time a call number was used
847 * It is important to know the last time that a call number was used locally so
848 * that it is not used again too soon. The reason for this is the same as the
849 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
851 * For example, say that a call is up. Then, the remote side sends a HANGUP,
852 * which we respond to with an ACK. However, there is no way to know whether
853 * the ACK made it there successfully. If it were to get lost, the remote
854 * side may retransmit the HANGUP. If in the meantime, this call number has
855 * been reused locally, given the right set of circumstances, this retransmitted
856 * HANGUP could potentially improperly hang up the new session. So, to avoid
857 * this potential issue, we must wait a specified timeout period before reusing
858 * a local call number.
860 * The specified time that we must wait before reusing a local call number is
861 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
863 static struct timeval lastused[IAX_MAX_CALLS];
865 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);
866 static int expire_registry(const void *data);
867 static int iax2_answer(struct ast_channel *c);
868 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
869 static int iax2_devicestate(void *data);
870 static int iax2_digit_begin(struct ast_channel *c, char digit);
871 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
872 static int iax2_do_register(struct iax2_registry *reg);
873 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
874 static int iax2_hangup(struct ast_channel *c);
875 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
876 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
877 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
878 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
879 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
880 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
881 static int iax2_sendtext(struct ast_channel *c, const char *text);
882 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
883 static int iax2_transfer(struct ast_channel *c, const char *dest);
884 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
885 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
886 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
887 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
888 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
889 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
890 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
891 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
892 static struct ast_frame *iax2_read(struct ast_channel *c);
893 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
894 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
895 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
896 static void prune_peers(void);
897 static void *iax2_dup_variable_datastore(void *);
898 static void iax2_free_variable_datastore(void *);
900 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
901 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
903 static const struct ast_channel_tech iax2_tech = {
905 .description = tdesc,
906 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
907 .properties = AST_CHAN_TP_WANTSJITTER,
908 .requester = iax2_request,
909 .devicestate = iax2_devicestate,
910 .send_digit_begin = iax2_digit_begin,
911 .send_digit_end = iax2_digit_end,
912 .send_text = iax2_sendtext,
913 .send_image = iax2_sendimage,
914 .send_html = iax2_sendhtml,
916 .hangup = iax2_hangup,
917 .answer = iax2_answer,
920 .write_video = iax2_write,
921 .indicate = iax2_indicate,
922 .setoption = iax2_setoption,
923 .bridge = iax2_bridge,
924 .transfer = iax2_transfer,
926 .func_channel_read = acf_channel_read,
927 .func_channel_write = acf_channel_write,
930 static void mwi_event_cb(const struct ast_event *event, void *userdata)
932 /* The MWI subscriptions exist just so the core knows we care about those
933 * mailboxes. However, we just grab the events out of the cache when it
934 * is time to send MWI, since it is only sent with a REGACK. */
937 /*! \brief Send manager event at call setup to link between Asterisk channel name
938 and IAX2 call identifiers */
939 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
941 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
942 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
943 pvt->owner ? pvt->owner->name : "",
944 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
948 static struct ast_datastore_info iax2_variable_datastore_info = {
949 .type = "IAX2_VARIABLE",
950 .duplicate = iax2_dup_variable_datastore,
951 .destroy = iax2_free_variable_datastore,
954 static void *iax2_dup_variable_datastore(void *old)
956 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
957 struct ast_var_t *oldvar, *newvar;
959 newlist = ast_calloc(sizeof(*newlist), 1);
961 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
965 AST_LIST_HEAD_INIT(newlist);
966 AST_LIST_LOCK(oldlist);
967 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
968 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
970 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
972 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
974 AST_LIST_UNLOCK(oldlist);
978 static void iax2_free_variable_datastore(void *old)
980 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
981 struct ast_var_t *oldvar;
983 AST_LIST_LOCK(oldlist);
984 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
987 AST_LIST_UNLOCK(oldlist);
988 AST_LIST_HEAD_DESTROY(oldlist);
993 /* WARNING: insert_idle_thread should only ever be called within the
994 * context of an iax2_process_thread() thread.
996 static void insert_idle_thread(struct iax2_thread *thread)
998 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
999 AST_LIST_LOCK(&dynamic_list);
1000 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1001 AST_LIST_UNLOCK(&dynamic_list);
1003 AST_LIST_LOCK(&idle_list);
1004 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1005 AST_LIST_UNLOCK(&idle_list);
1011 static struct iax2_thread *find_idle_thread(void)
1013 struct iax2_thread *thread = NULL;
1015 /* Pop the head of the idle list off */
1016 AST_LIST_LOCK(&idle_list);
1017 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1018 AST_LIST_UNLOCK(&idle_list);
1020 /* If we popped a thread off the idle list, just return it */
1022 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1026 /* Pop the head of the dynamic list off */
1027 AST_LIST_LOCK(&dynamic_list);
1028 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1029 AST_LIST_UNLOCK(&dynamic_list);
1031 /* If we popped a thread off the dynamic list, just return it */
1033 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1037 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1038 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1041 /* Set default values */
1042 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1043 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1045 /* Initialize lock and condition */
1046 ast_mutex_init(&thread->lock);
1047 ast_cond_init(&thread->cond, NULL);
1049 /* Create thread and send it on it's way */
1050 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1051 ast_cond_destroy(&thread->cond);
1052 ast_mutex_destroy(&thread->lock);
1057 /* this thread is not processing a full frame (since it is idle),
1058 so ensure that the field for the full frame call number is empty */
1059 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1061 /* Wait for the thread to be ready before returning it to the caller */
1062 while (!thread->ready_for_signal)
1068 #ifdef SCHED_MULTITHREADED
1069 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1071 struct iax2_thread *thread = NULL;
1072 static time_t lasterror;
1075 thread = find_idle_thread();
1077 if (thread != NULL) {
1078 thread->schedfunc = func;
1079 thread->scheddata = data;
1080 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1081 #ifdef DEBUG_SCHED_MULTITHREAD
1082 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1084 signal_condition(&thread->lock, &thread->cond);
1089 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
1094 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1097 static int iax2_sched_replace(int old_id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1101 res = ast_sched_replace(old_id, con, when, callback, data);
1102 signal_condition(&sched_lock, &sched_cond);
1107 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1111 res = ast_sched_add(con, when, callback, data);
1112 signal_condition(&sched_lock, &sched_cond);
1117 static int send_ping(const void *data);
1119 static void __send_ping(const void *data)
1121 int callno = (long)data;
1122 ast_mutex_lock(&iaxsl[callno]);
1123 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
1124 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1125 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1127 ast_mutex_unlock(&iaxsl[callno]);
1130 static int send_ping(const void *data)
1132 #ifdef SCHED_MULTITHREADED
1133 if (schedule_action(__send_ping, data))
1139 static int get_encrypt_methods(const char *s)
1142 if (!strcasecmp(s, "aes128"))
1143 e = IAX_ENCRYPT_AES128;
1144 else if (ast_true(s))
1145 e = IAX_ENCRYPT_AES128;
1151 static int send_lagrq(const void *data);
1153 static void __send_lagrq(const void *data)
1155 int callno = (long)data;
1156 /* Ping only if it's real not if it's bridged */
1157 ast_mutex_lock(&iaxsl[callno]);
1158 if (iaxs[callno] && iaxs[callno]->lagid != -1) {
1159 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1160 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1162 ast_mutex_unlock(&iaxsl[callno]);
1165 static int send_lagrq(const void *data)
1167 #ifdef SCHED_MULTITHREADED
1168 if (schedule_action(__send_lagrq, data))
1174 static unsigned char compress_subclass(int subclass)
1178 /* If it's 128 or smaller, just return it */
1179 if (subclass < IAX_FLAG_SC_LOG)
1181 /* Otherwise find its power */
1182 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1183 if (subclass & (1 << x)) {
1185 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1191 return power | IAX_FLAG_SC_LOG;
1194 static int uncompress_subclass(unsigned char csub)
1196 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1197 if (csub & IAX_FLAG_SC_LOG) {
1198 /* special case for 'compressed' -1 */
1202 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1209 * \note The only member of the peer passed here guaranteed to be set is the name field
1211 static int peer_hash_cb(const void *obj, const int flags)
1213 const struct iax2_peer *peer = obj;
1215 return ast_str_hash(peer->name);
1219 * \note The only member of the peer passed here guaranteed to be set is the name field
1221 static int peer_cmp_cb(void *obj, void *arg, int flags)
1223 struct iax2_peer *peer = obj, *peer2 = arg;
1225 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1229 * \note The only member of the user passed here guaranteed to be set is the name field
1231 static int user_hash_cb(const void *obj, const int flags)
1233 const struct iax2_user *user = obj;
1235 return ast_str_hash(user->name);
1239 * \note The only member of the user passed here guaranteed to be set is the name field
1241 static int user_cmp_cb(void *obj, void *arg, int flags)
1243 struct iax2_user *user = obj, *user2 = arg;
1245 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1249 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1250 * so do not call it with a pvt lock held.
1252 static struct iax2_peer *find_peer(const char *name, int realtime)
1254 struct iax2_peer *peer = NULL;
1255 struct iax2_peer tmp_peer = {
1259 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1261 /* Now go for realtime if applicable */
1262 if(!peer && realtime)
1263 peer = realtime_peer(name, NULL);
1268 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1274 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1280 static inline struct iax2_user *user_ref(struct iax2_user *user)
1286 static inline struct iax2_user *user_unref(struct iax2_user *user)
1292 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1294 struct iax2_peer *peer = NULL;
1296 struct ao2_iterator i;
1298 i = ao2_iterator_init(peers, 0);
1299 while ((peer = ao2_iterator_next(&i))) {
1300 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1301 (peer->addr.sin_port == sin.sin_port)) {
1302 ast_copy_string(host, peer->name, len);
1311 peer = realtime_peer(NULL, &sin);
1313 ast_copy_string(host, peer->name, len);
1322 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1324 struct chan_iax2_pvt *tmp;
1327 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1330 if (ast_string_field_init(tmp, 32)) {
1343 ast_string_field_set(tmp,exten, "s");
1344 ast_string_field_set(tmp,host, host);
1348 jbconf.max_jitterbuf = maxjitterbuffer;
1349 jbconf.resync_threshold = resyncthreshold;
1350 jbconf.max_contig_interp = maxjitterinterps;
1351 jbconf.target_extra = jittertargetextra;
1352 jb_setconf(tmp->jb,&jbconf);
1354 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1359 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1361 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1363 size_t afdatalen = new->afdatalen;
1364 memcpy(new, fr, sizeof(*new));
1365 iax_frame_wrap(new, &fr->af);
1366 new->afdatalen = afdatalen;
1369 new->direction = DIRECTION_INGRESS;
1375 #define NEW_PREVENT 0
1379 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur)
1381 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1382 (cur->addr.sin_port == sin->sin_port)) {
1383 /* This is the main host */
1384 if ((cur->peercallno == callno) ||
1385 ((dcallno == cur->callno) && !cur->peercallno)) {
1386 /* That's us. Be sure we keep track of the peer call number */
1390 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1391 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1392 /* We're transferring */
1393 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1399 static void update_max_trunk(void)
1401 int max = TRUNK_CALL_START;
1403 /* XXX Prolly don't need locks here XXX */
1404 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1410 ast_debug(1, "New max trunk callno is %d\n", max);
1413 static void update_max_nontrunk(void)
1417 /* XXX Prolly don't need locks here XXX */
1418 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1422 maxnontrunkcall = max;
1424 ast_debug(1, "New max nontrunk callno is %d\n", max);
1427 static int make_trunk(unsigned short callno, int locked)
1431 struct timeval now = ast_tvnow();
1432 if (iaxs[callno]->oseqno) {
1433 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1436 if (callno & TRUNK_CALL_START) {
1437 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1440 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1441 ast_mutex_lock(&iaxsl[x]);
1442 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1443 iaxs[x] = iaxs[callno];
1444 iaxs[x]->callno = x;
1445 iaxs[callno] = NULL;
1446 /* Update the two timers that should have been started */
1447 iaxs[x]->pingid = iax2_sched_replace(iaxs[x]->pingid, sched,
1448 ping_time * 1000, send_ping, (void *)(long)x);
1449 iaxs[x]->lagid = iax2_sched_replace(iaxs[x]->lagid, sched,
1450 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1452 ast_mutex_unlock(&iaxsl[callno]);
1455 ast_mutex_unlock(&iaxsl[x]);
1458 ast_mutex_unlock(&iaxsl[x]);
1460 if (x >= IAX_MAX_CALLS - 1) {
1461 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1464 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1465 /* We move this call from a non-trunked to a trunked call */
1467 update_max_nontrunk();
1472 * \todo XXX Note that this function contains a very expensive operation that
1473 * happens for *every* incoming media frame. It iterates through every
1474 * possible call number, locking and unlocking each one, to try to match the
1475 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1476 * So, for a call with a local call number of 20000, every incoming audio
1477 * frame would require 20000 mutex lock and unlock operations. Ouch.
1479 * It's a shame that IAX2 media frames carry the source call number instead of
1480 * the destination call number. If they did, this lookup wouldn't be needed.
1481 * However, it's too late to change that now. Instead, we need to come up with
1482 * a better way of indexing active calls so that these frequent lookups are not
1485 * \note Calling this function while holding another pvt lock can cause a deadlock.
1487 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd)
1494 if (new <= NEW_ALLOW) {
1495 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1496 ast_mutex_lock(&iaxsl[x]);
1498 /* Look for an exact match */
1499 if (match(sin, callno, dcallno, iaxs[x])) {
1503 ast_mutex_unlock(&iaxsl[x]);
1505 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1506 ast_mutex_lock(&iaxsl[x]);
1508 /* Look for an exact match */
1509 if (match(sin, callno, dcallno, iaxs[x])) {
1513 ast_mutex_unlock(&iaxsl[x]);
1516 if ((res < 1) && (new >= NEW_ALLOW)) {
1517 /* It may seem odd that we look through the peer list for a name for
1518 * this *incoming* call. Well, it is weird. However, users don't
1519 * have an IP address/port number that we can match against. So,
1520 * this is just checking for a peer that has that IP/port and
1521 * assuming that we have a user of the same name. This isn't always
1522 * correct, but it will be changed if needed after authentication. */
1523 if (!iax2_getpeername(*sin, host, sizeof(host)))
1524 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1526 for (x=1;x<TRUNK_CALL_START;x++) {
1527 /* Find first unused call number that hasn't been used in a while */
1528 ast_mutex_lock(&iaxsl[x]);
1529 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1530 ast_mutex_unlock(&iaxsl[x]);
1532 /* We've still got lock held if we found a spot */
1533 if (x >= TRUNK_CALL_START) {
1534 ast_log(LOG_WARNING, "No more space\n");
1537 iaxs[x] = new_iax(sin, host);
1538 update_max_nontrunk();
1541 ast_debug(1, "Creating new call structure %d\n", x);
1542 iaxs[x]->sockfd = sockfd;
1543 iaxs[x]->addr.sin_port = sin->sin_port;
1544 iaxs[x]->addr.sin_family = sin->sin_family;
1545 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1546 iaxs[x]->peercallno = callno;
1547 iaxs[x]->callno = x;
1548 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1549 iaxs[x]->expiry = min_reg_expire;
1550 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1551 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1552 iaxs[x]->amaflags = amaflags;
1553 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1555 ast_string_field_set(iaxs[x], accountcode, accountcode);
1556 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1557 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1559 ast_log(LOG_WARNING, "Out of resources\n");
1560 ast_mutex_unlock(&iaxsl[x]);
1563 ast_mutex_unlock(&iaxsl[x]);
1569 static void iax2_frame_free(struct iax_frame *fr)
1571 if (fr->retrans > -1)
1572 ast_sched_del(sched, fr->retrans);
1577 * \brief Queue a frame to a call's owning asterisk channel
1579 * \pre This function assumes that iaxsl[callno] is locked when called.
1581 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1582 * was valid before calling it, it may no longer be valid after calling it.
1583 * This function may unlock and lock the mutex associated with this callno,
1584 * meaning that another thread may grab it and destroy the call.
1586 static int iax2_queue_frame(int callno, struct ast_frame *f)
1589 if (iaxs[callno] && iaxs[callno]->owner) {
1590 if (ast_channel_trylock(iaxs[callno]->owner)) {
1591 /* Avoid deadlock by pausing and trying again */
1592 ast_mutex_unlock(&iaxsl[callno]);
1594 ast_mutex_lock(&iaxsl[callno]);
1596 ast_queue_frame(iaxs[callno]->owner, f);
1597 ast_channel_unlock(iaxs[callno]->owner);
1607 * \brief Queue a hangup frame on the ast_channel owner
1609 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1610 * is active for the given call number.
1612 * \pre Assumes lock for callno is already held.
1614 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1615 * was valid before calling it, it may no longer be valid after calling it.
1616 * This function may unlock and lock the mutex associated with this callno,
1617 * meaning that another thread may grab it and destroy the call.
1619 static int iax2_queue_hangup(int callno)
1622 if (iaxs[callno] && iaxs[callno]->owner) {
1623 if (ast_channel_trylock(iaxs[callno]->owner)) {
1624 /* Avoid deadlock by pausing and trying again */
1625 ast_mutex_unlock(&iaxsl[callno]);
1627 ast_mutex_lock(&iaxsl[callno]);
1629 ast_queue_hangup(iaxs[callno]->owner);
1630 ast_channel_unlock(iaxs[callno]->owner);
1640 * \brief Queue a control frame on the ast_channel owner
1642 * This function queues a control frame on the owner of the IAX2 pvt struct that
1643 * is active for the given call number.
1645 * \pre Assumes lock for callno is already held.
1647 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1648 * was valid before calling it, it may no longer be valid after calling it.
1649 * This function may unlock and lock the mutex associated with this callno,
1650 * meaning that another thread may grab it and destroy the call.
1652 static int iax2_queue_control_data(int callno,
1653 enum ast_control_frame_type control, const void *data, size_t datalen)
1656 if (iaxs[callno] && iaxs[callno]->owner) {
1657 if (ast_channel_trylock(iaxs[callno]->owner)) {
1658 /* Avoid deadlock by pausing and trying again */
1659 ast_mutex_unlock(&iaxsl[callno]);
1661 ast_mutex_lock(&iaxsl[callno]);
1663 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1664 ast_channel_unlock(iaxs[callno]->owner);
1672 static void destroy_firmware(struct iax_firmware *cur)
1674 /* Close firmware */
1676 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1682 static int try_firmware(char *s)
1685 struct iax_firmware *cur = NULL;
1686 int ifd, fd, res, len, chunk;
1687 struct ast_iax2_firmware_header *fwh, fwh2;
1688 struct MD5Context md5;
1689 unsigned char sum[16], buf[1024];
1692 if (!(s2 = alloca(strlen(s) + 100))) {
1693 ast_log(LOG_WARNING, "Alloca failed!\n");
1697 last = strrchr(s, '/');
1703 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1705 if ((res = stat(s, &stbuf) < 0)) {
1706 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1710 /* Make sure it's not a directory */
1711 if (S_ISDIR(stbuf.st_mode))
1713 ifd = open(s, O_RDONLY);
1715 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1718 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1720 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1724 /* Unlink our newly created file */
1727 /* Now copy the firmware into it */
1728 len = stbuf.st_size;
1731 if (chunk > sizeof(buf))
1732 chunk = sizeof(buf);
1733 res = read(ifd, buf, chunk);
1735 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1740 res = write(fd, buf, chunk);
1742 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1750 /* Return to the beginning */
1751 lseek(fd, 0, SEEK_SET);
1752 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1753 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1757 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1758 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1762 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1763 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1767 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1768 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1772 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1773 if (fwh == (void *) -1) {
1774 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1779 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1780 MD5Final(sum, &md5);
1781 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1782 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1783 munmap((void*)fwh, stbuf.st_size);
1788 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1789 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1790 /* Found a candidate */
1791 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1792 /* The version we have on loaded is older, load this one instead */
1794 /* This version is no newer than what we have. Don't worry about it.
1795 We'll consider it a proper load anyhow though */
1796 munmap((void*)fwh, stbuf.st_size);
1802 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1804 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1809 munmap((void*)cur->fwh, cur->mmaplen);
1814 cur->mmaplen = stbuf.st_size;
1821 static int iax_check_version(char *dev)
1824 struct iax_firmware *cur = NULL;
1826 if (ast_strlen_zero(dev))
1829 AST_LIST_LOCK(&firmwares);
1830 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1831 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1832 res = ntohs(cur->fwh->version);
1836 AST_LIST_UNLOCK(&firmwares);
1841 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1844 unsigned int bs = desc & 0xff;
1845 unsigned int start = (desc >> 8) & 0xffffff;
1847 struct iax_firmware *cur;
1849 if (ast_strlen_zero((char *)dev) || !bs)
1854 AST_LIST_LOCK(&firmwares);
1855 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1856 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1858 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1859 if (start < ntohl(cur->fwh->datalen)) {
1860 bytes = ntohl(cur->fwh->datalen) - start;
1863 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1866 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1874 AST_LIST_UNLOCK(&firmwares);
1880 static void reload_firmware(int unload)
1882 struct iax_firmware *cur = NULL;
1885 char dir[256], fn[256];
1887 AST_LIST_LOCK(&firmwares);
1889 /* Mark all as dead */
1890 AST_LIST_TRAVERSE(&firmwares, cur, list)
1893 /* Now that we have marked them dead... load new ones */
1895 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1898 while((de = readdir(fwd))) {
1899 if (de->d_name[0] != '.') {
1900 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1901 if (!try_firmware(fn)) {
1902 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
1908 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1911 /* Clean up leftovers */
1912 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1915 AST_LIST_REMOVE_CURRENT(list);
1916 destroy_firmware(cur);
1918 AST_LIST_TRAVERSE_SAFE_END;
1920 AST_LIST_UNLOCK(&firmwares);
1924 * \note This function assumes that iaxsl[callno] is locked when called.
1926 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1927 * was valid before calling it, it may no longer be valid after calling it.
1928 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1929 * associated with this callno, meaning that another thread may grab it and destroy the call.
1931 static int __do_deliver(void *data)
1933 /* Just deliver the packet by using queueing. This is called by
1934 the IAX thread with the iaxsl lock held. */
1935 struct iax_frame *fr = data;
1937 fr->af.has_timing_info = 0;
1938 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1939 iax2_queue_frame(fr->callno, &fr->af);
1940 /* Free our iax frame */
1941 iax2_frame_free(fr);
1942 /* And don't run again */
1946 static int handle_error(void)
1948 /* XXX Ideally we should figure out why an error occurred and then abort those
1949 rather than continuing to try. Unfortunately, the published interface does
1950 not seem to work XXX */
1952 struct sockaddr_in *sin;
1955 struct sock_extended_err e;
1960 m.msg_controllen = sizeof(e);
1962 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1964 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1966 if (m.msg_controllen) {
1967 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1969 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1971 ast_log(LOG_WARNING, "No address detected??\n");
1973 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1980 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1983 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1986 ast_debug(1, "Received error: %s\n", strerror(errno));
1993 static int send_packet(struct iax_frame *f)
1996 int callno = f->callno;
1998 /* Don't send if there was an error, but return error instead */
1999 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2002 /* Called with iaxsl held */
2004 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
2007 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
2008 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
2009 sizeof(iaxs[callno]->transfer));
2012 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2013 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
2014 sizeof(iaxs[callno]->addr));
2018 ast_debug(1, "Received error: %s\n", strerror(errno));
2025 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
2027 /* Decrement AUTHREQ count if needed */
2028 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
2029 struct iax2_user *user;
2030 struct iax2_user tmp_user = {
2031 .name = pvt->username,
2034 user = ao2_find(users, &tmp_user, OBJ_POINTER);
2036 ast_atomic_fetchadd_int(&user->curauthreq, -1);
2040 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
2042 /* No more pings or lagrq's */
2043 if (pvt->pingid > -1)
2044 ast_sched_del(sched, pvt->pingid);
2046 if (pvt->lagid > -1)
2047 ast_sched_del(sched, pvt->lagid);
2049 if (pvt->autoid > -1)
2050 ast_sched_del(sched, pvt->autoid);
2052 if (pvt->authid > -1)
2053 ast_sched_del(sched, pvt->authid);
2055 if (pvt->initid > -1)
2056 ast_sched_del(sched, pvt->initid);
2059 ast_sched_del(sched, pvt->jbid);
2064 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2065 * for the given call number may disappear during its execution.
2067 static int iax2_predestroy(int callno)
2069 struct ast_channel *c = NULL;
2070 struct chan_iax2_pvt *pvt = iaxs[callno];
2075 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2076 iax2_destroy_helper(pvt);
2077 ast_set_flag(pvt, IAX_ALREADYGONE);
2080 if ((c = pvt->owner)) {
2082 iax2_queue_hangup(callno);
2084 ast_module_unref(ast_module_info->self);
2090 static void iax2_destroy(int callno)
2092 struct chan_iax2_pvt *pvt = NULL;
2093 struct iax_frame *cur = NULL;
2094 struct ast_channel *owner = NULL;
2098 lastused[callno] = ast_tvnow();
2100 owner = pvt ? pvt->owner : NULL;
2103 if (ast_channel_trylock(owner)) {
2104 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
2105 ast_mutex_unlock(&iaxsl[callno]);
2107 ast_mutex_lock(&iaxsl[callno]);
2112 iaxs[callno] = NULL;
2116 iax2_destroy_helper(pvt);
2119 ast_set_flag(pvt, IAX_ALREADYGONE);
2122 /* If there's an owner, prod it to give up */
2123 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2124 * because we already hold the owner channel lock. */
2125 ast_queue_hangup(owner);
2128 AST_LIST_LOCK(&frame_queue);
2129 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2130 /* Cancel any pending transmissions */
2131 if (cur->callno == pvt->callno)
2134 AST_LIST_UNLOCK(&frame_queue);
2137 pvt->reg->callno = 0;
2141 ast_variables_destroy(pvt->vars);
2145 while (jb_getall(pvt->jb, &frame) == JB_OK)
2146 iax2_frame_free(frame.data);
2147 jb_destroy(pvt->jb);
2148 /* gotta free up the stringfields */
2149 ast_string_field_free_memory(pvt);
2154 ast_channel_unlock(owner);
2156 if (callno & 0x4000)
2160 static int update_packet(struct iax_frame *f)
2162 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2163 struct ast_iax2_full_hdr *fh = f->data;
2164 /* Mark this as a retransmission */
2165 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2167 f->iseqno = iaxs[f->callno]->iseqno;
2168 fh->iseqno = f->iseqno;
2172 static int attempt_transmit(const void *data);
2173 static void __attempt_transmit(const void *data)
2175 /* Attempt to transmit the frame to the remote peer...
2176 Called without iaxsl held. */
2177 struct iax_frame *f = (struct iax_frame *)data;
2179 int callno = f->callno;
2180 /* Make sure this call is still active */
2182 ast_mutex_lock(&iaxsl[callno]);
2183 if (callno && iaxs[callno]) {
2184 if ((f->retries < 0) /* Already ACK'd */ ||
2185 (f->retries >= max_retries) /* Too many attempts */) {
2186 /* Record an error if we've transmitted too many times */
2187 if (f->retries >= max_retries) {
2189 /* Transfer timeout */
2190 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2191 } else if (f->final) {
2193 iax2_destroy(callno);
2195 if (iaxs[callno]->owner)
2196 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);
2197 iaxs[callno]->error = ETIMEDOUT;
2198 if (iaxs[callno]->owner) {
2199 struct ast_frame fr = { 0, };
2201 fr.frametype = AST_FRAME_CONTROL;
2202 fr.subclass = AST_CONTROL_HANGUP;
2203 iax2_queue_frame(callno, &fr); /* XXX */
2204 /* Remember, owner could disappear */
2205 if (iaxs[callno] && iaxs[callno]->owner)
2206 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2208 if (iaxs[callno]->reg) {
2209 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2210 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2211 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2213 iax2_destroy(callno);
2220 /* Update it if it needs it */
2222 /* Attempt transmission */
2225 /* Try again later after 10 times as long */
2227 if (f->retrytime > MAX_RETRY_TIME)
2228 f->retrytime = MAX_RETRY_TIME;
2229 /* Transfer messages max out at one second */
2230 if (f->transfer && (f->retrytime > 1000))
2231 f->retrytime = 1000;
2232 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2235 /* Make sure it gets freed */
2240 ast_mutex_unlock(&iaxsl[callno]);
2241 /* Do not try again */
2243 /* Don't attempt delivery, just remove it from the queue */
2244 AST_LIST_LOCK(&frame_queue);
2245 AST_LIST_REMOVE(&frame_queue, f, list);
2246 AST_LIST_UNLOCK(&frame_queue);
2248 /* Free the IAX frame */
2253 static int attempt_transmit(const void *data)
2255 #ifdef SCHED_MULTITHREADED
2256 if (schedule_action(__attempt_transmit, data))
2258 __attempt_transmit(data);
2262 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2264 struct iax2_peer *peer;
2268 e->command = "iax2 prune realtime";
2270 "Usage: iax2 prune realtime [<peername>|all]\n"
2271 " Prunes object(s) from the cache\n";
2274 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2278 return CLI_SHOWUSAGE;
2279 if (!strcmp(a->argv[3], "all")) {
2281 ast_cli(a->fd, "Cache flushed successfully.\n");
2282 } else if ((peer = find_peer(a->argv[3], 0))) {
2283 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2284 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2285 expire_registry(peer_ref(peer));
2286 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2288 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2292 ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2298 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2302 e->command = "iax2 test losspct";
2304 "Usage: iax2 test losspct <percentage>\n"
2305 " For testing, throws away <percentage> percent of incoming packets\n";
2311 return CLI_SHOWUSAGE;
2313 test_losspct = atoi(a->argv[3]);
2319 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2323 e->command = "iax2 test late";
2325 "Usage: iax2 test late <ms>\n"
2326 " For testing, count the next frame as <ms> ms late\n";
2333 return CLI_SHOWUSAGE;
2335 test_late = atoi(a->argv[3]);
2340 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2344 e->command = "iax2 test resync";
2346 "Usage: iax2 test resync <ms>\n"
2347 " For testing, adjust all future frames by <ms> ms\n";
2354 return CLI_SHOWUSAGE;
2356 test_resync = atoi(a->argv[3]);
2361 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2365 e->command = "iax2 test jitter";
2367 "Usage: iax2 test jitter <ms> <pct>\n"
2368 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2369 " percentage of packets. If <pct> is not specified, adds\n"
2370 " jitter to all packets.\n";
2376 if (a->argc < 4 || a->argc > 5)
2377 return CLI_SHOWUSAGE;
2379 test_jit = atoi(a->argv[3]);
2381 test_jitpct = atoi(a->argv[4]);
2385 #endif /* IAXTESTS */
2387 /*! \brief peer_status: Report Peer status in character string */
2388 /* returns 1 if peer is online, -1 if unmonitored */
2389 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2393 if (peer->lastms < 0) {
2394 ast_copy_string(status, "UNREACHABLE", statuslen);
2395 } else if (peer->lastms > peer->maxms) {
2396 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2398 } else if (peer->lastms) {
2399 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2402 ast_copy_string(status, "UNKNOWN", statuslen);
2405 ast_copy_string(status, "Unmonitored", statuslen);
2411 /*! \brief Show one peer in detail */
2412 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2416 struct iax2_peer *peer;
2417 char codec_buf[512];
2418 int x = 0, codec = 0, load_realtime = 0;
2422 e->command = "iax2 show peer";
2424 "Usage: iax2 show peer <name>\n"
2425 " Display details on specific IAX peer\n";
2428 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2432 return CLI_SHOWUSAGE;
2434 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2436 peer = find_peer(a->argv[3], load_realtime);
2438 ast_cli(a->fd, "\n\n");
2439 ast_cli(a->fd, " * Name : %s\n", peer->name);
2440 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2441 ast_cli(a->fd, " Context : %s\n", peer->context);
2442 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
2443 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2444 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2445 ast_cli(a->fd, " Expire : %d\n", peer->expire);
2446 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
2447 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2448 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2449 ast_cli(a->fd, " Username : %s\n", peer->username);
2450 ast_cli(a->fd, " Codecs : ");
2451 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2452 ast_cli(a->fd, "%s\n", codec_buf);
2454 ast_cli(a->fd, " Codec Order : (");
2455 for(x = 0; x < 32 ; x++) {
2456 codec = ast_codec_pref_index(&peer->prefs,x);
2459 ast_cli(a->fd, "%s", ast_getformatname(codec));
2460 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2461 ast_cli(a->fd, "|");
2465 ast_cli(a->fd, "none");
2466 ast_cli(a->fd, ")\n");
2468 ast_cli(a->fd, " Status : ");
2469 peer_status(peer, status, sizeof(status));
2470 ast_cli(a->fd, "%s\n",status);
2471 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2472 ast_cli(a->fd, "\n");
2475 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2476 ast_cli(a->fd, "\n");
2482 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2485 struct iax2_peer *peer;
2487 int wordlen = strlen(word);
2488 struct ao2_iterator i;
2490 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2494 i = ao2_iterator_init(peers, 0);
2495 while ((peer = ao2_iterator_next(&i))) {
2496 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2497 res = ast_strdup(peer->name);
2507 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2509 struct iax_frame *cur;
2510 int cnt = 0, dead = 0, final = 0;
2514 e->command = "iax2 show stats";
2516 "Usage: iax2 show stats\n"
2517 " Display statistics on IAX channel driver.\n";
2524 return CLI_SHOWUSAGE;
2526 AST_LIST_LOCK(&frame_queue);
2527 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2528 if (cur->retries < 0)
2534 AST_LIST_UNLOCK(&frame_queue);
2536 ast_cli(a->fd, " IAX Statistics\n");
2537 ast_cli(a->fd, "---------------------\n");
2538 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2539 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2540 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2541 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2543 trunk_timed = trunk_untimed = 0;
2544 if (trunk_maxmtu > trunk_nmaxmtu)
2545 trunk_nmaxmtu = trunk_maxmtu;
2550 /*! \brief Set trunk MTU from CLI */
2551 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2557 e->command = "iax2 set mtu";
2559 "Usage: iax2 set mtu <value>\n"
2560 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2561 " zero to disable. Disabling means that the operating system\n"
2562 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2563 " packet exceeds the UDP payload size. This is substantially\n"
2564 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2565 " greater for G.711 samples.\n";
2572 return CLI_SHOWUSAGE;
2573 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2574 mtuv = MAX_TRUNK_MTU;
2576 mtuv = atoi(a->argv[3]);
2579 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2580 global_max_trunk_mtu = 0;
2583 if (mtuv < 172 || mtuv > 4000) {
2584 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
2585 return CLI_SHOWUSAGE;
2587 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2588 global_max_trunk_mtu = mtuv;
2592 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2594 struct iax2_dpcache *dp = NULL;
2595 char tmp[1024], *pc = NULL;
2597 struct timeval tv = ast_tvnow();
2601 e->command = "iax2 show cache";
2603 "Usage: iax2 show cache\n"
2604 " Display currently cached IAX Dialplan results.\n";
2610 AST_LIST_LOCK(&dpcache);
2612 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2614 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2615 s = dp->expiry.tv_sec - tv.tv_sec;
2617 if (dp->flags & CACHE_FLAG_EXISTS)
2618 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2619 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2620 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2621 if (dp->flags & CACHE_FLAG_CANEXIST)
2622 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2623 if (dp->flags & CACHE_FLAG_PENDING)
2624 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2625 if (dp->flags & CACHE_FLAG_TIMEOUT)
2626 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2627 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2628 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2629 if (dp->flags & CACHE_FLAG_MATCHMORE)
2630 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2631 if (dp->flags & CACHE_FLAG_UNKNOWN)
2632 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2633 /* Trim trailing pipe */
2634 if (!ast_strlen_zero(tmp))
2635 tmp[strlen(tmp) - 1] = '\0';
2637 ast_copy_string(tmp, "(none)", sizeof(tmp));
2639 pc = strchr(dp->peercontext, '@');
2641 pc = dp->peercontext;
2644 for (x = 0; x < sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2645 if (dp->waiters[x] > -1)
2648 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2650 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2653 AST_LIST_LOCK(&dpcache);
2658 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2660 static void unwrap_timestamp(struct iax_frame *fr)
2664 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2665 x = fr->ts - iaxs[fr->callno]->last;
2667 /* Sudden big jump backwards in timestamp:
2668 What likely happened here is that miniframe timestamp has circled but we haven't
2669 gotten the update from the main packet. We'll just pretend that we did, and
2670 update the timestamp appropriately. */
2671 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2673 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2676 /* Sudden apparent big jump forwards in timestamp:
2677 What's likely happened is this is an old miniframe belonging to the previous
2678 top-16-bit timestamp that has turned up out of order.
2679 Adjust the timestamp appropriately. */
2680 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2682 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2687 static int get_from_jb(const void *p);
2689 static void update_jbsched(struct chan_iax2_pvt *pvt)
2693 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2695 when = jb_next(pvt->jb) - when;
2698 /* XXX should really just empty until when > 0.. */
2702 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
2703 CALLNO_TO_PTR(pvt->callno));
2706 static void __get_from_jb(const void *p)
2708 int callno = PTR_TO_CALLNO(p);
2709 struct chan_iax2_pvt *pvt = NULL;
2710 struct iax_frame *fr;
2715 struct timeval tv = ast_tvnow();
2717 /* Make sure we have a valid private structure before going on */
2718 ast_mutex_lock(&iaxsl[callno]);
2722 ast_mutex_unlock(&iaxsl[callno]);
2728 /* round up a millisecond since ast_sched_runq does; */
2729 /* prevents us from spinning while waiting for our now */
2730 /* to catch up with runq's now */
2733 now = ast_tvdiff_ms(tv, pvt->rxcore);
2735 if(now >= (next = jb_next(pvt->jb))) {
2736 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2741 /* __do_deliver() can cause the call to disappear */
2746 struct ast_frame af = { 0, };
2748 /* create an interpolation frame */
2749 af.frametype = AST_FRAME_VOICE;
2750 af.subclass = pvt->voiceformat;
2751 af.samples = frame.ms * 8;
2752 af.src = "IAX2 JB interpolation";
2753 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2754 af.offset = AST_FRIENDLY_OFFSET;
2756 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2757 * which we'd need to malloc, and then it would free it. That seems like a drag */
2758 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2759 iax2_queue_frame(callno, &af);
2760 /* iax2_queue_frame() could cause the call to disappear */
2766 iax2_frame_free(frame.data);
2773 /* shouldn't happen */
2778 update_jbsched(pvt);
2779 ast_mutex_unlock(&iaxsl[callno]);
2782 static int get_from_jb(const void *data)
2784 #ifdef SCHED_MULTITHREADED
2785 if (schedule_action(__get_from_jb, data))
2787 __get_from_jb(data);
2792 * \note This function assumes fr->callno is locked
2794 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2795 * was valid before calling it, it may no longer be valid after calling it.
2797 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2803 /* Attempt to recover wrapped timestamps */
2804 unwrap_timestamp(fr);
2806 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2807 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2808 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2811 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2813 fr->af.delivery = ast_tv(0,0);
2816 type = JB_TYPE_CONTROL;
2819 if(fr->af.frametype == AST_FRAME_VOICE) {
2820 type = JB_TYPE_VOICE;
2821 len = ast_codec_get_samples(&fr->af) / 8;
2822 } else if(fr->af.frametype == AST_FRAME_CNG) {
2823 type = JB_TYPE_SILENCE;
2826 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2833 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2834 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2835 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2836 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2837 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2840 /* deliver any frames in the jb */
2841 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2842 __do_deliver(frame.data);
2843 /* __do_deliver() can make the call disappear */
2844 if (!iaxs[fr->callno])
2848 jb_reset(iaxs[fr->callno]->jb);
2850 if (iaxs[fr->callno]->jbid > -1)
2851 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2853 iaxs[fr->callno]->jbid = -1;
2855 /* deliver this frame now */
2862 /* insert into jitterbuffer */
2863 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2864 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2865 calc_rxstamp(iaxs[fr->callno],fr->ts));
2866 if (ret == JB_DROP) {
2868 } else if (ret == JB_SCHED) {
2869 update_jbsched(iaxs[fr->callno]);
2874 /* Free our iax frame */
2875 iax2_frame_free(fr);
2881 static int iax2_transmit(struct iax_frame *fr)
2883 /* Lock the queue and place this packet at the end */
2884 /* By setting this to 0, the network thread will send it for us, and
2885 queue retransmission if necessary */
2887 AST_LIST_LOCK(&frame_queue);
2888 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
2889 AST_LIST_UNLOCK(&frame_queue);
2890 /* Wake up the network and scheduler thread */
2891 if (netthreadid != AST_PTHREADT_NULL)
2892 pthread_kill(netthreadid, SIGURG);
2893 signal_condition(&sched_lock, &sched_cond);
2899 static int iax2_digit_begin(struct ast_channel *c, char digit)
2901 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2904 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2906 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2909 static int iax2_sendtext(struct ast_channel *c, const char *text)
2912 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2913 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2916 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2918 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2921 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2923 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2926 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2928 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2929 ast_mutex_lock(&iaxsl[callno]);
2931 iaxs[callno]->owner = newchan;
2933 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2934 ast_mutex_unlock(&iaxsl[callno]);
2939 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2940 * so do not call this with a pvt lock held.
2942 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2944 struct ast_variable *var;
2945 struct ast_variable *tmp;
2946 struct iax2_peer *peer=NULL;
2947 time_t regseconds = 0, nowtime;
2951 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2954 sprintf(porta, "%d", ntohs(sin->sin_port));
2955 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2957 /* We'll need the peer name in order to build the structure! */
2958 for (tmp = var; tmp; tmp = tmp->next) {
2959 if (!strcasecmp(tmp->name, "name"))
2960 peername = tmp->value;
2967 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2970 ast_variables_destroy(var);
2974 for (tmp = var; tmp; tmp = tmp->next) {
2975 /* Make sure it's not a user only... */
2976 if (!strcasecmp(tmp->name, "type")) {
2977 if (strcasecmp(tmp->value, "friend") &&
2978 strcasecmp(tmp->value, "peer")) {
2979 /* Whoops, we weren't supposed to exist! */
2980 peer = peer_unref(peer);
2983 } else if (!strcasecmp(tmp->name, "regseconds")) {
2984 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2985 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2986 inet_aton(tmp->value, &(peer->addr.sin_addr));
2987 } else if (!strcasecmp(tmp->name, "port")) {
2988 peer->addr.sin_port = htons(atoi(tmp->value));
2989 } else if (!strcasecmp(tmp->name, "host")) {
2990 if (!strcasecmp(tmp->value, "dynamic"))
2995 ast_variables_destroy(var);
3000 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3001 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3002 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3003 if (peer->expire > -1) {
3004 if (!ast_sched_del(sched, peer->expire)) {
3009 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3010 if (peer->expire == -1)
3013 ao2_link(peers, peer);
3014 if (ast_test_flag(peer, IAX_DYNAMIC))
3015 reg_source_db(peer);
3017 ast_set_flag(peer, IAX_TEMPONLY);
3020 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3022 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3023 memset(&peer->addr, 0, sizeof(peer->addr));
3024 realtime_update_peer(peer->name, &peer->addr, 0);
3025 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3026 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3029 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3030 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3037 static struct iax2_user *realtime_user(const char *username)
3039 struct ast_variable *var;
3040 struct ast_variable *tmp;
3041 struct iax2_user *user=NULL;
3043 var = ast_load_realtime("iaxusers", "name", username, NULL);
3049 /* Make sure it's not a peer only... */
3050 if (!strcasecmp(tmp->name, "type")) {
3051 if (strcasecmp(tmp->value, "friend") &&
3052 strcasecmp(tmp->value, "user")) {
3059 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3061 ast_variables_destroy(var);
3066 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3067 ast_set_flag(user, IAX_RTCACHEFRIENDS);
3068 ao2_link(users, user);
3070 ast_set_flag(user, IAX_TEMPONLY);
3076 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3079 char regseconds[20];
3081 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3082 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3083 ast_update_realtime("iaxpeers", "name", peername,
3084 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
3085 "regseconds", regseconds, NULL);
3088 struct create_addr_info {
3101 char context[AST_MAX_CONTEXT];
3102 char peercontext[AST_MAX_CONTEXT];
3103 char mohinterpret[MAX_MUSICCLASS];
3104 char mohsuggest[MAX_MUSICCLASS];
3107 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
3109 struct iax2_peer *peer;
3112 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3113 cai->sockfd = defaultsockfd;
3115 sin->sin_family = AF_INET;
3117 if (!(peer = find_peer(peername, 1))) {
3119 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
3120 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3123 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3124 /* use global iax prefs for unknown peer/user */
3125 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
3131 /* if the peer has no address (current or default), return failure */
3132 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3135 /* if the peer is being monitored and is currently unreachable, return failure */
3136 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3139 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
3140 cai->maxtime = peer->maxms;
3141 cai->capability = peer->capability;
3142 cai->encmethods = peer->encmethods;
3143 cai->sockfd = peer->sockfd;
3144 cai->adsi = peer->adsi;
3145 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
3146 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3147 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3148 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3149 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3150 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3151 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3152 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3153 if (ast_strlen_zero(peer->dbsecret)) {
3154 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3159 family = ast_strdupa(peer->dbsecret);
3160 key = strchr(family, '/');
3163 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3164 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3169 if (peer->addr.sin_addr.s_addr) {
3170 sin->sin_addr = peer->addr.sin_addr;
3171 sin->sin_port = peer->addr.sin_port;
3173 sin->sin_addr = peer->defaddr.sin_addr;
3174 sin->sin_port = peer->defaddr.sin_port;
3185 static void __auto_congest(const void *nothing)
3187 int callno = PTR_TO_CALLNO(nothing);
3188 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3189 ast_mutex_lock(&iaxsl[callno]);
3191 iaxs[callno]->initid = -1;
3192 iax2_queue_frame(callno, &f);
3193 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3195 ast_mutex_unlock(&iaxsl[callno]);
3198 static int auto_congest(const void *data)
3200 #ifdef SCHED_MULTITHREADED
3201 if (schedule_action(__auto_congest, data))
3203 __auto_congest(data);
3207 static unsigned int iax2_datetime(const char *tz)
3209 struct timeval t = ast_tvnow();
3212 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
3213 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3214 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3215 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3216 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3217 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3218 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3222 struct parsed_dial_string {
3234 * \brief Parses an IAX dial string into its component parts.
3235 * \param data the string to be parsed
3236 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3239 * This function parses the string and fills the structure
3240 * with pointers to its component parts. The input string
3243 * \note This function supports both plaintext passwords and RSA
3244 * key names; if the password string is formatted as '[keyname]',
3245 * then the keyname will be placed into the key field, and the
3246 * password field will be set to NULL.
3248 * \note The dial string format is:
3249 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3251 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3253 if (ast_strlen_zero(data))
3256 pds->peer = strsep(&data, "/");
3257 pds->exten = strsep(&data, "/");
3258 pds->options = data;
3262 pds->exten = strsep(&data, "@");
3263 pds->context = data;
3266 if (strchr(pds->peer, '@')) {
3268 pds->username = strsep(&data, "@");
3272 if (pds->username) {
3273 data = pds->username;
3274 pds->username = strsep(&data, ":");
3275 pds->password = data;
3279 pds->peer = strsep(&data, ":");
3282 /* check for a key name wrapped in [] in the secret position, if found,
3283 move it to the key field instead
3285 if (pds->password && (pds->password[0] == '[')) {
3286 pds->key = ast_strip_quoted(pds->password, "[", "]");
3287 pds->password = NULL;
3291 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3293 struct sockaddr_in sin;
3294 char *l=NULL, *n=NULL, *tmpstr;
3295 struct iax_ie_data ied;
3296 char *defaultrdest = "s";
3297 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3298 struct parsed_dial_string pds;
3299 struct create_addr_info cai;
3300 struct ast_var_t *var;
3301 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3302 const char* osp_token_ptr;
3303 unsigned int osp_token_length;
3304 unsigned char osp_block_index;
3305 unsigned int osp_block_length;
3306 unsigned char osp_buffer[256];
3308 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3309 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3313 memset(&cai, 0, sizeof(cai));
3314 cai.encmethods = iax2_encryption;
3316 memset(&pds, 0, sizeof(pds));
3317 tmpstr = ast_strdupa(dest);
3318 parse_dial_string(tmpstr, &pds);
3321 pds.exten = defaultrdest;
3323 if (create_addr(pds.peer, &sin, &cai)) {
3324 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3328 if (!pds.username && !ast_strlen_zero(cai.username))
3329 pds.username = cai.username;
3330 if (!pds.password && !ast_strlen_zero(cai.secret))
3331 pds.password = cai.secret;
3332 if (!pds.key && !ast_strlen_zero(cai.outkey))
3333 pds.key = cai.outkey;
3334 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3335 pds.context = cai.peercontext;
3337 /* Keep track of the context for outgoing calls too */
3338 ast_copy_string(c->context, cai.context, sizeof(c->context));
3341 sin.sin_port = htons(atoi(pds.port));
3344 n = c->cid.cid_name;
3346 /* Now build request */
3347 memset(&ied, 0, sizeof(ied));
3349 /* On new call, first IE MUST be IAX version of caller */
3350 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3351 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3352 if (pds.options && strchr(pds.options, 'a')) {
3353 /* Request auto answer */
3354 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3357 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3360 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3361 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3364 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3366 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3369 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3370 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3373 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3374 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3375 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3377 if (!ast_strlen_zero(c->language))
3378 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3379 if (!ast_strlen_zero(c->cid.cid_dnid))
3380 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3381 if (!ast_strlen_zero(c->cid.cid_rdnis))
3382 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3385 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3388 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3391 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3393 ast_mutex_lock(&iaxsl[callno]);
3395 if (!ast_strlen_zero(c->context))
3396 ast_string_field_set(iaxs[callno], context, c->context);
3399 ast_string_field_set(iaxs[callno], username, pds.username);
3401 iaxs[callno]->encmethods = cai.encmethods;
3403 iaxs[callno]->adsi = cai.adsi;
3405 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3406 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3409 ast_string_field_set(iaxs[callno], outkey, pds.key);
3411 ast_string_field_set(iaxs[callno], secret, pds.password);
3413 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3414 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3415 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3416 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3418 if (iaxs[callno]->maxtime) {
3419 /* Initialize pingtime and auto-congest time */
3420 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3421 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3422 } else if (autokill) {
3423 iaxs[callno]->pingtime = autokill / 2;
3424 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3427 /* Check if there is an OSP token set by IAXCHANINFO function */
3428 osp_token_ptr = iaxs[callno]->osptoken;
3429 if (!ast_strlen_zero(osp_token_ptr)) {
3430 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3431 osp_block_index = 0;
3432 while (osp_token_length > 0) {
3433 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3434 osp_buffer[0] = osp_block_index;
3435 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3436 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3438 osp_token_ptr += osp_block_length;
3439 osp_token_length -= osp_block_length;
3442 ast_log(LOG_WARNING, "OSP token is too long\n");
3443 } else if (iaxdebug)
3444 ast_debug(1, "OSP token is undefined\n");
3446 /* send the command using the appropriate socket for this peer */
3447 iaxs[callno]->sockfd = cai.sockfd;
3449 /* Add remote vars */
3450 if (variablestore) {
3451 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
3452 AST_LIST_LOCK(variablelist);
3453 AST_LIST_TRAVERSE(variablelist, var, entries) {
3456 /* Automatically divide the value up into sized chunks */
3457 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
3458 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
3459 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3462 AST_LIST_UNLOCK(variablelist);
3465 /* Transmit the string in a "NEW" request */
3466 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3468 ast_mutex_unlock(&iaxsl[callno]);
3469 ast_setstate(c, AST_STATE_RINGING);
3474 static int iax2_hangup(struct ast_channel *c)
3476 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3478 struct iax_ie_data ied;
3479 memset(&ied, 0, sizeof(ied));
3480 ast_mutex_lock(&iaxsl[callno]);
3481 if (callno && iaxs[callno]) {
3482 ast_debug(1, "We're hanging up %s now...\n", c->name);
3483 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3484 /* Send the hangup unless we have had a transmission error or are already gone */
3485 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3486 if (!iaxs[callno]->error && !alreadygone) {
3487 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3488 if (!iaxs[callno]) {
3489 ast_mutex_unlock(&iaxsl[callno]);
3493 /* Explicitly predestroy it */
3494 iax2_predestroy(callno);
3495 /* If we were already gone to begin with, destroy us now */
3496 if (alreadygone && iaxs[callno]) {
3497 ast_debug(1, "Really destroying %s now...\n", c->name);
3498 iax2_destroy(callno);
3501 ast_mutex_unlock(&iaxsl[callno]);
3502 ast_verb(3, "Hungup '%s'\n", c->name);
3506 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3508 struct ast_option_header *h;
3512 case AST_OPTION_TXGAIN:
3513 case AST_OPTION_RXGAIN:
3514 /* these two cannot be sent, because they require a result */
3518 if (!(h = ast_malloc(datalen + sizeof(*h))))
3521 h->flag = AST_OPTION_FLAG_REQUEST;
3522 h->option = htons(option);
3523 memcpy(h->data, data, datalen);
3524 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3525 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3526 datalen + sizeof(*h), -1);
3532 static struct ast_frame *iax2_read(struct ast_channel *c)
3534 ast_log(LOG_NOTICE, "I should never be called!\n");
3535 return &ast_null_frame;
3538 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3541 struct iax_ie_data ied0;
3542 struct iax_ie_data ied1;
3543 unsigned int transferid = (unsigned int)ast_random();
3544 memset(&ied0, 0, sizeof(ied0));
3545 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3546 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3547 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3549 memset(&ied1, 0, sizeof(ied1));
3550 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3551 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3552 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3554 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3557 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3560 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3561 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3565 static void lock_both(unsigned short callno0, unsigned short callno1)
3567 ast_mutex_lock(&iaxsl[callno0]);
3568 while (ast_mutex_trylock(&iaxsl[callno1])) {
3569 ast_mutex_unlock(&iaxsl[callno0]);
3571 ast_mutex_lock(&iaxsl[callno0]);
3575 static void unlock_both(unsigned short callno0, unsigned short callno1)
3577 ast_mutex_unlock(&iaxsl[callno1]);
3578 ast_mutex_unlock(&iaxsl[callno0]);
3581 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)
3583 struct ast_channel *cs[3];
3584 struct ast_channel *who, *other;
3587 int transferstarted=0;
3588 struct ast_frame *f;
3589 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3590 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3591 struct timeval waittimer = {0, 0}, tv;
3593 lock_both(callno0, callno1);
3594 if (!iaxs[callno0] || !iaxs[callno1]) {
3595 unlock_both(callno0, callno1);
3596 return AST_BRIDGE_FAILED;
3598 /* Put them in native bridge mode */
3599 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3600 iaxs[callno0]->bridgecallno = callno1;
3601 iaxs[callno1]->bridgecallno = callno0;
3603 unlock_both(callno0, callno1);
3605 /* If not, try to bridge until we can execute a transfer, if we can */
3608 for (/* ever */;;) {
3609 /* Check in case we got masqueraded into */
3610 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3611 ast_verb(3, "Can't masquerade, we're different...\n");
3612 /* Remove from native mode */
3613 if (c0->tech == &iax2_tech) {
3614 ast_mutex_lock(&iaxsl[callno0]);
3615 iaxs[callno0]->bridgecallno = 0;
3616 ast_mutex_unlock(&iaxsl[callno0]);
3618 if (c1->tech == &iax2_tech) {
3619 ast_mutex_lock(&iaxsl[callno1]);
3620 iaxs[callno1]->bridgecallno = 0;
3621 ast_mutex_unlock(&iaxsl[callno1]);
3623 return AST_BRIDGE_FAILED_NOWARN;
3625 if (c0->nativeformats != c1->nativeformats) {
3628 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3629 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3630 ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3631 /* Remove from native mode */
3632 lock_both(callno0, callno1);
3634 iaxs[callno0]->bridgecallno = 0;
3636 iaxs[callno1]->bridgecallno = 0;
3637 unlock_both(callno0, callno1);
3638 return AST_BRIDGE_FAILED_NOWARN;
3640 /* check if transfered and if we really want native bridging */
3641 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3642 /* Try the transfer */
3643 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3644 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3645 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3646 transferstarted = 1;
3648 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3649 /* Call has been transferred. We're no longer involved */
3651 if (ast_tvzero(waittimer)) {
3653 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3654 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3655 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3658 res = AST_BRIDGE_COMPLETE;
3663 who = ast_waitfor_n(cs, 2, &to);
3664 if (timeoutms > -1) {
3665 timeoutms -= (1000 - to);
3671 res = AST_BRIDGE_RETRY;
3674 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {