2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47 #include <netinet/in_systm.h>
48 #include <netinet/ip.h>
50 #include <sys/signal.h>
61 #include "asterisk/zapata.h"
63 #include "asterisk/lock.h"
64 #include "asterisk/frame.h"
65 #include "asterisk/channel.h"
66 #include "asterisk/logger.h"
67 #include "asterisk/module.h"
68 #include "asterisk/pbx.h"
69 #include "asterisk/sched.h"
70 #include "asterisk/io.h"
71 #include "asterisk/config.h"
72 #include "asterisk/options.h"
73 #include "asterisk/cli.h"
74 #include "asterisk/translate.h"
75 #include "asterisk/md5.h"
76 #include "asterisk/cdr.h"
77 #include "asterisk/crypto.h"
78 #include "asterisk/acl.h"
79 #include "asterisk/manager.h"
80 #include "asterisk/callerid.h"
81 #include "asterisk/app.h"
82 #include "asterisk/astdb.h"
83 #include "asterisk/musiconhold.h"
84 #include "asterisk/features.h"
85 #include "asterisk/utils.h"
86 #include "asterisk/causes.h"
87 #include "asterisk/localtime.h"
88 #include "asterisk/aes.h"
89 #include "asterisk/dnsmgr.h"
90 #include "asterisk/devicestate.h"
91 #include "asterisk/netsock.h"
92 #include "asterisk/stringfields.h"
93 #include "asterisk/linkedlists.h"
94 #include "asterisk/event.h"
97 #include "iax2-parser.h"
98 #include "iax2-provision.h"
99 #include "jitterbuf.h"
101 /* Define SCHED_MULTITHREADED to run the scheduler in a special
102 multithreaded mode. */
103 #define SCHED_MULTITHREADED
105 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
106 thread is actually doing. */
107 #define DEBUG_SCHED_MULTITHREAD
109 #ifndef IPTOS_MINCOST
110 #define IPTOS_MINCOST 0x02
114 static int nochecksums = 0;
118 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
119 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
121 #define DEFAULT_THREAD_COUNT 10
122 #define DEFAULT_MAX_THREAD_COUNT 100
123 #define DEFAULT_RETRY_TIME 1000
124 #define MEMORY_SIZE 100
125 #define DEFAULT_DROP 3
126 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
127 but keeps the division between trunked and non-trunked better. */
128 #define TRUNK_CALL_START 0x4000
130 #define DEBUG_SUPPORT
132 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
134 /* Sample over last 100 units to determine historic jitter */
137 static struct ast_codec_pref prefs;
139 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
142 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
143 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
144 #define MAX_TRUNK_MTU 1240
146 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
147 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
150 static char context[80] = "default";
152 static char language[MAX_LANGUAGE] = "";
153 static char regcontext[AST_MAX_CONTEXT] = "";
155 static int maxauthreq = 3;
156 static int max_retries = 4;
157 static int ping_time = 20;
158 static int lagrq_time = 10;
159 static int maxtrunkcall = TRUNK_CALL_START;
160 static int maxnontrunkcall = 1;
161 static int maxjitterbuffer=1000;
162 static int resyncthreshold=1000;
163 static int maxjitterinterps=10;
164 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
166 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
168 static int trunkfreq = 20;
169 static int trunkmaxsize = MAX_TRUNKDATA;
171 static int authdebug = 1;
172 static int autokill = 0;
173 static int iaxcompat = 0;
175 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
177 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
179 static unsigned int tos = 0;
181 static unsigned int cos = 0;
183 static int min_reg_expire;
184 static int max_reg_expire;
186 static int srvlookup = 0;
188 static int timingfd = -1; /* Timing file descriptor */
190 static struct ast_netsock_list *netsock;
191 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
192 static int defaultsockfd = -1;
194 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
197 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
199 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
200 ~AST_FORMAT_SLINEAR & \
205 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
207 ~AST_FORMAT_G726_AAL2 & \
210 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
214 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
215 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
216 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
218 static struct io_context *io;
219 static struct sched_context *sched;
221 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
223 static int iaxdebug = 0;
225 static int iaxtrunkdebug = 0;
227 static int test_losspct = 0;
229 static int test_late = 0;
230 static int test_resync = 0;
231 static int test_jit = 0;
232 static int test_jitpct = 0;
233 #endif /* IAXTESTS */
235 static char accountcode[AST_MAX_ACCOUNT_CODE];
236 static char mohinterpret[MAX_MUSICCLASS];
237 static char mohsuggest[MAX_MUSICCLASS];
238 static int amaflags = 0;
240 static int delayreject = 0;
241 static int iax2_encryption = 0;
243 static struct ast_flags globalflags = { 0 };
245 static pthread_t netthreadid = AST_PTHREADT_NULL;
246 static pthread_t schedthreadid = AST_PTHREADT_NULL;
247 AST_MUTEX_DEFINE_STATIC(sched_lock);
248 static ast_cond_t sched_cond;
251 IAX_STATE_STARTED = (1 << 0),
252 IAX_STATE_AUTHENTICATED = (1 << 1),
253 IAX_STATE_TBD = (1 << 2),
254 IAX_STATE_UNCHANGED = (1 << 3),
257 struct iax2_context {
258 char context[AST_MAX_CONTEXT];
259 struct iax2_context *next;
263 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
264 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
265 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
266 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
267 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
268 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
269 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
270 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
271 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
272 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
273 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
274 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
275 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
276 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
277 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
278 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
279 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
280 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
281 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
282 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
283 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
284 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
285 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
286 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
287 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
290 static int global_rtautoclear = 120;
292 static int reload_config(void);
293 static int iax2_reload(int fd, int argc, char *argv[]);
297 AST_DECLARE_STRING_FIELDS(
298 AST_STRING_FIELD(name);
299 AST_STRING_FIELD(secret);
300 AST_STRING_FIELD(dbsecret);
301 AST_STRING_FIELD(accountcode);
302 AST_STRING_FIELD(mohinterpret);
303 AST_STRING_FIELD(mohsuggest);
304 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
305 AST_STRING_FIELD(language);
306 AST_STRING_FIELD(cid_num);
307 AST_STRING_FIELD(cid_name);
316 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
317 int curauthreq; /*!< Current number of outstanding AUTHREQs */
318 struct ast_codec_pref prefs;
320 struct iax2_context *contexts;
321 struct ast_variable *vars;
322 AST_LIST_ENTRY(iax2_user) entry;
326 AST_DECLARE_STRING_FIELDS(
327 AST_STRING_FIELD(name);
328 AST_STRING_FIELD(username);
329 AST_STRING_FIELD(secret);
330 AST_STRING_FIELD(dbsecret);
331 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
333 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
334 AST_STRING_FIELD(context); /*!< For transfers only */
335 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
336 AST_STRING_FIELD(mailbox); /*!< Mailbox */
337 AST_STRING_FIELD(mohinterpret);
338 AST_STRING_FIELD(mohsuggest);
339 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
340 /* Suggested caller id if registering */
341 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
342 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
343 AST_STRING_FIELD(zonetag); /*!< Time Zone */
345 struct ast_codec_pref prefs;
346 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
347 struct sockaddr_in addr;
349 int sockfd; /*!< Socket to use for transmission */
354 /* Dynamic Registration fields */
355 struct sockaddr_in defaddr; /*!< Default address if there is one */
356 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
357 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
359 int expire; /*!< Schedule entry for expiry */
360 int expiry; /*!< How soon to expire */
361 int capability; /*!< Capability */
364 int callno; /*!< Call number of POKE request */
365 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
366 int lastms; /*!< How long last response took (in ms), or -1 for no response */
367 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
369 int pokefreqok; /*!< How often to check if the host is up */
370 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
371 int historicms; /*!< How long recent average responses took */
372 int smoothing; /*!< Sample over how many units to determine historic ms */
374 struct ast_event_sub *mwi_event_sub;
377 AST_LIST_ENTRY(iax2_peer) entry;
380 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
382 struct iax2_trunk_peer {
385 struct sockaddr_in addr;
386 struct timeval txtrunktime; /*!< Transmit trunktime */
387 struct timeval rxtrunktime; /*!< Receive trunktime */
388 struct timeval lasttxtime; /*!< Last transmitted trunktime */
389 struct timeval trunkact; /*!< Last trunk activity */
390 unsigned int lastsent; /*!< Last sent time */
391 /* Trunk data and length */
392 unsigned char *trunkdata;
393 unsigned int trunkdatalen;
394 unsigned int trunkdataalloc;
398 AST_LIST_ENTRY(iax2_trunk_peer) list;
401 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
403 struct iax_firmware {
404 AST_LIST_ENTRY(iax_firmware) list;
408 struct ast_iax2_firmware_header *fwh;
413 REG_STATE_UNREGISTERED = 0,
416 REG_STATE_REGISTERED,
422 enum iax_transfer_state {
427 TRANSFER_PASSTHROUGH,
431 TRANSFER_MPASSTHROUGH,
436 struct iax2_registry {
437 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
439 char secret[80]; /*!< Password or key name in []'s */
441 int expire; /*!< Sched ID of expiration */
442 int refresh; /*!< How often to refresh */
443 enum iax_reg_state regstate;
444 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
445 int callno; /*!< Associated call number if applicable */
446 struct sockaddr_in us; /*!< Who the server thinks we are */
447 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
448 AST_LIST_ENTRY(iax2_registry) entry;
451 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
453 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
454 #define MIN_RETRY_TIME 100
455 #define MAX_RETRY_TIME 10000
457 #define MAX_JITTER_BUFFER 50
458 #define MIN_JITTER_BUFFER 10
460 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
462 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
464 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
465 #define TS_GAP_FOR_JB_RESYNC 5000
467 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
468 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
469 static int iaxdynamicthreadcount = 0;
470 static int iaxactivethreadcount = 0;
484 struct chan_iax2_pvt {
485 /*! Socket to send/receive on for this call */
487 /*! Last received voice format */
489 /*! Last received video format */
491 /*! Last sent voice format */
493 /*! Last sent video format */
495 /*! What we are capable of sending */
497 /*! Last received timestamp */
499 /*! Last sent timestamp - never send the same timestamp twice in a single call */
500 unsigned int lastsent;
501 /*! Next outgoing timestamp if everything is good */
502 unsigned int nextpred;
503 /*! True if the last voice we transmitted was not silence/CNG */
504 unsigned int notsilenttx:1;
506 unsigned int pingtime;
507 /*! Max time for initial response */
510 struct sockaddr_in addr;
511 /*! Actual used codec preferences */
512 struct ast_codec_pref prefs;
513 /*! Requested codec preferences */
514 struct ast_codec_pref rprefs;
515 /*! Our call number */
516 unsigned short callno;
518 unsigned short peercallno;
519 /*! Peer selected format */
521 /*! Peer capability */
523 /*! timeval that we base our transmission on */
524 struct timeval offset;
525 /*! timeval that we base our delivery on */
526 struct timeval rxcore;
527 /*! The jitterbuffer */
529 /*! active jb read scheduler id */
533 /*! Error, as discovered by the manager */
535 /*! Owner if we have one */
536 struct ast_channel *owner;
537 /*! What's our state? */
538 struct ast_flags state;
539 /*! Expiry (optional) */
541 /*! Next outgoing sequence number */
542 unsigned char oseqno;
543 /*! Next sequence number they have not yet acknowledged */
544 unsigned char rseqno;
545 /*! Next incoming sequence number */
546 unsigned char iseqno;
547 /*! Last incoming sequence number we have acknowledged */
548 unsigned char aseqno;
550 AST_DECLARE_STRING_FIELDS(
552 AST_STRING_FIELD(peer);
553 /*! Default Context */
554 AST_STRING_FIELD(context);
555 /*! Caller ID if available */
556 AST_STRING_FIELD(cid_num);
557 AST_STRING_FIELD(cid_name);
558 /*! Hidden Caller ID (i.e. ANI) if appropriate */
559 AST_STRING_FIELD(ani);
561 AST_STRING_FIELD(dnid);
563 AST_STRING_FIELD(rdnis);
564 /*! Requested Extension */
565 AST_STRING_FIELD(exten);
566 /*! Expected Username */
567 AST_STRING_FIELD(username);
568 /*! Expected Secret */
569 AST_STRING_FIELD(secret);
571 AST_STRING_FIELD(challenge);
572 /*! Public keys permitted keys for incoming authentication */
573 AST_STRING_FIELD(inkeys);
574 /*! Private key for outgoing authentication */
575 AST_STRING_FIELD(outkey);
576 /*! Preferred language */
577 AST_STRING_FIELD(language);
578 /*! Hostname/peername for naming purposes */
579 AST_STRING_FIELD(host);
581 AST_STRING_FIELD(dproot);
582 AST_STRING_FIELD(accountcode);
583 AST_STRING_FIELD(mohinterpret);
584 AST_STRING_FIELD(mohsuggest);
585 /*! received OSP token */
586 AST_STRING_FIELD(osptoken);
589 /*! permitted authentication methods */
591 /*! permitted encryption methods */
593 /*! Encryption AES-128 Key */
595 /*! Decryption AES-128 Key */
597 /*! 32 bytes of semi-random data */
598 unsigned char semirand[32];
599 /*! Associated registry */
600 struct iax2_registry *reg;
601 /*! Associated peer for poking */
602 struct iax2_peer *peerpoke;
607 /*! Transferring status */
608 enum iax_transfer_state transferring;
609 /*! Transfer identifier */
611 /*! Who we are IAX transferring to */
612 struct sockaddr_in transfer;
613 /*! What's the new call number for the transfer */
614 unsigned short transfercallno;
615 /*! Transfer decrypt AES-128 Key */
616 aes_encrypt_ctx tdcx;
618 /*! Status of knowledge of peer ADSI capability */
621 /*! Who we are bridged to */
622 unsigned short bridgecallno;
624 int pingid; /*!< Transmit PING request */
625 int lagid; /*!< Retransmit lag request */
626 int autoid; /*!< Auto hangup for Dialplan requestor */
627 int authid; /*!< Authentication rejection ID */
628 int authfail; /*!< Reason to report failure */
629 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
634 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
635 struct ast_variable *vars;
636 /*! last received remote rr */
637 struct iax_rr remote_rr;
638 /*! Current base time: (just for stats) */
640 /*! Dropped frame count: (just for stats) */
642 /*! received frame count: (just for stats) */
646 static AST_LIST_HEAD_STATIC(queue, iax_frame);
648 static AST_LIST_HEAD_STATIC(users, iax2_user);
650 static AST_LIST_HEAD_STATIC(peers, iax2_peer);
652 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
655 /*! Extension exists */
656 CACHE_FLAG_EXISTS = (1 << 0),
657 /*! Extension is nonexistent */
658 CACHE_FLAG_NONEXISTENT = (1 << 1),
659 /*! Extension can exist */
660 CACHE_FLAG_CANEXIST = (1 << 2),
661 /*! Waiting to hear back response */
662 CACHE_FLAG_PENDING = (1 << 3),
664 CACHE_FLAG_TIMEOUT = (1 << 4),
665 /*! Request transmitted */
666 CACHE_FLAG_TRANSMITTED = (1 << 5),
668 CACHE_FLAG_UNKNOWN = (1 << 6),
670 CACHE_FLAG_MATCHMORE = (1 << 7),
673 struct iax2_dpcache {
674 char peercontext[AST_MAX_CONTEXT];
675 char exten[AST_MAX_EXTENSION];
677 struct timeval expiry;
679 unsigned short callno;
681 AST_LIST_ENTRY(iax2_dpcache) cache_list;
682 AST_LIST_ENTRY(iax2_dpcache) peer_list;
685 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
687 static void reg_source_db(struct iax2_peer *p);
688 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
690 static void destroy_peer(struct iax2_peer *peer);
691 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
693 enum iax2_thread_iostate {
696 IAX_IOSTATE_PROCESSING,
697 IAX_IOSTATE_SCHEDREADY,
700 enum iax2_thread_type {
701 IAX_THREAD_TYPE_POOL,
702 IAX_THREAD_TYPE_DYNAMIC,
706 AST_LIST_ENTRY(iax2_thread) list;
707 enum iax2_thread_type type;
708 enum iax2_thread_iostate iostate;
709 #ifdef SCHED_MULTITHREADED
710 void (*schedfunc)(void *);
713 #ifdef DEBUG_SCHED_MULTITHREAD
719 struct sockaddr_in iosin;
720 unsigned char buf[4096];
729 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
730 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
731 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
733 static void *iax2_process_thread(void *data);
735 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
737 ast_mutex_lock(lock);
738 ast_cond_signal(cond);
739 ast_mutex_unlock(lock);
742 static void iax_debug_output(const char *data)
745 ast_verbose("%s", data);
748 static void iax_error_output(const char *data)
750 ast_log(LOG_WARNING, "%s", data);
753 static void jb_error_output(const char *fmt, ...)
759 vsnprintf(buf, sizeof(buf), fmt, args);
762 ast_log(LOG_ERROR, buf);
765 static void jb_warning_output(const char *fmt, ...)
771 vsnprintf(buf, sizeof(buf), fmt, args);
774 ast_log(LOG_WARNING, buf);
777 static void jb_debug_output(const char *fmt, ...)
783 vsnprintf(buf, sizeof(buf), fmt, args);
790 * \brief an array of iax2 pvt structures
792 * The container for active chan_iax2_pvt structures is implemented as an
793 * array for extremely quick direct access to the correct pvt structure
794 * based on the local call number. The local call number is used as the
795 * index into the array where the associated pvt structure is stored.
797 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
799 * \brief chan_iax2_pvt structure locks
801 * These locks are used when accessing a pvt structure in the iaxs array.
802 * The index used here is the same as used in the iaxs array. It is the
803 * local call number for the associated pvt struct.
805 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
807 * \brief The last time a call number was used
809 * It is important to know the last time that a call number was used locally so
810 * that it is not used again too soon. The reason for this is the same as the
811 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
813 * For example, say that a call is up. Then, the remote side sends a HANGUP,
814 * which we respond to with an ACK. However, there is no way to know whether
815 * the ACK made it there successfully. If it were to get lost, the remote
816 * side may retransmit the HANGUP. If in the meantime, this call number has
817 * been reused locally, given the right set of circumstances, this retransmitted
818 * HANGUP could potentially improperly hang up the new session. So, to avoid
819 * this potential issue, we must wait a specified timeout period before reusing
820 * a local call number.
822 * The specified time that we must wait before reusing a local call number is
823 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
825 static struct timeval lastused[IAX_MAX_CALLS];
827 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);
828 static int expire_registry(void *data);
829 static int iax2_answer(struct ast_channel *c);
830 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
831 static int iax2_devicestate(void *data);
832 static int iax2_digit_begin(struct ast_channel *c, char digit);
833 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
834 static int iax2_do_register(struct iax2_registry *reg);
835 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
836 static int iax2_hangup(struct ast_channel *c);
837 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
838 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
839 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
840 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
841 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
842 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
843 static int iax2_sendtext(struct ast_channel *c, const char *text);
844 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
845 static int iax2_transfer(struct ast_channel *c, const char *dest);
846 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
847 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
848 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
849 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
850 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
851 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
852 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
853 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
854 static struct ast_frame *iax2_read(struct ast_channel *c);
855 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
856 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
857 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
858 static void destroy_user(struct iax2_user *user);
859 static void prune_peers(void);
861 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
862 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
864 static const struct ast_channel_tech iax2_tech = {
866 .description = tdesc,
867 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
868 .properties = AST_CHAN_TP_WANTSJITTER,
869 .requester = iax2_request,
870 .devicestate = iax2_devicestate,
871 .send_digit_begin = iax2_digit_begin,
872 .send_digit_end = iax2_digit_end,
873 .send_text = iax2_sendtext,
874 .send_image = iax2_sendimage,
875 .send_html = iax2_sendhtml,
877 .hangup = iax2_hangup,
878 .answer = iax2_answer,
881 .write_video = iax2_write,
882 .indicate = iax2_indicate,
883 .setoption = iax2_setoption,
884 .bridge = iax2_bridge,
885 .transfer = iax2_transfer,
887 .func_channel_read = acf_channel_read,
888 .func_channel_write = acf_channel_write,
891 static void mwi_event_cb(const struct ast_event *event, void *userdata)
893 /* The MWI subscriptions exist just so the core knows we care about those
894 * mailboxes. However, we just grab the events out of the cache when it
895 * is time to send MWI, since it is only sent with a REGACK. */
898 static void insert_idle_thread(struct iax2_thread *thread)
900 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
901 AST_LIST_LOCK(&dynamic_list);
902 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
903 AST_LIST_UNLOCK(&dynamic_list);
905 AST_LIST_LOCK(&idle_list);
906 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
907 AST_LIST_UNLOCK(&idle_list);
913 static struct iax2_thread *find_idle_thread(void)
916 struct iax2_thread *thread = NULL;
918 /* Pop the head of the idle list off */
919 AST_LIST_LOCK(&idle_list);
920 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
921 AST_LIST_UNLOCK(&idle_list);
923 /* If we popped a thread off the idle list, just return it */
927 /* Pop the head of the dynamic list off */
928 AST_LIST_LOCK(&dynamic_list);
929 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
930 AST_LIST_UNLOCK(&dynamic_list);
932 /* If we popped a thread off the dynamic list, just return it */
936 /* If we can't create a new dynamic thread for any reason, return no thread at all */
937 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
940 /* Set default values */
941 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
942 thread->type = IAX_THREAD_TYPE_DYNAMIC;
944 /* Initialize lock and condition */
945 ast_mutex_init(&thread->lock);
946 ast_cond_init(&thread->cond, NULL);
948 /* Create thread and send it on it's way */
949 pthread_attr_init(&attr);
950 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
951 if (ast_pthread_create_background(&thread->threadid, &attr, iax2_process_thread, thread)) {
952 ast_cond_destroy(&thread->cond);
953 ast_mutex_destroy(&thread->lock);
961 #ifdef SCHED_MULTITHREADED
962 static int __schedule_action(void (*func)(void *data), void *data, const char *funcname)
964 struct iax2_thread *thread = NULL;
965 static time_t lasterror;
968 thread = find_idle_thread();
970 if (thread != NULL) {
971 thread->schedfunc = func;
972 thread->scheddata = data;
973 thread->iostate = IAX_IOSTATE_SCHEDREADY;
974 #ifdef DEBUG_SCHED_MULTITHREAD
975 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
977 signal_condition(&thread->lock, &thread->cond);
982 ast_log(LOG_NOTICE, "Out of idle IAX2 threads for scheduling!\n");
987 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
990 static int send_ping(void *data);
992 static void __send_ping(void *data)
994 int callno = (long)data;
995 ast_mutex_lock(&iaxsl[callno]);
996 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
997 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
998 iaxs[callno]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, data);
1000 ast_mutex_unlock(&iaxsl[callno]);
1003 static int send_ping(void *data)
1005 #ifdef SCHED_MULTITHREADED
1006 if (schedule_action(__send_ping, data))
1012 static int get_encrypt_methods(const char *s)
1015 if (!strcasecmp(s, "aes128"))
1016 e = IAX_ENCRYPT_AES128;
1017 else if (ast_true(s))
1018 e = IAX_ENCRYPT_AES128;
1024 static int send_lagrq(void *data);
1026 static void __send_lagrq(void *data)
1028 int callno = (long)data;
1029 /* Ping only if it's real not if it's bridged */
1030 ast_mutex_lock(&iaxsl[callno]);
1031 if (iaxs[callno] && iaxs[callno]->lagid != -1) {
1032 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1033 iaxs[callno]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1035 ast_mutex_unlock(&iaxsl[callno]);
1038 static int send_lagrq(void *data)
1040 #ifdef SCHED_MULTITHREADED
1041 if (schedule_action(__send_lagrq, data))
1047 static unsigned char compress_subclass(int subclass)
1051 /* If it's 128 or smaller, just return it */
1052 if (subclass < IAX_FLAG_SC_LOG)
1054 /* Otherwise find its power */
1055 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1056 if (subclass & (1 << x)) {
1058 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1064 return power | IAX_FLAG_SC_LOG;
1067 static int uncompress_subclass(unsigned char csub)
1069 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1070 if (csub & IAX_FLAG_SC_LOG) {
1071 /* special case for 'compressed' -1 */
1075 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1081 static struct iax2_peer *find_peer(const char *name, int realtime)
1083 struct iax2_peer *peer = NULL;
1085 /* Grab peer from linked list */
1086 AST_LIST_LOCK(&peers);
1087 AST_LIST_TRAVERSE(&peers, peer, entry) {
1088 if (!strcasecmp(peer->name, name)) {
1092 AST_LIST_UNLOCK(&peers);
1094 /* Now go for realtime if applicable */
1095 if(!peer && realtime)
1096 peer = realtime_peer(name, NULL);
1100 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len, int lockpeer)
1102 struct iax2_peer *peer = NULL;
1106 AST_LIST_LOCK(&peers);
1107 AST_LIST_TRAVERSE(&peers, peer, entry) {
1108 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1109 (peer->addr.sin_port == sin.sin_port)) {
1110 ast_copy_string(host, peer->name, len);
1116 AST_LIST_UNLOCK(&peers);
1118 peer = realtime_peer(NULL, &sin);
1120 ast_copy_string(host, peer->name, len);
1121 if (ast_test_flag(peer, IAX_TEMPONLY))
1130 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, int lockpeer, const char *host)
1132 struct chan_iax2_pvt *tmp;
1135 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1138 if (ast_string_field_init(tmp, 32)) {
1151 ast_string_field_set(tmp,exten, "s");
1152 ast_string_field_set(tmp,host, host);
1156 jbconf.max_jitterbuf = maxjitterbuffer;
1157 jbconf.resync_threshold = resyncthreshold;
1158 jbconf.max_contig_interp = maxjitterinterps;
1159 jbconf.target_extra = jittertargetextra;
1160 jb_setconf(tmp->jb,&jbconf);
1162 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1167 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1169 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1171 size_t mallocd_datalen = new->mallocd_datalen;
1172 memcpy(new, fr, sizeof(*new));
1173 iax_frame_wrap(new, &fr->af);
1174 new->mallocd_datalen = mallocd_datalen;
1177 new->direction = DIRECTION_INGRESS;
1183 #define NEW_PREVENT 0
1187 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur)
1189 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1190 (cur->addr.sin_port == sin->sin_port)) {
1191 /* This is the main host */
1192 if ((cur->peercallno == callno) ||
1193 ((dcallno == cur->callno) && !cur->peercallno)) {
1194 /* That's us. Be sure we keep track of the peer call number */
1198 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1199 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1200 /* We're transferring */
1201 if (dcallno == cur->callno)
1207 static void update_max_trunk(void)
1209 int max = TRUNK_CALL_START;
1211 /* XXX Prolly don't need locks here XXX */
1212 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1217 if (option_debug && iaxdebug)
1218 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1221 static void update_max_nontrunk(void)
1225 /* XXX Prolly don't need locks here XXX */
1226 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1230 maxnontrunkcall = max;
1231 if (option_debug && iaxdebug)
1232 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1235 static int make_trunk(unsigned short callno, int locked)
1240 if (iaxs[callno]->oseqno) {
1241 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1244 if (callno & TRUNK_CALL_START) {
1245 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1248 gettimeofday(&now, NULL);
1249 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1250 ast_mutex_lock(&iaxsl[x]);
1251 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1252 iaxs[x] = iaxs[callno];
1253 iaxs[x]->callno = x;
1254 iaxs[callno] = NULL;
1255 /* Update the two timers that should have been started */
1256 if (iaxs[x]->pingid > -1)
1257 ast_sched_del(sched, iaxs[x]->pingid);
1258 if (iaxs[x]->lagid > -1)
1259 ast_sched_del(sched, iaxs[x]->lagid);
1260 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1261 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1263 ast_mutex_unlock(&iaxsl[callno]);
1266 ast_mutex_unlock(&iaxsl[x]);
1269 ast_mutex_unlock(&iaxsl[x]);
1271 if (x >= IAX_MAX_CALLS - 1) {
1272 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1276 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1277 /* We move this call from a non-trunked to a trunked call */
1279 update_max_nontrunk();
1284 * \todo XXX Note that this function contains a very expensive operation that
1285 * happens for *every* incoming media frame. It iterates through every
1286 * possible call number, locking and unlocking each one, to try to match the
1287 * incoming frame to an active call. Call numbers can be up to 2^15, 32768.
1288 * So, for an call with a local call number of 20000, every incoming audio
1289 * frame would require 20000 mutex lock and unlock operations. Ouch.
1291 * It's a shame that IAX2 media frames carry the source call number instead of
1292 * the destination call number. If they did, this lookup wouldn't be needed.
1293 * However, it's too late to change that now. Instead, we need to come up with
1294 * a better way of indexing active calls so that these frequent lookups are not
1297 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int lockpeer, int sockfd)
1303 if (new <= NEW_ALLOW) {
1304 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1305 ast_mutex_lock(&iaxsl[x]);
1307 /* Look for an exact match */
1308 if (match(sin, callno, dcallno, iaxs[x])) {
1312 ast_mutex_unlock(&iaxsl[x]);
1314 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1315 ast_mutex_lock(&iaxsl[x]);
1317 /* Look for an exact match */
1318 if (match(sin, callno, dcallno, iaxs[x])) {
1322 ast_mutex_unlock(&iaxsl[x]);
1325 if ((res < 1) && (new >= NEW_ALLOW)) {
1326 /* It may seem odd that we look through the peer list for a name for
1327 * this *incoming* call. Well, it is weird. However, users don't
1328 * have an IP address/port number that we can match against. So,
1329 * this is just checking for a peer that has that IP/port and
1330 * assuming that we have a user of the same name. This isn't always
1331 * correct, but it will be changed if needed after authentication. */
1332 if (!iax2_getpeername(*sin, host, sizeof(host), lockpeer))
1333 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1334 gettimeofday(&now, NULL);
1335 for (x=1;x<TRUNK_CALL_START;x++) {
1336 /* Find first unused call number that hasn't been used in a while */
1337 ast_mutex_lock(&iaxsl[x]);
1338 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1339 ast_mutex_unlock(&iaxsl[x]);
1341 /* We've still got lock held if we found a spot */
1342 if (x >= TRUNK_CALL_START) {
1343 ast_log(LOG_WARNING, "No more space\n");
1346 iaxs[x] = new_iax(sin, lockpeer, host);
1347 update_max_nontrunk();
1349 if (option_debug && iaxdebug)
1350 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1351 iaxs[x]->sockfd = sockfd;
1352 iaxs[x]->addr.sin_port = sin->sin_port;
1353 iaxs[x]->addr.sin_family = sin->sin_family;
1354 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1355 iaxs[x]->peercallno = callno;
1356 iaxs[x]->callno = x;
1357 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1358 iaxs[x]->expiry = min_reg_expire;
1359 iaxs[x]->pingid = ast_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1360 iaxs[x]->lagid = ast_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1361 iaxs[x]->amaflags = amaflags;
1362 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1364 ast_string_field_set(iaxs[x], accountcode, accountcode);
1365 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1366 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1368 ast_log(LOG_WARNING, "Out of resources\n");
1369 ast_mutex_unlock(&iaxsl[x]);
1372 ast_mutex_unlock(&iaxsl[x]);
1378 static void iax2_frame_free(struct iax_frame *fr)
1380 if (fr->retrans > -1)
1381 ast_sched_del(sched, fr->retrans);
1385 static int iax2_queue_frame(int callno, struct ast_frame *f)
1387 /* Assumes lock for callno is already held... */
1389 if (iaxs[callno] && iaxs[callno]->owner) {
1390 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1391 /* Avoid deadlock by pausing and trying again */
1392 ast_mutex_unlock(&iaxsl[callno]);
1394 ast_mutex_lock(&iaxsl[callno]);
1396 ast_queue_frame(iaxs[callno]->owner, f);
1397 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1406 static void destroy_firmware(struct iax_firmware *cur)
1408 /* Close firmware */
1410 munmap(cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1416 static int try_firmware(char *s)
1419 struct iax_firmware *cur = NULL;
1420 int ifd, fd, res, len, chunk;
1421 struct ast_iax2_firmware_header *fwh, fwh2;
1422 struct MD5Context md5;
1423 unsigned char sum[16], buf[1024];
1426 if (!(s2 = alloca(strlen(s) + 100))) {
1427 ast_log(LOG_WARNING, "Alloca failed!\n");
1431 last = strrchr(s, '/');
1437 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1439 if ((res = stat(s, &stbuf) < 0)) {
1440 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1444 /* Make sure it's not a directory */
1445 if (S_ISDIR(stbuf.st_mode))
1447 ifd = open(s, O_RDONLY);
1449 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1452 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1454 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1458 /* Unlink our newly created file */
1461 /* Now copy the firmware into it */
1462 len = stbuf.st_size;
1465 if (chunk > sizeof(buf))
1466 chunk = sizeof(buf);
1467 res = read(ifd, buf, chunk);
1469 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1474 res = write(fd, buf, chunk);
1476 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1484 /* Return to the beginning */
1485 lseek(fd, 0, SEEK_SET);
1486 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1487 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1491 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1492 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1496 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1497 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1501 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1502 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1506 fwh = mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1507 if (fwh == (void *) -1) {
1508 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1513 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1514 MD5Final(sum, &md5);
1515 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1516 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1517 munmap(fwh, stbuf.st_size);
1522 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1523 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1524 /* Found a candidate */
1525 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1526 /* The version we have on loaded is older, load this one instead */
1528 /* This version is no newer than what we have. Don't worry about it.
1529 We'll consider it a proper load anyhow though */
1530 munmap(fwh, stbuf.st_size);
1536 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
1538 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
1543 munmap(cur->fwh, cur->mmaplen);
1548 cur->mmaplen = stbuf.st_size;
1555 static int iax_check_version(char *dev)
1558 struct iax_firmware *cur = NULL;
1560 if (ast_strlen_zero(dev))
1563 AST_LIST_LOCK(&firmwares);
1564 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1565 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1566 res = ntohs(cur->fwh->version);
1570 AST_LIST_UNLOCK(&firmwares);
1575 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1578 unsigned int bs = desc & 0xff;
1579 unsigned int start = (desc >> 8) & 0xffffff;
1581 struct iax_firmware *cur;
1583 if (ast_strlen_zero((char *)dev) || !bs)
1588 AST_LIST_LOCK(&firmwares);
1589 AST_LIST_TRAVERSE(&firmwares, cur, list) {
1590 if (strcmp((char *)dev, (char *)cur->fwh->devname))
1592 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1593 if (start < ntohl(cur->fwh->datalen)) {
1594 bytes = ntohl(cur->fwh->datalen) - start;
1597 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1600 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1608 AST_LIST_UNLOCK(&firmwares);
1614 static void reload_firmware(void)
1616 struct iax_firmware *cur = NULL;
1619 char dir[256], fn[256];
1621 AST_LIST_LOCK(&firmwares);
1623 /* Mark all as dead */
1624 AST_LIST_TRAVERSE(&firmwares, cur, list)
1627 /* Now that we have marked them dead... load new ones */
1628 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1631 while((de = readdir(fwd))) {
1632 if (de->d_name[0] != '.') {
1633 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1634 if (!try_firmware(fn)) {
1635 if (option_verbose > 1)
1636 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1642 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1644 /* Clean up leftovers */
1645 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
1648 AST_LIST_REMOVE_CURRENT(&firmwares, list);
1649 destroy_firmware(cur);
1651 AST_LIST_TRAVERSE_SAFE_END
1653 AST_LIST_UNLOCK(&firmwares);
1656 static int __do_deliver(void *data)
1658 /* Just deliver the packet by using queueing. This is called by
1659 the IAX thread with the iaxsl lock held. */
1660 struct iax_frame *fr = data;
1662 fr->af.has_timing_info = 0;
1663 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1664 iax2_queue_frame(fr->callno, &fr->af);
1665 /* Free our iax frame */
1666 iax2_frame_free(fr);
1667 /* And don't run again */
1671 static int handle_error(void)
1673 /* XXX Ideally we should figure out why an error occurred and then abort those
1674 rather than continuing to try. Unfortunately, the published interface does
1675 not seem to work XXX */
1677 struct sockaddr_in *sin;
1680 struct sock_extended_err e;
1685 m.msg_controllen = sizeof(e);
1687 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1689 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1691 if (m.msg_controllen) {
1692 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1694 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1696 ast_log(LOG_WARNING, "No address detected??\n");
1698 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1705 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1708 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1712 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1719 static int send_packet(struct iax_frame *f)
1722 int callno = f->callno;
1724 /* Don't send if there was an error, but return error instead */
1725 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1728 /* Called with iaxsl held */
1729 if (option_debug > 2 && iaxdebug)
1730 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));
1733 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1734 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1735 sizeof(iaxs[callno]->transfer));
1738 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1739 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1740 sizeof(iaxs[callno]->addr));
1743 if (option_debug && iaxdebug)
1744 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1751 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1753 struct iax2_user *user = NULL;
1755 /* Decrement AUTHREQ count if needed */
1756 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1757 AST_LIST_LOCK(&users);
1758 AST_LIST_TRAVERSE(&users, user, entry) {
1759 if (!strcmp(user->name, pvt->username)) {
1764 AST_LIST_UNLOCK(&users);
1765 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1767 /* No more pings or lagrq's */
1768 if (pvt->pingid > -1)
1769 ast_sched_del(sched, pvt->pingid);
1771 if (pvt->lagid > -1)
1772 ast_sched_del(sched, pvt->lagid);
1774 if (pvt->autoid > -1)
1775 ast_sched_del(sched, pvt->autoid);
1777 if (pvt->authid > -1)
1778 ast_sched_del(sched, pvt->authid);
1780 if (pvt->initid > -1)
1781 ast_sched_del(sched, pvt->initid);
1784 ast_sched_del(sched, pvt->jbid);
1788 static int iax2_predestroy(int callno)
1790 struct ast_channel *c = NULL;
1791 struct chan_iax2_pvt *pvt = iaxs[callno];
1796 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1797 iax2_destroy_helper(pvt);
1798 ast_set_flag(pvt, IAX_ALREADYGONE);
1801 if ((c = pvt->owner)) {
1802 c->_softhangup |= AST_SOFTHANGUP_DEV;
1804 ast_queue_hangup(c);
1806 ast_module_unref(ast_module_info->self);
1812 static void iax2_destroy(int callno)
1814 struct chan_iax2_pvt *pvt = NULL;
1815 struct iax_frame *cur = NULL;
1816 struct ast_channel *owner = NULL;
1820 gettimeofday(&lastused[callno], NULL);
1822 owner = pvt ? pvt->owner : NULL;
1825 if (ast_mutex_trylock(&owner->lock)) {
1826 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1827 ast_mutex_unlock(&iaxsl[callno]);
1829 ast_mutex_lock(&iaxsl[callno]);
1834 iaxs[callno] = NULL;
1838 iax2_destroy_helper(pvt);
1841 ast_set_flag(pvt, IAX_ALREADYGONE);
1844 /* If there's an owner, prod it to give up */
1845 owner->_softhangup |= AST_SOFTHANGUP_DEV;
1846 ast_queue_hangup(owner);
1849 AST_LIST_LOCK(&queue);
1850 AST_LIST_TRAVERSE(&queue, cur, list) {
1851 /* Cancel any pending transmissions */
1852 if (cur->callno == pvt->callno)
1855 AST_LIST_UNLOCK(&queue);
1858 pvt->reg->callno = 0;
1862 ast_variables_destroy(pvt->vars);
1866 while (jb_getall(pvt->jb, &frame) == JB_OK)
1867 iax2_frame_free(frame.data);
1868 jb_destroy(pvt->jb);
1869 /* gotta free up the stringfields */
1870 ast_string_field_free_pools(pvt);
1875 ast_mutex_unlock(&owner->lock);
1877 if (callno & 0x4000)
1881 static int update_packet(struct iax_frame *f)
1883 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
1884 struct ast_iax2_full_hdr *fh = f->data;
1885 /* Mark this as a retransmission */
1886 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
1888 f->iseqno = iaxs[f->callno]->iseqno;
1889 fh->iseqno = f->iseqno;
1893 static int attempt_transmit(void *data);
1894 static void __attempt_transmit(void *data)
1896 /* Attempt to transmit the frame to the remote peer...
1897 Called without iaxsl held. */
1898 struct iax_frame *f = data;
1900 int callno = f->callno;
1901 /* Make sure this call is still active */
1903 ast_mutex_lock(&iaxsl[callno]);
1904 if (callno && iaxs[callno]) {
1905 if ((f->retries < 0) /* Already ACK'd */ ||
1906 (f->retries >= max_retries) /* Too many attempts */) {
1907 /* Record an error if we've transmitted too many times */
1908 if (f->retries >= max_retries) {
1910 /* Transfer timeout */
1911 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
1912 } else if (f->final) {
1914 iax2_destroy(callno);
1916 if (iaxs[callno]->owner)
1917 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);
1918 iaxs[callno]->error = ETIMEDOUT;
1919 if (iaxs[callno]->owner) {
1920 struct ast_frame fr = { 0, };
1922 fr.frametype = AST_FRAME_CONTROL;
1923 fr.subclass = AST_CONTROL_HANGUP;
1924 iax2_queue_frame(callno, &fr);
1925 /* Remember, owner could disappear */
1926 if (iaxs[callno]->owner)
1927 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1929 if (iaxs[callno]->reg) {
1930 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
1931 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
1932 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
1934 iax2_destroy(callno);
1941 /* Update it if it needs it */
1943 /* Attempt transmission */
1946 /* Try again later after 10 times as long */
1948 if (f->retrytime > MAX_RETRY_TIME)
1949 f->retrytime = MAX_RETRY_TIME;
1950 /* Transfer messages max out at one second */
1951 if (f->transfer && (f->retrytime > 1000))
1952 f->retrytime = 1000;
1953 f->retrans = ast_sched_add(sched, f->retrytime, attempt_transmit, f);
1956 /* Make sure it gets freed */
1961 ast_mutex_unlock(&iaxsl[callno]);
1962 /* Do not try again */
1964 /* Don't attempt delivery, just remove it from the queue */
1965 AST_LIST_LOCK(&queue);
1966 AST_LIST_REMOVE(&queue, f, list);
1967 AST_LIST_UNLOCK(&queue);
1969 /* Free the IAX frame */
1974 static int attempt_transmit(void *data)
1976 #ifdef SCHED_MULTITHREADED
1977 if (schedule_action(__attempt_transmit, data))
1979 __attempt_transmit(data);
1983 static int iax2_prune_realtime(int fd, int argc, char *argv[])
1985 struct iax2_peer *peer;
1988 return RESULT_SHOWUSAGE;
1989 if (!strcmp(argv[3],"all")) {
1991 ast_cli(fd, "OK cache is flushed.\n");
1992 } else if ((peer = find_peer(argv[3], 0))) {
1993 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
1994 ast_set_flag(peer, IAX_RTAUTOCLEAR);
1995 expire_registry((void*)peer->name);
1996 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
1998 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2001 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
2004 return RESULT_SUCCESS;
2007 static int iax2_test_losspct(int fd, int argc, char *argv[])
2010 return RESULT_SHOWUSAGE;
2012 test_losspct = atoi(argv[3]);
2014 return RESULT_SUCCESS;
2018 static int iax2_test_late(int fd, int argc, char *argv[])
2021 return RESULT_SHOWUSAGE;
2023 test_late = atoi(argv[3]);
2025 return RESULT_SUCCESS;
2028 static int iax2_test_resync(int fd, int argc, char *argv[])
2031 return RESULT_SHOWUSAGE;
2033 test_resync = atoi(argv[3]);
2035 return RESULT_SUCCESS;
2038 static int iax2_test_jitter(int fd, int argc, char *argv[])
2040 if (argc < 4 || argc > 5)
2041 return RESULT_SHOWUSAGE;
2043 test_jit = atoi(argv[3]);
2045 test_jitpct = atoi(argv[4]);
2047 return RESULT_SUCCESS;
2049 #endif /* IAXTESTS */
2051 /*! \brief peer_status: Report Peer status in character string */
2052 /* returns 1 if peer is online, -1 if unmonitored */
2053 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2057 if (peer->lastms < 0) {
2058 ast_copy_string(status, "UNREACHABLE", statuslen);
2059 } else if (peer->lastms > peer->maxms) {
2060 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2062 } else if (peer->lastms) {
2063 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2066 ast_copy_string(status, "UNKNOWN", statuslen);
2069 ast_copy_string(status, "Unmonitored", statuslen);
2075 /*! \brief Show one peer in detail */
2076 static int iax2_show_peer(int fd, int argc, char *argv[])
2080 struct iax2_peer *peer;
2081 char codec_buf[512];
2082 int x = 0, codec = 0, load_realtime = 0;
2085 return RESULT_SHOWUSAGE;
2087 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2089 peer = find_peer(argv[3], load_realtime);
2092 ast_cli(fd, " * Name : %s\n", peer->name);
2093 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2094 ast_cli(fd, " Context : %s\n", peer->context);
2095 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2096 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2097 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2098 ast_cli(fd, " Expire : %d\n", peer->expire);
2099 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2100 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));
2101 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2102 ast_cli(fd, " Username : %s\n", peer->username);
2103 ast_cli(fd, " Codecs : ");
2104 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2105 ast_cli(fd, "%s\n", codec_buf);
2107 ast_cli(fd, " Codec Order : (");
2108 for(x = 0; x < 32 ; x++) {
2109 codec = ast_codec_pref_index(&peer->prefs,x);
2112 ast_cli(fd, "%s", ast_getformatname(codec));
2113 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2118 ast_cli(fd, "none");
2121 ast_cli(fd, " Status : ");
2122 peer_status(peer, status, sizeof(status));
2123 ast_cli(fd, "%s\n",status);
2124 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2126 if (ast_test_flag(peer, IAX_TEMPONLY))
2129 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2133 return RESULT_SUCCESS;
2136 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2139 struct iax2_peer *p = NULL;
2141 int wordlen = strlen(word);
2143 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2145 AST_LIST_LOCK(&peers);
2146 AST_LIST_TRAVERSE(&peers, p, entry) {
2147 if (!strncasecmp(p->name, word, wordlen) && ++which > state) {
2148 res = ast_strdup(p->name);
2152 AST_LIST_UNLOCK(&peers);
2158 static int iax2_show_stats(int fd, int argc, char *argv[])
2160 struct iax_frame *cur;
2161 int cnt = 0, dead=0, final=0;
2164 return RESULT_SHOWUSAGE;
2166 AST_LIST_LOCK(&queue);
2167 AST_LIST_TRAVERSE(&queue, cur, list) {
2168 if (cur->retries < 0)
2174 AST_LIST_UNLOCK(&queue);
2176 ast_cli(fd, " IAX Statistics\n");
2177 ast_cli(fd, "---------------------\n");
2178 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2179 ast_cli(fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2180 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2182 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2184 trunk_timed = trunk_untimed = 0;
2185 if (trunk_maxmtu > trunk_nmaxmtu)
2186 trunk_nmaxmtu = trunk_maxmtu;
2188 return RESULT_SUCCESS;
2191 /*! \brief Set trunk MTU from CLI */
2192 static int iax2_set_mtu(int fd, int argc, char *argv[])
2197 return RESULT_SHOWUSAGE;
2198 if (strncasecmp(argv[3], "default", strlen(argv[3])) == 0)
2199 mtuv = MAX_TRUNK_MTU;
2201 mtuv = atoi(argv[3]);
2204 ast_cli(fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2205 global_max_trunk_mtu = 0;
2206 return RESULT_SUCCESS;
2208 if (mtuv < 172 || mtuv > 4000) {
2209 ast_cli(fd, "Trunk MTU must be between 172 and 4000\n");
2210 return RESULT_SHOWUSAGE;
2212 ast_cli(fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2213 global_max_trunk_mtu = mtuv;
2214 return RESULT_SUCCESS;
2217 static int iax2_show_cache(int fd, int argc, char *argv[])
2219 struct iax2_dpcache *dp = NULL;
2220 char tmp[1024], *pc = NULL;
2224 gettimeofday(&tv, NULL);
2226 AST_LIST_LOCK(&dpcache);
2228 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2230 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2231 s = dp->expiry.tv_sec - tv.tv_sec;
2233 if (dp->flags & CACHE_FLAG_EXISTS)
2234 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2235 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2236 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2237 if (dp->flags & CACHE_FLAG_CANEXIST)
2238 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2239 if (dp->flags & CACHE_FLAG_PENDING)
2240 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2241 if (dp->flags & CACHE_FLAG_TIMEOUT)
2242 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2243 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2244 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2245 if (dp->flags & CACHE_FLAG_MATCHMORE)
2246 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2247 if (dp->flags & CACHE_FLAG_UNKNOWN)
2248 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2249 /* Trim trailing pipe */
2250 if (!ast_strlen_zero(tmp))
2251 tmp[strlen(tmp) - 1] = '\0';
2253 ast_copy_string(tmp, "(none)", sizeof(tmp));
2255 pc = strchr(dp->peercontext, '@');
2257 pc = dp->peercontext;
2260 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2261 if (dp->waiters[x] > -1)
2264 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2266 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2269 AST_LIST_LOCK(&dpcache);
2271 return RESULT_SUCCESS;
2274 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2276 static void unwrap_timestamp(struct iax_frame *fr)
2280 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2281 x = fr->ts - iaxs[fr->callno]->last;
2283 /* Sudden big jump backwards in timestamp:
2284 What likely happened here is that miniframe timestamp has circled but we haven't
2285 gotten the update from the main packet. We'll just pretend that we did, and
2286 update the timestamp appropriately. */
2287 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2288 if (option_debug && iaxdebug)
2289 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2292 /* Sudden apparent big jump forwards in timestamp:
2293 What's likely happened is this is an old miniframe belonging to the previous
2294 top-16-bit timestamp that has turned up out of order.
2295 Adjust the timestamp appropriately. */
2296 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2297 if (option_debug && iaxdebug)
2298 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2303 static int get_from_jb(void *p);
2305 static void update_jbsched(struct chan_iax2_pvt *pvt)
2309 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2311 when = jb_next(pvt->jb) - when;
2313 if(pvt->jbid > -1) ast_sched_del(sched, pvt->jbid);
2316 /* XXX should really just empty until when > 0.. */
2320 pvt->jbid = ast_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2322 /* Signal scheduler thread */
2323 signal_condition(&sched_lock, &sched_cond);
2326 static void __get_from_jb(void *p)
2328 int callno = PTR_TO_CALLNO(p);
2329 struct chan_iax2_pvt *pvt = NULL;
2330 struct iax_frame *fr;
2337 /* Make sure we have a valid private structure before going on */
2338 ast_mutex_lock(&iaxsl[callno]);
2342 ast_mutex_unlock(&iaxsl[callno]);
2348 gettimeofday(&tv,NULL);
2349 /* round up a millisecond since ast_sched_runq does; */
2350 /* prevents us from spinning while waiting for our now */
2351 /* to catch up with runq's now */
2354 now = ast_tvdiff_ms(tv, pvt->rxcore);
2356 if(now >= (next = jb_next(pvt->jb))) {
2357 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2365 struct ast_frame af = { 0, };
2367 /* create an interpolation frame */
2368 af.frametype = AST_FRAME_VOICE;
2369 af.subclass = pvt->voiceformat;
2370 af.samples = frame.ms * 8;
2371 af.src = "IAX2 JB interpolation";
2372 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2373 af.offset = AST_FRIENDLY_OFFSET;
2375 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2376 * which we'd need to malloc, and then it would free it. That seems like a drag */
2377 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
2378 iax2_queue_frame(callno, &af);
2382 iax2_frame_free(frame.data);
2389 /* shouldn't happen */
2393 update_jbsched(pvt);
2394 ast_mutex_unlock(&iaxsl[callno]);
2397 static int get_from_jb(void *data)
2399 #ifdef SCHED_MULTITHREADED
2400 if (schedule_action(__get_from_jb, data))
2402 __get_from_jb(data);
2406 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2412 /* Attempt to recover wrapped timestamps */
2413 unwrap_timestamp(fr);
2416 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2417 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2418 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2422 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2424 fr->af.delivery = ast_tv(0,0);
2427 type = JB_TYPE_CONTROL;
2430 if(fr->af.frametype == AST_FRAME_VOICE) {
2431 type = JB_TYPE_VOICE;
2432 len = ast_codec_get_samples(&fr->af) / 8;
2433 } else if(fr->af.frametype == AST_FRAME_CNG) {
2434 type = JB_TYPE_SILENCE;
2437 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2444 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2445 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2446 if( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) &&
2447 iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner) &&
2448 (ast_bridged_channel(iaxs[fr->callno]->owner)->tech->properties & AST_CHAN_TP_WANTSJITTER)) {
2451 /* deliver any frames in the jb */
2452 while(jb_getall(iaxs[fr->callno]->jb,&frame) == JB_OK)
2453 __do_deliver(frame.data);
2455 jb_reset(iaxs[fr->callno]->jb);
2457 if (iaxs[fr->callno]->jbid > -1)
2458 ast_sched_del(sched, iaxs[fr->callno]->jbid);
2460 iaxs[fr->callno]->jbid = -1;
2462 /* deliver this frame now */
2469 /* insert into jitterbuffer */
2470 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2471 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2472 calc_rxstamp(iaxs[fr->callno],fr->ts));
2473 if (ret == JB_DROP) {
2475 } else if (ret == JB_SCHED) {
2476 update_jbsched(iaxs[fr->callno]);
2481 /* Free our iax frame */
2482 iax2_frame_free(fr);
2488 static int iax2_transmit(struct iax_frame *fr)
2490 /* Lock the queue and place this packet at the end */
2491 /* By setting this to 0, the network thread will send it for us, and
2492 queue retransmission if necessary */
2494 AST_LIST_LOCK(&queue);
2495 AST_LIST_INSERT_TAIL(&queue, fr, list);
2496 AST_LIST_UNLOCK(&queue);
2497 /* Wake up the network and scheduler thread */
2498 pthread_kill(netthreadid, SIGURG);
2499 signal_condition(&sched_lock, &sched_cond);
2505 static int iax2_digit_begin(struct ast_channel *c, char digit)
2507 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2510 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2512 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2515 static int iax2_sendtext(struct ast_channel *c, const char *text)
2518 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2519 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2522 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2524 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2527 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2529 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2532 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2534 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2535 ast_mutex_lock(&iaxsl[callno]);
2537 iaxs[callno]->owner = newchan;
2539 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2540 ast_mutex_unlock(&iaxsl[callno]);
2544 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2546 struct ast_variable *var;
2547 struct ast_variable *tmp;
2548 struct iax2_peer *peer=NULL;
2549 time_t regseconds = 0, nowtime;
2553 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2556 sprintf(porta, "%d", ntohs(sin->sin_port));
2557 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2559 /* We'll need the peer name in order to build the structure! */
2560 for (tmp = var; tmp; tmp = tmp->next) {
2561 if (!strcasecmp(tmp->name, "name"))
2562 peername = tmp->value;
2569 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2572 ast_variables_destroy(var);
2576 for (tmp = var; tmp; tmp = tmp->next) {
2577 /* Make sure it's not a user only... */
2578 if (!strcasecmp(tmp->name, "type")) {
2579 if (strcasecmp(tmp->value, "friend") &&
2580 strcasecmp(tmp->value, "peer")) {
2581 /* Whoops, we weren't supposed to exist! */
2586 } else if (!strcasecmp(tmp->name, "regseconds")) {
2587 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
2588 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2589 inet_aton(tmp->value, &(peer->addr.sin_addr));
2590 } else if (!strcasecmp(tmp->name, "port")) {
2591 peer->addr.sin_port = htons(atoi(tmp->value));
2592 } else if (!strcasecmp(tmp->name, "host")) {
2593 if (!strcasecmp(tmp->value, "dynamic"))
2598 ast_variables_destroy(var);
2603 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2604 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2605 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2606 if (peer->expire > -1)
2607 ast_sched_del(sched, peer->expire);
2608 peer->expire = ast_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, (void*)peer->name);
2610 AST_LIST_LOCK(&peers);
2611 AST_LIST_INSERT_HEAD(&peers, peer, entry);
2612 AST_LIST_UNLOCK(&peers);
2613 if (ast_test_flag(peer, IAX_DYNAMIC))
2614 reg_source_db(peer);
2616 ast_set_flag(peer, IAX_TEMPONLY);
2619 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2621 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2622 memset(&peer->addr, 0, sizeof(peer->addr));
2623 realtime_update_peer(peer->name, &peer->addr, 0);
2625 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2626 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2630 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2631 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2638 static struct iax2_user *realtime_user(const char *username)
2640 struct ast_variable *var;
2641 struct ast_variable *tmp;
2642 struct iax2_user *user=NULL;
2644 var = ast_load_realtime("iaxusers", "name", username, NULL);
2650 /* Make sure it's not a peer only... */
2651 if (!strcasecmp(tmp->name, "type")) {
2652 if (strcasecmp(tmp->value, "friend") &&
2653 strcasecmp(tmp->value, "user")) {
2660 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2662 ast_variables_destroy(var);
2667 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2668 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2669 AST_LIST_LOCK(&users);
2670 AST_LIST_INSERT_HEAD(&users, user, entry);
2671 AST_LIST_UNLOCK(&users);
2673 ast_set_flag(user, IAX_TEMPONLY);
2679 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2682 char regseconds[20];
2684 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2685 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2686 ast_update_realtime("iaxpeers", "name", peername,
2687 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2688 "regseconds", regseconds, NULL);
2691 struct create_addr_info {
2704 char context[AST_MAX_CONTEXT];
2705 char peercontext[AST_MAX_CONTEXT];
2706 char mohinterpret[MAX_MUSICCLASS];
2707 char mohsuggest[MAX_MUSICCLASS];
2710 static int create_addr(const char *peername, struct sockaddr_in *sin, struct create_addr_info *cai)
2712 struct iax2_peer *peer;
2714 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2715 cai->sockfd = defaultsockfd;
2717 sin->sin_family = AF_INET;
2719 if (!(peer = find_peer(peername, 1))) {
2721 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
2722 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2725 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2726 /* use global iax prefs for unknown peer/user */
2727 ast_codec_pref_convert(&prefs, cai->prefs, sizeof(cai->prefs), 1);
2733 /* if the peer has no address (current or default), return failure */
2734 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
2735 if (ast_test_flag(peer, IAX_TEMPONLY))
2740 /* if the peer is being monitored and is currently unreachable, return failure */
2741 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0))) {
2742 if (ast_test_flag(peer, IAX_TEMPONLY))
2747 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2748 cai->maxtime = peer->maxms;
2749 cai->capability = peer->capability;
2750 cai->encmethods = peer->encmethods;
2751 cai->sockfd = peer->sockfd;
2752 cai->adsi = peer->adsi;
2753 ast_codec_pref_convert(&peer->prefs, cai->prefs, sizeof(cai->prefs), 1);
2754 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2755 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2756 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2757 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2758 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2759 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2760 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2761 if (ast_strlen_zero(peer->dbsecret)) {
2762 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2767 family = ast_strdupa(peer->dbsecret);
2768 key = strchr(family, '/');
2771 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2772 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2773 if (ast_test_flag(peer, IAX_TEMPONLY))
2779 if (peer->addr.sin_addr.s_addr) {
2780 sin->sin_addr = peer->addr.sin_addr;
2781 sin->sin_port = peer->addr.sin_port;
2783 sin->sin_addr = peer->defaddr.sin_addr;
2784 sin->sin_port = peer->defaddr.sin_port;
2787 if (ast_test_flag(peer, IAX_TEMPONLY))
2793 static void __auto_congest(void *nothing)
2795 int callno = PTR_TO_CALLNO(nothing);
2796 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2797 ast_mutex_lock(&iaxsl[callno]);
2799 iaxs[callno]->initid = -1;
2800 iax2_queue_frame(callno, &f);
2801 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
2803 ast_mutex_unlock(&iaxsl[callno]);
2806 static int auto_congest(void *data)
2808 #ifdef SCHED_MULTITHREADED
2809 if (schedule_action(__auto_congest, data))
2811 __auto_congest(data);
2815 static unsigned int iax2_datetime(const char *tz)
2821 localtime_r(&t, &tm);
2822 if (!ast_strlen_zero(tz))
2823 ast_localtime(&t, &tm, tz);
2824 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
2825 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
2826 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
2827 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
2828 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
2829 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
2833 struct parsed_dial_string {
2845 * \brief Parses an IAX dial string into its component parts.
2846 * \param data the string to be parsed
2847 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
2850 * This function parses the string and fills the structure
2851 * with pointers to its component parts. The input string
2854 * \note This function supports both plaintext passwords and RSA
2855 * key names; if the password string is formatted as '[keyname]',
2856 * then the keyname will be placed into the key field, and the
2857 * password field will be set to NULL.
2859 * \note The dial string format is:
2860 * [username[:password]@]peer[:port][/exten[@@context]][/options]
2862 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
2864 if (ast_strlen_zero(data))
2867 pds->peer = strsep(&data, "/");
2868 pds->exten = strsep(&data, "/");
2869 pds->options = data;
2873 pds->exten = strsep(&data, "@");
2874 pds->context = data;
2877 if (strchr(pds->peer, '@')) {
2879 pds->username = strsep(&data, "@");
2883 if (pds->username) {
2884 data = pds->username;
2885 pds->username = strsep(&data, ":");
2886 pds->password = data;
2890 pds->peer = strsep(&data, ":");
2893 /* check for a key name wrapped in [] in the secret position, if found,
2894 move it to the key field instead
2896 if (pds->password && (pds->password[0] == '[')) {
2897 pds->key = ast_strip_quoted(pds->password, "[", "]");
2898 pds->password = NULL;
2902 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
2904 struct sockaddr_in sin;
2905 char *l=NULL, *n=NULL, *tmpstr;
2906 struct iax_ie_data ied;
2907 char *defaultrdest = "s";
2908 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
2909 struct parsed_dial_string pds;
2910 struct create_addr_info cai;
2911 struct ast_var_t *var;
2912 const char* osp_token_ptr;
2913 unsigned int osp_token_length;
2914 unsigned char osp_block_index;
2915 unsigned int osp_block_length;
2916 unsigned char osp_buffer[256];
2918 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
2919 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
2923 memset(&cai, 0, sizeof(cai));
2924 cai.encmethods = iax2_encryption;
2926 memset(&pds, 0, sizeof(pds));
2927 tmpstr = ast_strdupa(dest);
2928 parse_dial_string(tmpstr, &pds);
2931 pds.exten = defaultrdest;
2933 if (create_addr(pds.peer, &sin, &cai)) {
2934 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
2938 if (!pds.username && !ast_strlen_zero(cai.username))
2939 pds.username = cai.username;
2940 if (!pds.password && !ast_strlen_zero(cai.secret))
2941 pds.password = cai.secret;
2942 if (!pds.key && !ast_strlen_zero(cai.outkey))
2943 pds.key = cai.outkey;
2944 if (!pds.context && !ast_strlen_zero(cai.peercontext))
2945 pds.context = cai.peercontext;
2947 /* Keep track of the context for outgoing calls too */
2948 ast_copy_string(c->context, cai.context, sizeof(c->context));
2951 sin.sin_port = htons(atoi(pds.port));
2954 n = c->cid.cid_name;
2956 /* Now build request */
2957 memset(&ied, 0, sizeof(ied));
2959 /* On new call, first IE MUST be IAX version of caller */
2960 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
2961 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
2962 if (pds.options && strchr(pds.options, 'a')) {
2963 /* Request auto answer */
2964 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
2967 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
2970 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
2971 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2974 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
2976 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
2979 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
2980 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
2983 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
2984 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
2985 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
2987 if (!ast_strlen_zero(c->language))
2988 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
2989 if (!ast_strlen_zero(c->cid.cid_dnid))
2990 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
2991 if (!ast_strlen_zero(c->cid.cid_rdnis))
2992 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
2995 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
2998 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3001 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3003 ast_mutex_lock(&iaxsl[callno]);
3005 if (!ast_strlen_zero(c->context))
3006 ast_string_field_set(iaxs[callno], context, c->context);
3009 ast_string_field_set(iaxs[callno], username, pds.username);
3011 iaxs[callno]->encmethods = cai.encmethods;
3013 iaxs[callno]->adsi = cai.adsi;
3015 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3016 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3019 ast_string_field_set(iaxs[callno], outkey, pds.key);
3021 ast_string_field_set(iaxs[callno], secret, pds.password);
3023 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3024 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3025 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3026 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3028 if (iaxs[callno]->maxtime) {
3029 /* Initialize pingtime and auto-congest time */
3030 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3031 iaxs[callno]->initid = ast_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3032 } else if (autokill) {
3033 iaxs[callno]->pingtime = autokill / 2;
3034 iaxs[callno]->initid = ast_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3037 /* Check if there is an OSP token set by IAXCHANINFO function */
3038 osp_token_ptr = iaxs[callno]->osptoken;
3039 if (!ast_strlen_zero(osp_token_ptr)) {
3040 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3041 osp_block_index = 0;
3042 while (osp_token_length > 0) {
3043 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3044 osp_buffer[0] = osp_block_index;
3045 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3046 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3048 osp_token_ptr += osp_block_length;
3049 osp_token_length -= osp_block_length;
3052 ast_log(LOG_WARNING, "OSP token is too long\n");
3053 } else if (option_debug && iaxdebug)
3054 ast_log(LOG_DEBUG, "OSP token is undefined\n");
3056 /* send the command using the appropriate socket for this peer */
3057 iaxs[callno]->sockfd = cai.sockfd;
3059 /* Add remote vars */
3060 AST_LIST_TRAVERSE(&c->varshead, var, entries) {
3061 if (!strncmp(ast_var_name(var), "~IAX2~", strlen("~IAX2~"))) {
3064 /* Automatically divide the value up into sized chunks */
3065 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) - strlen("~IAX2~") + 1)) {
3066 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var) + strlen("~IAX2~"), ast_var_value(var) + i);
3067 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3072 /* Transmit the string in a "NEW" request */
3073 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3075 ast_mutex_unlock(&iaxsl[callno]);
3076 ast_setstate(c, AST_STATE_RINGING);
3081 static int iax2_hangup(struct ast_channel *c)
3083 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3085 struct iax_ie_data ied;
3086 memset(&ied, 0, sizeof(ied));
3087 ast_mutex_lock(&iaxsl[callno]);
3088 if (callno && iaxs[callno]) {
3090 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3091 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3092 /* Send the hangup unless we have had a transmission error or are already gone */
3093 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3094 if (!iaxs[callno]->error && !alreadygone)
3095 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3096 /* Explicitly predestroy it */
3097 iax2_predestroy(callno);
3098 /* If we were already gone to begin with, destroy us now */
3101 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3102 iax2_destroy(callno);
3105 ast_mutex_unlock(&iaxsl[callno]);
3106 if (option_verbose > 2)
3107 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3111 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3113 struct ast_option_header *h;
3117 case AST_OPTION_TXGAIN:
3118 case AST_OPTION_RXGAIN:
3119 /* these two cannot be sent, because they require a result */
3123 if (!(h = ast_malloc(datalen + sizeof(*h))))
3126 h->flag = AST_OPTION_FLAG_REQUEST;
3127 h->option = htons(option);
3128 memcpy(h->data, data, datalen);
3129 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3130 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3131 datalen + sizeof(*h), -1);
3137 static struct ast_frame *iax2_read(struct ast_channel *c)
3139 ast_log(LOG_NOTICE, "I should never be called!\n");
3140 return &ast_null_frame;
3143 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3146 struct iax_ie_data ied0;
3147 struct iax_ie_data ied1;
3148 unsigned int transferid = (unsigned int)ast_random();
3149 memset(&ied0, 0, sizeof(ied0));
3150 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3151 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3152 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3154 memset(&ied1, 0, sizeof(ied1));
3155 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3156 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3157 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3159 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3162 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3165 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3166 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3170 static void lock_both(unsigned short callno0, unsigned short callno1)
3172 ast_mutex_lock(&iaxsl[callno0]);
3173 while (ast_mutex_trylock(&iaxsl[callno1])) {
3174 ast_mutex_unlock(&iaxsl[callno0]);
3176 ast_mutex_lock(&iaxsl[callno0]);
3180 static void unlock_both(unsigned short callno0, unsigned short callno1)
3182 ast_mutex_unlock(&iaxsl[callno1]);
3183 ast_mutex_unlock(&iaxsl[callno0]);
3186 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)
3188 struct ast_channel *cs[3];
3189 struct ast_channel *who, *other;
3192 int transferstarted=0;
3193 struct ast_frame *f;
3194 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3195 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);