2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
50 #include <sys/signal.h>
62 #include <sys/ioctl.h>
63 #include <zaptel/zaptel.h>
66 #include "asterisk/lock.h"
67 #include "asterisk/frame.h"
68 #include "asterisk/channel.h"
69 #include "asterisk/logger.h"
70 #include "asterisk/module.h"
71 #include "asterisk/pbx.h"
72 #include "asterisk/sched.h"
73 #include "asterisk/io.h"
74 #include "asterisk/config.h"
75 #include "asterisk/options.h"
76 #include "asterisk/cli.h"
77 #include "asterisk/translate.h"
78 #include "asterisk/md5.h"
79 #include "asterisk/cdr.h"
80 #include "asterisk/crypto.h"
81 #include "asterisk/acl.h"
82 #include "asterisk/manager.h"
83 #include "asterisk/callerid.h"
84 #include "asterisk/app.h"
85 #include "asterisk/astdb.h"
86 #include "asterisk/musiconhold.h"
87 #include "asterisk/features.h"
88 #include "asterisk/utils.h"
89 #include "asterisk/causes.h"
90 #include "asterisk/localtime.h"
91 #include "asterisk/aes.h"
92 #include "asterisk/dnsmgr.h"
93 #include "asterisk/devicestate.h"
94 #include "asterisk/netsock.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/linkedlists.h"
99 #include "iax2-parser.h"
100 #include "iax2-provision.h"
101 #include "jitterbuf.h"
103 /* Define SCHED_MULTITHREADED to run the scheduler in a special
104 multithreaded mode. */
105 #define SCHED_MULTITHREADED
107 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
108 thread is actually doing. */
109 #define DEBUG_SCHED_MULTITHREAD
111 #ifndef IPTOS_MINCOST
112 #define IPTOS_MINCOST 0x02
116 static int nochecksums = 0;
120 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
121 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
123 #define DEFAULT_THREAD_COUNT 10
124 #define DEFAULT_MAX_THREAD_COUNT 100
125 #define DEFAULT_RETRY_TIME 1000
126 #define MEMORY_SIZE 100
127 #define DEFAULT_DROP 3
128 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
129 but keeps the division between trunked and non-trunked better. */
130 #define TRUNK_CALL_START 0x4000
132 #define DEBUG_SUPPORT
134 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
136 /* Sample over last 100 units to determine historic jitter */
139 static struct ast_codec_pref prefs;
141 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
144 /*! \brief Maximum transimission unit for the UDP packet in the trunk not to be
145 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
146 #define MAX_TRUNK_MTU 1240
148 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
149 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
152 static char context[80] = "default";
154 static char language[MAX_LANGUAGE] = "";
155 static char regcontext[AST_MAX_CONTEXT] = "";
157 static int maxauthreq = 3;
158 static int max_retries = 4;
159 static int ping_time = 20;
160 static int lagrq_time = 10;
161 static int maxtrunkcall = TRUNK_CALL_START;
162 static int maxnontrunkcall = 1;
163 static int maxjitterbuffer=1000;
164 static int resyncthreshold=1000;
165 static int maxjitterinterps=10;
166 static int trunkfreq = 20;
167 static int authdebug = 1;
168 static int autokill = 0;
169 static int iaxcompat = 0;
171 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
173 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
175 static unsigned int tos = 0;
177 static int min_reg_expire;
178 static int max_reg_expire;
180 static int timingfd = -1; /* Timing file descriptor */
182 static struct ast_netsock_list *netsock;
183 static int defaultsockfd = -1;
185 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
188 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
190 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
191 ~AST_FORMAT_SLINEAR & \
196 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
198 ~AST_FORMAT_G726_AAL2 & \
201 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
205 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
206 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
207 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
209 static struct io_context *io;
210 static struct sched_context *sched;
212 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
214 static int iaxdebug = 0;
216 static int iaxtrunkdebug = 0;
218 static int test_losspct = 0;
220 static int test_late = 0;
221 static int test_resync = 0;
222 static int test_jit = 0;
223 static int test_jitpct = 0;
224 #endif /* IAXTESTS */
226 static char accountcode[AST_MAX_ACCOUNT_CODE];
227 static char mohinterpret[MAX_MUSICCLASS];
228 static char mohsuggest[MAX_MUSICCLASS];
229 static int amaflags = 0;
231 static int delayreject = 0;
232 static int iax2_encryption = 0;
234 static struct ast_flags globalflags = { 0 };
236 static pthread_t netthreadid = AST_PTHREADT_NULL;
237 static pthread_t schedthreadid = AST_PTHREADT_NULL;
238 AST_MUTEX_DEFINE_STATIC(sched_lock);
239 static ast_cond_t sched_cond;
242 IAX_STATE_STARTED = (1 << 0),
243 IAX_STATE_AUTHENTICATED = (1 << 1),
244 IAX_STATE_TBD = (1 << 2),
245 IAX_STATE_UNCHANGED = (1 << 3),
248 struct iax2_context {
249 char context[AST_MAX_CONTEXT];
250 struct iax2_context *next;
254 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
255 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
256 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
257 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
258 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
259 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
260 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
261 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
262 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
263 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
264 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
265 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
266 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
267 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
268 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
269 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
270 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
271 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
272 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
273 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
274 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
275 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
276 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
277 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
278 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
281 static int global_rtautoclear = 120;
283 static int reload_config(void);
284 static int iax2_reload(int fd, int argc, char *argv[]);
288 AST_DECLARE_STRING_FIELDS(
289 AST_STRING_FIELD(name);
290 AST_STRING_FIELD(secret);
291 AST_STRING_FIELD(dbsecret);
292 AST_STRING_FIELD(accountcode);
293 AST_STRING_FIELD(mohinterpret);
294 AST_STRING_FIELD(mohsuggest);
295 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
296 AST_STRING_FIELD(language);
297 AST_STRING_FIELD(cid_num);
298 AST_STRING_FIELD(cid_name);
307 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
308 int curauthreq; /*!< Current number of outstanding AUTHREQs */
309 struct ast_codec_pref prefs;
311 struct iax2_context *contexts;
312 struct ast_variable *vars;
313 AST_LIST_ENTRY(iax2_user) entry;
317 AST_DECLARE_STRING_FIELDS(
318 AST_STRING_FIELD(name);
319 AST_STRING_FIELD(username);
320 AST_STRING_FIELD(secret);
321 AST_STRING_FIELD(dbsecret);
322 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
324 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
325 AST_STRING_FIELD(context); /*!< For transfers only */
326 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
327 AST_STRING_FIELD(mailbox); /*!< Mailbox */
328 AST_STRING_FIELD(mohinterpret);
329 AST_STRING_FIELD(mohsuggest);
330 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
331 /* Suggested caller id if registering */
332 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
333 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
334 AST_STRING_FIELD(zonetag); /*!< Time Zone */
336 struct ast_codec_pref prefs;
337 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
338 struct sockaddr_in addr;
340 int sockfd; /*!< Socket to use for transmission */
345 /* Dynamic Registration fields */
346 struct sockaddr_in defaddr; /*!< Default address if there is one */
347 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
348 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
350 int expire; /*!< Schedule entry for expiry */
351 int expiry; /*!< How soon to expire */
352 int capability; /*!< Capability */
355 int callno; /*!< Call number of POKE request */
356 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
357 int lastms; /*!< How long last response took (in ms), or -1 for no response */
358 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
360 int pokefreqok; /*!< How often to check if the host is up */
361 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
362 int historicms; /*!< How long recent average responses took */
363 int smoothing; /*!< Sample over how many units to determine historic ms */
366 AST_LIST_ENTRY(iax2_peer) entry;
369 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
371 struct iax2_trunk_peer {
374 struct sockaddr_in addr;
375 struct timeval txtrunktime; /*!< Transmit trunktime */
376 struct timeval rxtrunktime; /*!< Receive trunktime */
377 struct timeval lasttxtime; /*!< Last transmitted trunktime */
378 struct timeval trunkact; /*!< Last trunk activity */
379 unsigned int lastsent; /*!< Last sent time */
380 /* Trunk data and length */
381 unsigned char *trunkdata;
382 unsigned int trunkdatalen;
383 unsigned int trunkdataalloc;
387 AST_LIST_ENTRY(iax2_trunk_peer) list;
390 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
392 struct iax_firmware {
393 AST_LIST_ENTRY(iax_firmware) list;
397 struct ast_iax2_firmware_header *fwh;
402 REG_STATE_UNREGISTERED = 0,
405 REG_STATE_REGISTERED,
411 enum iax_transfer_state {
416 TRANSFER_PASSTHROUGH,
420 TRANSFER_MPASSTHROUGH,
425 struct iax2_registry {
426 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
428 char secret[80]; /*!< Password or key name in []'s */
430 int expire; /*!< Sched ID of expiration */
431 int refresh; /*!< How often to refresh */
432 enum iax_reg_state regstate;
433 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
434 int callno; /*!< Associated call number if applicable */
435 struct sockaddr_in us; /*!< Who the server thinks we are */
436 struct iax2_registry *next;
437 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
440 static struct iax2_registry *registrations;
442 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
443 #define MIN_RETRY_TIME 100
444 #define MAX_RETRY_TIME 10000
446 #define MAX_JITTER_BUFFER 50
447 #define MIN_JITTER_BUFFER 10
449 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
450 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
452 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
454 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
455 #define TS_GAP_FOR_JB_RESYNC 5000
457 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
458 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
459 static int iaxdynamicthreadcount = 0;
471 struct chan_iax2_pvt {
472 /*! Socket to send/receive on for this call */
474 /*! Last received voice format */
476 /*! Last received video format */
478 /*! Last sent voice format */
480 /*! Last sent video format */
482 /*! What we are capable of sending */
484 /*! Last received timestamp */
486 /*! Last sent timestamp - never send the same timestamp twice in a single call */
487 unsigned int lastsent;
488 /*! Next outgoing timestamp if everything is good */
489 unsigned int nextpred;
490 /*! True if the last voice we transmitted was not silence/CNG */
493 unsigned int pingtime;
494 /*! Max time for initial response */
497 struct sockaddr_in addr;
498 /*! Actual used codec preferences */
499 struct ast_codec_pref prefs;
500 /*! Requested codec preferences */
501 struct ast_codec_pref rprefs;
502 /*! Our call number */
503 unsigned short callno;
505 unsigned short peercallno;
506 /*! Peer selected format */
508 /*! Peer capability */
510 /*! timeval that we base our transmission on */
511 struct timeval offset;
512 /*! timeval that we base our delivery on */
513 struct timeval rxcore;
514 /*! The jitterbuffer */
516 /*! active jb read scheduler id */
520 /*! Error, as discovered by the manager */
522 /*! Owner if we have one */
523 struct ast_channel *owner;
524 /*! What's our state? */
525 struct ast_flags state;
526 /*! Expiry (optional) */
528 /*! Next outgoing sequence number */
529 unsigned char oseqno;
530 /*! Next sequence number they have not yet acknowledged */
531 unsigned char rseqno;
532 /*! Next incoming sequence number */
533 unsigned char iseqno;
534 /*! Last incoming sequence number we have acknowledged */
535 unsigned char aseqno;
537 AST_DECLARE_STRING_FIELDS(
539 AST_STRING_FIELD(peer);
540 /*! Default Context */
541 AST_STRING_FIELD(context);
542 /*! Caller ID if available */
543 AST_STRING_FIELD(cid_num);
544 AST_STRING_FIELD(cid_name);
545 /*! Hidden Caller ID (i.e. ANI) if appropriate */
546 AST_STRING_FIELD(ani);
548 AST_STRING_FIELD(dnid);
550 AST_STRING_FIELD(rdnis);
551 /*! Requested Extension */
552 AST_STRING_FIELD(exten);
553 /*! Expected Username */
554 AST_STRING_FIELD(username);
555 /*! Expected Secret */
556 AST_STRING_FIELD(secret);
558 AST_STRING_FIELD(challenge);
559 /*! Public keys permitted keys for incoming authentication */
560 AST_STRING_FIELD(inkeys);
561 /*! Private key for outgoing authentication */
562 AST_STRING_FIELD(outkey);
563 /*! Preferred language */
564 AST_STRING_FIELD(language);
565 /*! Hostname/peername for naming purposes */
566 AST_STRING_FIELD(host);
568 AST_STRING_FIELD(dproot);
569 AST_STRING_FIELD(accountcode);
570 AST_STRING_FIELD(mohinterpret);
571 AST_STRING_FIELD(mohsuggest);
574 /*! permitted authentication methods */
576 /*! permitted encryption methods */
578 /*! Encryption AES-128 Key */
580 /*! Decryption AES-128 Key */
582 /*! 32 bytes of semi-random data */
583 unsigned char semirand[32];
584 /*! Associated registry */
585 struct iax2_registry *reg;
586 /*! Associated peer for poking */
587 struct iax2_peer *peerpoke;
592 /*! Transferring status */
593 enum iax_transfer_state transferring;
594 /*! Transfer identifier */
596 /*! Who we are IAX transfering to */
597 struct sockaddr_in transfer;
598 /*! What's the new call number for the transfer */
599 unsigned short transfercallno;
600 /*! Transfer decrypt AES-128 Key */
601 aes_encrypt_ctx tdcx;
603 /*! Status of knowledge of peer ADSI capability */
606 /*! Who we are bridged to */
607 unsigned short bridgecallno;
609 int pingid; /*!< Transmit PING request */
610 int lagid; /*!< Retransmit lag request */
611 int autoid; /*!< Auto hangup for Dialplan requestor */
612 int authid; /*!< Authentication rejection ID */
613 int authfail; /*!< Reason to report failure */
614 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
619 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
620 struct ast_variable *vars;
621 /*! last received remote rr */
622 struct iax_rr remote_rr;
623 /*! Current base time: (just for stats) */
625 /*! Dropped frame count: (just for stats) */
627 /*! received frame count: (just for stats) */
631 static struct ast_iax2_queue {
632 AST_LIST_HEAD(, iax_frame) queue;
635 .queue = AST_LIST_HEAD_INIT_VALUE
638 static AST_LIST_HEAD_STATIC(users, iax2_user);
640 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
642 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
644 /*! Extension exists */
645 #define CACHE_FLAG_EXISTS (1 << 0)
646 /*! Extension is nonexistent */
647 #define CACHE_FLAG_NONEXISTENT (1 << 1)
648 /*! Extension can exist */
649 #define CACHE_FLAG_CANEXIST (1 << 2)
650 /*! Waiting to hear back response */
651 #define CACHE_FLAG_PENDING (1 << 3)
653 #define CACHE_FLAG_TIMEOUT (1 << 4)
654 /*! Request transmitted */
655 #define CACHE_FLAG_TRANSMITTED (1 << 5)
657 #define CACHE_FLAG_UNKNOWN (1 << 6)
659 #define CACHE_FLAG_MATCHMORE (1 << 7)
661 struct iax2_dpcache {
662 char peercontext[AST_MAX_CONTEXT];
663 char exten[AST_MAX_EXTENSION];
665 struct timeval expiry;
667 unsigned short callno;
669 AST_LIST_ENTRY(iax2_dpcache) cache_list;
670 AST_LIST_ENTRY(iax2_dpcache) peer_list;
673 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
675 static void reg_source_db(struct iax2_peer *p);
676 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
678 static void destroy_peer(struct iax2_peer *peer);
679 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
681 #define IAX_IOSTATE_IDLE 0
682 #define IAX_IOSTATE_READY 1
683 #define IAX_IOSTATE_PROCESSING 2
684 #define IAX_IOSTATE_SCHEDREADY 3
686 #define IAX_TYPE_POOL 1
687 #define IAX_TYPE_DYNAMIC 2
690 AST_LIST_ENTRY(iax2_thread) list;
693 #ifdef SCHED_MULTITHREADED
694 void (*schedfunc)(void *);
697 #ifdef DEBUG_SCHED_MULTITHREAD
703 struct sockaddr_in iosin;
704 unsigned char buf[4096];
713 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
714 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
715 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
717 static void *iax2_process_thread(void *data);
719 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
721 ast_mutex_lock(lock);
722 ast_cond_signal(cond);
723 ast_mutex_unlock(lock);
726 static void iax_debug_output(const char *data)
729 ast_verbose("%s", data);
732 static void iax_error_output(const char *data)
734 ast_log(LOG_WARNING, "%s", data);
737 static void jb_error_output(const char *fmt, ...)
743 vsnprintf(buf, 1024, fmt, args);
746 ast_log(LOG_ERROR, buf);
749 static void jb_warning_output(const char *fmt, ...)
755 vsnprintf(buf, 1024, fmt, args);
758 ast_log(LOG_WARNING, buf);
761 static void jb_debug_output(const char *fmt, ...)
767 vsnprintf(buf, 1024, fmt, args);
773 /* XXX We probably should use a mutex when working with this XXX */
774 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
775 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
776 static struct timeval lastused[IAX_MAX_CALLS];
778 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);
779 static int expire_registry(void *data);
780 static int iax2_answer(struct ast_channel *c);
781 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
782 static int iax2_devicestate(void *data);
783 static int iax2_digit_begin(struct ast_channel *c, char digit);
784 static int iax2_digit_end(struct ast_channel *c, char digit);
785 static int iax2_do_register(struct iax2_registry *reg);
786 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
787 static int iax2_hangup(struct ast_channel *c);
788 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
789 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
790 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
791 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
792 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
793 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
794 static int iax2_sendtext(struct ast_channel *c, const char *text);
795 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
796 static int iax2_transfer(struct ast_channel *c, const char *dest);
797 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
798 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
799 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
800 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
801 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
802 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
803 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
804 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
805 static struct ast_frame *iax2_read(struct ast_channel *c);
806 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
807 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
808 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
809 static void destroy_user(struct iax2_user *user);
810 static void prune_peers(void);
812 static const struct ast_channel_tech iax2_tech = {
814 .description = tdesc,
815 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
816 .properties = AST_CHAN_TP_WANTSJITTER,
817 .requester = iax2_request,
818 .devicestate = iax2_devicestate,
819 .send_digit_begin = iax2_digit_begin,
820 .send_digit_end = iax2_digit_end,
821 .send_text = iax2_sendtext,
822 .send_image = iax2_sendimage,
823 .send_html = iax2_sendhtml,
825 .hangup = iax2_hangup,
826 .answer = iax2_answer,
829 .write_video = iax2_write,
830 .indicate = iax2_indicate,
831 .setoption = iax2_setoption,
832 .bridge = iax2_bridge,
833 .transfer = iax2_transfer,
837 static struct iax2_thread *find_idle_thread(void)
839 struct iax2_thread *thread = NULL;
841 /* Pop the head of the list off */
842 AST_LIST_LOCK(&idle_list);
843 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
844 AST_LIST_UNLOCK(&idle_list);
846 /* If no idle thread is available from the regular list, try dynamic */
847 if (thread == NULL) {
848 AST_LIST_LOCK(&dynamic_list);
849 thread = AST_LIST_FIRST(&dynamic_list);
850 if (thread != NULL) {
851 AST_LIST_REMOVE(&dynamic_list, thread, list);
853 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
854 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
855 /* We need to MAKE a thread! */
856 thread = ast_calloc(1, sizeof(*thread));
857 if (thread != NULL) {
858 thread->threadnum = iaxdynamicthreadcount;
859 thread->type = IAX_TYPE_DYNAMIC;
860 ast_mutex_init(&thread->lock);
861 ast_cond_init(&thread->cond, NULL);
862 if (ast_pthread_create(&thread->threadid, NULL, iax2_process_thread, thread)) {
866 /* All went well and the thread is up, so increment our count */
867 iaxdynamicthreadcount++;
871 AST_LIST_UNLOCK(&dynamic_list);
877 #ifdef SCHED_MULTITHREADED
878 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
880 struct iax2_thread *thread = NULL;
881 static time_t lasterror;
884 thread = find_idle_thread();
886 if (thread != NULL) {
887 thread->schedfunc = func;
888 thread->scheddata = data;
889 thread->iostate = IAX_IOSTATE_SCHEDREADY;
890 #ifdef DEBUG_SCHED_MULTITHREAD
891 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
893 signal_condition(&thread->lock, &thread->cond);
898 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
903 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
906 static void __send_ping(void *data)
908 int callno = (long)data;
909 send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
912 static int send_ping(void *data)
914 int callno = (long)data;
916 #ifdef SCHED_MULTITHREADED
917 if (schedule_action(__send_ping, data))
926 static int get_encrypt_methods(const char *s)
929 if (!strcasecmp(s, "aes128"))
930 e = IAX_ENCRYPT_AES128;
931 else if (ast_true(s))
932 e = IAX_ENCRYPT_AES128;
938 static void __send_lagrq(void *data)
940 int callno = (long)data;
941 /* Ping only if it's real not if it's bridged */
942 send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
945 static int send_lagrq(void *data)
947 int callno = (long)data;
949 #ifdef SCHED_MULTITHREADED
950 if (schedule_action(__send_lagrq, data))
959 static unsigned char compress_subclass(int subclass)
963 /* If it's 128 or smaller, just return it */
964 if (subclass < IAX_FLAG_SC_LOG)
966 /* Otherwise find its power */
967 for (x = 0; x < IAX_MAX_SHIFT; x++) {
968 if (subclass & (1 << x)) {
970 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
976 return power | IAX_FLAG_SC_LOG;
979 static int uncompress_subclass(unsigned char csub)
981 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
982 if (csub & IAX_FLAG_SC_LOG) {
983 /* special case for 'compressed' -1 */
987 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
993 static struct iax2_peer *find_peer(const char *name, int realtime)
995 struct iax2_peer *peer = NULL;
997 /* Grab peer from linked list */
998 AST_LIST_LOCK(&peers);
999 AST_LIST_TRAVERSE(&peers, peer, entry) {
1000 if (!strcasecmp(peer->name, name)) {
1004 AST_LIST_UNLOCK(&peers);
1006 /* Now go for realtime if applicable */
1007 if(!peer && realtime)
1008 peer = realtime_peer(name, NULL);
1012 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1014 struct iax2_peer *peer = NULL;
1018 AST_LIST_LOCK(&peers);
1019 AST_LIST_TRAVERSE(&peers, peer, entry) {
1020 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1021 (peer->addr.sin_port == sin.sin_port)) {
1022 ast_copy_string(host, peer->name, len);
1028 AST_LIST_UNLOCK(&peers);
1030 peer = realtime_peer(NULL, &sin);
1032 ast_copy_string(host, peer->name, len);
1033 if (ast_test_flag(peer, IAX_TEMPONLY))
1042 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1044 struct chan_iax2_pvt *tmp;
1047 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1050 if (ast_string_field_init(tmp, 32)) {
1058 tmp->peercallno = 0;
1059 tmp->transfercallno = 0;
1060 tmp->bridgecallno = 0;
1067 ast_string_field_set(tmp,exten, "s");
1068 ast_string_field_set(tmp,host, host);
1072 jbconf.max_jitterbuf = maxjitterbuffer;
1073 jbconf.resync_threshold = resyncthreshold;
1074 jbconf.max_contig_interp = maxjitterinterps;
1075 jb_setconf(tmp->jb,&jbconf);
1077 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1082 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1084 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen);
1086 size_t mallocd_datalen = new->mallocd_datalen;
1087 memcpy(new, fr, sizeof(*new));
1088 iax_frame_wrap(new, &fr->af);
1089 new->mallocd_datalen = mallocd_datalen;
1092 new->direction = DIRECTION_INGRESS;
1098 #define NEW_PREVENT 0
1102 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1104 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1105 (cur->addr.sin_port == sin->sin_port)) {
1106 /* This is the main host */
1107 if ((cur->peercallno == callno) ||
1108 ((dcallno == cur->callno) && !cur->peercallno)) {
1109 /* That's us. Be sure we keep track of the peer call number */
1113 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1114 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1115 /* We're transferring */
1116 if (dcallno == cur->callno)
1122 static void update_max_trunk(void)
1124 int max = TRUNK_CALL_START;
1126 /* XXX Prolly don't need locks here XXX */
1127 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1132 if (option_debug && iaxdebug)
1133 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1136 static void update_max_nontrunk(void)
1140 /* XXX Prolly don't need locks here XXX */
1141 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1145 maxnontrunkcall = max;
1146 if (option_debug && iaxdebug)
1147 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1150 static int make_trunk(unsigned short callno, int locked)
1155 if (iaxs[callno]->oseqno) {
1156 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1159 if (callno & TRUNK_CALL_START) {
1160 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1163 gettimeofday(&now, NULL);
1164 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1165 ast_mutex_lock(&iaxsl[x]);
1166 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1167 iaxs[x] = iaxs[callno];
1168 iaxs[x]->callno = x;
1169 iaxs[callno] = NULL;
1170 /* Update the two timers that should have been started */
1171 if (iaxs[x]->pingid > -1)
1172 ast_sched_del(sched, iaxs[x]->pingid);
1173 if (iaxs[x]->lagid > -1)
1174 ast_sched_del(sched, iaxs[x]->lagid);
1175 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1176 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1178 ast_mutex_unlock(&iaxsl[callno]);
1181 ast_mutex_unlock(&iaxsl[x]);
1184 ast_mutex_unlock(&iaxsl[x]);
1186 if (x >= IAX_MAX_CALLS - 1) {
1187 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1191 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1192 /* We move this call from a non-trunked to a trunked call */
1194 update_max_nontrunk();
1198 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1204 if (new <= NEW_ALLOW) {
1205 /* Look for an existing connection first */
1206 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1207 ast_mutex_lock(&iaxsl[x]);
1209 /* Look for an exact match */
1210 if (match(sin, callno, dcallno, iaxs[x])) {
1214 ast_mutex_unlock(&iaxsl[x]);
1216 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1217 ast_mutex_lock(&iaxsl[x]);
1219 /* Look for an exact match */
1220 if (match(sin, callno, dcallno, iaxs[x])) {
1224 ast_mutex_unlock(&iaxsl[x]);
1227 if ((res < 1) && (new >= NEW_ALLOW)) {
1228 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1229 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1230 gettimeofday(&now, NULL);
1231 for (x=1;x<TRUNK_CALL_START;x++) {
1232 /* Find first unused call number that hasn't been used in a while */
1233 ast_mutex_lock(&iaxsl[x]);
1234 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1235 ast_mutex_unlock(&iaxsl[x]);
1237 /* We've still got lock held if we found a spot */
1238 if (x >= TRUNK_CALL_START) {
1239 ast_log(LOG_WARNING, "No more space\n");
1242 iaxs[x] = new_iax(sin, lockpeer, host);
1243 update_max_nontrunk();
1245 if (option_debug && iaxdebug)
1246 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1247 iaxs[x]->sockfd = sockfd;
1248 iaxs[x]->addr.sin_port = sin->sin_port;
1249 iaxs[x]->addr.sin_family = sin->sin_family;
1250 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1251 iaxs[x]->peercallno = callno;
1252 iaxs[x]->callno = x;
1253 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1254 iaxs[x]->expiry = min_reg_expire;
1255 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1256 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1257 iaxs[x]->amaflags = amaflags;
1258 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1260 ast_string_field_set(iaxs[x], accountcode, accountcode);
1261 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1262 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1264 ast_log(LOG_WARNING, "Out of resources\n");
1265 ast_mutex_unlock(&iaxsl[x]);
1268 ast_mutex_unlock(&iaxsl[x]);
1274 static void iax2_frame_free(struct iax_frame *fr)
1276 if (fr->retrans > -1)
1277 ast_sched_del(sched, fr->retrans);
1281 static int iax2_queue_frame(int callno, struct ast_frame *f)
1283 /* Assumes lock for callno is already held... */
1285 if (iaxs[callno] && iaxs[callno]->owner) {
1286 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1287 /* Avoid deadlock by pausing and trying again */
1288 ast_mutex_unlock(&iaxsl[callno]);
1290 ast_mutex_lock(&iaxsl[callno]);
1292 ast_queue_frame(iaxs[callno]->owner, f);
1293 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1302 static void destroy_firmware(struct iax_firmware *cur)
1304 /* Close firmware */
1306 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1312 static int try_firmware(char *s)
1315 struct iax_firmware *cur = NULL;
1316 int ifd, fd, res, len, chunk;
1317 struct ast_iax2_firmware_header *fwh, fwh2;
1318 struct MD5Context md5;
1319 unsigned char sum[16], buf[1024];
1322 if (!(s2 = alloca(strlen(s) + 100))) {
1323 ast_log(LOG_WARNING, "Alloca failed!\n");
1327 last = strrchr(s, '/');
1333 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1335 if ((res = stat(s, &stbuf) < 0)) {
1336 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1340 /* Make sure it's not a directory */
1341 if (S_ISDIR(stbuf.st_mode))
1343 ifd = open(s, O_RDONLY);
1345 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1348 fd = open(s2, O_RDWR | O_CREAT | O_EXCL);
1350 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1354 /* Unlink our newly created file */
1357 /* Now copy the firmware into it */
1358 len = stbuf.st_size;
1361 if (chunk > sizeof(buf))
1362 chunk = sizeof(buf);
1363 res = read(ifd, buf, chunk);
1365 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1370 res = write(fd, buf, chunk);
1372 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1380 /* Return to the beginning */
1381 lseek(fd, 0, SEEK_SET);
1382 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1383 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1387 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1388 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1392 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1393 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1397 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1398 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1402 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1404 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1409 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1410 MD5Final(sum, &md5);
1411 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1412 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1413 munmap(fwh, stbuf.st_size);
1418 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1419 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1420 /* Found a candidate */
1421 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1422 /* The version we have on loaded is older, load this one instead */
1424 /* This version is no newer than what we have. Don't worry about it.
1425 We'll consider it a proper load anyhow though */
1426 munmap(fwh, stbuf.st_size);
1432 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1434 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1439 munmap(cur->fwh, cur->mmaplen);
1444 cur->mmaplen = stbuf.st_size;
1451 static int iax_check_version(char *dev)
1454 struct iax_firmware *cur = NULL;
1456 if (ast_strlen_zero(dev))
1459 AST_LIST_LOCK(&firmwares);
1460 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1461 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1462 res = ntohs(cur->fwh->version);
1466 AST_LIST_UNLOCK(&firmwares);
1471 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1474 unsigned int bs = desc & 0xff;
1475 unsigned int start = (desc >> 8) & 0xffffff;
1477 struct iax_firmware *cur;
1479 if (ast_strlen_zero((char *)dev) || !bs)
1484 AST_LIST_LOCK(&firmwares);
1485 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1486 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1488 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1489 if (start < ntohl(cur->fwh->datalen)) {
1490 bytes = ntohl(cur->fwh->datalen) - start;
1493 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1496 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1504 AST_LIST_UNLOCK(&firmwares);
1510 static void reload_firmware(void)
1512 struct iax_firmware *cur = NULL;
1515 char dir[256], fn[256];
1517 AST_LIST_LOCK(&firmwares);
1519 /* Mark all as dead */
1520 AST_LIST_TRAVERSE(&firmwares, cur, list)
1523 /* Now that we have marked them dead... load new ones */
1524 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1527 while((de = readdir(fwd))) {
1528 if (de->d_name[0] != '.') {
1529 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1530 if (!try_firmware(fn)) {
1531 if (option_verbose > 1)
1532 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1538 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1540 /* Clean up leftovers */
1541 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1544 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1545 destroy_firmware(cur);
1547 AST_LIST_TRAVERSE_SAFE_END
1549 AST_LIST_UNLOCK(&firmwares);
1552 static int __do_deliver(void *data)
1554 /* Just deliver the packet by using queueing. This is called by
1555 the IAX thread with the iaxsl lock held. */
1556 struct iax_frame *fr = data;
1558 fr->af.has_timing_info = 0;
1559 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1560 iax2_queue_frame(fr->callno, &fr->af);
1561 /* Free our iax frame */
1562 iax2_frame_free(fr);
1563 /* And don't run again */
1567 static int handle_error(void)
1569 /* XXX Ideally we should figure out why an error occured and then abort those
1570 rather than continuing to try. Unfortunately, the published interface does
1571 not seem to work XXX */
1573 struct sockaddr_in *sin;
1576 struct sock_extended_err e;
1581 m.msg_controllen = sizeof(e);
1583 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1585 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1587 if (m.msg_controllen) {
1588 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1590 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1592 ast_log(LOG_WARNING, "No address detected??\n");
1594 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1601 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1604 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1608 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1615 static int send_packet(struct iax_frame *f)
1618 int callno = f->callno;
1620 /* Don't send if there was an error, but return error instead */
1621 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1624 /* Called with iaxsl held */
1625 if (option_debug > 2 && iaxdebug)
1626 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1629 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1630 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1631 sizeof(iaxs[callno]->transfer));
1634 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1635 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1636 sizeof(iaxs[callno]->addr));
1639 if (option_debug && iaxdebug)
1640 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1647 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1649 struct iax2_user *user = NULL;
1651 /* Decrement AUTHREQ count if needed */
1652 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1653 AST_LIST_LOCK(&users);
1654 AST_LIST_TRAVERSE(&users, user, entry) {
1655 if (!strcmp(user->name, pvt->username)) {
1660 AST_LIST_UNLOCK(&users);
1661 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1663 /* No more pings or lagrq's */
1664 if (pvt->pingid > -1)
1665 ast_sched_del(sched, pvt->pingid);
1667 if (pvt->lagid > -1)
1668 ast_sched_del(sched, pvt->lagid);
1670 if (pvt->autoid > -1)
1671 ast_sched_del(sched, pvt->autoid);
1673 if (pvt->authid > -1)
1674 ast_sched_del(sched, pvt->authid);
1676 if (pvt->initid > -1)
1677 ast_sched_del(sched, pvt->initid);
1680 ast_sched_del(sched, pvt->jbid);
1684 static int iax2_predestroy(int callno)
1686 struct ast_channel *c = NULL;
1687 struct chan_iax2_pvt *pvt = iaxs[callno];
1692 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1693 iax2_destroy_helper(pvt);
1694 ast_set_flag(pvt, IAX_ALREADYGONE);
1697 if ((c = pvt->owner)) {
1698 c->_softhangup |= AST_SOFTHANGUP_DEV;
1700 ast_queue_hangup(c);
1707 static void iax2_destroy(int callno)
1709 struct chan_iax2_pvt *pvt = NULL;
1710 struct iax_frame *cur = NULL;
1711 struct ast_channel *owner = NULL;
1715 gettimeofday(&lastused[callno], NULL);
1717 owner = pvt ? pvt->owner : NULL;
1720 if (ast_mutex_trylock(&owner->lock)) {
1721 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1722 ast_mutex_unlock(&iaxsl[callno]);
1724 ast_mutex_lock(&iaxsl[callno]);
1729 iaxs[callno] = NULL;
1733 iax2_destroy_helper(pvt);
1736 ast_set_flag(pvt, IAX_ALREADYGONE);
1739 /* If there's an owner, prod it to give up */
1740 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1741 ast_queue_hangup(owner);
1744 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1745 /* Cancel any pending transmissions */
1746 if (cur->callno == pvt->callno)
1750 pvt->reg->callno = 0;
1754 ast_variables_destroy(pvt->vars);
1758 while (jb_getall(pvt->jb, &frame) == JB_OK)
1759 iax2_frame_free(frame.data);
1760 jb_destroy(pvt->jb);
1761 /* gotta free up the stringfields */
1762 ast_string_field_free_pools(pvt);
1767 ast_mutex_unlock(&owner->lock);
1769 if (callno & 0x4000)
1773 static int update_packet(struct iax_frame *f)
1775 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1776 struct ast_iax2_full_hdr *fh = f->data;
1777 /* Mark this as a retransmission */
1778 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1780 f->iseqno = iaxs[f->callno]->iseqno;
1781 fh->iseqno = f->iseqno;
1785 static int attempt_transmit(void *data);
1786 static void __attempt_transmit(void *data)
1788 /* Attempt to transmit the frame to the remote peer...
1789 Called without iaxsl held. */
1790 struct iax_frame *f = data;
1792 int callno = f->callno;
1793 /* Make sure this call is still active */
1795 ast_mutex_lock(&iaxsl[callno]);
1796 if (callno && iaxs[callno]) {
1797 if ((f->retries < 0) /* Already ACK'd */ ||
1798 (f->retries >= max_retries) /* Too many attempts */) {
1799 /* Record an error if we've transmitted too many times */
1800 if (f->retries >= max_retries) {
1802 /* Transfer timeout */
1803 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1804 } else if (f->final) {
1806 iax2_destroy(callno);
1808 if (iaxs[callno]->owner)
1809 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);
1810 iaxs[callno]->error = ETIMEDOUT;
1811 if (iaxs[callno]->owner) {
1812 struct ast_frame fr = { 0, };
1814 fr.frametype = AST_FRAME_CONTROL;
1815 fr.subclass = AST_CONTROL_HANGUP;
1816 iax2_queue_frame(callno, &fr);
1817 /* Remember, owner could disappear */
1818 if (iaxs[callno]->owner)
1819 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1821 if (iaxs[callno]->reg) {
1822 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1823 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1824 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1826 iax2_destroy(callno);
1833 /* Update it if it needs it */
1835 /* Attempt transmission */
1838 /* Try again later after 10 times as long */
1840 if (f->retrytime > MAX_RETRY_TIME)
1841 f->retrytime = MAX_RETRY_TIME;
1842 /* Transfer messages max out at one second */
1843 if (f->transfer && (f->retrytime > 1000))
1844 f->retrytime = 1000;
1845 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1848 /* Make sure it gets freed */
1853 ast_mutex_unlock(&iaxsl[callno]);
1854 /* Do not try again */
1856 /* Don't attempt delivery, just remove it from the queue */
1857 AST_LIST_LOCK(&iaxq.queue);
1858 AST_LIST_REMOVE(&iaxq.queue, f, list);
1860 AST_LIST_UNLOCK(&iaxq.queue);
1862 /* Free the IAX frame */
1867 static int attempt_transmit(void *data)
1869 #ifdef SCHED_MULTITHREADED
1870 if (schedule_action(__attempt_transmit, data))
1872 __attempt_transmit(data);
1876 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1878 struct iax2_peer *peer;
1881 return RESULT_SHOWUSAGE;
1882 if (!strcmp(argv[3],"all")) {
1884 ast_cli(fd, "OK cache is flushed.\n");
1885 } else if ((peer = find_peer(argv[3], 0))) {
1886 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1887 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1888 expire_registry((void*)peer->name);
1889 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1891 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
1894 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
1897 return RESULT_SUCCESS;
1900 static int iax2_test_losspct(int fd, int argc, char *argv[])
1903 return RESULT_SHOWUSAGE;
1905 test_losspct = atoi(argv[3]);
1907 return RESULT_SUCCESS;
1911 static int iax2_test_late(int fd, int argc, char *argv[])
1914 return RESULT_SHOWUSAGE;
1916 test_late = atoi(argv[3]);
1918 return RESULT_SUCCESS;
1921 static int iax2_test_resync(int fd, int argc, char *argv[])
1924 return RESULT_SHOWUSAGE;
1926 test_resync = atoi(argv[3]);
1928 return RESULT_SUCCESS;
1931 static int iax2_test_jitter(int fd, int argc, char *argv[])
1933 if (argc < 4 || argc > 5)
1934 return RESULT_SHOWUSAGE;
1936 test_jit = atoi(argv[3]);
1938 test_jitpct = atoi(argv[4]);
1940 return RESULT_SUCCESS;
1942 #endif /* IAXTESTS */
1944 /*! \brief peer_status: Report Peer status in character string */
1945 /* returns 1 if peer is online, -1 if unmonitored */
1946 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
1950 if (peer->lastms < 0) {
1951 ast_copy_string(status, "UNREACHABLE", statuslen);
1952 } else if (peer->lastms > peer->maxms) {
1953 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
1955 } else if (peer->lastms) {
1956 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
1959 ast_copy_string(status, "UNKNOWN", statuslen);
1962 ast_copy_string(status, "Unmonitored", statuslen);
1968 /*! \brief Show one peer in detail */
1969 static int iax2_show_peer(int fd, int argc, char *argv[])
1973 struct iax2_peer *peer;
1974 char codec_buf[512];
1975 int x = 0, codec = 0, load_realtime = 0;
1978 return RESULT_SHOWUSAGE;
1980 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
1982 peer = find_peer(argv[3], load_realtime);
1985 ast_cli(fd, " * Name : %s\n", peer->name);
1986 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
1987 ast_cli(fd, " Context : %s\n", peer->context);
1988 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
1989 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
1990 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
1991 ast_cli(fd, " Expire : %d\n", peer->expire);
1992 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
1993 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
1994 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
1995 ast_cli(fd, " Username : %s\n", peer->username);
1996 ast_cli(fd, " Codecs : ");
1997 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
1998 ast_cli(fd, "%s\n", codec_buf);
2000 ast_cli(fd, " Codec Order : (");
2001 for(x = 0; x < 32 ; x++) {
2002 codec = ast_codec_pref_index(&peer->prefs,x);
2005 ast_cli(fd, "%s", ast_getformatname(codec));
2006 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2011 ast_cli(fd, "none");
2014 ast_cli(fd, " Status : ");
2015 peer_status(peer, status, sizeof(status));
2016 ast_cli(fd, "%s\n",status);
2017 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2019 if (ast_test_flag(peer, IAX_TEMPONLY))
2022 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2026 return RESULT_SUCCESS;
2029 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2032 struct iax2_peer *p = NULL;
2034 int wordlen = strlen(word);
2036 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2038 AST_LIST_LOCK(&peers);
2039 AST_LIST_TRAVERSE(&peers, p, entry) {
2040 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2041 res = ast_strdup(p->name);
2045 AST_LIST_UNLOCK(&peers);
2051 static int iax2_show_stats(int fd, int argc, char *argv[])
2053 struct iax_frame *cur;
2054 int cnt = 0, dead=0, final=0;
2056 return RESULT_SHOWUSAGE;
2057 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2058 if (cur->retries < 0)
2064 ast_cli(fd, " IAX Statistics\n");
2065 ast_cli(fd, "---------------------\n");
2066 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2067 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2068 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2070 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2072 trunk_timed = trunk_untimed = 0;
2073 if (trunk_maxmtu > trunk_nmaxmtu)
2074 trunk_nmaxmtu = trunk_maxmtu;
2076 return RESULT_SUCCESS;
2079 /*! \brief Set trunk MTU from CLI */
2080 static int iax2_set_mtu(int fd, int argc, char *argv[])
2085 return RESULT_SHOWUSAGE;
2086 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0)
2087 mtuv = MAX_TRUNK_MTU;
2089 mtuv = atoi(argv[3]);
2092 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2093 global_max_trunk_mtu = 0;
2094 return RESULT_SUCCESS;
2096 if (mtuv < 172 || mtuv > 4000) {
2097 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n");
2098 return RESULT_SHOWUSAGE;
2100 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2101 global_max_trunk_mtu = mtuv;
2102 return RESULT_SUCCESS;
2105 static int iax2_show_cache(int fd, int argc, char *argv[])
2107 struct iax2_dpcache *dp = NULL;
2108 char tmp[1024], *pc = NULL;
2112 gettimeofday(&tv, NULL);
2114 AST_LIST_LOCK(&dpcache);
2116 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2118 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2119 s = dp->expiry.tv_sec - tv.tv_sec;
2121 if (dp->flags & CACHE_FLAG_EXISTS)
2122 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2123 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2124 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2125 if (dp->flags & CACHE_FLAG_CANEXIST)
2126 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2127 if (dp->flags & CACHE_FLAG_PENDING)
2128 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2129 if (dp->flags & CACHE_FLAG_TIMEOUT)
2130 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2131 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2132 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2133 if (dp->flags & CACHE_FLAG_MATCHMORE)
2134 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2135 if (dp->flags & CACHE_FLAG_UNKNOWN)
2136 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2137 /* Trim trailing pipe */
2138 if (!ast_strlen_zero(tmp))
2139 tmp[strlen(tmp) - 1] = '\0';
2141 ast_copy_string(tmp, "(none)", sizeof(tmp));
2143 pc = strchr(dp->peercontext, '@');
2145 pc = dp->peercontext;
2148 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2149 if (dp->waiters[x] > -1)
2152 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2154 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2157 AST_LIST_LOCK(&dpcache);
2159 return RESULT_SUCCESS;
2162 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2164 static void unwrap_timestamp(struct iax_frame *fr)
2168 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2169 x = fr->ts - iaxs[fr->callno]->last;
2171 /* Sudden big jump backwards in timestamp:
2172 What likely happened here is that miniframe timestamp has circled but we haven't
2173 gotten the update from the main packet. We'll just pretend that we did, and
2174 update the timestamp appropriately. */
2175 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2176 if (option_debug && iaxdebug)
2177 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2180 /* Sudden apparent big jump forwards in timestamp:
2181 What's likely happened is this is an old miniframe belonging to the previous
2182 top-16-bit timestamp that has turned up out of order.
2183 Adjust the timestamp appropriately. */
2184 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2185 if (option_debug && iaxdebug)
2186 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2191 static int get_from_jb(void *p);
2193 static void update_jbsched(struct chan_iax2_pvt *pvt)
2197 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2199 when = jb_next(pvt->jb) - when;
2201 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2204 /* XXX should really just empty until when > 0.. */
2208 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2210 /* Signal scheduler thread */
2211 signal_condition(&sched_lock, &sched_cond);
2214 static void __get_from_jb(void *p)
2216 int callno = PTR_TO_CALLNO(p);
2217 struct chan_iax2_pvt *pvt = NULL;
2218 struct iax_frame *fr;
2225 /* Make sure we have a valid private structure before going on */
2226 ast_mutex_lock(&iaxsl[callno]);
2230 ast_mutex_unlock(&iaxsl[callno]);
2236 gettimeofday(&tv,NULL);
2237 /* round up a millisecond since ast_sched_runq does; */
2238 /* prevents us from spinning while waiting for our now */
2239 /* to catch up with runq's now */
2242 now = ast_tvdiff_ms(tv, pvt->rxcore);
2244 if(now >= (next = jb_next(pvt->jb))) {
2245 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2253 struct ast_frame af;
2255 /* create an interpolation frame */
2256 af.frametype = AST_FRAME_VOICE;
2257 af.subclass = pvt->voiceformat;
2259 af.samples = frame.ms * 8;
2261 af.src = "IAX2 JB interpolation";
2263 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2264 af.offset=AST_FRIENDLY_OFFSET;
2266 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2267 * which we'd need to malloc, and then it would free it. That seems like a drag */
2268 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2269 iax2_queue_frame(callno, &af);
2273 iax2_frame_free(frame.data);
2280 /* shouldn't happen */
2284 update_jbsched(pvt);
2285 ast_mutex_unlock(&iaxsl[callno]);
2288 static int get_from_jb(void *data)
2290 #ifdef SCHED_MULTITHREADED
2291 if (schedule_action(__get_from_jb, data))
2293 __get_from_jb(data);
2297 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2303 /* Attempt to recover wrapped timestamps */
2304 unwrap_timestamp(fr);
2307 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2308 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2309 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2313 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2315 fr->af.delivery = ast_tv(0,0);
2318 type = JB_TYPE_CONTROL;
2321 if(fr->af.frametype == AST_FRAME_VOICE) {
2322 type = JB_TYPE_VOICE;
2323 len = ast_codec_get_samples(&fr->af) / 8;
2324 } else if(fr->af.frametype == AST_FRAME_CNG) {
2325 type = JB_TYPE_SILENCE;
2328 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2335 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2336 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2337 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2338 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2339 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2342 /* deliver any frames in the jb */
2343 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2344 __do_deliver(frame.data);
2346 jb_reset(iaxs[fr->callno]->jb);
2348 if (iaxs[fr->callno]->jbid > -1)
2349 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2351 iaxs[fr->callno]->jbid = -1;
2353 /* deliver this frame now */
2360 /* insert into jitterbuffer */
2361 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2362 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2363 calc_rxstamp(iaxs[fr->callno],fr->ts));
2364 if (ret == JB_DROP) {
2366 } else if (ret == JB_SCHED) {
2367 update_jbsched(iaxs[fr->callno]);
2372 /* Free our iax frame */
2373 iax2_frame_free(fr);
2379 static int iax2_transmit(struct iax_frame *fr)
2381 /* Lock the queue and place this packet at the end */
2382 /* By setting this to 0, the network thread will send it for us, and
2383 queue retransmission if necessary */
2385 AST_LIST_LOCK(&iaxq.queue);
2386 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2388 AST_LIST_UNLOCK(&iaxq.queue);
2389 /* Wake up the network and scheduler thread */
2390 pthread_kill(netthreadid, SIGURG);
2391 signal_condition(&sched_lock, &sched_cond);
2397 static int iax2_digit_begin(struct ast_channel *c, char digit)
2399 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2402 static int iax2_digit_end(struct ast_channel *c, char digit)
2404 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2407 static int iax2_sendtext(struct ast_channel *c, const char *text)
2410 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2411 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2414 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2416 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2419 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2421 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2424 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2426 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2427 ast_mutex_lock(&iaxsl[callno]);
2429 iaxs[callno]->owner = newchan;
2431 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2432 ast_mutex_unlock(&iaxsl[callno]);
2436 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2438 struct ast_variable *var;
2439 struct ast_variable *tmp;
2440 struct iax2_peer *peer=NULL;
2441 time_t regseconds = 0, nowtime;
2445 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2448 sprintf(porta, "%d", ntohs(sin->sin_port));
2449 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2451 /* We'll need the peer name in order to build the structure! */
2452 for (tmp = var; tmp; tmp = tmp->next) {
2453 if (!strcasecmp(tmp->name, "name"))
2454 peername = tmp->value;
2461 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2466 for (tmp = var; tmp; tmp = tmp->next) {
2467 /* Make sure it's not a user only... */
2468 if (!strcasecmp(tmp->name, "type")) {
2469 if (strcasecmp(tmp->value, "friend") &&
2470 strcasecmp(tmp->value, "peer")) {
2471 /* Whoops, we weren't supposed to exist! */
2476 } else if (!strcasecmp(tmp->name, "regseconds")) {
2477 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2478 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2479 inet_aton(tmp->value, &(peer->addr.sin_addr));
2480 } else if (!strcasecmp(tmp->name, "port")) {
2481 peer->addr.sin_port = htons(atoi(tmp->value));
2482 } else if (!strcasecmp(tmp->name, "host")) {
2483 if (!strcasecmp(tmp->value, "dynamic"))
2490 ast_variables_destroy(var);
2492 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2493 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2494 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2495 if (peer->expire > -1)
2496 ast_sched_del(sched, peer->expire);
2497 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2499 AST_LIST_LOCK(&peers);
2500 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2501 AST_LIST_UNLOCK(&peers);
2502 if (ast_test_flag(peer, IAX_DYNAMIC))
2503 reg_source_db(peer);
2505 ast_set_flag(peer, IAX_TEMPONLY);
2508 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2510 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2511 memset(&peer->addr, 0, sizeof(peer->addr));
2512 realtime_update_peer(peer->name, &peer->addr, 0);
2514 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2515 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2519 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2520 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2527 static struct iax2_user *realtime_user(const char *username)
2529 struct ast_variable *var;
2530 struct ast_variable *tmp;
2531 struct iax2_user *user=NULL;
2533 var = ast_load_realtime("iaxusers", "name", username, NULL);
2539 /* Make sure it's not a peer only... */
2540 if (!strcasecmp(tmp->name, "type")) {
2541 if (strcasecmp(tmp->value, "friend") &&
2542 strcasecmp(tmp->value, "user")) {
2549 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2553 ast_variables_destroy(var);
2555 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2556 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2557 AST_LIST_LOCK(&users);
2558 AST_LIST_INSERT_HEAD(&users, user, entry);
2559 AST_LIST_UNLOCK(&users);
2561 ast_set_flag(user, IAX_TEMPONLY);
2567 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2570 char regseconds[20];
2572 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2573 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2574 ast_update_realtime("iaxpeers", "name", peername,
2575 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2576 "regseconds", regseconds, NULL);
2579 struct create_addr_info {
2592 char context[AST_MAX_CONTEXT];
2593 char peercontext[AST_MAX_CONTEXT];
2594 char mohinterpret[MAX_MUSICCLASS];
2595 char mohsuggest[MAX_MUSICCLASS];
2598 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2600 struct ast_hostent ahp;
2602 struct iax2_peer *peer;
2604 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2605 cai->sockfd = defaultsockfd;
2607 sin->sin_family = AF_INET;
2609 if (!(peer = find_peer(peername, 1))) {
2612 hp = ast_gethostbyname(peername, &ahp);
2614 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2615 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2616 /* use global iax prefs for unknown peer/user */
2617 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2620 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2627 /* if the peer has no address (current or default), return failure */
2628 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2629 if (ast_test_flag(peer, IAX_TEMPONLY))
2634 /* if the peer is being monitored and is currently unreachable, return failure */
2635 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2636 if (ast_test_flag(peer, IAX_TEMPONLY))
2641 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2642 cai->maxtime = peer->maxms;
2643 cai->capability = peer->capability;
2644 cai->encmethods = peer->encmethods;
2645 cai->sockfd = peer->sockfd;
2646 cai->adsi = peer->adsi;
2647 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2648 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2649 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2650 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2651 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2652 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2653 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2654 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2655 if (ast_strlen_zero(peer->dbsecret)) {
2656 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2661 family = ast_strdupa(peer->dbsecret);
2662 key = strchr(family, '/');
2665 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2666 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2667 if (ast_test_flag(peer, IAX_TEMPONLY))
2673 if (peer->addr.sin_addr.s_addr) {
2674 sin->sin_addr = peer->addr.sin_addr;
2675 sin->sin_port = peer->addr.sin_port;
2677 sin->sin_addr = peer->defaddr.sin_addr;
2678 sin->sin_port = peer->defaddr.sin_port;
2681 if (ast_test_flag(peer, IAX_TEMPONLY))
2687 static void __auto_congest(void *nothing)
2689 int callno = PTR_TO_CALLNO(nothing);
2690 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2691 ast_mutex_lock(&iaxsl[callno]);
2693 iaxs[callno]->initid = -1;
2694 iax2_queue_frame(callno, &f);
2695 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2697 ast_mutex_unlock(&iaxsl[callno]);
2700 static int auto_congest(void *data)
2702 #ifdef SCHED_MULTITHREADED
2703 if (schedule_action(__auto_congest, data))
2705 __auto_congest(data);
2709 static unsigned int iax2_datetime(const char *tz)
2715 localtime_r(&t, &tm);
2716 if (!ast_strlen_zero(tz))
2717 ast_localtime(&t, &tm, tz);
2718 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2719 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2720 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2721 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2722 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2723 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2727 struct parsed_dial_string {
2739 * \brief Parses an IAX dial string into its component parts.
2740 * \param data the string to be parsed
2741 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2744 * This function parses the string and fills the structure
2745 * with pointers to its component parts. The input string
2748 * \note This function supports both plaintext passwords and RSA
2749 * key names; if the password string is formatted as '[keyname]',
2750 * then the keyname will be placed into the key field, and the
2751 * password field will be set to NULL.
2753 * \note The dial string format is:
2754 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2756 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2758 if (ast_strlen_zero(data))
2761 pds->peer = strsep(&data, "/");
2762 pds->exten = strsep(&data, "/");
2763 pds->options = data;
2767 pds->exten = strsep(&data, "@");
2768 pds->context = data;
2771 if (strchr(pds->peer, '@')) {
2773 pds->username = strsep(&data, "@");
2777 if (pds->username) {
2778 data = pds->username;
2779 pds->username = strsep(&data, ":");
2780 pds->password = data;
2784 pds->peer = strsep(&data, ":");
2787 /* check for a key name wrapped in [] in the secret position, if found,
2788 move it to the key field instead
2790 if (pds->password && (pds->password[0] == '[')) {
2791 pds->key = ast_strip_quoted(pds->password, "[", "]");
2792 pds->password = NULL;
2796 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2798 struct sockaddr_in sin;
2799 char *l=NULL, *n=NULL, *tmpstr;
2800 struct iax_ie_data ied;
2801 char *defaultrdest = "s";
2802 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2803 struct parsed_dial_string pds;
2804 struct create_addr_info cai;
2806 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2807 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2811 memset(&cai, 0, sizeof(cai));
2812 cai.encmethods = iax2_encryption;
2814 memset(&pds, 0, sizeof(pds));
2815 tmpstr = ast_strdupa(dest);
2816 parse_dial_string(tmpstr, &pds);
2819 pds.exten = defaultrdest;
2821 if (create_addr(pds.peer, &sin, &cai)) {
2822 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2826 if (!pds.username && !ast_strlen_zero(cai.username))
2827 pds.username = cai.username;
2828 if (!pds.password && !ast_strlen_zero(cai.secret))
2829 pds.password = cai.secret;
2830 if (!pds.key && !ast_strlen_zero(cai.outkey))
2831 pds.key = cai.outkey;
2832 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2833 pds.context = cai.peercontext;
2835 /* Keep track of the context for outgoing calls too */
2836 ast_copy_string(c->context, cai.context, sizeof(c->context));
2839 sin.sin_port = htons(atoi(pds.port));
2842 n = c->cid.cid_name;
2844 /* Now build request */
2845 memset(&ied, 0, sizeof(ied));
2847 /* On new call, first IE MUST be IAX version of caller */
2848 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2849 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2850 if (pds.options && strchr(pds.options, 'a')) {
2851 /* Request auto answer */
2852 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2855 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2858 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2859 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2862 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2864 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2867 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2868 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2871 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2872 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2873 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2875 if (!ast_strlen_zero(c->language))
2876 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2877 if (!ast_strlen_zero(c->cid.cid_dnid))
2878 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2879 if (!ast_strlen_zero(c->cid.cid_rdnis))
2880 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2883 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2886 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
2889 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
2891 ast_mutex_lock(&iaxsl[callno]);
2893 if (!ast_strlen_zero(c->context))
2894 ast_string_field_set(iaxs[callno], context, c->context);
2897 ast_string_field_set(iaxs[callno], username, pds.username);
2899 iaxs[callno]->encmethods = cai.encmethods;
2901 iaxs[callno]->adsi = cai.adsi;
2903 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
2904 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
2907 ast_string_field_set(iaxs[callno], outkey, pds.key);
2909 ast_string_field_set(iaxs[callno], secret, pds.password);
2911 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
2912 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
2913 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
2914 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
2916 if (iaxs[callno]->maxtime) {
2917 /* Initialize pingtime and auto-congest time */
2918 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
2919 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
2920 } else if (autokill) {
2921 iaxs[callno]->pingtime = autokill / 2;
2922 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
2925 /* send the command using the appropriate socket for this peer */
2926 iaxs[callno]->sockfd = cai.sockfd;
2928 /* Transmit the string in a "NEW" request */
2929 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
2931 ast_mutex_unlock(&iaxsl[callno]);
2932 ast_setstate(c, AST_STATE_RINGING);
2937 static int iax2_hangup(struct ast_channel *c)
2939 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2941 struct iax_ie_data ied;
2942 memset(&ied, 0, sizeof(ied));
2943 ast_mutex_lock(&iaxsl[callno]);
2944 if (callno && iaxs[callno]) {
2946 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
2947 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
2948 /* Send the hangup unless we have had a transmission error or are already gone */
2949 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
2950 if (!iaxs[callno]->error && !alreadygone)
2951 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
2952 /* Explicitly predestroy it */
2953 iax2_predestroy(callno);
2954 /* If we were already gone to begin with, destroy us now */
2957 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
2958 iax2_destroy(callno);
2961 ast_mutex_unlock(&iaxsl[callno]);
2962 if (option_verbose > 2)
2963 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
2967 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
2969 struct ast_option_header *h;
2973 case AST_OPTION_TXGAIN:
2974 case AST_OPTION_RXGAIN:
2975 /* these two cannot be sent, because they require a result */
2979 if (!(h = ast_malloc(datalen + sizeof(*h))))
2982 h->flag = AST_OPTION_FLAG_REQUEST;
2983 h->option = htons(option);
2984 memcpy(h->data, data, datalen);
2985 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
2986 AST_CONTROL_OPTION, 0, (unsigned char *) h,
2987 datalen + sizeof(*h), -1);
2993 static struct ast_frame *iax2_read(struct ast_channel *c)
2995 ast_log(LOG_NOTICE, "I should never be called!\n");
2996 return &ast_null_frame;
2999 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3002 struct iax_ie_data ied0;
3003 struct iax_ie_data ied1;
3004 unsigned int transferid = (unsigned int)ast_random();
3005 memset(&ied0, 0, sizeof(ied0));
3006 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3007 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3008 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3010 memset(&ied1, 0, sizeof(ied1));
3011 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3012 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3013 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3015 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3018 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3021 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3022 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3026 static void lock_both(unsigned short callno0, unsigned short callno1)
3028 ast_mutex_lock(&iaxsl[callno0]);
3029 while (ast_mutex_trylock(&iaxsl[callno1])) {
3030 ast_mutex_unlock(&iaxsl[callno0]);
3032 ast_mutex_lock(&iaxsl[callno0]);
3036 static void unlock_both(unsigned short callno0, unsigned short callno1)
3038 ast_mutex_unlock(&iaxsl[callno1]);
3039 ast_mutex_unlock(&iaxsl[callno0]);
3042 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)
3044 struct ast_channel *cs[3];
3045 struct ast_channel *who, *other;
3048 int transferstarted=0;
3049 struct ast_frame *f;
3050 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3051 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3052 struct timeval waittimer = {0, 0}, tv;
3054 lock_both(callno0, callno1);
3055 /* Put them in native bridge mode */
3056 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3057 iaxs[callno0]->bridgecallno = callno1;
3058 iaxs[callno1]->bridgecallno = callno0;
3060 unlock_both(callno0, callno1);
3062 /* If not, try to bridge until we can execute a transfer, if we can */
3065 for (/* ever */;;) {
3066 /* Check in case we got masqueraded into */
3067 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3068 if (option_verbose > 2)
3069 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3070 /* Remove from native mode */
3071 if (c0->tech == &iax2_tech) {
3072 ast_mutex_lock(&iaxsl[callno0]);
3073 iaxs[callno0]->bridgecallno = 0;
3074 ast_mutex_unlock(&iaxsl[callno0]);
3076 if (c1->tech == &iax2_tech) {
3077 ast_mutex_lock(&iaxsl[callno1]);
3078 iaxs[callno1]->bridgecallno = 0;
3079 ast_mutex_unlock(&iaxsl[callno1]);
3081 return AST_BRIDGE_FAILED_NOWARN;
3083 if (c0->nativeformats != c1->nativeformats) {
3084 if (option_verbose > 2) {
3087 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3088 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3089 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3091 /* Remove from native mode */
3092 lock_both(callno0, callno1);
3093 iaxs[callno0]->bridgecallno = 0;
3094 iaxs[callno1]->bridgecallno = 0;
3095 unlock_both(callno0, callno1);
3096 return AST_BRIDGE_FAILED_NOWARN;
3098 /* check if transfered and if we really want native bridging */
3099 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3100 /* Try the transfer */
3101 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3102 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3103 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3104 transferstarted = 1;
3106 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3107 /* Call has been transferred. We're no longer involved */
3108 gettimeofday(&tv, NULL);
3109 if (ast_tvzero(waittimer)) {
3111 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3112 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3113 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3116 res = AST_BRIDGE_COMPLETE;
3121 who = ast_waitfor_n(cs, 2, &to);
3122 if (timeoutms > -1) {
3123 timeoutms -= (1000 - to);
3129 res = AST_BRIDGE_RETRY;
3132 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3133 res = AST_BRIDGE_FAILED;
3142 res = AST_BRIDGE_COMPLETE;
3145 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3148 res = AST_BRIDGE_COMPLETE;
3151 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3152 if ((f->frametype == AST_FRAME_VOICE) ||
3153 (f->frametype == AST_FRAME_TEXT) ||
3154 (f->frametype == AST_FRAME_VIDEO) ||
3155 (f->frametype == AST_FRAME_IMAGE) ||
3156 (f->frametype == AST_FRAME_DTMF)) {
3157 /* monitored dtmf take out of the bridge.
3158 * check if we monitor the specific source.
3160 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3161 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3164 res = AST_BRIDGE_COMPLETE;
3165 /* Remove from native mode */
3168 /* everything else goes to the other side */
3169 ast_write(other, f);
3172 /* Swap who gets priority */
3177 lock_both(callno0, callno1);
3179 iaxs[callno0]->bridgecallno = 0;
3181 iaxs[callno1]->bridgecallno = 0;
3182 unlock_both(callno0, callno1);
3186 static int iax2_answer(struct ast_channel *c)
3188 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3190 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3191 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3194 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
3196 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3198 if (option_debug && iaxdebug)
3199 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3201 if (!strcasecmp(iaxs[callno]->mohinterpret, "passthrough"))
3202 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3204 switch (condition) {
3205 case AST_CONTROL_HOLD:
3206 ast_moh_start(c, data, iaxs[callno]->mohinterpret);
3208 case AST_CONTROL_UNHOLD:
3212 return send_command_locked(callno, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3216 static int iax2_transfer(struct ast_channel *c, const char *dest)
3218 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3219 struct iax_ie_data ied;
3220 char tmp[256], *context;
3221 ast_copy_string(tmp, dest, sizeof(tmp));
3222 context = strchr(tmp, '@');
3227 memset(&ied, 0, sizeof(ied));
3228 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3230 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3232 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3233 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3236 static int iax2_getpeertrunk(struct sockaddr_in sin)
3238 struct iax2_peer *peer = NULL;
3241 AST_LIST_LOCK(&peers);
3242 AST_LIST_TRAVERSE(&peers, peer, entry) {
3243 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3244 (peer->addr.sin_port == sin.sin_port)) {
3245 res = ast_test_flag(peer, IAX_TRUNK);
3249 AST_LIST_UNLOCK(&peers);
3254 /*! \brief Create new call, interface with the PBX core */
3255 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3257 struct ast_channel *tmp;
3258 struct chan_iax2_pvt *i;
3259 struct ast_variable *v = NULL;
3261 if (!(i = iaxs[callno])) {
3262 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
3266 /* Don't hold call lock */
3267 ast_mutex_unlock(&iaxsl[callno]);
3268 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, "IAX2/%s-%d", i->host, i->callno);
3269 ast_mutex_lock(&iaxsl[callno]);
3272 tmp->tech = &iax2_tech;
3273 /* We can support any format by default, until we get restricted */
3274 tmp->nativeformats = capability;
3275 tmp->readformat = ast_best_codec(capability);
3276 tmp->writeformat = ast_best_codec(capability);
3277 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3279 /* Don't use ast_set_callerid() here because it will
3280 * generate a NewCallerID event before the NewChannel event */
3281 tmp->cid.cid_num = ast_strdup(i->cid_num);
3282 tmp->cid.cid_name = ast_strdup(i->cid_name);
3283 if (!ast_strlen_zero(i->ani))
3284 tmp->cid.cid_ani = ast_strdup(i->ani);
3286 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3287 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3288 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3289 tmp->cid.cid_pres = i->calling_pres;
3290 tmp->cid.cid_ton = i->calling_ton;
3291 tmp->cid.cid_tns = i->calling_tns;
3292 if (!ast_strlen_zero(i->language))
3293 ast_string_field_set(tmp, language, i->language);
3294 if (!ast_strlen_zero(i->accountcode))
3295 ast_string_field_set(tmp, accountcode, i->accountcode);
3297 tmp->amaflags = i->amaflags;
3298 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3299 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3301 tmp->adsicpe = i->peeradsicpe;
3303 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3305 i->capability = capability;
3306 if (state != AST_STATE_DOWN) {
3307 if (ast_pbx_start(tmp)) {
3308 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3315 for (v = i->vars ; v ; v = v->next)
3316 pbx_builtin_setvar_helper(tmp, v->name, v->value);
3321 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3323 unsigned long int mssincetx; /* unsigned to handle overflows */
3326 tpeer->trunkact = *tv;
3327 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3328 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3329 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3330 tpeer->txtrunktime = *tv;
3331 tpeer->lastsent = 999999;
3333 /* Update last transmit time now */
3334 tpeer->lasttxtime = *tv;
3336 /* Calculate ms offset */
3337 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3338 /* Predict from last value */
3339 pred = tpeer->lastsent + sampms;
3340 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3343 /* We never send the same timestamp twice, so fudge a little if we must */
3344 if (ms == tpeer->lastsent)
3345 ms = tpeer->lastsent + 1;
3346 tpeer->lastsent = ms;
3350 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3352 long ms; /* NOT unsigned */
3353 if (ast_tvzero(iaxs[callno]->rxcore)) {
3354 /* Initialize rxcore time if appropriate */
3355 gettimeofday(&iaxs[callno]->rxcore, NULL);
3356 /* Round to nearest 20ms so traces look pretty */
3357 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3359 /* Calculate difference between trunk and channel */
3360 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3361 /* Return as the sum of trunk time and the difference between trunk and real time */
3365 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3371 struct timeval *delivery = NULL;
3374 /* What sort of frame do we have?: voice is self-explanatory
3375 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3376 non-genuine frames are CONTROL frames [ringing etc], DTMF
3377 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3378 the others need a timestamp slaved to the voice frames so that they go in sequence
3381 if (f->frametype == AST_FRAME_VOICE) {
3383 delivery = &f->delivery;
3384 } else if (f->frametype == AST_FRAME_IAX) {
3386 } else if (f->frametype == AST_FRAME_CNG) {
3390 if (ast_tvzero(p->offset)) {
3391 gettimeofday(&p->offset, NULL);
3392 /* Round to nearest 20ms for nice looking traces */
3393 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3395 /* If the timestamp is specified, just send it as is */
3398 /* If we have a time that the frame arrived, always use it to make our timestamp */
3399 if (delivery && !ast_tvzero(*delivery)) {
3400 ms = ast_tvdiff_ms(*delivery, p->offset);
3401 if (option_debug > 2 && iaxdebug)
3402 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3404 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3408 /* On a voice frame, use predicted values if appropriate */
3409 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3410 /* Adjust our txcore, keeping voice and non-voice synchronized */
3412 When we send voice, we usually send "calculated" timestamps worked out
3413 on the basis of the number of samples sent. When we send other frames,
3414 we usually send timestamps worked out from the real clock.
3415 The problem is that they can tend to drift out of step because the
3416 source channel's clock and our clock may not be exactly at the same rate.
3417 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3418 for this call. Moving it adjusts timestamps for non-voice frames.
3419 We make the adjustment in the style of a moving average. Each time we
3420 adjust p->offset by 10% of the difference between our clock-derived
3421 timestamp and the predicted timestamp. That's why you see "10000"
3422 below even though IAX2 timestamps are in milliseconds.
3423 The use of a moving average avoids offset moving too radically.
3424 Generally, "adjust" roams back and forth around 0, with offset hardly
3425 changing at all. But if a consistent different starts to develop it
3426 will be eliminated over the course of 10 frames (200-300msecs)
3428 adjust = (ms - p->nextpred);
3430 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3431 else if (adjust > 0)
3432 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3435 p->nextpred = ms; /*f->samples / 8;*/
3436 if (p->nextpred <= p->lastsent)
3437 p->nextpred = p->lastsent + 3;
3441 /* in this case, just use the actual
3442 * time, since we're either way off
3443 * (shouldn't happen), or we're ending a
3444 * silent period -- and seed the next
3445 * predicted time. Also, round ms to the
3446 * next multiple of frame size (so our
3447 * silent periods are multiples of
3448 * frame size too) */
3450 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3451 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3452 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3454 if (f->samples >= 8) /* check to make sure we dont core dump */
3456 int diff = ms % (f->samples / 8);
3458 ms += f->samples/8 - diff;
3465 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3466 it's a genuine frame */
3468 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3469 if (ms <= p->lastsent)
3470 ms = p->lastsent + 3;
3471 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3472 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3473 ms = p->lastsent + 3;
3479 p->nextpred = p->nextpred + f->samples / 8;
3483 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3485 /* Returns where in "receive time" we are. That is, how many ms
3486 since we received (or would have received) the frame with timestamp 0 */
3490 #endif /* IAXTESTS */
3491 /* Setup rxcore if necessary */
3492 if (ast_tvzero(p->rxcore)) {
3493 p->rxcore = ast_tvnow();
3494 if (option_debug && iaxdebug)
3495 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3496 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3497 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3499 if (option_debug && iaxdebug)
3500 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3501 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3505 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3508 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3509 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3510 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3519 #endif /* IAXTESTS */
3523 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3525 struct iax2_trunk_peer *tpeer = NULL;
3527 /* Finds and locks trunk peer */
3528 AST_LIST_LOCK(&tpeers);
3530 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
3531 if (!inaddrcmp(&tpeer->addr, sin)) {
3532 ast_mutex_lock(&tpeer->lock);
3538 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
3539 ast_mutex_init(&tpeer->lock);
3540 tpeer->lastsent = 9999;
3541 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3542 tpeer->trunkact = ast_tvnow();
3543 ast_mutex_lock(&tpeer->lock);
3546 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3549 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3550 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
3554 AST_LIST_UNLOCK(&tpeers);
3559 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
3561 struct ast_frame *f;
3562 struct iax2_trunk_peer *tpeer;
3566 struct ast_iax2_meta_trunk_entry *met;
3567 struct ast_iax2_meta_trunk_mini *mtm;
3570 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
3572 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
3573 /* Need to reallocate space */
3574 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
3575 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
3576 ast_mutex_unlock(&tpeer->lock);
3580 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
3581 tpeer->trunkdata = tmp;
3583 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
3585 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3586 ast_mutex_unlock(&tpeer->lock);
3591 /* Append to meta frame */
3592 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
3593 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
3594 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
3595 mtm->len = htons(f->datalen);
3596 mtm->mini.callno = htons(pvt->callno);
3597 mtm->mini.ts = htons(0xffff & fr->ts);
3598 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
3599 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
3601 met = (struct ast_iax2_meta_trunk_entry *)ptr;
3602 /* Store call number and length in meta header */
3603 met->callno = htons(pvt->callno);
3604 met->len = htons(f->datalen);
3605 /* Advance pointers/decrease length past trunk entry header */
3606 ptr += sizeof(struct ast_iax2_meta_trunk_entry);