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
30 * \todo Implement musicclass settings for IAX2 devices
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/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"
90 #include "asterisk/timing.h"
93 #include "iax2-parser.h"
94 #include "iax2-provision.h"
95 #include "jitterbuf.h"
97 /* Define SCHED_MULTITHREADED to run the scheduler in a special
98 multithreaded mode. */
99 #define SCHED_MULTITHREADED
101 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
102 thread is actually doing. */
103 #define DEBUG_SCHED_MULTITHREAD
107 static int nochecksums = 0;
111 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
112 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
114 #define DEFAULT_THREAD_COUNT 10
115 #define DEFAULT_MAX_THREAD_COUNT 100
116 #define DEFAULT_RETRY_TIME 1000
117 #define MEMORY_SIZE 100
118 #define DEFAULT_DROP 3
120 #define DEBUG_SUPPORT
122 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
124 /* Sample over last 100 units to determine historic jitter */
127 static struct ast_codec_pref prefs;
129 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
132 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
133 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
134 #define MAX_TRUNK_MTU 1240
136 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
137 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
140 static char context[80] = "default";
141 static char default_parkinglot[AST_MAX_CONTEXT];
143 static char language[MAX_LANGUAGE] = "";
144 static char regcontext[AST_MAX_CONTEXT] = "";
146 static int maxauthreq = 3;
147 static int max_retries = 4;
148 static int ping_time = 21;
149 static int lagrq_time = 10;
150 static int maxjitterbuffer=1000;
151 static int resyncthreshold=1000;
152 static int maxjitterinterps=10;
153 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
155 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
157 static int trunkfreq = 20;
158 static int trunkmaxsize = MAX_TRUNKDATA;
160 static int authdebug = 1;
161 static int autokill = 0;
162 static int iaxcompat = 0;
164 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
166 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
168 static unsigned int tos = 0;
170 static unsigned int cos = 0;
172 static int min_reg_expire;
173 static int max_reg_expire;
175 static int srvlookup = 0;
177 static int timingfd = -1; /* Timing file descriptor */
179 static struct ast_netsock_list *netsock;
180 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
181 static int defaultsockfd = -1;
183 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
186 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
188 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
189 ~AST_FORMAT_SLINEAR & \
194 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
196 ~AST_FORMAT_G726_AAL2 & \
199 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
203 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
204 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
205 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
207 static struct io_context *io;
208 static struct sched_context *sched;
210 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
212 static int iaxdebug = 0;
214 static int iaxtrunkdebug = 0;
216 static int test_losspct = 0;
218 static int test_late = 0;
219 static int test_resync = 0;
220 static int test_jit = 0;
221 static int test_jitpct = 0;
222 #endif /* IAXTESTS */
224 static char accountcode[AST_MAX_ACCOUNT_CODE];
225 static char mohinterpret[MAX_MUSICCLASS];
226 static char mohsuggest[MAX_MUSICCLASS];
227 static int amaflags = 0;
229 static int delayreject = 0;
230 static int iax2_encryption = 0;
232 static struct ast_flags globalflags = { 0 };
234 static pthread_t netthreadid = AST_PTHREADT_NULL;
235 static pthread_t schedthreadid = AST_PTHREADT_NULL;
236 AST_MUTEX_DEFINE_STATIC(sched_lock);
237 static ast_cond_t sched_cond;
240 IAX_STATE_STARTED = (1 << 0),
241 IAX_STATE_AUTHENTICATED = (1 << 1),
242 IAX_STATE_TBD = (1 << 2),
243 IAX_STATE_UNCHANGED = (1 << 3),
246 struct iax2_context {
247 char context[AST_MAX_CONTEXT];
248 struct iax2_context *next;
252 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
253 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
254 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
255 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
256 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
257 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
258 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
259 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
260 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
261 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
262 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
263 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
264 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
265 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
266 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
267 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
268 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
269 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
270 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
271 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
272 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
273 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
274 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
275 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
276 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
277 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
278 response, so that we've achieved a three-way handshake with
279 them before sending voice or anything else*/
282 static int global_rtautoclear = 120;
284 static int reload_config(void);
287 AST_DECLARE_STRING_FIELDS(
288 AST_STRING_FIELD(name);
289 AST_STRING_FIELD(secret);
290 AST_STRING_FIELD(dbsecret);
291 AST_STRING_FIELD(accountcode);
292 AST_STRING_FIELD(mohinterpret);
293 AST_STRING_FIELD(mohsuggest);
294 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
295 AST_STRING_FIELD(language);
296 AST_STRING_FIELD(cid_num);
297 AST_STRING_FIELD(cid_name);
298 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
307 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
308 int curauthreq; /*!< Current number of outstanding AUTHREQs */
309 struct ast_codec_pref prefs;
311 struct iax2_context *contexts;
312 struct ast_variable *vars;
316 AST_DECLARE_STRING_FIELDS(
317 AST_STRING_FIELD(name);
318 AST_STRING_FIELD(username);
319 AST_STRING_FIELD(secret);
320 AST_STRING_FIELD(dbsecret);
321 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
323 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
324 AST_STRING_FIELD(context); /*!< For transfers only */
325 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
326 AST_STRING_FIELD(mailbox); /*!< Mailbox */
327 AST_STRING_FIELD(mohinterpret);
328 AST_STRING_FIELD(mohsuggest);
329 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
330 /* Suggested caller id if registering */
331 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
332 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
333 AST_STRING_FIELD(zonetag); /*!< Time Zone */
334 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
336 struct ast_codec_pref prefs;
337 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
338 struct sockaddr_in addr;
340 int sockfd; /*!< Socket to use for transmission */
345 /* Dynamic Registration fields */
346 struct sockaddr_in defaddr; /*!< Default address if there is one */
347 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
348 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
350 int expire; /*!< Schedule entry for expiry */
351 int expiry; /*!< How soon to expire */
352 int capability; /*!< Capability */
355 int callno; /*!< Call number of POKE request */
356 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
357 int lastms; /*!< How long last response took (in ms), or -1 for no response */
358 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
360 int pokefreqok; /*!< How often to check if the host is up */
361 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
362 int historicms; /*!< How long recent average responses took */
363 int smoothing; /*!< Sample over how many units to determine historic ms */
365 struct ast_event_sub *mwi_event_sub;
370 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
372 struct iax2_trunk_peer {
375 struct sockaddr_in addr;
376 struct timeval txtrunktime; /*!< Transmit trunktime */
377 struct timeval rxtrunktime; /*!< Receive trunktime */
378 struct timeval lasttxtime; /*!< Last transmitted trunktime */
379 struct timeval trunkact; /*!< Last trunk activity */
380 unsigned int lastsent; /*!< Last sent time */
381 /* Trunk data and length */
382 unsigned char *trunkdata;
383 unsigned int trunkdatalen;
384 unsigned int trunkdataalloc;
388 AST_LIST_ENTRY(iax2_trunk_peer) list;
391 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
393 struct iax_firmware {
394 AST_LIST_ENTRY(iax_firmware) list;
398 struct ast_iax2_firmware_header *fwh;
403 REG_STATE_UNREGISTERED = 0,
406 REG_STATE_REGISTERED,
412 enum iax_transfer_state {
422 struct iax2_registry {
423 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
425 char secret[80]; /*!< Password or key name in []'s */
426 int expire; /*!< Sched ID of expiration */
427 int refresh; /*!< How often to refresh */
428 enum iax_reg_state regstate;
429 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
430 int callno; /*!< Associated call number if applicable */
431 struct sockaddr_in us; /*!< Who the server thinks we are */
432 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
433 AST_LIST_ENTRY(iax2_registry) entry;
436 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
438 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
439 #define MIN_RETRY_TIME 100
440 #define MAX_RETRY_TIME 10000
442 #define MAX_JITTER_BUFFER 50
443 #define MIN_JITTER_BUFFER 10
445 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
447 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
449 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
450 #define TS_GAP_FOR_JB_RESYNC 5000
452 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
453 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
454 static int iaxdynamicthreadcount = 0;
455 static int iaxactivethreadcount = 0;
469 struct chan_iax2_pvt {
470 /*! Socket to send/receive on for this call */
472 /*! Last received voice format */
474 /*! Last received video format */
476 /*! Last sent voice format */
478 /*! Last sent video format */
480 /*! What we are capable of sending */
482 /*! Last received timestamp */
484 /*! Last sent timestamp - never send the same timestamp twice in a single call */
485 unsigned int lastsent;
486 /*! Timestamp of the last video frame sent */
487 unsigned int lastvsent;
488 /*! Next outgoing timestamp if everything is good */
489 unsigned int nextpred;
490 /*! True if the last voice we transmitted was not silence/CNG */
491 unsigned int notsilenttx:1;
493 unsigned int pingtime;
494 /*! Max time for initial response */
497 struct sockaddr_in addr;
498 /*! Actual used codec preferences */
499 struct ast_codec_pref prefs;
500 /*! Requested codec preferences */
501 struct ast_codec_pref rprefs;
502 /*! Our call number */
503 unsigned short callno;
505 unsigned short peercallno;
506 /*! Negotiated format, this is only used to remember what format was
507 chosen for an unauthenticated call so that the channel can get
508 created later using the right format */
510 /*! Peer selected format */
512 /*! Peer capability */
514 /*! timeval that we base our transmission on */
515 struct timeval offset;
516 /*! timeval that we base our delivery on */
517 struct timeval rxcore;
518 /*! The jitterbuffer */
520 /*! active jb read scheduler id */
524 /*! Error, as discovered by the manager */
526 /*! Owner if we have one */
527 struct ast_channel *owner;
528 /*! What's our state? */
529 struct ast_flags state;
530 /*! Expiry (optional) */
532 /*! Next outgoing sequence number */
533 unsigned char oseqno;
534 /*! Next sequence number they have not yet acknowledged */
535 unsigned char rseqno;
536 /*! Next incoming sequence number */
537 unsigned char iseqno;
538 /*! Last incoming sequence number we have acknowledged */
539 unsigned char aseqno;
541 AST_DECLARE_STRING_FIELDS(
543 AST_STRING_FIELD(peer);
544 /*! Default Context */
545 AST_STRING_FIELD(context);
546 /*! Caller ID if available */
547 AST_STRING_FIELD(cid_num);
548 AST_STRING_FIELD(cid_name);
549 /*! Hidden Caller ID (i.e. ANI) if appropriate */
550 AST_STRING_FIELD(ani);
552 AST_STRING_FIELD(dnid);
554 AST_STRING_FIELD(rdnis);
555 /*! Requested Extension */
556 AST_STRING_FIELD(exten);
557 /*! Expected Username */
558 AST_STRING_FIELD(username);
559 /*! Expected Secret */
560 AST_STRING_FIELD(secret);
562 AST_STRING_FIELD(challenge);
563 /*! Public keys permitted keys for incoming authentication */
564 AST_STRING_FIELD(inkeys);
565 /*! Private key for outgoing authentication */
566 AST_STRING_FIELD(outkey);
567 /*! Preferred language */
568 AST_STRING_FIELD(language);
569 /*! Hostname/peername for naming purposes */
570 AST_STRING_FIELD(host);
572 AST_STRING_FIELD(dproot);
573 AST_STRING_FIELD(accountcode);
574 AST_STRING_FIELD(mohinterpret);
575 AST_STRING_FIELD(mohsuggest);
576 /*! received OSP token */
577 AST_STRING_FIELD(osptoken);
578 /*! Default parkinglot */
579 AST_STRING_FIELD(parkinglot);
582 /*! permitted authentication methods */
584 /*! permitted encryption methods */
586 /*! Encryption AES-128 Key */
587 ast_aes_encrypt_key ecx;
588 /*! Decryption AES-128 Key */
589 ast_aes_decrypt_key dcx;
590 /*! 32 bytes of semi-random data */
591 unsigned char semirand[32];
592 /*! Associated registry */
593 struct iax2_registry *reg;
594 /*! Associated peer for poking */
595 struct iax2_peer *peerpoke;
600 /*! Transferring status */
601 enum iax_transfer_state transferring;
602 /*! Transfer identifier */
604 /*! Who we are IAX transferring to */
605 struct sockaddr_in transfer;
606 /*! What's the new call number for the transfer */
607 unsigned short transfercallno;
608 /*! Transfer encrypt AES-128 Key */
609 ast_aes_encrypt_key tdcx;
611 /*! If transfer has been attempted */
612 unsigned int triedtransfer:1;
613 /*! Whether media is released */
614 unsigned int mediareleased:1;
615 /*! If media released, the peer to send media to */
616 struct sockaddr_in media;
618 /*! Status of knowledge of peer ADSI capability */
621 /*! Who we are bridged to */
622 unsigned short bridgecallno;
624 int pingid; /*!< Transmit PING request */
625 int lagid; /*!< Retransmit lag request */
626 int autoid; /*!< Auto hangup for Dialplan requestor */
627 int authid; /*!< Authentication rejection ID */
628 int authfail; /*!< Reason to report failure */
629 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
634 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
635 struct ast_variable *vars;
636 /*! last received remote rr */
637 struct iax_rr remote_rr;
638 /*! Current base time: (just for stats) */
640 /*! Dropped frame count: (just for stats) */
642 /*! received frame count: (just for stats) */
647 * \brief a list of frames that may need to be retransmitted
649 * \note The contents of this list do not need to be explicitly destroyed
650 * on module unload. This is because all active calls are destroyed, and
651 * all frames in this queue will get destroyed as a part of that process.
653 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
656 * This module will get much higher performance when doing a lot of
657 * user and peer lookups if the number of buckets is increased from 1.
658 * However, to maintain old behavior for Asterisk 1.4, these are set to
659 * 1 by default. When using multiple buckets, search order through these
660 * containers is considered random, so you will not be able to depend on
661 * the order the entires are specified in iax.conf for matching order. */
663 #define MAX_PEER_BUCKETS 17
665 #define MAX_PEER_BUCKETS 563
667 static struct ao2_container *peers;
669 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
670 static struct ao2_container *users;
672 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
675 /*! Extension exists */
676 CACHE_FLAG_EXISTS = (1 << 0),
677 /*! Extension is nonexistent */
678 CACHE_FLAG_NONEXISTENT = (1 << 1),
679 /*! Extension can exist */
680 CACHE_FLAG_CANEXIST = (1 << 2),
681 /*! Waiting to hear back response */
682 CACHE_FLAG_PENDING = (1 << 3),
684 CACHE_FLAG_TIMEOUT = (1 << 4),
685 /*! Request transmitted */
686 CACHE_FLAG_TRANSMITTED = (1 << 5),
688 CACHE_FLAG_UNKNOWN = (1 << 6),
690 CACHE_FLAG_MATCHMORE = (1 << 7),
693 struct iax2_dpcache {
694 char peercontext[AST_MAX_CONTEXT];
695 char exten[AST_MAX_EXTENSION];
697 struct timeval expiry;
699 unsigned short callno;
701 AST_LIST_ENTRY(iax2_dpcache) cache_list;
702 AST_LIST_ENTRY(iax2_dpcache) peer_list;
705 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
707 static void reg_source_db(struct iax2_peer *p);
708 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
710 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
711 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state);
712 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
714 enum iax2_thread_iostate {
717 IAX_IOSTATE_PROCESSING,
718 IAX_IOSTATE_SCHEDREADY,
721 enum iax2_thread_type {
722 IAX_THREAD_TYPE_POOL,
723 IAX_THREAD_TYPE_DYNAMIC,
726 struct iax2_pkt_buf {
727 AST_LIST_ENTRY(iax2_pkt_buf) entry;
729 unsigned char buf[1];
733 AST_LIST_ENTRY(iax2_thread) list;
734 enum iax2_thread_type type;
735 enum iax2_thread_iostate iostate;
736 #ifdef SCHED_MULTITHREADED
737 void (*schedfunc)(const void *);
738 const void *scheddata;
740 #ifdef DEBUG_SCHED_MULTITHREAD
746 struct sockaddr_in iosin;
747 unsigned char readbuf[4096];
755 unsigned int ready_for_signal:1;
756 /*! if this thread is processing a full frame,
757 some information about that frame will be stored
758 here, so we can avoid dispatching any more full
759 frames for that callno to other threads */
761 unsigned short callno;
762 struct sockaddr_in sin;
766 /*! Queued up full frames for processing. If more full frames arrive for
767 * a call which this thread is already processing a full frame for, they
768 * are queued up here. */
769 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
773 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
774 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
775 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
777 static void *iax2_process_thread(void *data);
779 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
781 ast_mutex_lock(lock);
782 ast_cond_signal(cond);
783 ast_mutex_unlock(lock);
786 static void iax_debug_output(const char *data)
789 ast_verbose("%s", data);
792 static void iax_error_output(const char *data)
794 ast_log(LOG_WARNING, "%s", data);
797 static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
803 vsnprintf(buf, sizeof(buf), fmt, args);
806 ast_log(LOG_ERROR, "%s", buf);
809 static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
815 vsnprintf(buf, sizeof(buf), fmt, args);
818 ast_log(LOG_WARNING, "%s", buf);
821 static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
827 vsnprintf(buf, sizeof(buf), fmt, args);
830 ast_verbose("%s", buf);
834 * \brief an array of iax2 pvt structures
836 * The container for active chan_iax2_pvt structures is implemented as an
837 * array for extremely quick direct access to the correct pvt structure
838 * based on the local call number. The local call number is used as the
839 * index into the array where the associated pvt structure is stored.
841 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
844 * \brief Another container of iax2_pvt structures
846 * Active IAX2 pvt structs are also stored in this container, if they are a part
847 * of an active call where we know the remote side's call number. The reason
848 * for this is that incoming media frames do not contain our call number. So,
849 * instead of having to iterate the entire iaxs array, we use this container to
850 * look up calls where the remote side is using a given call number.
852 static struct ao2_container *iax_peercallno_pvts;
855 * \brief chan_iax2_pvt structure locks
857 * These locks are used when accessing a pvt structure in the iaxs array.
858 * The index used here is the same as used in the iaxs array. It is the
859 * local call number for the associated pvt struct.
861 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
864 * \brief The last time a call number was used
866 * It is important to know the last time that a call number was used locally so
867 * that it is not used again too soon. The reason for this is the same as the
868 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
870 * For example, say that a call is up. Then, the remote side sends a HANGUP,
871 * which we respond to with an ACK. However, there is no way to know whether
872 * the ACK made it there successfully. If it were to get lost, the remote
873 * side may retransmit the HANGUP. If in the meantime, this call number has
874 * been reused locally, given the right set of circumstances, this retransmitted
875 * HANGUP could potentially improperly hang up the new session. So, to avoid
876 * this potential issue, we must wait a specified timeout period before reusing
877 * a local call number.
879 * The specified time that we must wait before reusing a local call number is
880 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
882 static struct timeval lastused[ARRAY_LEN(iaxs)];
884 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
885 but keeps the division between trunked and non-trunked better. */
886 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
888 static int maxtrunkcall = TRUNK_CALL_START;
889 static int maxnontrunkcall = 1;
891 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);
892 static int expire_registry(const void *data);
893 static int iax2_answer(struct ast_channel *c);
894 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
895 static int iax2_devicestate(void *data);
896 static int iax2_digit_begin(struct ast_channel *c, char digit);
897 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
898 static int iax2_do_register(struct iax2_registry *reg);
899 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
900 static int iax2_hangup(struct ast_channel *c);
901 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
902 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
903 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
904 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final, int media);
905 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
906 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
907 static int iax2_sendtext(struct ast_channel *c, const char *text);
908 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
909 static int iax2_transfer(struct ast_channel *c, const char *dest);
910 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
911 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
912 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
913 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
914 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
915 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
916 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
917 static int send_command_media(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
918 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
919 static struct ast_frame *iax2_read(struct ast_channel *c);
920 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
921 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
922 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
923 static void prune_peers(void);
924 static void *iax2_dup_variable_datastore(void *);
925 static void iax2_free_variable_datastore(void *);
927 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
928 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
930 static const struct ast_channel_tech iax2_tech = {
932 .description = tdesc,
933 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
934 .properties = AST_CHAN_TP_WANTSJITTER,
935 .requester = iax2_request,
936 .devicestate = iax2_devicestate,
937 .send_digit_begin = iax2_digit_begin,
938 .send_digit_end = iax2_digit_end,
939 .send_text = iax2_sendtext,
940 .send_image = iax2_sendimage,
941 .send_html = iax2_sendhtml,
943 .hangup = iax2_hangup,
944 .answer = iax2_answer,
947 .write_video = iax2_write,
948 .indicate = iax2_indicate,
949 .setoption = iax2_setoption,
950 .bridge = iax2_bridge,
951 .transfer = iax2_transfer,
953 .func_channel_read = acf_channel_read,
954 .func_channel_write = acf_channel_write,
957 static void mwi_event_cb(const struct ast_event *event, void *userdata)
959 /* The MWI subscriptions exist just so the core knows we care about those
960 * mailboxes. However, we just grab the events out of the cache when it
961 * is time to send MWI, since it is only sent with a REGACK. */
964 /*! \brief Send manager event at call setup to link between Asterisk channel name
965 and IAX2 call identifiers */
966 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
968 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
969 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
970 pvt->owner ? pvt->owner->name : "",
971 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
975 static struct ast_datastore_info iax2_variable_datastore_info = {
976 .type = "IAX2_VARIABLE",
977 .duplicate = iax2_dup_variable_datastore,
978 .destroy = iax2_free_variable_datastore,
981 static void *iax2_dup_variable_datastore(void *old)
983 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
984 struct ast_var_t *oldvar, *newvar;
986 newlist = ast_calloc(sizeof(*newlist), 1);
988 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
992 AST_LIST_HEAD_INIT(newlist);
993 AST_LIST_LOCK(oldlist);
994 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
995 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
997 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
999 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1001 AST_LIST_UNLOCK(oldlist);
1005 static void iax2_free_variable_datastore(void *old)
1007 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1008 struct ast_var_t *oldvar;
1010 AST_LIST_LOCK(oldlist);
1011 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1014 AST_LIST_UNLOCK(oldlist);
1015 AST_LIST_HEAD_DESTROY(oldlist);
1020 /* WARNING: insert_idle_thread should only ever be called within the
1021 * context of an iax2_process_thread() thread.
1023 static void insert_idle_thread(struct iax2_thread *thread)
1025 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1026 AST_LIST_LOCK(&dynamic_list);
1027 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1028 AST_LIST_UNLOCK(&dynamic_list);
1030 AST_LIST_LOCK(&idle_list);
1031 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1032 AST_LIST_UNLOCK(&idle_list);
1038 static struct iax2_thread *find_idle_thread(void)
1040 struct iax2_thread *thread = NULL;
1042 /* Pop the head of the idle list off */
1043 AST_LIST_LOCK(&idle_list);
1044 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1045 AST_LIST_UNLOCK(&idle_list);
1047 /* If we popped a thread off the idle list, just return it */
1049 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1053 /* Pop the head of the dynamic list off */
1054 AST_LIST_LOCK(&dynamic_list);
1055 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1056 AST_LIST_UNLOCK(&dynamic_list);
1058 /* If we popped a thread off the dynamic list, just return it */
1060 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1064 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1065 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1068 /* Set default values */
1069 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1070 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1072 /* Initialize lock and condition */
1073 ast_mutex_init(&thread->lock);
1074 ast_cond_init(&thread->cond, NULL);
1076 /* Create thread and send it on it's way */
1077 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1078 ast_cond_destroy(&thread->cond);
1079 ast_mutex_destroy(&thread->lock);
1084 /* this thread is not processing a full frame (since it is idle),
1085 so ensure that the field for the full frame call number is empty */
1086 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1088 /* Wait for the thread to be ready before returning it to the caller */
1089 while (!thread->ready_for_signal)
1095 #ifdef SCHED_MULTITHREADED
1096 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1098 struct iax2_thread *thread = NULL;
1099 static time_t lasterror;
1102 thread = find_idle_thread();
1104 if (thread != NULL) {
1105 thread->schedfunc = func;
1106 thread->scheddata = data;
1107 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1108 #ifdef DEBUG_SCHED_MULTITHREAD
1109 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1111 signal_condition(&thread->lock, &thread->cond);
1116 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1121 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1124 static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1126 AST_SCHED_REPLACE(id, con, when, callback, data);
1127 signal_condition(&sched_lock, &sched_cond);
1132 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1136 res = ast_sched_add(con, when, callback, data);
1137 signal_condition(&sched_lock, &sched_cond);
1142 static int send_ping(const void *data);
1144 static void __send_ping(const void *data)
1146 int callno = (long) data;
1148 ast_mutex_lock(&iaxsl[callno]);
1151 if (iaxs[callno]->peercallno) {
1152 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1153 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1155 /* I am the schedule, so I'm allowed to do this */
1156 iaxs[callno]->pingid = -1;
1158 } else if (option_debug > 0) {
1159 ast_log(LOG_DEBUG, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno);
1162 ast_mutex_unlock(&iaxsl[callno]);
1165 static int send_ping(const void *data)
1167 #ifdef SCHED_MULTITHREADED
1168 if (schedule_action(__send_ping, data))
1175 static int get_encrypt_methods(const char *s)
1178 if (!strcasecmp(s, "aes128"))
1179 e = IAX_ENCRYPT_AES128;
1180 else if (ast_true(s))
1181 e = IAX_ENCRYPT_AES128;
1187 static int send_lagrq(const void *data);
1189 static void __send_lagrq(const void *data)
1191 int callno = (long) data;
1193 ast_mutex_lock(&iaxsl[callno]);
1196 if (iaxs[callno]->peercallno) {
1197 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1198 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1200 /* I am the schedule, so I'm allowed to do this */
1201 iaxs[callno]->lagid = -1;
1203 } else if (option_debug > 0) {
1204 ast_log(LOG_DEBUG, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno);
1207 ast_mutex_unlock(&iaxsl[callno]);
1210 static int send_lagrq(const void *data)
1212 #ifdef SCHED_MULTITHREADED
1213 if (schedule_action(__send_lagrq, data))
1220 static unsigned char compress_subclass(int subclass)
1224 /* If it's 128 or smaller, just return it */
1225 if (subclass < IAX_FLAG_SC_LOG)
1227 /* Otherwise find its power */
1228 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1229 if (subclass & (1 << x)) {
1231 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1237 return power | IAX_FLAG_SC_LOG;
1240 static int uncompress_subclass(unsigned char csub)
1242 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1243 if (csub & IAX_FLAG_SC_LOG) {
1244 /* special case for 'compressed' -1 */
1248 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1255 * \note The only member of the peer passed here guaranteed to be set is the name field
1257 static int peer_hash_cb(const void *obj, const int flags)
1259 const struct iax2_peer *peer = obj;
1261 return ast_str_hash(peer->name);
1265 * \note The only member of the peer passed here guaranteed to be set is the name field
1267 static int peer_cmp_cb(void *obj, void *arg, int flags)
1269 struct iax2_peer *peer = obj, *peer2 = arg;
1271 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1275 * \note The only member of the user passed here guaranteed to be set is the name field
1277 static int user_hash_cb(const void *obj, const int flags)
1279 const struct iax2_user *user = obj;
1281 return ast_str_hash(user->name);
1285 * \note The only member of the user passed here guaranteed to be set is the name field
1287 static int user_cmp_cb(void *obj, void *arg, int flags)
1289 struct iax2_user *user = obj, *user2 = arg;
1291 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1295 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1296 * so do not call it with a pvt lock held.
1298 static struct iax2_peer *find_peer(const char *name, int realtime)
1300 struct iax2_peer *peer = NULL;
1301 struct iax2_peer tmp_peer = {
1305 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1307 /* Now go for realtime if applicable */
1308 if(!peer && realtime)
1309 peer = realtime_peer(name, NULL);
1314 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1320 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1326 static inline struct iax2_user *user_ref(struct iax2_user *user)
1332 static inline struct iax2_user *user_unref(struct iax2_user *user)
1338 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1340 struct iax2_peer *peer = NULL;
1342 struct ao2_iterator i;
1344 i = ao2_iterator_init(peers, 0);
1345 while ((peer = ao2_iterator_next(&i))) {
1346 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1347 (peer->addr.sin_port == sin.sin_port)) {
1348 ast_copy_string(host, peer->name, len);
1357 peer = realtime_peer(NULL, &sin);
1359 ast_copy_string(host, peer->name, len);
1368 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1370 /* Decrement AUTHREQ count if needed */
1371 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1372 struct iax2_user *user;
1373 struct iax2_user tmp_user = {
1374 .name = pvt->username,
1377 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1379 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1383 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1385 /* No more pings or lagrq's */
1386 AST_SCHED_DEL(sched, pvt->pingid);
1387 AST_SCHED_DEL(sched, pvt->lagid);
1388 AST_SCHED_DEL(sched, pvt->autoid);
1389 AST_SCHED_DEL(sched, pvt->authid);
1390 AST_SCHED_DEL(sched, pvt->initid);
1391 AST_SCHED_DEL(sched, pvt->jbid);
1394 static void iax2_frame_free(struct iax_frame *fr)
1396 AST_SCHED_DEL(sched, fr->retrans);
1400 static void pvt_destructor(void *obj)
1402 struct chan_iax2_pvt *pvt = obj;
1403 struct iax_frame *cur = NULL;
1405 iax2_destroy_helper(pvt);
1408 ast_set_flag(pvt, IAX_ALREADYGONE);
1410 AST_LIST_LOCK(&frame_queue);
1411 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1412 /* Cancel any pending transmissions */
1413 if (cur->callno == pvt->callno) {
1417 AST_LIST_UNLOCK(&frame_queue);
1420 pvt->reg->callno = 0;
1426 ast_variables_destroy(pvt->vars);
1430 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1431 iax2_frame_free(frame.data);
1434 jb_destroy(pvt->jb);
1435 ast_string_field_free_memory(pvt);
1439 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1441 struct chan_iax2_pvt *tmp;
1444 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1448 if (ast_string_field_init(tmp, 32)) {
1461 ast_string_field_set(tmp,exten, "s");
1462 ast_string_field_set(tmp,host, host);
1466 jbconf.max_jitterbuf = maxjitterbuffer;
1467 jbconf.resync_threshold = resyncthreshold;
1468 jbconf.max_contig_interp = maxjitterinterps;
1469 jbconf.target_extra = jittertargetextra;
1470 jb_setconf(tmp->jb,&jbconf);
1472 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1477 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1479 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1481 size_t afdatalen = new->afdatalen;
1482 memcpy(new, fr, sizeof(*new));
1483 iax_frame_wrap(new, &fr->af);
1484 new->afdatalen = afdatalen;
1487 new->direction = DIRECTION_INGRESS;
1493 #define NEW_PREVENT 0
1497 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1499 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1500 (cur->addr.sin_port == sin->sin_port)) {
1501 /* This is the main host */
1502 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1503 (check_dcallno ? dcallno == cur->callno : 1) ) {
1504 /* That's us. Be sure we keep track of the peer call number */
1508 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1509 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1510 /* We're transferring */
1511 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_NONE && cur->transfercallno == callno))
1517 static void update_max_trunk(void)
1519 int max = TRUNK_CALL_START;
1522 /* XXX Prolly don't need locks here XXX */
1523 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1531 ast_debug(1, "New max trunk callno is %d\n", max);
1534 static void update_max_nontrunk(void)
1538 /* XXX Prolly don't need locks here XXX */
1539 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1543 maxnontrunkcall = max;
1545 ast_debug(1, "New max nontrunk callno is %d\n", max);
1548 static int make_trunk(unsigned short callno, int locked)
1552 struct timeval now = ast_tvnow();
1553 if (iaxs[callno]->oseqno) {
1554 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1557 if (callno & TRUNK_CALL_START) {
1558 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1561 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1562 ast_mutex_lock(&iaxsl[x]);
1563 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1565 * \note We delete these before switching the slot, because if
1566 * they fire in the meantime, they will generate a warning.
1568 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
1569 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
1570 iaxs[x] = iaxs[callno];
1571 iaxs[x]->callno = x;
1572 iaxs[callno] = NULL;
1573 /* Update the two timers that should have been started */
1574 iaxs[x]->pingid = iax2_sched_add(sched,
1575 ping_time * 1000, send_ping, (void *)(long)x);
1576 iaxs[x]->lagid = iax2_sched_add(sched,
1577 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1579 ast_mutex_unlock(&iaxsl[callno]);
1582 ast_mutex_unlock(&iaxsl[x]);
1585 ast_mutex_unlock(&iaxsl[x]);
1587 if (x >= ARRAY_LEN(iaxs) - 1) {
1588 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1591 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1592 /* We move this call from a non-trunked to a trunked call */
1594 update_max_nontrunk();
1598 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1600 if (!pvt->peercallno) {
1601 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1605 ao2_link(iax_peercallno_pvts, pvt);
1608 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1610 if (!pvt->peercallno) {
1611 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1615 ao2_unlink(iax_peercallno_pvts, pvt);
1619 * \note Calling this function while holding another pvt lock can cause a deadlock.
1621 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1628 if (new <= NEW_ALLOW) {
1630 struct chan_iax2_pvt *pvt;
1631 struct chan_iax2_pvt tmp_pvt = {
1633 .peercallno = callno,
1635 .frames_received = check_dcallno,
1638 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1640 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1641 if (return_locked) {
1642 ast_mutex_lock(&iaxsl[pvt->callno]);
1651 /* This will occur on the first response to a message that we initiated,
1652 * such as a PING. */
1653 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1654 iaxs[dcallno]->peercallno = callno;
1656 store_by_peercallno(iaxs[dcallno]);
1661 /* If we get here, we SHOULD NOT find a call structure for this
1662 callno; if we do, it means that there is a call structure that
1663 has a peer callno but did NOT get entered into the hash table,
1666 If we find a call structure using this old, slow method, output a log
1667 message so we'll know about it. After a few months of leaving this in
1668 place, if we don't hear about people seeing these messages, we can
1669 remove this code for good.
1672 for (x = 1; !res && x < maxnontrunkcall; x++) {
1673 ast_mutex_lock(&iaxsl[x]);
1675 /* Look for an exact match */
1676 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1680 if (!res || !return_locked)
1681 ast_mutex_unlock(&iaxsl[x]);
1683 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1684 ast_mutex_lock(&iaxsl[x]);
1686 /* Look for an exact match */
1687 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1691 if (!res || !return_locked)
1692 ast_mutex_unlock(&iaxsl[x]);
1696 if (!res && (new >= NEW_ALLOW)) {
1697 int start, found = 0;
1699 /* It may seem odd that we look through the peer list for a name for
1700 * this *incoming* call. Well, it is weird. However, users don't
1701 * have an IP address/port number that we can match against. So,
1702 * this is just checking for a peer that has that IP/port and
1703 * assuming that we have a user of the same name. This isn't always
1704 * correct, but it will be changed if needed after authentication. */
1705 if (!iax2_getpeername(*sin, host, sizeof(host)))
1706 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1709 start = 1 + (ast_random() % (TRUNK_CALL_START - 1));
1710 for (x = start; 1; x++) {
1711 if (x == TRUNK_CALL_START) {
1716 /* Find first unused call number that hasn't been used in a while */
1717 ast_mutex_lock(&iaxsl[x]);
1718 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1722 ast_mutex_unlock(&iaxsl[x]);
1724 if (x == start - 1) {
1728 /* We've still got lock held if we found a spot */
1729 if (x == start - 1 && !found) {
1730 ast_log(LOG_WARNING, "No more space\n");
1733 iaxs[x] = new_iax(sin, host);
1734 update_max_nontrunk();
1737 ast_debug(1, "Creating new call structure %d\n", x);
1738 iaxs[x]->sockfd = sockfd;
1739 iaxs[x]->addr.sin_port = sin->sin_port;
1740 iaxs[x]->addr.sin_family = sin->sin_family;
1741 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1742 iaxs[x]->peercallno = callno;
1743 iaxs[x]->callno = x;
1744 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1745 iaxs[x]->expiry = min_reg_expire;
1746 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1747 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1748 iaxs[x]->amaflags = amaflags;
1749 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1751 ast_string_field_set(iaxs[x], accountcode, accountcode);
1752 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1753 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1754 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
1756 if (iaxs[x]->peercallno) {
1757 store_by_peercallno(iaxs[x]);
1760 ast_log(LOG_WARNING, "Out of resources\n");
1761 ast_mutex_unlock(&iaxsl[x]);
1765 ast_mutex_unlock(&iaxsl[x]);
1771 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1773 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1776 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1778 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1782 * \brief Queue a frame to a call's owning asterisk channel
1784 * \pre This function assumes that iaxsl[callno] is locked when called.
1786 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1787 * was valid before calling it, it may no longer be valid after calling it.
1788 * This function may unlock and lock the mutex associated with this callno,
1789 * meaning that another thread may grab it and destroy the call.
1791 static int iax2_queue_frame(int callno, struct ast_frame *f)
1794 if (iaxs[callno] && iaxs[callno]->owner) {
1795 if (ast_channel_trylock(iaxs[callno]->owner)) {
1796 /* Avoid deadlock by pausing and trying again */
1797 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1799 ast_queue_frame(iaxs[callno]->owner, f);
1800 ast_channel_unlock(iaxs[callno]->owner);
1810 * \brief Queue a hangup frame on the ast_channel owner
1812 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1813 * is active for the given call number.
1815 * \pre Assumes lock for callno is already held.
1817 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1818 * was valid before calling it, it may no longer be valid after calling it.
1819 * This function may unlock and lock the mutex associated with this callno,
1820 * meaning that another thread may grab it and destroy the call.
1822 static int iax2_queue_hangup(int callno)
1825 if (iaxs[callno] && iaxs[callno]->owner) {
1826 if (ast_channel_trylock(iaxs[callno]->owner)) {
1827 /* Avoid deadlock by pausing and trying again */
1828 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1830 ast_queue_hangup(iaxs[callno]->owner);
1831 ast_channel_unlock(iaxs[callno]->owner);
1841 * \brief Queue a control frame on the ast_channel owner
1843 * This function queues a control frame on the owner of the IAX2 pvt struct that
1844 * is active for the given call number.
1846 * \pre Assumes lock for callno is already held.
1848 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1849 * was valid before calling it, it may no longer be valid after calling it.
1850 * This function may unlock and lock the mutex associated with this callno,
1851 * meaning that another thread may grab it and destroy the call.
1853 static int iax2_queue_control_data(int callno,
1854 enum ast_control_frame_type control, const void *data, size_t datalen)
1857 if (iaxs[callno] && iaxs[callno]->owner) {
1858 if (ast_channel_trylock(iaxs[callno]->owner)) {
1859 /* Avoid deadlock by pausing and trying again */
1860 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1862 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1863 ast_channel_unlock(iaxs[callno]->owner);
1871 static void destroy_firmware(struct iax_firmware *cur)
1873 /* Close firmware */
1875 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1881 static int try_firmware(char *s)
1884 struct iax_firmware *cur = NULL;
1885 int ifd, fd, res, len, chunk;
1886 struct ast_iax2_firmware_header *fwh, fwh2;
1887 struct MD5Context md5;
1888 unsigned char sum[16], buf[1024];
1891 if (!(s2 = alloca(strlen(s) + 100))) {
1892 ast_log(LOG_WARNING, "Alloca failed!\n");
1896 last = strrchr(s, '/');
1902 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1904 if ((res = stat(s, &stbuf) < 0)) {
1905 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1909 /* Make sure it's not a directory */
1910 if (S_ISDIR(stbuf.st_mode))
1912 ifd = open(s, O_RDONLY);
1914 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1917 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1919 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1923 /* Unlink our newly created file */
1926 /* Now copy the firmware into it */
1927 len = stbuf.st_size;
1930 if (chunk > sizeof(buf))
1931 chunk = sizeof(buf);
1932 res = read(ifd, buf, chunk);
1934 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1939 res = write(fd, buf, chunk);
1941 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1949 /* Return to the beginning */
1950 lseek(fd, 0, SEEK_SET);
1951 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1952 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1956 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1957 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1961 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1962 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1966 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1967 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1971 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1972 if (fwh == (void *) -1) {
1973 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1978 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1979 MD5Final(sum, &md5);
1980 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1981 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1982 munmap((void*)fwh, stbuf.st_size);
1987 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1988 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1989 /* Found a candidate */
1990 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1991 /* The version we have on loaded is older, load this one instead */
1993 /* This version is no newer than what we have. Don't worry about it.
1994 We'll consider it a proper load anyhow though */
1995 munmap((void*)fwh, stbuf.st_size);
2001 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2003 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2008 munmap((void*)cur->fwh, cur->mmaplen);
2013 cur->mmaplen = stbuf.st_size;
2020 static int iax_check_version(char *dev)
2023 struct iax_firmware *cur = NULL;
2025 if (ast_strlen_zero(dev))
2028 AST_LIST_LOCK(&firmwares);
2029 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2030 if (!strcmp(dev, (char *)cur->fwh->devname)) {
2031 res = ntohs(cur->fwh->version);
2035 AST_LIST_UNLOCK(&firmwares);
2040 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2043 unsigned int bs = desc & 0xff;
2044 unsigned int start = (desc >> 8) & 0xffffff;
2046 struct iax_firmware *cur;
2048 if (ast_strlen_zero((char *)dev) || !bs)
2053 AST_LIST_LOCK(&firmwares);
2054 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2055 if (strcmp((char *)dev, (char *)cur->fwh->devname))
2057 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2058 if (start < ntohl(cur->fwh->datalen)) {
2059 bytes = ntohl(cur->fwh->datalen) - start;
2062 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2065 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2073 AST_LIST_UNLOCK(&firmwares);
2079 static void reload_firmware(int unload)
2081 struct iax_firmware *cur = NULL;
2084 char dir[256], fn[256];
2086 AST_LIST_LOCK(&firmwares);
2088 /* Mark all as dead */
2089 AST_LIST_TRAVERSE(&firmwares, cur, list)
2092 /* Now that we have marked them dead... load new ones */
2094 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2097 while((de = readdir(fwd))) {
2098 if (de->d_name[0] != '.') {
2099 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2100 if (!try_firmware(fn)) {
2101 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2107 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2110 /* Clean up leftovers */
2111 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2114 AST_LIST_REMOVE_CURRENT(list);
2115 destroy_firmware(cur);
2117 AST_LIST_TRAVERSE_SAFE_END;
2119 AST_LIST_UNLOCK(&firmwares);
2123 * \note This function assumes that iaxsl[callno] is locked when called.
2125 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2126 * was valid before calling it, it may no longer be valid after calling it.
2127 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2128 * associated with this callno, meaning that another thread may grab it and destroy the call.
2130 static int __do_deliver(void *data)
2132 /* Just deliver the packet by using queueing. This is called by
2133 the IAX thread with the iaxsl lock held. */
2134 struct iax_frame *fr = data;
2136 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2137 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2138 iax2_queue_frame(fr->callno, &fr->af);
2139 /* Free our iax frame */
2140 iax2_frame_free(fr);
2141 /* And don't run again */
2145 static int handle_error(void)
2147 /* XXX Ideally we should figure out why an error occurred and then abort those
2148 rather than continuing to try. Unfortunately, the published interface does
2149 not seem to work XXX */
2151 struct sockaddr_in *sin;
2154 struct sock_extended_err e;
2159 m.msg_controllen = sizeof(e);
2161 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2163 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2165 if (m.msg_controllen) {
2166 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2168 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2170 ast_log(LOG_WARNING, "No address detected??\n");
2172 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2179 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2182 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2185 ast_debug(1, "Received error: %s\n", strerror(errno));
2192 static int send_packet(struct iax_frame *f)
2195 int callno = f->callno;
2196 struct sockaddr_in *addr;
2198 /* Don't send if there was an error, but return error instead */
2199 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2202 /* Called with iaxsl held */
2204 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));
2207 addr = &iaxs[callno]->media;
2208 } else if (f->transfer) {
2209 addr = &iaxs[callno]->transfer;
2211 addr = &iaxs[callno]->addr;
2215 iax_showframe(f, NULL, 0, addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2217 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)addr,
2218 sizeof(iaxs[callno]->media));
2222 ast_debug(1, "Received error: %s\n", strerror(errno));
2231 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2232 * for the given call number may disappear during its execution.
2234 static int iax2_predestroy(int callno)
2236 struct ast_channel *c = NULL;
2237 struct chan_iax2_pvt *pvt = iaxs[callno];
2242 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2243 iax2_destroy_helper(pvt);
2244 ast_set_flag(pvt, IAX_ALREADYGONE);
2247 if ((c = pvt->owner)) {
2249 iax2_queue_hangup(callno);
2251 ast_module_unref(ast_module_info->self);
2257 static void iax2_destroy(int callno)
2259 struct chan_iax2_pvt *pvt = NULL;
2260 struct ast_channel *owner = NULL;
2264 lastused[callno] = ast_tvnow();
2266 owner = pvt ? pvt->owner : NULL;
2269 if (ast_channel_trylock(owner)) {
2270 ast_debug(3, "Avoiding IAX destroy deadlock\n");
2271 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2277 iaxs[callno] = NULL;
2284 /* If there's an owner, prod it to give up */
2285 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2286 * because we already hold the owner channel lock. */
2287 ast_queue_hangup(owner);
2290 if (pvt->peercallno) {
2291 remove_by_peercallno(pvt);
2301 ast_channel_unlock(owner);
2304 if (callno & 0x4000) {
2309 static int update_packet(struct iax_frame *f)
2311 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2312 struct ast_iax2_full_hdr *fh = f->data;
2313 /* Mark this as a retransmission */
2314 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2316 f->iseqno = iaxs[f->callno]->iseqno;
2317 fh->iseqno = f->iseqno;
2321 static int attempt_transmit(const void *data);
2322 static void __attempt_transmit(const void *data)
2324 /* Attempt to transmit the frame to the remote peer...
2325 Called without iaxsl held. */
2326 struct iax_frame *f = (struct iax_frame *)data;
2328 int callno = f->callno;
2329 /* Make sure this call is still active */
2331 ast_mutex_lock(&iaxsl[callno]);
2332 if (callno && iaxs[callno]) {
2333 if ((f->retries < 0) /* Already ACK'd */ ||
2334 (f->retries >= max_retries) /* Too many attempts */) {
2335 /* Record an error if we've transmitted too many times */
2336 if (f->retries >= max_retries) {
2338 /* Transfer timeout */
2339 struct iax_ie_data ied;
2340 memset(&ied, 0, sizeof(ied));
2341 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, iaxs[callno]->transferid);
2342 if (iaxs[callno]->mediareleased) {
2343 send_command_media(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos);
2345 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos, -1);
2347 } else if (f->final) {
2349 iax2_destroy(callno);
2351 if (iaxs[callno]->owner)
2352 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);
2353 iaxs[callno]->error = ETIMEDOUT;
2354 if (iaxs[callno]->owner) {
2355 struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
2357 iax2_queue_frame(callno, &fr); /* XXX */
2358 /* Remember, owner could disappear */
2359 if (iaxs[callno] && iaxs[callno]->owner)
2360 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2362 if (iaxs[callno]->reg) {
2363 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2364 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2365 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2367 iax2_destroy(callno);
2374 /* Update it if it needs it */
2376 /* Attempt transmission */
2379 /* Try again later after 10 times as long */
2381 if (f->retrytime > MAX_RETRY_TIME)
2382 f->retrytime = MAX_RETRY_TIME;
2383 /* Transfer messages max out at one second */
2384 if (f->transfer && (f->retrytime > 1000))
2385 f->retrytime = 1000;
2386 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2389 /* Make sure it gets freed */
2394 ast_mutex_unlock(&iaxsl[callno]);
2395 /* Do not try again */
2397 /* Don't attempt delivery, just remove it from the queue */
2398 AST_LIST_LOCK(&frame_queue);
2399 AST_LIST_REMOVE(&frame_queue, f, list);
2400 AST_LIST_UNLOCK(&frame_queue);
2402 /* Free the IAX frame */
2407 static int attempt_transmit(const void *data)
2409 #ifdef SCHED_MULTITHREADED
2410 if (schedule_action(__attempt_transmit, data))
2412 __attempt_transmit(data);
2416 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2418 struct iax2_peer *peer;
2422 e->command = "iax2 prune realtime";
2424 "Usage: iax2 prune realtime [<peername>|all]\n"
2425 " Prunes object(s) from the cache\n";
2428 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2432 return CLI_SHOWUSAGE;
2433 if (!strcmp(a->argv[3], "all")) {
2435 ast_cli(a->fd, "Cache flushed successfully.\n");
2436 } else if ((peer = find_peer(a->argv[3], 0))) {
2437 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2438 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2439 expire_registry(peer_ref(peer));
2440 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2442 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2446 ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2452 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2456 e->command = "iax2 test losspct";
2458 "Usage: iax2 test losspct <percentage>\n"
2459 " For testing, throws away <percentage> percent of incoming packets\n";
2465 return CLI_SHOWUSAGE;
2467 test_losspct = atoi(a->argv[3]);
2473 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2477 e->command = "iax2 test late";
2479 "Usage: iax2 test late <ms>\n"
2480 " For testing, count the next frame as <ms> ms late\n";
2487 return CLI_SHOWUSAGE;
2489 test_late = atoi(a->argv[3]);
2494 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2498 e->command = "iax2 test resync";
2500 "Usage: iax2 test resync <ms>\n"
2501 " For testing, adjust all future frames by <ms> ms\n";
2508 return CLI_SHOWUSAGE;
2510 test_resync = atoi(a->argv[3]);
2515 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2519 e->command = "iax2 test jitter";
2521 "Usage: iax2 test jitter <ms> <pct>\n"
2522 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2523 " percentage of packets. If <pct> is not specified, adds\n"
2524 " jitter to all packets.\n";
2530 if (a->argc < 4 || a->argc > 5)
2531 return CLI_SHOWUSAGE;
2533 test_jit = atoi(a->argv[3]);
2535 test_jitpct = atoi(a->argv[4]);
2539 #endif /* IAXTESTS */
2541 /*! \brief peer_status: Report Peer status in character string */
2542 /* returns 1 if peer is online, -1 if unmonitored */
2543 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2547 if (peer->lastms < 0) {
2548 ast_copy_string(status, "UNREACHABLE", statuslen);
2549 } else if (peer->lastms > peer->maxms) {
2550 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2552 } else if (peer->lastms) {
2553 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2556 ast_copy_string(status, "UNKNOWN", statuslen);
2559 ast_copy_string(status, "Unmonitored", statuslen);
2565 /*! \brief Show one peer in detail */
2566 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2570 struct iax2_peer *peer;
2571 char codec_buf[512];
2572 int x = 0, codec = 0, load_realtime = 0;
2576 e->command = "iax2 show peer";
2578 "Usage: iax2 show peer <name>\n"
2579 " Display details on specific IAX peer\n";
2582 return complete_iax2_show_peer(a->line, a->word, a->pos, a->n);
2586 return CLI_SHOWUSAGE;
2588 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2590 peer = find_peer(a->argv[3], load_realtime);
2592 ast_cli(a->fd, "\n\n");
2593 ast_cli(a->fd, " * Name : %s\n", peer->name);
2594 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2595 ast_cli(a->fd, " Context : %s\n", peer->context);
2596 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
2597 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
2598 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2599 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2600 ast_cli(a->fd, " Expire : %d\n", peer->expire);
2601 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
2602 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));
2603 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2604 ast_cli(a->fd, " Username : %s\n", peer->username);
2605 ast_cli(a->fd, " Codecs : ");
2606 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2607 ast_cli(a->fd, "%s\n", codec_buf);
2609 ast_cli(a->fd, " Codec Order : (");
2610 for(x = 0; x < 32 ; x++) {
2611 codec = ast_codec_pref_index(&peer->prefs,x);
2614 ast_cli(a->fd, "%s", ast_getformatname(codec));
2615 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2616 ast_cli(a->fd, "|");
2620 ast_cli(a->fd, "none");
2621 ast_cli(a->fd, ")\n");
2623 ast_cli(a->fd, " Status : ");
2624 peer_status(peer, status, sizeof(status));
2625 ast_cli(a->fd, "%s\n",status);
2626 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");
2627 ast_cli(a->fd, "\n");
2630 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2631 ast_cli(a->fd, "\n");
2637 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2640 struct iax2_peer *peer;
2642 int wordlen = strlen(word);
2643 struct ao2_iterator i;
2645 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2649 i = ao2_iterator_init(peers, 0);
2650 while ((peer = ao2_iterator_next(&i))) {
2651 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2652 res = ast_strdup(peer->name);
2662 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2664 struct iax_frame *cur;
2665 int cnt = 0, dead = 0, final = 0;
2669 e->command = "iax2 show stats";
2671 "Usage: iax2 show stats\n"
2672 " Display statistics on IAX channel driver.\n";
2679 return CLI_SHOWUSAGE;
2681 AST_LIST_LOCK(&frame_queue);
2682 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2683 if (cur->retries < 0)
2689 AST_LIST_UNLOCK(&frame_queue);
2691 ast_cli(a->fd, " IAX Statistics\n");
2692 ast_cli(a->fd, "---------------------\n");
2693 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2694 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2695 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2696 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2698 trunk_timed = trunk_untimed = 0;
2699 if (trunk_maxmtu > trunk_nmaxmtu)
2700 trunk_nmaxmtu = trunk_maxmtu;
2705 /*! \brief Set trunk MTU from CLI */
2706 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2712 e->command = "iax2 set mtu";
2714 "Usage: iax2 set mtu <value>\n"
2715 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2716 " zero to disable. Disabling means that the operating system\n"
2717 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2718 " packet exceeds the UDP payload size. This is substantially\n"
2719 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2720 " greater for G.711 samples.\n";
2727 return CLI_SHOWUSAGE;
2728 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2729 mtuv = MAX_TRUNK_MTU;
2731 mtuv = atoi(a->argv[3]);
2734 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2735 global_max_trunk_mtu = 0;
2738 if (mtuv < 172 || mtuv > 4000) {
2739 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
2740 return CLI_SHOWUSAGE;
2742 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2743 global_max_trunk_mtu = mtuv;
2747 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2749 struct iax2_dpcache *dp = NULL;
2750 char tmp[1024], *pc = NULL;
2752 struct timeval tv = ast_tvnow();
2756 e->command = "iax2 show cache";
2758 "Usage: iax2 show cache\n"
2759 " Display currently cached IAX Dialplan results.\n";
2765 AST_LIST_LOCK(&dpcache);
2767 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2769 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2770 s = dp->expiry.tv_sec - tv.tv_sec;
2772 if (dp->flags & CACHE_FLAG_EXISTS)
2773 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2774 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2775 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2776 if (dp->flags & CACHE_FLAG_CANEXIST)
2777 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2778 if (dp->flags & CACHE_FLAG_PENDING)
2779 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2780 if (dp->flags & CACHE_FLAG_TIMEOUT)
2781 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2782 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2783 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2784 if (dp->flags & CACHE_FLAG_MATCHMORE)
2785 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2786 if (dp->flags & CACHE_FLAG_UNKNOWN)
2787 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2788 /* Trim trailing pipe */
2789 if (!ast_strlen_zero(tmp))
2790 tmp[strlen(tmp) - 1] = '\0';
2792 ast_copy_string(tmp, "(none)", sizeof(tmp));
2794 pc = strchr(dp->peercontext, '@');
2796 pc = dp->peercontext;
2799 for (x = 0; x < sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2800 if (dp->waiters[x] > -1)
2803 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2805 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2808 AST_LIST_LOCK(&dpcache);
2813 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2815 static void unwrap_timestamp(struct iax_frame *fr)
2819 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2820 x = fr->ts - iaxs[fr->callno]->last;
2822 /* Sudden big jump backwards in timestamp:
2823 What likely happened here is that miniframe timestamp has circled but we haven't
2824 gotten the update from the main packet. We'll just pretend that we did, and
2825 update the timestamp appropriately. */
2826 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2828 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2831 /* Sudden apparent big jump forwards in timestamp:
2832 What's likely happened is this is an old miniframe belonging to the previous
2833 top-16-bit timestamp that has turned up out of order.
2834 Adjust the timestamp appropriately. */
2835 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2837 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2842 static int get_from_jb(const void *p);
2844 static void update_jbsched(struct chan_iax2_pvt *pvt)
2848 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2850 when = jb_next(pvt->jb) - when;
2853 /* XXX should really just empty until when > 0.. */
2857 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
2858 CALLNO_TO_PTR(pvt->callno));
2861 static void __get_from_jb(const void *p)
2863 int callno = PTR_TO_CALLNO(p);
2864 struct chan_iax2_pvt *pvt = NULL;
2865 struct iax_frame *fr;
2870 struct timeval tv = ast_tvnow();
2872 /* Make sure we have a valid private structure before going on */
2873 ast_mutex_lock(&iaxsl[callno]);
2877 ast_mutex_unlock(&iaxsl[callno]);
2883 /* round up a millisecond since ast_sched_runq does; */
2884 /* prevents us from spinning while waiting for our now */
2885 /* to catch up with runq's now */
2888 now = ast_tvdiff_ms(tv, pvt->rxcore);
2890 if(now >= (next = jb_next(pvt->jb))) {
2891 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2896 /* __do_deliver() can cause the call to disappear */
2901 struct ast_frame af = { 0, };
2903 /* create an interpolation frame */
2904 af.frametype = AST_FRAME_VOICE;
2905 af.subclass = pvt->voiceformat;
2906 af.samples = frame.ms * 8;
2907 af.src = "IAX2 JB interpolation";
2908 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2909 af.offset = AST_FRIENDLY_OFFSET;
2911 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2912 * which we'd need to malloc, and then it would free it. That seems like a drag */
2913 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2914 iax2_queue_frame(callno, &af);
2915 /* iax2_queue_frame() could cause the call to disappear */
2921 iax2_frame_free(frame.data);
2928 /* shouldn't happen */
2933 update_jbsched(pvt);
2934 ast_mutex_unlock(&iaxsl[callno]);
2937 static int get_from_jb(const void *data)
2939 #ifdef SCHED_MULTITHREADED
2940 if (schedule_action(__get_from_jb, data))
2942 __get_from_jb(data);
2947 * \note This function assumes fr->callno is locked
2949 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2950 * was valid before calling it, it may no longer be valid after calling it.
2952 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2957 struct ast_channel *owner = NULL;
2958 struct ast_channel *bridge = NULL;
2960 /* Attempt to recover wrapped timestamps */
2961 unwrap_timestamp(fr);
2963 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2964 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2965 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2968 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2970 fr->af.delivery = ast_tv(0,0);
2973 type = JB_TYPE_CONTROL;
2976 if(fr->af.frametype == AST_FRAME_VOICE) {
2977 type = JB_TYPE_VOICE;
2978 len = ast_codec_get_samples(&fr->af) / 8;
2979 } else if(fr->af.frametype == AST_FRAME_CNG) {
2980 type = JB_TYPE_SILENCE;
2983 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2990 if ((owner = iaxs[fr->callno]->owner))
2991 bridge = ast_bridged_channel(owner);
2993 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2994 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2995 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
2998 /* deliver any frames in the jb */
2999 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
3000 __do_deliver(frame.data);
3001 /* __do_deliver() can make the call disappear */
3002 if (!iaxs[fr->callno])
3006 jb_reset(iaxs[fr->callno]->jb);
3008 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
3010 /* deliver this frame now */
3017 /* insert into jitterbuffer */
3018 /* TODO: Perhaps we could act immediately if it's not droppable and late */
3019 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
3020 calc_rxstamp(iaxs[fr->callno],fr->ts));
3021 if (ret == JB_DROP) {
3023 } else if (ret == JB_SCHED) {
3024 update_jbsched(iaxs[fr->callno]);
3029 /* Free our iax frame */
3030 iax2_frame_free(fr);
3036 static int iax2_transmit(struct iax_frame *fr)
3038 /* Lock the queue and place this packet at the end */
3039 /* By setting this to 0, the network thread will send it for us, and
3040 queue retransmission if necessary */
3042 AST_LIST_LOCK(&frame_queue);
3043 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
3044 AST_LIST_UNLOCK(&frame_queue);
3045 /* Wake up the network and scheduler thread */
3046 if (netthreadid != AST_PTHREADT_NULL)
3047 pthread_kill(netthreadid, SIGURG);
3048 signal_condition(&sched_lock, &sched_cond);
3054 static int iax2_digit_begin(struct ast_channel *c, char digit)
3056 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
3059 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
3061 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
3064 static int iax2_sendtext(struct ast_channel *c, const char *text)
3067 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
3068 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
3071 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
3073 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data.ptr, img->datalen, -1);
3076 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
3078 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
3081 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
3083 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
3084 ast_mutex_lock(&iaxsl[callno]);
3086 iaxs[callno]->owner = newchan;
3088 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
3089 ast_mutex_unlock(&iaxsl[callno]);
3094 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3095 * so do not call this with a pvt lock held.
3097 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
3099 struct ast_variable *var = NULL;
3100 struct ast_variable *tmp;
3101 struct iax2_peer *peer=NULL;
3102 time_t regseconds = 0, nowtime;
3106 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
3108 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
3111 sprintf(porta, "%d", ntohs(sin->sin_port));
3112 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
3114 /* We'll need the peer name in order to build the structure! */
3115 for (tmp = var; tmp; tmp = tmp->next) {
3116 if (!strcasecmp(tmp->name, "name"))
3117 peername = tmp->value;
3121 if (!var && peername) { /* Last ditch effort */
3122 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
3124 * If this one loaded something, then we need to ensure that the host
3125 * field matched. The only reason why we can't have this as a criteria
3126 * is because we only have the IP address and the host field might be
3127 * set as a name (and the reverse PTR might not match).
3130 for (tmp = var; tmp; tmp = tmp->next) {
3131 if (!strcasecmp(tmp->name, "host")) {
3132 struct ast_hostent ahp;
3134 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3136 ast_variables_destroy(var);
3147 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
3150 ast_variables_destroy(var);
3154 for (tmp = var; tmp; tmp = tmp->next) {
3155 /* Make sure it's not a user only... */
3156 if (!strcasecmp(tmp->name, "type")) {
3157 if (strcasecmp(tmp->value, "friend") &&
3158 strcasecmp(tmp->value, "peer")) {
3159 /* Whoops, we weren't supposed to exist! */
3160 peer = peer_unref(peer);
3163 } else if (!strcasecmp(tmp->name, "regseconds")) {
3164 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
3165 } else if (!strcasecmp(tmp->name, "ipaddr")) {
3166 inet_aton(tmp->value, &(peer->addr.sin_addr));
3167 } else if (!strcasecmp(tmp->name, "port")) {
3168 peer->addr.sin_port = htons(atoi(tmp->value));
3169 } else if (!strcasecmp(tmp->name, "host")) {
3170 if (!strcasecmp(tmp->value, "dynamic"))
3175 ast_variables_destroy(var);
3180 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3181 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3182 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {