2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
30 * \todo Implement musicclass settings for IAX2 devices
39 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
49 #include <sys/signal.h>
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
90 #include "asterisk/timing.h"
93 #include "iax2-parser.h"
94 #include "iax2-provision.h"
95 #include "jitterbuf.h"
97 /* Define SCHED_MULTITHREADED to run the scheduler in a special
98 multithreaded mode. */
99 #define SCHED_MULTITHREADED
101 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
102 thread is actually doing. */
103 #define DEBUG_SCHED_MULTITHREAD
107 static int nochecksums
= 0;
110 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
111 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
113 #define DEFAULT_THREAD_COUNT 10
114 #define DEFAULT_MAX_THREAD_COUNT 100
115 #define DEFAULT_RETRY_TIME 1000
116 #define MEMORY_SIZE 100
117 #define DEFAULT_DROP 3
119 #define DEBUG_SUPPORT
121 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
123 /* Sample over last 100 units to determine historic jitter */
126 static struct ast_codec_pref prefs
;
128 static const char tdesc
[] = "Inter Asterisk eXchange Driver (Ver 2)";
131 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
132 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
133 #define MAX_TRUNK_MTU 1240
135 static int global_max_trunk_mtu
; /*!< Maximum MTU, 0 if not used */
136 static int trunk_timed
, trunk_untimed
, trunk_maxmtu
, trunk_nmaxmtu
; /*!< Trunk MTU statistics */
138 #define DEFAULT_CONTEXT "default"
140 static char default_parkinglot
[AST_MAX_CONTEXT
];
142 static char language
[MAX_LANGUAGE
] = "";
143 static char regcontext
[AST_MAX_CONTEXT
] = "";
145 static int maxauthreq
= 3;
146 static int max_retries
= 4;
147 static int ping_time
= 21;
148 static int lagrq_time
= 10;
149 static int maxjitterbuffer
=1000;
150 static int resyncthreshold
=1000;
151 static int maxjitterinterps
=10;
152 static int jittertargetextra
= 40; /* number of milliseconds the new jitter buffer adds on to its size */
154 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
156 static int trunkfreq
= 20;
157 static int trunkmaxsize
= MAX_TRUNKDATA
;
159 static int authdebug
= 1;
160 static int autokill
= 0;
161 static int iaxcompat
= 0;
163 static int iaxdefaultdpcache
=10 * 60; /* Cache dialplan entries for 10 minutes by default */
165 static int iaxdefaulttimeout
= 5; /* Default to wait no more than 5 seconds for a reply to come back */
172 static int min_reg_expire
;
173 static int max_reg_expire
;
175 static int srvlookup
= 0;
177 static int timingfd
= -1; /* Timing file descriptor */
179 static struct ast_netsock_list
*netsock
;
180 static struct ast_netsock_list
*outsock
; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
181 static int defaultsockfd
= -1;
183 int (*iax2_regfunk
)(const char *username
, int onoff
) = NULL
;
186 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
188 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
189 ~AST_FORMAT_SLINEAR & \
194 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
196 ~AST_FORMAT_G726_AAL2 & \
199 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
203 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
204 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
205 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
207 /* if a pvt has encryption setup done and is running on the call */
208 #define IAX_CALLENCRYPTED(pvt) \
209 (ast_test_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(pvt, IAX_KEYPOPULATED))
211 #define IAX_DEBUGDIGEST(msg, key) do { \
213 char digest[33] = ""; \
218 for (idx = 0; idx < 16; idx++) \
219 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
221 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
224 static struct io_context
*io
;
225 static struct sched_context
*sched
;
227 static int iax2_capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
229 static int iaxdebug
= 0;
231 static int iaxtrunkdebug
= 0;
233 static int test_losspct
= 0;
235 static int test_late
= 0;
236 static int test_resync
= 0;
237 static int test_jit
= 0;
238 static int test_jitpct
= 0;
239 #endif /* IAXTESTS */
241 static char accountcode
[AST_MAX_ACCOUNT_CODE
];
242 static char mohinterpret
[MAX_MUSICCLASS
];
243 static char mohsuggest
[MAX_MUSICCLASS
];
244 static int amaflags
= 0;
246 static int delayreject
= 0;
247 static int iax2_encryption
= 0;
249 static struct ast_flags globalflags
= { 0 };
251 static pthread_t netthreadid
= AST_PTHREADT_NULL
;
252 static pthread_t schedthreadid
= AST_PTHREADT_NULL
;
253 AST_MUTEX_DEFINE_STATIC(sched_lock
);
254 static ast_cond_t sched_cond
;
257 IAX_STATE_STARTED
= (1 << 0),
258 IAX_STATE_AUTHENTICATED
= (1 << 1),
259 IAX_STATE_TBD
= (1 << 2),
260 IAX_STATE_UNCHANGED
= (1 << 3),
263 struct iax2_context
{
264 char context
[AST_MAX_CONTEXT
];
265 struct iax2_context
*next
;
269 IAX_HASCALLERID
= (1 << 0), /*!< CallerID has been specified */
270 IAX_DELME
= (1 << 1), /*!< Needs to be deleted */
271 IAX_TEMPONLY
= (1 << 2), /*!< Temporary (realtime) */
272 IAX_TRUNK
= (1 << 3), /*!< Treat as a trunk */
273 IAX_NOTRANSFER
= (1 << 4), /*!< Don't native bridge */
274 IAX_USEJITTERBUF
= (1 << 5), /*!< Use jitter buffer */
275 IAX_DYNAMIC
= (1 << 6), /*!< dynamic peer */
276 IAX_SENDANI
= (1 << 7), /*!< Send ANI along with CallerID */
277 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
278 IAX_ALREADYGONE
= (1 << 9), /*!< Already disconnected */
279 IAX_PROVISION
= (1 << 10), /*!< This is a provisioning request */
280 IAX_QUELCH
= (1 << 11), /*!< Whether or not we quelch audio */
281 IAX_ENCRYPTED
= (1 << 12), /*!< Whether we should assume encrypted tx/rx */
282 IAX_KEYPOPULATED
= (1 << 13), /*!< Whether we have a key populated */
283 IAX_CODEC_USER_FIRST
= (1 << 14), /*!< are we willing to let the other guy choose the codec? */
284 IAX_CODEC_NOPREFS
= (1 << 15), /*!< Force old behaviour by turning off prefs */
285 IAX_CODEC_NOCAP
= (1 << 16), /*!< only consider requested format and ignore capabilities*/
286 IAX_RTCACHEFRIENDS
= (1 << 17), /*!< let realtime stay till your reload */
287 IAX_RTUPDATE
= (1 << 18), /*!< Send a realtime update */
288 IAX_RTAUTOCLEAR
= (1 << 19), /*!< erase me on expire */
289 IAX_FORCEJITTERBUF
= (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
290 IAX_RTIGNOREREGEXPIRE
= (1 << 21), /*!< When using realtime, ignore registration expiration */
291 IAX_TRUNKTIMESTAMPS
= (1 << 22), /*!< Send trunk timestamps */
292 IAX_TRANSFERMEDIA
= (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
293 IAX_MAXAUTHREQ
= (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
294 IAX_DELAYPBXSTART
= (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
295 response, so that we've achieved a three-way handshake with
296 them before sending voice or anything else*/
297 IAX_ALLOWFWDOWNLOAD
= (1 << 26), /*!< Allow the FWDOWNL command? */
298 IAX_NOKEYROTATE
= (1 << 27), /*!< Disable key rotation with encryption */
301 static int global_rtautoclear
= 120;
303 static int reload_config(void);
306 AST_DECLARE_STRING_FIELDS(
307 AST_STRING_FIELD(name
);
308 AST_STRING_FIELD(secret
);
309 AST_STRING_FIELD(dbsecret
);
310 AST_STRING_FIELD(accountcode
);
311 AST_STRING_FIELD(mohinterpret
);
312 AST_STRING_FIELD(mohsuggest
);
313 AST_STRING_FIELD(inkeys
); /*!< Key(s) this user can use to authenticate to us */
314 AST_STRING_FIELD(language
);
315 AST_STRING_FIELD(cid_num
);
316 AST_STRING_FIELD(cid_name
);
317 AST_STRING_FIELD(parkinglot
); /*!< Default parkinglot for device */
326 int maxauthreq
; /*!< Maximum allowed outstanding AUTHREQs */
327 int curauthreq
; /*!< Current number of outstanding AUTHREQs */
328 struct ast_codec_pref prefs
;
330 struct iax2_context
*contexts
;
331 struct ast_variable
*vars
;
335 AST_DECLARE_STRING_FIELDS(
336 AST_STRING_FIELD(name
);
337 AST_STRING_FIELD(username
);
338 AST_STRING_FIELD(secret
);
339 AST_STRING_FIELD(dbsecret
);
340 AST_STRING_FIELD(outkey
); /*!< What key we use to talk to this peer */
342 AST_STRING_FIELD(regexten
); /*!< Extension to register (if regcontext is used) */
343 AST_STRING_FIELD(context
); /*!< For transfers only */
344 AST_STRING_FIELD(peercontext
); /*!< Context to pass to peer */
345 AST_STRING_FIELD(mailbox
); /*!< Mailbox */
346 AST_STRING_FIELD(mohinterpret
);
347 AST_STRING_FIELD(mohsuggest
);
348 AST_STRING_FIELD(inkeys
); /*!< Key(s) this peer can use to authenticate to us */
349 /* Suggested caller id if registering */
350 AST_STRING_FIELD(cid_num
); /*!< Default context (for transfer really) */
351 AST_STRING_FIELD(cid_name
); /*!< Default context (for transfer really) */
352 AST_STRING_FIELD(zonetag
); /*!< Time Zone */
353 AST_STRING_FIELD(parkinglot
); /*!< Default parkinglot for device */
355 struct ast_codec_pref prefs
;
356 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
357 struct sockaddr_in addr
;
359 int sockfd
; /*!< Socket to use for transmission */
364 /* Dynamic Registration fields */
365 struct sockaddr_in defaddr
; /*!< Default address if there is one */
366 int authmethods
; /*!< Authentication methods (IAX_AUTH_*) */
367 int encmethods
; /*!< Encryption methods (IAX_ENCRYPT_*) */
369 int expire
; /*!< Schedule entry for expiry */
370 int expiry
; /*!< How soon to expire */
371 int capability
; /*!< Capability */
374 int callno
; /*!< Call number of POKE request */
375 int pokeexpire
; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
376 int lastms
; /*!< How long last response took (in ms), or -1 for no response */
377 int maxms
; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
379 int pokefreqok
; /*!< How often to check if the host is up */
380 int pokefreqnotok
; /*!< How often to check when the host has been determined to be down */
381 int historicms
; /*!< How long recent average responses took */
382 int smoothing
; /*!< Sample over how many units to determine historic ms */
384 struct ast_event_sub
*mwi_event_sub
;
389 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
391 struct iax2_trunk_peer
{
394 struct sockaddr_in addr
;
395 struct timeval txtrunktime
; /*!< Transmit trunktime */
396 struct timeval rxtrunktime
; /*!< Receive trunktime */
397 struct timeval lasttxtime
; /*!< Last transmitted trunktime */
398 struct timeval trunkact
; /*!< Last trunk activity */
399 unsigned int lastsent
; /*!< Last sent time */
400 /* Trunk data and length */
401 unsigned char *trunkdata
;
402 unsigned int trunkdatalen
;
403 unsigned int trunkdataalloc
;
407 AST_LIST_ENTRY(iax2_trunk_peer
) list
;
410 static AST_LIST_HEAD_STATIC(tpeers
, iax2_trunk_peer
);
412 struct iax_firmware
{
413 AST_LIST_ENTRY(iax_firmware
) list
;
417 struct ast_iax2_firmware_header
*fwh
;
422 REG_STATE_UNREGISTERED
= 0,
425 REG_STATE_REGISTERED
,
431 enum iax_transfer_state
{
441 struct iax2_registry
{
442 struct sockaddr_in addr
; /*!< Who we connect to for registration purposes */
444 char secret
[80]; /*!< Password or key name in []'s */
445 int expire
; /*!< Sched ID of expiration */
446 int refresh
; /*!< How often to refresh */
447 enum iax_reg_state regstate
;
448 int messages
; /*!< Message count, low 8 bits = new, high 8 bits = old */
449 int callno
; /*!< Associated call number if applicable */
450 struct sockaddr_in us
; /*!< Who the server thinks we are */
451 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
452 AST_LIST_ENTRY(iax2_registry
) entry
;
455 static AST_LIST_HEAD_STATIC(registrations
, iax2_registry
);
457 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
458 #define MIN_RETRY_TIME 100
459 #define MAX_RETRY_TIME 10000
461 #define MAX_JITTER_BUFFER 50
462 #define MIN_JITTER_BUFFER 10
464 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
466 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
468 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
469 #define TS_GAP_FOR_JB_RESYNC 5000
471 static int iaxthreadcount
= DEFAULT_THREAD_COUNT
;
472 static int iaxmaxthreadcount
= DEFAULT_MAX_THREAD_COUNT
;
473 static int iaxdynamicthreadcount
= 0;
474 static int iaxdynamicthreadnum
= 0;
475 static int iaxactivethreadcount
= 0;
489 struct chan_iax2_pvt
{
490 /*! Socket to send/receive on for this call */
492 /*! Last received voice format */
494 /*! Last received video format */
496 /*! Last sent voice format */
498 /*! Last sent video format */
500 /*! What we are capable of sending */
502 /*! Last received timestamp */
504 /*! Last sent timestamp - never send the same timestamp twice in a single call */
505 unsigned int lastsent
;
506 /*! Timestamp of the last video frame sent */
507 unsigned int lastvsent
;
508 /*! Next outgoing timestamp if everything is good */
509 unsigned int nextpred
;
510 /*! True if the last voice we transmitted was not silence/CNG */
511 unsigned int notsilenttx
:1;
513 unsigned int pingtime
;
514 /*! Max time for initial response */
517 struct sockaddr_in addr
;
518 /*! Actual used codec preferences */
519 struct ast_codec_pref prefs
;
520 /*! Requested codec preferences */
521 struct ast_codec_pref rprefs
;
522 /*! Our call number */
523 unsigned short callno
;
525 unsigned short peercallno
;
526 /*! Negotiated format, this is only used to remember what format was
527 chosen for an unauthenticated call so that the channel can get
528 created later using the right format */
530 /*! Peer selected format */
532 /*! Peer capability */
534 /*! timeval that we base our transmission on */
535 struct timeval offset
;
536 /*! timeval that we base our delivery on */
537 struct timeval rxcore
;
538 /*! The jitterbuffer */
540 /*! active jb read scheduler id */
544 /*! Error, as discovered by the manager */
546 /*! Owner if we have one */
547 struct ast_channel
*owner
;
548 /*! What's our state? */
549 struct ast_flags state
;
550 /*! Expiry (optional) */
552 /*! Next outgoing sequence number */
553 unsigned char oseqno
;
554 /*! Next sequence number they have not yet acknowledged */
555 unsigned char rseqno
;
556 /*! Next incoming sequence number */
557 unsigned char iseqno
;
558 /*! Last incoming sequence number we have acknowledged */
559 unsigned char aseqno
;
561 AST_DECLARE_STRING_FIELDS(
563 AST_STRING_FIELD(peer
);
564 /*! Default Context */
565 AST_STRING_FIELD(context
);
566 /*! Caller ID if available */
567 AST_STRING_FIELD(cid_num
);
568 AST_STRING_FIELD(cid_name
);
569 /*! Hidden Caller ID (i.e. ANI) if appropriate */
570 AST_STRING_FIELD(ani
);
572 AST_STRING_FIELD(dnid
);
574 AST_STRING_FIELD(rdnis
);
575 /*! Requested Extension */
576 AST_STRING_FIELD(exten
);
577 /*! Expected Username */
578 AST_STRING_FIELD(username
);
579 /*! Expected Secret */
580 AST_STRING_FIELD(secret
);
582 AST_STRING_FIELD(challenge
);
583 /*! Public keys permitted keys for incoming authentication */
584 AST_STRING_FIELD(inkeys
);
585 /*! Private key for outgoing authentication */
586 AST_STRING_FIELD(outkey
);
587 /*! Preferred language */
588 AST_STRING_FIELD(language
);
589 /*! Hostname/peername for naming purposes */
590 AST_STRING_FIELD(host
);
592 AST_STRING_FIELD(dproot
);
593 AST_STRING_FIELD(accountcode
);
594 AST_STRING_FIELD(mohinterpret
);
595 AST_STRING_FIELD(mohsuggest
);
596 /*! received OSP token */
597 AST_STRING_FIELD(osptoken
);
598 /*! Default parkinglot */
599 AST_STRING_FIELD(parkinglot
);
602 /*! permitted authentication methods */
604 /*! permitted encryption methods */
606 /*! Encryption AES-128 Key */
607 ast_aes_encrypt_key ecx
;
608 /*! Decryption AES-128 Key */
609 ast_aes_decrypt_key dcx
;
610 /*! scheduler id associated with iax_key_rotate
611 * for encrypted calls*/
613 /*! 32 bytes of semi-random data */
614 unsigned char semirand
[32];
615 /*! Associated registry */
616 struct iax2_registry
*reg
;
617 /*! Associated peer for poking */
618 struct iax2_peer
*peerpoke
;
623 /*! Transferring status */
624 enum iax_transfer_state transferring
;
625 /*! Transfer identifier */
627 /*! Who we are IAX transferring to */
628 struct sockaddr_in transfer
;
629 /*! What's the new call number for the transfer */
630 unsigned short transfercallno
;
631 /*! Transfer encrypt AES-128 Key */
632 ast_aes_encrypt_key tdcx
;
634 /*! If transfer has been attempted */
635 unsigned int triedtransfer
:1;
636 /*! Whether media is released */
637 unsigned int mediareleased
:1;
638 /*! If media released, the peer to send media to */
639 struct sockaddr_in media
;
641 /*! Status of knowledge of peer ADSI capability */
644 /*! Who we are bridged to */
645 unsigned short bridgecallno
;
647 int pingid
; /*!< Transmit PING request */
648 int lagid
; /*!< Retransmit lag request */
649 int autoid
; /*!< Auto hangup for Dialplan requestor */
650 int authid
; /*!< Authentication rejection ID */
651 int authfail
; /*!< Reason to report failure */
652 int initid
; /*!< Initial peer auto-congest ID (based on qualified peers) */
657 AST_LIST_HEAD_NOLOCK(, iax2_dpcache
) dpentries
;
658 struct ast_variable
*vars
;
659 /*! last received remote rr */
660 struct iax_rr remote_rr
;
661 /*! Current base time: (just for stats) */
663 /*! Dropped frame count: (just for stats) */
665 /*! received frame count: (just for stats) */
670 * \brief a list of frames that may need to be retransmitted
672 * \note The contents of this list do not need to be explicitly destroyed
673 * on module unload. This is because all active calls are destroyed, and
674 * all frames in this queue will get destroyed as a part of that process.
676 static AST_LIST_HEAD_STATIC(frame_queue
, iax_frame
);
679 * This module will get much higher performance when doing a lot of
680 * user and peer lookups if the number of buckets is increased from 1.
681 * However, to maintain old behavior for Asterisk 1.4, these are set to
682 * 1 by default. When using multiple buckets, search order through these
683 * containers is considered random, so you will not be able to depend on
684 * the order the entires are specified in iax.conf for matching order. */
686 #define MAX_PEER_BUCKETS 17
688 #define MAX_PEER_BUCKETS 563
690 static struct ao2_container
*peers
;
692 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
693 static struct ao2_container
*users
;
695 static AST_LIST_HEAD_STATIC(firmwares
, iax_firmware
);
698 /*! Extension exists */
699 CACHE_FLAG_EXISTS
= (1 << 0),
700 /*! Extension is nonexistent */
701 CACHE_FLAG_NONEXISTENT
= (1 << 1),
702 /*! Extension can exist */
703 CACHE_FLAG_CANEXIST
= (1 << 2),
704 /*! Waiting to hear back response */
705 CACHE_FLAG_PENDING
= (1 << 3),
707 CACHE_FLAG_TIMEOUT
= (1 << 4),
708 /*! Request transmitted */
709 CACHE_FLAG_TRANSMITTED
= (1 << 5),
711 CACHE_FLAG_UNKNOWN
= (1 << 6),
713 CACHE_FLAG_MATCHMORE
= (1 << 7),
716 struct iax2_dpcache
{
717 char peercontext
[AST_MAX_CONTEXT
];
718 char exten
[AST_MAX_EXTENSION
];
720 struct timeval expiry
;
722 unsigned short callno
;
724 AST_LIST_ENTRY(iax2_dpcache
) cache_list
;
725 AST_LIST_ENTRY(iax2_dpcache
) peer_list
;
728 static AST_LIST_HEAD_STATIC(dpcache
, iax2_dpcache
);
730 static void reg_source_db(struct iax2_peer
*p
);
731 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
);
733 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
);
734 static char *complete_iax2_peers(const char *line
, const char *word
, int pos
, int state
);
735 static char *complete_iax2_unregister(const char *line
, const char *word
, int pos
, int state
);
737 enum iax2_thread_iostate
{
740 IAX_IOSTATE_PROCESSING
,
741 IAX_IOSTATE_SCHEDREADY
,
744 enum iax2_thread_type
{
745 IAX_THREAD_TYPE_POOL
,
746 IAX_THREAD_TYPE_DYNAMIC
,
749 struct iax2_pkt_buf
{
750 AST_LIST_ENTRY(iax2_pkt_buf
) entry
;
752 unsigned char buf
[1];
756 AST_LIST_ENTRY(iax2_thread
) list
;
757 enum iax2_thread_type type
;
758 enum iax2_thread_iostate iostate
;
759 #ifdef SCHED_MULTITHREADED
760 void (*schedfunc
)(const void *);
761 const void *scheddata
;
763 #ifdef DEBUG_SCHED_MULTITHREAD
769 struct sockaddr_in iosin
;
770 unsigned char readbuf
[4096];
778 unsigned int ready_for_signal
:1;
779 /*! if this thread is processing a full frame,
780 some information about that frame will be stored
781 here, so we can avoid dispatching any more full
782 frames for that callno to other threads */
784 unsigned short callno
;
785 struct sockaddr_in sin
;
789 /*! Queued up full frames for processing. If more full frames arrive for
790 * a call which this thread is already processing a full frame for, they
791 * are queued up here. */
792 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf
) full_frames
;
796 static AST_LIST_HEAD_STATIC(idle_list
, iax2_thread
);
797 static AST_LIST_HEAD_STATIC(active_list
, iax2_thread
);
798 static AST_LIST_HEAD_STATIC(dynamic_list
, iax2_thread
);
800 static void *iax2_process_thread(void *data
);
802 static void signal_condition(ast_mutex_t
*lock
, ast_cond_t
*cond
)
804 ast_mutex_lock(lock
);
805 ast_cond_signal(cond
);
806 ast_mutex_unlock(lock
);
810 * \brief an array of iax2 pvt structures
812 * The container for active chan_iax2_pvt structures is implemented as an
813 * array for extremely quick direct access to the correct pvt structure
814 * based on the local call number. The local call number is used as the
815 * index into the array where the associated pvt structure is stored.
817 static struct chan_iax2_pvt
*iaxs
[IAX_MAX_CALLS
];
820 * \brief Another container of iax2_pvt structures
822 * Active IAX2 pvt structs are also stored in this container, if they are a part
823 * of an active call where we know the remote side's call number. The reason
824 * for this is that incoming media frames do not contain our call number. So,
825 * instead of having to iterate the entire iaxs array, we use this container to
826 * look up calls where the remote side is using a given call number.
828 static struct ao2_container
*iax_peercallno_pvts
;
831 * \brief chan_iax2_pvt structure locks
833 * These locks are used when accessing a pvt structure in the iaxs array.
834 * The index used here is the same as used in the iaxs array. It is the
835 * local call number for the associated pvt struct.
837 static ast_mutex_t iaxsl
[ARRAY_LEN(iaxs
)];
840 * \brief The last time a call number was used
842 * It is important to know the last time that a call number was used locally so
843 * that it is not used again too soon. The reason for this is the same as the
844 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
846 * For example, say that a call is up. Then, the remote side sends a HANGUP,
847 * which we respond to with an ACK. However, there is no way to know whether
848 * the ACK made it there successfully. If it were to get lost, the remote
849 * side may retransmit the HANGUP. If in the meantime, this call number has
850 * been reused locally, given the right set of circumstances, this retransmitted
851 * HANGUP could potentially improperly hang up the new session. So, to avoid
852 * this potential issue, we must wait a specified timeout period before reusing
853 * a local call number.
855 * The specified time that we must wait before reusing a local call number is
856 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
858 static struct timeval lastused
[ARRAY_LEN(iaxs
)];
860 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
861 but keeps the division between trunked and non-trunked better. */
862 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
864 /* Debug routines... */
865 static struct sockaddr_in debugaddr
;
867 static void iax_outputframe(struct iax_frame
*f
, struct ast_iax2_full_hdr
*fhi
, int rx
, struct sockaddr_in
*sin
, int datalen
)
870 (sin
&& debugaddr
.sin_addr
.s_addr
&&
871 (!ntohs(debugaddr
.sin_port
) ||
872 debugaddr
.sin_port
== sin
->sin_port
) &&
873 debugaddr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
)) {
875 iax_showframe(f
, fhi
, rx
, sin
, datalen
);
878 iax_showframe(f
, fhi
, rx
, sin
, datalen
);
884 static void iax_debug_output(const char *data
)
887 ast_verbose("%s", data
);
890 static void iax_error_output(const char *data
)
892 ast_log(LOG_WARNING
, "%s", data
);
895 static void __attribute__((format (printf
, 1, 2))) jb_error_output(const char *fmt
, ...)
901 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
904 ast_log(LOG_ERROR
, "%s", buf
);
907 static void __attribute__((format (printf
, 1, 2))) jb_warning_output(const char *fmt
, ...)
913 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
916 ast_log(LOG_WARNING
, "%s", buf
);
919 static void __attribute__((format (printf
, 1, 2))) jb_debug_output(const char *fmt
, ...)
925 vsnprintf(buf
, sizeof(buf
), fmt
, args
);
928 ast_verbose("%s", buf
);
931 static int maxtrunkcall
= TRUNK_CALL_START
;
932 static int maxnontrunkcall
= 1;
934 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
);
935 static int expire_registry(const void *data
);
936 static int iax2_answer(struct ast_channel
*c
);
937 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
);
938 static int iax2_devicestate(void *data
);
939 static int iax2_digit_begin(struct ast_channel
*c
, char digit
);
940 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
);
941 static int iax2_do_register(struct iax2_registry
*reg
);
942 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
);
943 static int iax2_hangup(struct ast_channel
*c
);
944 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
);
945 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
946 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
947 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
, int media
);
948 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
);
949 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
);
950 static int iax2_sendtext(struct ast_channel
*c
, const char *text
);
951 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
);
952 static int iax2_transfer(struct ast_channel
*c
, const char *dest
);
953 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
);
954 static int send_trunk(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
);
955 static int send_command(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
956 static int send_command_final(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
957 static int send_command_immediate(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
958 static int send_command_locked(unsigned short callno
, char, int, unsigned int, const unsigned char *, int, int);
959 static int send_command_transfer(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int);
960 static int send_command_media(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int);
961 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
);
962 static struct ast_frame
*iax2_read(struct ast_channel
*c
);
963 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
964 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
965 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
);
966 static void prune_peers(void);
967 static void *iax2_dup_variable_datastore(void *);
968 static void iax2_free_variable_datastore(void *);
970 static int acf_channel_read(struct ast_channel
*chan
, const char *funcname
, char *preparse
, char *buf
, size_t buflen
);
971 static int acf_channel_write(struct ast_channel
*chan
, const char *function
, char *data
, const char *value
);
973 static const struct ast_channel_tech iax2_tech
= {
975 .description
= tdesc
,
976 .capabilities
= IAX_CAPABILITY_FULLBANDWIDTH
,
977 .properties
= AST_CHAN_TP_WANTSJITTER
,
978 .requester
= iax2_request
,
979 .devicestate
= iax2_devicestate
,
980 .send_digit_begin
= iax2_digit_begin
,
981 .send_digit_end
= iax2_digit_end
,
982 .send_text
= iax2_sendtext
,
983 .send_image
= iax2_sendimage
,
984 .send_html
= iax2_sendhtml
,
986 .hangup
= iax2_hangup
,
987 .answer
= iax2_answer
,
990 .write_video
= iax2_write
,
991 .indicate
= iax2_indicate
,
992 .setoption
= iax2_setoption
,
993 .bridge
= iax2_bridge
,
994 .transfer
= iax2_transfer
,
996 .func_channel_read
= acf_channel_read
,
997 .func_channel_write
= acf_channel_write
,
1000 static void mwi_event_cb(const struct ast_event
*event
, void *userdata
)
1002 /* The MWI subscriptions exist just so the core knows we care about those
1003 * mailboxes. However, we just grab the events out of the cache when it
1004 * is time to send MWI, since it is only sent with a REGACK. */
1007 /*! \brief Send manager event at call setup to link between Asterisk channel name
1008 and IAX2 call identifiers */
1009 static void iax2_ami_channelupdate(struct chan_iax2_pvt
*pvt
)
1011 manager_event(EVENT_FLAG_SYSTEM
, "ChannelUpdate",
1012 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1013 pvt
->owner
? pvt
->owner
->name
: "",
1014 pvt
->callno
, pvt
->peercallno
, pvt
->peer
? pvt
->peer
: "");
1018 static struct ast_datastore_info iax2_variable_datastore_info
= {
1019 .type
= "IAX2_VARIABLE",
1020 .duplicate
= iax2_dup_variable_datastore
,
1021 .destroy
= iax2_free_variable_datastore
,
1024 static void *iax2_dup_variable_datastore(void *old
)
1026 AST_LIST_HEAD(, ast_var_t
) *oldlist
= old
, *newlist
;
1027 struct ast_var_t
*oldvar
, *newvar
;
1029 newlist
= ast_calloc(sizeof(*newlist
), 1);
1031 ast_log(LOG_ERROR
, "Unable to duplicate iax2 variables\n");
1035 AST_LIST_HEAD_INIT(newlist
);
1036 AST_LIST_LOCK(oldlist
);
1037 AST_LIST_TRAVERSE(oldlist
, oldvar
, entries
) {
1038 newvar
= ast_var_assign(ast_var_name(oldvar
), ast_var_value(oldvar
));
1040 AST_LIST_INSERT_TAIL(newlist
, newvar
, entries
);
1042 ast_log(LOG_ERROR
, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar
));
1044 AST_LIST_UNLOCK(oldlist
);
1048 static void iax2_free_variable_datastore(void *old
)
1050 AST_LIST_HEAD(, ast_var_t
) *oldlist
= old
;
1051 struct ast_var_t
*oldvar
;
1053 AST_LIST_LOCK(oldlist
);
1054 while ((oldvar
= AST_LIST_REMOVE_HEAD(oldlist
, entries
))) {
1057 AST_LIST_UNLOCK(oldlist
);
1058 AST_LIST_HEAD_DESTROY(oldlist
);
1063 /* WARNING: insert_idle_thread should only ever be called within the
1064 * context of an iax2_process_thread() thread.
1066 static void insert_idle_thread(struct iax2_thread
*thread
)
1068 if (thread
->type
== IAX_THREAD_TYPE_DYNAMIC
) {
1069 AST_LIST_LOCK(&dynamic_list
);
1070 AST_LIST_INSERT_TAIL(&dynamic_list
, thread
, list
);
1071 AST_LIST_UNLOCK(&dynamic_list
);
1073 AST_LIST_LOCK(&idle_list
);
1074 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
1075 AST_LIST_UNLOCK(&idle_list
);
1081 static struct iax2_thread
*find_idle_thread(void)
1083 struct iax2_thread
*thread
= NULL
;
1085 /* Pop the head of the idle list off */
1086 AST_LIST_LOCK(&idle_list
);
1087 thread
= AST_LIST_REMOVE_HEAD(&idle_list
, list
);
1088 AST_LIST_UNLOCK(&idle_list
);
1090 /* If we popped a thread off the idle list, just return it */
1092 memset(&thread
->ffinfo
, 0, sizeof(thread
->ffinfo
));
1096 /* Pop the head of the dynamic list off */
1097 AST_LIST_LOCK(&dynamic_list
);
1098 thread
= AST_LIST_REMOVE_HEAD(&dynamic_list
, list
);
1099 AST_LIST_UNLOCK(&dynamic_list
);
1101 /* If we popped a thread off the dynamic list, just return it */
1103 memset(&thread
->ffinfo
, 0, sizeof(thread
->ffinfo
));
1107 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1108 if (iaxdynamicthreadcount
>= iaxmaxthreadcount
|| !(thread
= ast_calloc(1, sizeof(*thread
))))
1111 /* Set default values */
1112 ast_atomic_fetchadd_int(&iaxdynamicthreadcount
, 1);
1113 thread
->threadnum
= ast_atomic_fetchadd_int(&iaxdynamicthreadnum
, 1);
1114 thread
->type
= IAX_THREAD_TYPE_DYNAMIC
;
1116 /* Initialize lock and condition */
1117 ast_mutex_init(&thread
->lock
);
1118 ast_cond_init(&thread
->cond
, NULL
);
1120 /* Create thread and send it on it's way */
1121 if (ast_pthread_create_detached_background(&thread
->threadid
, NULL
, iax2_process_thread
, thread
)) {
1122 ast_cond_destroy(&thread
->cond
);
1123 ast_mutex_destroy(&thread
->lock
);
1128 /* this thread is not processing a full frame (since it is idle),
1129 so ensure that the field for the full frame call number is empty */
1130 memset(&thread
->ffinfo
, 0, sizeof(thread
->ffinfo
));
1132 /* Wait for the thread to be ready before returning it to the caller */
1133 while (!thread
->ready_for_signal
)
1139 #ifdef SCHED_MULTITHREADED
1140 static int __schedule_action(void (*func
)(const void *data
), const void *data
, const char *funcname
)
1142 struct iax2_thread
*thread
= NULL
;
1143 static time_t lasterror
;
1146 thread
= find_idle_thread();
1148 if (thread
!= NULL
) {
1149 thread
->schedfunc
= func
;
1150 thread
->scheddata
= data
;
1151 thread
->iostate
= IAX_IOSTATE_SCHEDREADY
;
1152 #ifdef DEBUG_SCHED_MULTITHREAD
1153 ast_copy_string(thread
->curfunc
, funcname
, sizeof(thread
->curfunc
));
1155 signal_condition(&thread
->lock
, &thread
->cond
);
1160 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1165 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1168 static int iax2_sched_replace(int id
, struct sched_context
*con
, int when
, ast_sched_cb callback
, const void *data
)
1170 AST_SCHED_REPLACE(id
, con
, when
, callback
, data
);
1171 signal_condition(&sched_lock
, &sched_cond
);
1176 static int iax2_sched_add(struct sched_context
*con
, int when
, ast_sched_cb callback
, const void *data
)
1180 res
= ast_sched_add(con
, when
, callback
, data
);
1181 signal_condition(&sched_lock
, &sched_cond
);
1186 static int send_ping(const void *data
);
1188 static void __send_ping(const void *data
)
1190 int callno
= (long) data
;
1192 ast_mutex_lock(&iaxsl
[callno
]);
1195 if (iaxs
[callno
]->peercallno
) {
1196 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PING
, 0, NULL
, 0, -1);
1197 iaxs
[callno
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, data
);
1199 /* I am the schedule, so I'm allowed to do this */
1200 iaxs
[callno
]->pingid
= -1;
1202 } else if (option_debug
> 0) {
1203 ast_log(LOG_DEBUG
, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno
);
1206 ast_mutex_unlock(&iaxsl
[callno
]);
1209 static int send_ping(const void *data
)
1211 #ifdef SCHED_MULTITHREADED
1212 if (schedule_action(__send_ping
, data
))
1219 static int get_encrypt_methods(const char *s
)
1222 if (!strcasecmp(s
, "aes128"))
1223 e
= IAX_ENCRYPT_AES128
;
1224 else if (ast_true(s
))
1225 e
= IAX_ENCRYPT_AES128
;
1231 static int send_lagrq(const void *data
);
1233 static void __send_lagrq(const void *data
)
1235 int callno
= (long) data
;
1237 ast_mutex_lock(&iaxsl
[callno
]);
1240 if (iaxs
[callno
]->peercallno
) {
1241 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_LAGRQ
, 0, NULL
, 0, -1);
1242 iaxs
[callno
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, data
);
1244 /* I am the schedule, so I'm allowed to do this */
1245 iaxs
[callno
]->lagid
= -1;
1248 ast_log(LOG_WARNING
, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno
);
1251 ast_mutex_unlock(&iaxsl
[callno
]);
1254 static int send_lagrq(const void *data
)
1256 #ifdef SCHED_MULTITHREADED
1257 if (schedule_action(__send_lagrq
, data
))
1264 static unsigned char compress_subclass(int subclass
)
1268 /* If it's 128 or smaller, just return it */
1269 if (subclass
< IAX_FLAG_SC_LOG
)
1271 /* Otherwise find its power */
1272 for (x
= 0; x
< IAX_MAX_SHIFT
; x
++) {
1273 if (subclass
& (1 << x
)) {
1275 ast_log(LOG_WARNING
, "Can't compress subclass %d\n", subclass
);
1281 return power
| IAX_FLAG_SC_LOG
;
1284 static int uncompress_subclass(unsigned char csub
)
1286 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1287 if (csub
& IAX_FLAG_SC_LOG
) {
1288 /* special case for 'compressed' -1 */
1292 return 1 << (csub
& ~IAX_FLAG_SC_LOG
& IAX_MAX_SHIFT
);
1299 * \note The only member of the peer passed here guaranteed to be set is the name field
1301 static int peer_hash_cb(const void *obj
, const int flags
)
1303 const struct iax2_peer
*peer
= obj
;
1305 return ast_str_hash(peer
->name
);
1309 * \note The only member of the peer passed here guaranteed to be set is the name field
1311 static int peer_cmp_cb(void *obj
, void *arg
, int flags
)
1313 struct iax2_peer
*peer
= obj
, *peer2
= arg
;
1315 return !strcmp(peer
->name
, peer2
->name
) ? CMP_MATCH
| CMP_STOP
: 0;
1319 * \note The only member of the user passed here guaranteed to be set is the name field
1321 static int user_hash_cb(const void *obj
, const int flags
)
1323 const struct iax2_user
*user
= obj
;
1325 return ast_str_hash(user
->name
);
1329 * \note The only member of the user passed here guaranteed to be set is the name field
1331 static int user_cmp_cb(void *obj
, void *arg
, int flags
)
1333 struct iax2_user
*user
= obj
, *user2
= arg
;
1335 return !strcmp(user
->name
, user2
->name
) ? CMP_MATCH
| CMP_STOP
: 0;
1339 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1340 * so do not call it with a pvt lock held.
1342 static struct iax2_peer
*find_peer(const char *name
, int realtime
)
1344 struct iax2_peer
*peer
= NULL
;
1345 struct iax2_peer tmp_peer
= {
1349 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
1351 /* Now go for realtime if applicable */
1352 if(!peer
&& realtime
)
1353 peer
= realtime_peer(name
, NULL
);
1358 static struct iax2_peer
*peer_ref(struct iax2_peer
*peer
)
1364 static inline struct iax2_peer
*peer_unref(struct iax2_peer
*peer
)
1370 static inline struct iax2_user
*user_ref(struct iax2_user
*user
)
1376 static inline struct iax2_user
*user_unref(struct iax2_user
*user
)
1382 static int iax2_getpeername(struct sockaddr_in sin
, char *host
, int len
)
1384 struct iax2_peer
*peer
= NULL
;
1386 struct ao2_iterator i
;
1388 i
= ao2_iterator_init(peers
, 0);
1389 while ((peer
= ao2_iterator_next(&i
))) {
1390 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
1391 (peer
->addr
.sin_port
== sin
.sin_port
)) {
1392 ast_copy_string(host
, peer
->name
, len
);
1401 peer
= realtime_peer(NULL
, &sin
);
1403 ast_copy_string(host
, peer
->name
, len
);
1412 static void iax2_destroy_helper(struct chan_iax2_pvt
*pvt
)
1414 /* Decrement AUTHREQ count if needed */
1415 if (ast_test_flag(pvt
, IAX_MAXAUTHREQ
)) {
1416 struct iax2_user
*user
;
1417 struct iax2_user tmp_user
= {
1418 .name
= pvt
->username
,
1421 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
1423 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
1427 ast_clear_flag(pvt
, IAX_MAXAUTHREQ
);
1429 /* No more pings or lagrq's */
1430 AST_SCHED_DEL(sched
, pvt
->pingid
);
1431 AST_SCHED_DEL(sched
, pvt
->lagid
);
1432 AST_SCHED_DEL(sched
, pvt
->autoid
);
1433 AST_SCHED_DEL(sched
, pvt
->authid
);
1434 AST_SCHED_DEL(sched
, pvt
->initid
);
1435 AST_SCHED_DEL(sched
, pvt
->jbid
);
1436 AST_SCHED_DEL(sched
, pvt
->keyrotateid
);
1439 static void iax2_frame_free(struct iax_frame
*fr
)
1441 AST_SCHED_DEL(sched
, fr
->retrans
);
1445 static void pvt_destructor(void *obj
)
1447 struct chan_iax2_pvt
*pvt
= obj
;
1448 struct iax_frame
*cur
= NULL
;
1450 iax2_destroy_helper(pvt
);
1453 ast_set_flag(pvt
, IAX_ALREADYGONE
);
1455 AST_LIST_LOCK(&frame_queue
);
1456 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
1457 /* Cancel any pending transmissions */
1458 if (cur
->callno
== pvt
->callno
) {
1462 AST_LIST_UNLOCK(&frame_queue
);
1465 pvt
->reg
->callno
= 0;
1471 ast_variables_destroy(pvt
->vars
);
1475 while (jb_getall(pvt
->jb
, &frame
) == JB_OK
) {
1476 iax2_frame_free(frame
.data
);
1479 jb_destroy(pvt
->jb
);
1480 ast_string_field_free_memory(pvt
);
1484 static struct chan_iax2_pvt
*new_iax(struct sockaddr_in
*sin
, const char *host
)
1486 struct chan_iax2_pvt
*tmp
;
1489 if (!(tmp
= ao2_alloc(sizeof(*tmp
), pvt_destructor
))) {
1493 if (ast_string_field_init(tmp
, 32)) {
1505 tmp
->keyrotateid
= -1;
1507 ast_string_field_set(tmp
,exten
, "s");
1508 ast_string_field_set(tmp
,host
, host
);
1512 jbconf
.max_jitterbuf
= maxjitterbuffer
;
1513 jbconf
.resync_threshold
= resyncthreshold
;
1514 jbconf
.max_contig_interp
= maxjitterinterps
;
1515 jbconf
.target_extra
= jittertargetextra
;
1516 jb_setconf(tmp
->jb
,&jbconf
);
1518 AST_LIST_HEAD_INIT_NOLOCK(&tmp
->dpentries
);
1523 static struct iax_frame
*iaxfrdup2(struct iax_frame
*fr
)
1525 struct iax_frame
*new = iax_frame_new(DIRECTION_INGRESS
, fr
->af
.datalen
, fr
->cacheable
);
1527 size_t afdatalen
= new->afdatalen
;
1528 memcpy(new, fr
, sizeof(*new));
1529 iax_frame_wrap(new, &fr
->af
);
1530 new->afdatalen
= afdatalen
;
1533 new->direction
= DIRECTION_INGRESS
;
1539 #define NEW_PREVENT 0
1543 static int match(struct sockaddr_in
*sin
, unsigned short callno
, unsigned short dcallno
, const struct chan_iax2_pvt
*cur
, int check_dcallno
)
1545 if ((cur
->addr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1546 (cur
->addr
.sin_port
== sin
->sin_port
)) {
1547 /* This is the main host */
1548 if ( (cur
->peercallno
== 0 || cur
->peercallno
== callno
) &&
1549 (check_dcallno
? dcallno
== cur
->callno
: 1) ) {
1550 /* That's us. Be sure we keep track of the peer call number */
1554 if ((cur
->transfer
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1555 (cur
->transfer
.sin_port
== sin
->sin_port
) && (cur
->transferring
)) {
1556 /* We're transferring */
1557 if ((dcallno
== cur
->callno
) || (cur
->transferring
== TRANSFER_NONE
&& cur
->transfercallno
== callno
))
1563 static void update_max_trunk(void)
1565 int max
= TRUNK_CALL_START
;
1568 /* XXX Prolly don't need locks here XXX */
1569 for (x
= TRUNK_CALL_START
; x
< ARRAY_LEN(iaxs
) - 1; x
++) {
1577 ast_debug(1, "New max trunk callno is %d\n", max
);
1580 static void update_max_nontrunk(void)
1584 /* XXX Prolly don't need locks here XXX */
1585 for (x
=1;x
<TRUNK_CALL_START
- 1; x
++) {
1589 maxnontrunkcall
= max
;
1591 ast_debug(1, "New max nontrunk callno is %d\n", max
);
1594 static int make_trunk(unsigned short callno
, int locked
)
1598 struct timeval now
= ast_tvnow();
1599 if (iaxs
[callno
]->oseqno
) {
1600 ast_log(LOG_WARNING
, "Can't make trunk once a call has started!\n");
1603 if (callno
& TRUNK_CALL_START
) {
1604 ast_log(LOG_WARNING
, "Call %d is already a trunk\n", callno
);
1607 for (x
= TRUNK_CALL_START
; x
< ARRAY_LEN(iaxs
) - 1; x
++) {
1608 ast_mutex_lock(&iaxsl
[x
]);
1609 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) {
1611 * \note We delete these before switching the slot, because if
1612 * they fire in the meantime, they will generate a warning.
1614 AST_SCHED_DEL(sched
, iaxs
[callno
]->pingid
);
1615 AST_SCHED_DEL(sched
, iaxs
[callno
]->lagid
);
1616 iaxs
[x
] = iaxs
[callno
];
1617 iaxs
[x
]->callno
= x
;
1618 iaxs
[callno
] = NULL
;
1619 /* Update the two timers that should have been started */
1620 iaxs
[x
]->pingid
= iax2_sched_add(sched
,
1621 ping_time
* 1000, send_ping
, (void *)(long)x
);
1622 iaxs
[x
]->lagid
= iax2_sched_add(sched
,
1623 lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1625 ast_mutex_unlock(&iaxsl
[callno
]);
1628 ast_mutex_unlock(&iaxsl
[x
]);
1631 ast_mutex_unlock(&iaxsl
[x
]);
1633 if (x
>= ARRAY_LEN(iaxs
) - 1) {
1634 ast_log(LOG_WARNING
, "Unable to trunk call: Insufficient space\n");
1637 ast_debug(1, "Made call %d into trunk call %d\n", callno
, x
);
1638 /* We move this call from a non-trunked to a trunked call */
1640 update_max_nontrunk();
1644 static void store_by_peercallno(struct chan_iax2_pvt
*pvt
)
1646 if (!pvt
->peercallno
) {
1647 ast_log(LOG_ERROR
, "This should not be called without a peer call number.\n");
1651 ao2_link(iax_peercallno_pvts
, pvt
);
1654 static void remove_by_peercallno(struct chan_iax2_pvt
*pvt
)
1656 if (!pvt
->peercallno
) {
1657 ast_log(LOG_ERROR
, "This should not be called without a peer call number.\n");
1661 ao2_unlink(iax_peercallno_pvts
, pvt
);
1665 * \note Calling this function while holding another pvt lock can cause a deadlock.
1667 static int __find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int return_locked
, int check_dcallno
)
1674 if (new <= NEW_ALLOW
) {
1676 struct chan_iax2_pvt
*pvt
;
1677 struct chan_iax2_pvt tmp_pvt
= {
1679 .peercallno
= callno
,
1681 .frames_received
= check_dcallno
,
1684 memcpy(&tmp_pvt
.addr
, sin
, sizeof(tmp_pvt
.addr
));
1686 if ((pvt
= ao2_find(iax_peercallno_pvts
, &tmp_pvt
, OBJ_POINTER
))) {
1687 if (return_locked
) {
1688 ast_mutex_lock(&iaxsl
[pvt
->callno
]);
1697 /* This will occur on the first response to a message that we initiated,
1698 * such as a PING. */
1699 if (callno
&& dcallno
&& iaxs
[dcallno
] && !iaxs
[dcallno
]->peercallno
&& match(sin
, callno
, dcallno
, iaxs
[dcallno
], check_dcallno
)) {
1700 iaxs
[dcallno
]->peercallno
= callno
;
1702 store_by_peercallno(iaxs
[dcallno
]);
1707 /* If we get here, we SHOULD NOT find a call structure for this
1708 callno; if we do, it means that there is a call structure that
1709 has a peer callno but did NOT get entered into the hash table,
1712 If we find a call structure using this old, slow method, output a log
1713 message so we'll know about it. After a few months of leaving this in
1714 place, if we don't hear about people seeing these messages, we can
1715 remove this code for good.
1718 for (x
= 1; !res
&& x
< maxnontrunkcall
; x
++) {
1719 ast_mutex_lock(&iaxsl
[x
]);
1721 /* Look for an exact match */
1722 if (match(sin
, callno
, dcallno
, iaxs
[x
], check_dcallno
)) {
1726 if (!res
|| !return_locked
)
1727 ast_mutex_unlock(&iaxsl
[x
]);
1729 for (x
= TRUNK_CALL_START
; !res
&& x
< maxtrunkcall
; x
++) {
1730 ast_mutex_lock(&iaxsl
[x
]);
1732 /* Look for an exact match */
1733 if (match(sin
, callno
, dcallno
, iaxs
[x
], check_dcallno
)) {
1737 if (!res
|| !return_locked
)
1738 ast_mutex_unlock(&iaxsl
[x
]);
1742 if (!res
&& (new >= NEW_ALLOW
)) {
1743 int start
, found
= 0;
1745 /* It may seem odd that we look through the peer list for a name for
1746 * this *incoming* call. Well, it is weird. However, users don't
1747 * have an IP address/port number that we can match against. So,
1748 * this is just checking for a peer that has that IP/port and
1749 * assuming that we have a user of the same name. This isn't always
1750 * correct, but it will be changed if needed after authentication. */
1751 if (!iax2_getpeername(*sin
, host
, sizeof(host
)))
1752 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
1755 start
= 2 + (ast_random() % (TRUNK_CALL_START
- 1));
1756 for (x
= start
; 1; x
++) {
1757 if (x
== TRUNK_CALL_START
) {
1762 /* Find first unused call number that hasn't been used in a while */
1763 ast_mutex_lock(&iaxsl
[x
]);
1764 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) {
1768 ast_mutex_unlock(&iaxsl
[x
]);
1770 if (x
== start
- 1) {
1774 /* We've still got lock held if we found a spot */
1775 if (x
== start
- 1 && !found
) {
1776 ast_log(LOG_WARNING
, "No more space\n");
1779 iaxs
[x
] = new_iax(sin
, host
);
1780 update_max_nontrunk();
1783 ast_debug(1, "Creating new call structure %d\n", x
);
1784 iaxs
[x
]->sockfd
= sockfd
;
1785 iaxs
[x
]->addr
.sin_port
= sin
->sin_port
;
1786 iaxs
[x
]->addr
.sin_family
= sin
->sin_family
;
1787 iaxs
[x
]->addr
.sin_addr
.s_addr
= sin
->sin_addr
.s_addr
;
1788 iaxs
[x
]->peercallno
= callno
;
1789 iaxs
[x
]->callno
= x
;
1790 iaxs
[x
]->pingtime
= DEFAULT_RETRY_TIME
;
1791 iaxs
[x
]->expiry
= min_reg_expire
;
1792 iaxs
[x
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, (void *)(long)x
);
1793 iaxs
[x
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1794 iaxs
[x
]->amaflags
= amaflags
;
1795 ast_copy_flags(iaxs
[x
], &globalflags
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_NOKEYROTATE
);
1797 ast_string_field_set(iaxs
[x
], accountcode
, accountcode
);
1798 ast_string_field_set(iaxs
[x
], mohinterpret
, mohinterpret
);
1799 ast_string_field_set(iaxs
[x
], mohsuggest
, mohsuggest
);
1800 ast_string_field_set(iaxs
[x
], parkinglot
, default_parkinglot
);
1802 if (iaxs
[x
]->peercallno
) {
1803 store_by_peercallno(iaxs
[x
]);
1806 ast_log(LOG_WARNING
, "Out of resources\n");
1807 ast_mutex_unlock(&iaxsl
[x
]);
1811 ast_mutex_unlock(&iaxsl
[x
]);
1817 static int find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int full_frame
) {
1819 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 0, full_frame
);
1822 static int find_callno_locked(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int full_frame
) {
1824 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 1, full_frame
);
1828 * \brief Queue a frame to a call's owning asterisk channel
1830 * \pre This function assumes that iaxsl[callno] is locked when called.
1832 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1833 * was valid before calling it, it may no longer be valid after calling it.
1834 * This function may unlock and lock the mutex associated with this callno,
1835 * meaning that another thread may grab it and destroy the call.
1837 static int iax2_queue_frame(int callno
, struct ast_frame
*f
)
1840 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1841 if (ast_channel_trylock(iaxs
[callno
]->owner
)) {
1842 /* Avoid deadlock by pausing and trying again */
1843 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1845 ast_queue_frame(iaxs
[callno
]->owner
, f
);
1846 ast_channel_unlock(iaxs
[callno
]->owner
);
1856 * \brief Queue a hangup frame on the ast_channel owner
1858 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1859 * is active for the given call number.
1861 * \pre Assumes lock for callno is already held.
1863 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1864 * was valid before calling it, it may no longer be valid after calling it.
1865 * This function may unlock and lock the mutex associated with this callno,
1866 * meaning that another thread may grab it and destroy the call.
1868 static int iax2_queue_hangup(int callno
)
1871 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1872 if (ast_channel_trylock(iaxs
[callno
]->owner
)) {
1873 /* Avoid deadlock by pausing and trying again */
1874 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1876 ast_queue_hangup(iaxs
[callno
]->owner
);
1877 ast_channel_unlock(iaxs
[callno
]->owner
);
1887 * \brief Queue a control frame on the ast_channel owner
1889 * This function queues a control frame on the owner of the IAX2 pvt struct that
1890 * is active for the given call number.
1892 * \pre Assumes lock for callno is already held.
1894 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1895 * was valid before calling it, it may no longer be valid after calling it.
1896 * This function may unlock and lock the mutex associated with this callno,
1897 * meaning that another thread may grab it and destroy the call.
1899 static int iax2_queue_control_data(int callno
,
1900 enum ast_control_frame_type control
, const void *data
, size_t datalen
)
1903 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1904 if (ast_channel_trylock(iaxs
[callno
]->owner
)) {
1905 /* Avoid deadlock by pausing and trying again */
1906 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1908 ast_queue_control_data(iaxs
[callno
]->owner
, control
, data
, datalen
);
1909 ast_channel_unlock(iaxs
[callno
]->owner
);
1917 static void destroy_firmware(struct iax_firmware
*cur
)
1919 /* Close firmware */
1921 munmap((void*)cur
->fwh
, ntohl(cur
->fwh
->datalen
) + sizeof(*(cur
->fwh
)));
1927 static int try_firmware(char *s
)
1930 struct iax_firmware
*cur
= NULL
;
1931 int ifd
, fd
, res
, len
, chunk
;
1932 struct ast_iax2_firmware_header
*fwh
, fwh2
;
1933 struct MD5Context md5
;
1934 unsigned char sum
[16], buf
[1024];
1937 if (!(s2
= alloca(strlen(s
) + 100))) {
1938 ast_log(LOG_WARNING
, "Alloca failed!\n");
1942 last
= strrchr(s
, '/');
1948 snprintf(s2
, strlen(s
) + 100, "/var/tmp/%s-%ld", last
, (unsigned long)ast_random());
1950 if ((res
= stat(s
, &stbuf
) < 0)) {
1951 ast_log(LOG_WARNING
, "Failed to stat '%s': %s\n", s
, strerror(errno
));
1955 /* Make sure it's not a directory */
1956 if (S_ISDIR(stbuf
.st_mode
))
1958 ifd
= open(s
, O_RDONLY
);
1960 ast_log(LOG_WARNING
, "Cannot open '%s': %s\n", s
, strerror(errno
));
1963 fd
= open(s2
, O_RDWR
| O_CREAT
| O_EXCL
, AST_FILE_MODE
);
1965 ast_log(LOG_WARNING
, "Cannot open '%s' for writing: %s\n", s2
, strerror(errno
));
1969 /* Unlink our newly created file */
1972 /* Now copy the firmware into it */
1973 len
= stbuf
.st_size
;
1976 if (chunk
> sizeof(buf
))
1977 chunk
= sizeof(buf
);
1978 res
= read(ifd
, buf
, chunk
);
1980 ast_log(LOG_WARNING
, "Only read %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1985 res
= write(fd
, buf
, chunk
);
1987 ast_log(LOG_WARNING
, "Only write %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1995 /* Return to the beginning */
1996 lseek(fd
, 0, SEEK_SET
);
1997 if ((res
= read(fd
, &fwh2
, sizeof(fwh2
))) != sizeof(fwh2
)) {
1998 ast_log(LOG_WARNING
, "Unable to read firmware header in '%s'\n", s
);
2002 if (ntohl(fwh2
.magic
) != IAX_FIRMWARE_MAGIC
) {
2003 ast_log(LOG_WARNING
, "'%s' is not a valid firmware file\n", s
);
2007 if (ntohl(fwh2
.datalen
) != (stbuf
.st_size
- sizeof(fwh2
))) {
2008 ast_log(LOG_WARNING
, "Invalid data length in firmware '%s'\n", s
);
2012 if (fwh2
.devname
[sizeof(fwh2
.devname
) - 1] || ast_strlen_zero((char *)fwh2
.devname
)) {
2013 ast_log(LOG_WARNING
, "No or invalid device type specified for '%s'\n", s
);
2017 fwh
= (struct ast_iax2_firmware_header
*)mmap(NULL
, stbuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
2018 if (fwh
== (void *) -1) {
2019 ast_log(LOG_WARNING
, "mmap failed: %s\n", strerror(errno
));
2024 MD5Update(&md5
, fwh
->data
, ntohl(fwh
->datalen
));
2025 MD5Final(sum
, &md5
);
2026 if (memcmp(sum
, fwh
->chksum
, sizeof(sum
))) {
2027 ast_log(LOG_WARNING
, "Firmware file '%s' fails checksum\n", s
);
2028 munmap((void*)fwh
, stbuf
.st_size
);
2033 AST_LIST_TRAVERSE(&firmwares
, cur
, list
) {
2034 if (!strcmp((char *)cur
->fwh
->devname
, (char *)fwh
->devname
)) {
2035 /* Found a candidate */
2036 if (cur
->dead
|| (ntohs(cur
->fwh
->version
) < ntohs(fwh
->version
)))
2037 /* The version we have on loaded is older, load this one instead */
2039 /* This version is no newer than what we have. Don't worry about it.
2040 We'll consider it a proper load anyhow though */
2041 munmap((void*)fwh
, stbuf
.st_size
);
2047 if (!cur
&& ((cur
= ast_calloc(1, sizeof(*cur
))))) {
2049 AST_LIST_INSERT_TAIL(&firmwares
, cur
, list
);
2054 munmap((void*)cur
->fwh
, cur
->mmaplen
);
2059 cur
->mmaplen
= stbuf
.st_size
;
2066 static int iax_check_version(char *dev
)
2069 struct iax_firmware
*cur
= NULL
;
2071 if (ast_strlen_zero(dev
))
2074 AST_LIST_LOCK(&firmwares
);
2075 AST_LIST_TRAVERSE(&firmwares
, cur
, list
) {
2076 if (!strcmp(dev
, (char *)cur
->fwh
->devname
)) {
2077 res
= ntohs(cur
->fwh
->version
);
2081 AST_LIST_UNLOCK(&firmwares
);
2086 static int iax_firmware_append(struct iax_ie_data
*ied
, const unsigned char *dev
, unsigned int desc
)
2089 unsigned int bs
= desc
& 0xff;
2090 unsigned int start
= (desc
>> 8) & 0xffffff;
2092 struct iax_firmware
*cur
;
2094 if (ast_strlen_zero((char *)dev
) || !bs
)
2099 AST_LIST_LOCK(&firmwares
);
2100 AST_LIST_TRAVERSE(&firmwares
, cur
, list
) {
2101 if (strcmp((char *)dev
, (char *)cur
->fwh
->devname
))
2103 iax_ie_append_int(ied
, IAX_IE_FWBLOCKDESC
, desc
);
2104 if (start
< ntohl(cur
->fwh
->datalen
)) {
2105 bytes
= ntohl(cur
->fwh
->datalen
) - start
;
2108 iax_ie_append_raw(ied
, IAX_IE_FWBLOCKDATA
, cur
->fwh
->data
+ start
, bytes
);
2111 iax_ie_append(ied
, IAX_IE_FWBLOCKDATA
);
2119 AST_LIST_UNLOCK(&firmwares
);
2125 static void reload_firmware(int unload
)
2127 struct iax_firmware
*cur
= NULL
;
2130 char dir
[256], fn
[256];
2132 AST_LIST_LOCK(&firmwares
);
2134 /* Mark all as dead */
2135 AST_LIST_TRAVERSE(&firmwares
, cur
, list
)
2138 /* Now that we have marked them dead... load new ones */
2140 snprintf(dir
, sizeof(dir
), "%s/firmware/iax", ast_config_AST_DATA_DIR
);
2143 while((de
= readdir(fwd
))) {
2144 if (de
->d_name
[0] != '.') {
2145 snprintf(fn
, sizeof(fn
), "%s/%s", dir
, de
->d_name
);
2146 if (!try_firmware(fn
)) {
2147 ast_verb(2, "Loaded firmware '%s'\n", de
->d_name
);
2153 ast_log(LOG_WARNING
, "Error opening firmware directory '%s': %s\n", dir
, strerror(errno
));
2156 /* Clean up leftovers */
2157 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares
, cur
, list
) {
2160 AST_LIST_REMOVE_CURRENT(list
);
2161 destroy_firmware(cur
);
2163 AST_LIST_TRAVERSE_SAFE_END
;
2165 AST_LIST_UNLOCK(&firmwares
);
2169 * \note This function assumes that iaxsl[callno] is locked when called.
2171 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2172 * was valid before calling it, it may no longer be valid after calling it.
2173 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2174 * associated with this callno, meaning that another thread may grab it and destroy the call.
2176 static int __do_deliver(void *data
)
2178 /* Just deliver the packet by using queueing. This is called by
2179 the IAX thread with the iaxsl lock held. */
2180 struct iax_frame
*fr
= data
;
2182 ast_clear_flag(&fr
->af
, AST_FRFLAG_HAS_TIMING_INFO
);
2183 if (iaxs
[fr
->callno
] && !ast_test_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
))
2184 iax2_queue_frame(fr
->callno
, &fr
->af
);
2185 /* Free our iax frame */
2186 iax2_frame_free(fr
);
2187 /* And don't run again */
2191 static int handle_error(void)
2193 /* XXX Ideally we should figure out why an error occurred and then abort those
2194 rather than continuing to try. Unfortunately, the published interface does
2195 not seem to work XXX */
2197 struct sockaddr_in
*sin
;
2200 struct sock_extended_err e
;
2205 m
.msg_controllen
= sizeof(e
);
2207 res
= recvmsg(netsocket
, &m
, MSG_ERRQUEUE
);
2209 ast_log(LOG_WARNING
, "Error detected, but unable to read error: %s\n", strerror(errno
));
2211 if (m
.msg_controllen
) {
2212 sin
= (struct sockaddr_in
*)SO_EE_OFFENDER(&e
);
2214 ast_log(LOG_WARNING
, "Receive error from %s\n", ast_inet_ntoa(sin
->sin_addr
));
2216 ast_log(LOG_WARNING
, "No address detected??\n");
2218 ast_log(LOG_WARNING
, "Local error: %s\n", strerror(e
.ee_errno
));
2225 static int transmit_trunk(struct iax_frame
*f
, struct sockaddr_in
*sin
, int sockfd
)
2228 res
= sendto(sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)sin
,
2231 ast_debug(1, "Received error: %s\n", strerror(errno
));
2238 static int send_packet(struct iax_frame
*f
)
2241 int callno
= f
->callno
;
2242 struct sockaddr_in
*addr
;
2244 /* Don't send if there was an error, but return error instead */
2245 if (!callno
|| !iaxs
[callno
] || iaxs
[callno
]->error
)
2248 /* Called with iaxsl held */
2250 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f
->ts
, callno
, iaxs
[callno
]->peercallno
, ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
), ntohs(iaxs
[callno
]->addr
.sin_port
));
2253 addr
= &iaxs
[callno
]->media
;
2254 } else if (f
->transfer
) {
2255 addr
= &iaxs
[callno
]->transfer
;
2257 addr
= &iaxs
[callno
]->addr
;
2260 iax_outputframe(f
, NULL
, 0, addr
, f
->datalen
- sizeof(struct ast_iax2_full_hdr
));
2262 res
= sendto(iaxs
[callno
]->sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)addr
,
2263 sizeof(iaxs
[callno
]->media
));
2267 ast_debug(1, "Received error: %s\n", strerror(errno
));
2276 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2277 * for the given call number may disappear during its execution.
2279 static int iax2_predestroy(int callno
)
2281 struct ast_channel
*c
= NULL
;
2282 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
2287 if (!ast_test_flag(pvt
, IAX_ALREADYGONE
)) {
2288 iax2_destroy_helper(pvt
);
2289 ast_set_flag(pvt
, IAX_ALREADYGONE
);
2292 if ((c
= pvt
->owner
)) {
2294 iax2_queue_hangup(callno
);
2296 ast_module_unref(ast_module_info
->self
);
2302 static void iax2_destroy(int callno
)
2304 struct chan_iax2_pvt
*pvt
= NULL
;
2305 struct ast_channel
*owner
= NULL
;
2309 lastused
[callno
] = ast_tvnow();
2311 owner
= pvt
? pvt
->owner
: NULL
;
2314 if (ast_channel_trylock(owner
)) {
2315 ast_debug(3, "Avoiding IAX destroy deadlock\n");
2316 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
2322 iaxs
[callno
] = NULL
;
2329 /* If there's an owner, prod it to give up */
2330 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2331 * because we already hold the owner channel lock. */
2332 ast_queue_hangup(owner
);
2335 if (pvt
->peercallno
) {
2336 remove_by_peercallno(pvt
);
2346 ast_channel_unlock(owner
);
2349 if (callno
& 0x4000) {
2354 static int update_packet(struct iax_frame
*f
)
2356 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2357 struct ast_iax2_full_hdr
*fh
= f
->data
;
2358 /* Mark this as a retransmission */
2359 fh
->dcallno
= ntohs(IAX_FLAG_RETRANS
| f
->dcallno
);
2361 f
->iseqno
= iaxs
[f
->callno
]->iseqno
;
2362 fh
->iseqno
= f
->iseqno
;
2366 static int attempt_transmit(const void *data
);
2367 static void __attempt_transmit(const void *data
)
2369 /* Attempt to transmit the frame to the remote peer...
2370 Called without iaxsl held. */
2371 struct iax_frame
*f
= (struct iax_frame
*)data
;
2373 int callno
= f
->callno
;
2374 /* Make sure this call is still active */
2376 ast_mutex_lock(&iaxsl
[callno
]);
2377 if (callno
&& iaxs
[callno
]) {
2378 if ((f
->retries
< 0) /* Already ACK'd */ ||
2379 (f
->retries
>= max_retries
) /* Too many attempts */) {
2380 /* Record an error if we've transmitted too many times */
2381 if (f
->retries
>= max_retries
) {
2383 /* Transfer timeout */
2384 struct iax_ie_data ied
;
2385 memset(&ied
, 0, sizeof(ied
));
2386 iax_ie_append_int(&ied
, IAX_IE_TRANSFERID
, iaxs
[callno
]->transferid
);
2387 if (iaxs
[callno
]->mediareleased
) {
2388 send_command_media(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied
.buf
, ied
.pos
);
2390 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied
.buf
, ied
.pos
, -1);
2392 } else if (f
->final
) {
2394 iax2_destroy(callno
);
2396 if (iaxs
[callno
]->owner
)
2397 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
);
2398 iaxs
[callno
]->error
= ETIMEDOUT
;
2399 if (iaxs
[callno
]->owner
) {
2400 struct ast_frame fr
= { AST_FRAME_CONTROL
, AST_CONTROL_HANGUP
, .data
.uint32
= AST_CAUSE_DESTINATION_OUT_OF_ORDER
};
2402 iax2_queue_frame(callno
, &fr
); /* XXX */
2403 /* Remember, owner could disappear */
2404 if (iaxs
[callno
] && iaxs
[callno
]->owner
)
2405 iaxs
[callno
]->owner
->hangupcause
= AST_CAUSE_DESTINATION_OUT_OF_ORDER
;
2407 if (iaxs
[callno
]->reg
) {
2408 memset(&iaxs
[callno
]->reg
->us
, 0, sizeof(iaxs
[callno
]->reg
->us
));
2409 iaxs
[callno
]->reg
->regstate
= REG_STATE_TIMEOUT
;
2410 iaxs
[callno
]->reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
2412 iax2_destroy(callno
);
2419 /* Update it if it needs it */
2421 /* Attempt transmission */
2424 /* Try again later after 10 times as long */
2426 if (f
->retrytime
> MAX_RETRY_TIME
)
2427 f
->retrytime
= MAX_RETRY_TIME
;
2428 /* Transfer messages max out at one second */
2429 if (f
->transfer
&& (f
->retrytime
> 1000))
2430 f
->retrytime
= 1000;
2431 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
2434 /* Make sure it gets freed */
2439 ast_mutex_unlock(&iaxsl
[callno
]);
2440 /* Do not try again */
2442 /* Don't attempt delivery, just remove it from the queue */
2443 AST_LIST_LOCK(&frame_queue
);
2444 AST_LIST_REMOVE(&frame_queue
, f
, list
);
2445 AST_LIST_UNLOCK(&frame_queue
);
2447 /* Free the IAX frame */
2452 static int attempt_transmit(const void *data
)
2454 #ifdef SCHED_MULTITHREADED
2455 if (schedule_action(__attempt_transmit
, data
))
2457 __attempt_transmit(data
);
2461 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2463 struct iax2_peer
*peer
;
2467 e
->command
= "iax2 prune realtime";
2469 "Usage: iax2 prune realtime [<peername>|all]\n"
2470 " Prunes object(s) from the cache\n";
2474 return complete_iax2_peers(a
->line
, a
->word
, a
->pos
, a
->n
);
2479 return CLI_SHOWUSAGE
;
2480 if (!strcmp(a
->argv
[3], "all")) {
2482 ast_cli(a
->fd
, "Cache flushed successfully.\n");
2483 } else if ((peer
= find_peer(a
->argv
[3], 0))) {
2484 if(ast_test_flag(peer
, IAX_RTCACHEFRIENDS
)) {
2485 ast_set_flag(peer
, IAX_RTAUTOCLEAR
);
2486 expire_registry(peer_ref(peer
));
2487 ast_cli(a
->fd
, "Peer %s was removed from the cache.\n", a
->argv
[3]);
2489 ast_cli(a
->fd
, "Peer %s is not eligible for this operation.\n", a
->argv
[3]);
2493 ast_cli(a
->fd
, "Peer %s was not found in the cache.\n", a
->argv
[3]);
2499 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2503 e
->command
= "iax2 test losspct";
2505 "Usage: iax2 test losspct <percentage>\n"
2506 " For testing, throws away <percentage> percent of incoming packets\n";
2512 return CLI_SHOWUSAGE
;
2514 test_losspct
= atoi(a
->argv
[3]);
2520 static char *handle_cli_iax2_test_late(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2524 e
->command
= "iax2 test late";
2526 "Usage: iax2 test late <ms>\n"
2527 " For testing, count the next frame as <ms> ms late\n";
2534 return CLI_SHOWUSAGE
;
2536 test_late
= atoi(a
->argv
[3]);
2541 static char *handle_cli_iax2_test_resync(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2545 e
->command
= "iax2 test resync";
2547 "Usage: iax2 test resync <ms>\n"
2548 " For testing, adjust all future frames by <ms> ms\n";
2555 return CLI_SHOWUSAGE
;
2557 test_resync
= atoi(a
->argv
[3]);
2562 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2566 e
->command
= "iax2 test jitter";
2568 "Usage: iax2 test jitter <ms> <pct>\n"
2569 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2570 " percentage of packets. If <pct> is not specified, adds\n"
2571 " jitter to all packets.\n";
2577 if (a
->argc
< 4 || a
->argc
> 5)
2578 return CLI_SHOWUSAGE
;
2580 test_jit
= atoi(a
->argv
[3]);
2582 test_jitpct
= atoi(a
->argv
[4]);
2586 #endif /* IAXTESTS */
2588 /*! \brief peer_status: Report Peer status in character string */
2589 /* returns 1 if peer is online, -1 if unmonitored */
2590 static int peer_status(struct iax2_peer
*peer
, char *status
, int statuslen
)
2594 if (peer
->lastms
< 0) {
2595 ast_copy_string(status
, "UNREACHABLE", statuslen
);
2596 } else if (peer
->lastms
> peer
->maxms
) {
2597 snprintf(status
, statuslen
, "LAGGED (%d ms)", peer
->lastms
);
2599 } else if (peer
->lastms
) {
2600 snprintf(status
, statuslen
, "OK (%d ms)", peer
->lastms
);
2603 ast_copy_string(status
, "UNKNOWN", statuslen
);
2606 ast_copy_string(status
, "Unmonitored", statuslen
);
2612 /*! \brief Show one peer in detail */
2613 static char *handle_cli_iax2_show_peer(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2617 struct iax2_peer
*peer
;
2618 char codec_buf
[512];
2619 int x
= 0, codec
= 0, load_realtime
= 0;
2623 e
->command
= "iax2 show peer";
2625 "Usage: iax2 show peer <name>\n"
2626 " Display details on specific IAX peer\n";
2630 return complete_iax2_peers(a
->line
, a
->word
, a
->pos
, a
->n
);
2635 return CLI_SHOWUSAGE
;
2637 load_realtime
= (a
->argc
== 5 && !strcmp(a
->argv
[4], "load")) ? 1 : 0;
2639 peer
= find_peer(a
->argv
[3], load_realtime
);
2641 ast_cli(a
->fd
, "\n\n");
2642 ast_cli(a
->fd
, " * Name : %s\n", peer
->name
);
2643 ast_cli(a
->fd
, " Secret : %s\n", ast_strlen_zero(peer
->secret
) ? "<Not set>" : "<Set>");
2644 ast_cli(a
->fd
, " Context : %s\n", peer
->context
);
2645 ast_cli(a
->fd
, " Parking lot : %s\n", peer
->parkinglot
);
2646 ast_cli(a
->fd
, " Mailbox : %s\n", peer
->mailbox
);
2647 ast_cli(a
->fd
, " Dynamic : %s\n", ast_test_flag(peer
, IAX_DYNAMIC
) ? "Yes" : "No");
2648 ast_cli(a
->fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, "<unspecified>"));
2649 ast_cli(a
->fd
, " Expire : %d\n", peer
->expire
);
2650 ast_cli(a
->fd
, " ACL : %s\n", (peer
->ha
? "Yes" : "No"));
2651 ast_cli(a
->fd
, " Addr->IP : %s Port %d\n", peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)", ntohs(peer
->addr
.sin_port
));
2652 ast_cli(a
->fd
, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
2653 ast_cli(a
->fd
, " Username : %s\n", peer
->username
);
2654 ast_cli(a
->fd
, " Codecs : ");
2655 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
2656 ast_cli(a
->fd
, "%s\n", codec_buf
);
2658 ast_cli(a
->fd
, " Codec Order : (");
2659 for(x
= 0; x
< 32 ; x
++) {
2660 codec
= ast_codec_pref_index(&peer
->prefs
,x
);
2663 ast_cli(a
->fd
, "%s", ast_getformatname(codec
));
2664 if(x
< 31 && ast_codec_pref_index(&peer
->prefs
,x
+1))
2665 ast_cli(a
->fd
, "|");
2669 ast_cli(a
->fd
, "none");
2670 ast_cli(a
->fd
, ")\n");
2672 ast_cli(a
->fd
, " Status : ");
2673 peer_status(peer
, status
, sizeof(status
));
2674 ast_cli(a
->fd
, "%s\n",status
);
2675 ast_cli(a
->fd
, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer
->pokefreqok
, peer
->pokefreqnotok
, peer
->smoothing
? "On" : "Off");
2676 ast_cli(a
->fd
, "\n");
2679 ast_cli(a
->fd
, "Peer %s not found.\n", a
->argv
[3]);
2680 ast_cli(a
->fd
, "\n");
2686 static char *complete_iax2_peers(const char *line
, const char *word
, int pos
, int state
)
2689 struct iax2_peer
*peer
;
2691 int wordlen
= strlen(word
);
2692 struct ao2_iterator i
;
2694 i
= ao2_iterator_init(peers
, 0);
2695 while ((peer
= ao2_iterator_next(&i
))) {
2696 if (!strncasecmp(peer
->name
, word
, wordlen
) && ++which
> state
) {
2697 res
= ast_strdup(peer
->name
);
2707 static char *handle_cli_iax2_show_stats(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2709 struct iax_frame
*cur
;
2710 int cnt
= 0, dead
= 0, final
= 0;
2714 e
->command
= "iax2 show stats";
2716 "Usage: iax2 show stats\n"
2717 " Display statistics on IAX channel driver.\n";
2724 return CLI_SHOWUSAGE
;
2726 AST_LIST_LOCK(&frame_queue
);
2727 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
2728 if (cur
->retries
< 0)
2734 AST_LIST_UNLOCK(&frame_queue
);
2736 ast_cli(a
->fd
, " IAX Statistics\n");
2737 ast_cli(a
->fd
, "---------------------\n");
2738 ast_cli(a
->fd
, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2739 ast_cli(a
->fd
, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed
, trunk_untimed
,
2740 trunk_maxmtu
, trunk_nmaxmtu
, global_max_trunk_mtu
);
2741 ast_cli(a
->fd
, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead
, final
, cnt
);
2743 trunk_timed
= trunk_untimed
= 0;
2744 if (trunk_maxmtu
> trunk_nmaxmtu
)
2745 trunk_nmaxmtu
= trunk_maxmtu
;
2750 /*! \brief Set trunk MTU from CLI */
2751 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2757 e
->command
= "iax2 set mtu";
2759 "Usage: iax2 set mtu <value>\n"
2760 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2761 " zero to disable. Disabling means that the operating system\n"
2762 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2763 " packet exceeds the UDP payload size. This is substantially\n"
2764 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2765 " greater for G.711 samples.\n";
2772 return CLI_SHOWUSAGE
;
2773 if (strncasecmp(a
->argv
[3], "default", strlen(a
->argv
[3])) == 0)
2774 mtuv
= MAX_TRUNK_MTU
;
2776 mtuv
= atoi(a
->argv
[3]);
2779 ast_cli(a
->fd
, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu
);
2780 global_max_trunk_mtu
= 0;
2783 if (mtuv
< 172 || mtuv
> 4000) {
2784 ast_cli(a
->fd
, "Trunk MTU must be between 172 and 4000\n");
2785 return CLI_SHOWUSAGE
;
2787 ast_cli(a
->fd
, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu
, mtuv
);
2788 global_max_trunk_mtu
= mtuv
;
2792 static char *handle_cli_iax2_show_cache(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2794 struct iax2_dpcache
*dp
= NULL
;
2795 char tmp
[1024], *pc
= NULL
;
2797 struct timeval now
= ast_tvnow();
2801 e
->command
= "iax2 show cache";
2803 "Usage: iax2 show cache\n"
2804 " Display currently cached IAX Dialplan results.\n";
2810 AST_LIST_LOCK(&dpcache
);
2812 ast_cli(a
->fd
, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2814 AST_LIST_TRAVERSE(&dpcache
, dp
, cache_list
) {
2815 s
= dp
->expiry
.tv_sec
- now
.tv_sec
;
2817 if (dp
->flags
& CACHE_FLAG_EXISTS
)
2818 strncat(tmp
, "EXISTS|", sizeof(tmp
) - strlen(tmp
) - 1);
2819 if (dp
->flags
& CACHE_FLAG_NONEXISTENT
)
2820 strncat(tmp
, "NONEXISTENT|", sizeof(tmp
) - strlen(tmp
) - 1);
2821 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
2822 strncat(tmp
, "CANEXIST|", sizeof(tmp
) - strlen(tmp
) - 1);
2823 if (dp
->flags
& CACHE_FLAG_PENDING
)
2824 strncat(tmp
, "PENDING|", sizeof(tmp
) - strlen(tmp
) - 1);
2825 if (dp
->flags
& CACHE_FLAG_TIMEOUT
)
2826 strncat(tmp
, "TIMEOUT|", sizeof(tmp
) - strlen(tmp
) - 1);
2827 if (dp
->flags
& CACHE_FLAG_TRANSMITTED
)
2828 strncat(tmp
, "TRANSMITTED|", sizeof(tmp
) - strlen(tmp
) - 1);
2829 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
2830 strncat(tmp
, "MATCHMORE|", sizeof(tmp
) - strlen(tmp
) - 1);
2831 if (dp
->flags
& CACHE_FLAG_UNKNOWN
)
2832 strncat(tmp
, "UNKNOWN|", sizeof(tmp
) - strlen(tmp
) - 1);
2833 /* Trim trailing pipe */
2834 if (!ast_strlen_zero(tmp
)) {
2835 tmp
[strlen(tmp
) - 1] = '\0';
2837 ast_copy_string(tmp
, "(none)", sizeof(tmp
));
2840 pc
= strchr(dp
->peercontext
, '@');
2842 pc
= dp
->peercontext
;
2846 for (x
= 0; x
< ARRAY_LEN(dp
->waiters
); x
++) {
2847 if (dp
->waiters
[x
] > -1)
2851 ast_cli(a
->fd
, "%-20.20s %-12.12s %-9d %-8d %s\n", pc
, dp
->exten
, s
, y
, tmp
);
2853 ast_cli(a
->fd
, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc
, dp
->exten
, "(expired)", y
, tmp
);
2857 AST_LIST_LOCK(&dpcache
);
2862 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
);
2864 static void unwrap_timestamp(struct iax_frame
*fr
)
2866 /* Video mini frames only encode the lower 15 bits of the session
2867 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
2868 const int ts_shift
= (fr
->af
.frametype
== AST_FRAME_VIDEO
) ? 15 : 16;
2869 const int lower_mask
= (1 << ts_shift
) - 1;
2870 const int upper_mask
= ~lower_mask
;
2871 const int last_upper
= iaxs
[fr
->callno
]->last
& upper_mask
;
2873 if ( (fr
->ts
& upper_mask
) == last_upper
) {
2874 const int x
= fr
->ts
- iaxs
[fr
->callno
]->last
;
2875 const int threshold
= (ts_shift
== 15) ? 25000 : 50000;
2877 if (x
< -threshold
) {
2878 /* Sudden big jump backwards in timestamp:
2879 What likely happened here is that miniframe timestamp has circled but we haven't
2880 gotten the update from the main packet. We'll just pretend that we did, and
2881 update the timestamp appropriately. */
2882 fr
->ts
= (last_upper
+ (1 << ts_shift
)) | (fr
->ts
& lower_mask
);
2884 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2885 } else if (x
> threshold
) {
2886 /* Sudden apparent big jump forwards in timestamp:
2887 What's likely happened is this is an old miniframe belonging to the previous
2888 top 15 or 16-bit timestamp that has turned up out of order.
2889 Adjust the timestamp appropriately. */
2890 fr
->ts
= (last_upper
- (1 << ts_shift
)) | (fr
->ts
& lower_mask
);
2892 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2897 static int get_from_jb(const void *p
);
2899 static void update_jbsched(struct chan_iax2_pvt
*pvt
)
2903 when
= ast_tvdiff_ms(ast_tvnow(), pvt
->rxcore
);
2905 when
= jb_next(pvt
->jb
) - when
;
2908 /* XXX should really just empty until when > 0.. */
2912 pvt
->jbid
= iax2_sched_replace(pvt
->jbid
, sched
, when
, get_from_jb
,
2913 CALLNO_TO_PTR(pvt
->callno
));
2916 static void __get_from_jb(const void *p
)
2918 int callno
= PTR_TO_CALLNO(p
);
2919 struct chan_iax2_pvt
*pvt
= NULL
;
2920 struct iax_frame
*fr
;
2925 struct timeval now
= ast_tvnow();
2927 /* Make sure we have a valid private structure before going on */
2928 ast_mutex_lock(&iaxsl
[callno
]);
2932 ast_mutex_unlock(&iaxsl
[callno
]);
2938 /* round up a millisecond since ast_sched_runq does; */
2939 /* prevents us from spinning while waiting for our now */
2940 /* to catch up with runq's now */
2941 now
.tv_usec
+= 1000;
2943 ms
= ast_tvdiff_ms(now
, pvt
->rxcore
);
2945 if(ms
>= (next
= jb_next(pvt
->jb
))) {
2946 ret
= jb_get(pvt
->jb
,&frame
,ms
,ast_codec_interp_len(pvt
->voiceformat
));
2951 /* __do_deliver() can cause the call to disappear */
2956 struct ast_frame af
= { 0, };
2958 /* create an interpolation frame */
2959 af
.frametype
= AST_FRAME_VOICE
;
2960 af
.subclass
= pvt
->voiceformat
;
2961 af
.samples
= frame
.ms
* 8;
2962 af
.src
= "IAX2 JB interpolation";
2963 af
.delivery
= ast_tvadd(pvt
->rxcore
, ast_samp2tv(next
, 1000));
2964 af
.offset
= AST_FRIENDLY_OFFSET
;
2966 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2967 * which we'd need to malloc, and then it would free it. That seems like a drag */
2968 if (!ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
)) {
2969 iax2_queue_frame(callno
, &af
);
2970 /* iax2_queue_frame() could cause the call to disappear */
2976 iax2_frame_free(frame
.data
);
2983 /* shouldn't happen */
2988 update_jbsched(pvt
);
2989 ast_mutex_unlock(&iaxsl
[callno
]);
2992 static int get_from_jb(const void *data
)
2994 #ifdef SCHED_MULTITHREADED
2995 if (schedule_action(__get_from_jb
, data
))
2997 __get_from_jb(data
);
3002 * \note This function assumes fr->callno is locked
3004 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3005 * was valid before calling it, it may no longer be valid after calling it.
3007 static int schedule_delivery(struct iax_frame
*fr
, int updatehistory
, int fromtrunk
, unsigned int *tsout
)
3012 struct ast_channel
*owner
= NULL
;
3013 struct ast_channel
*bridge
= NULL
;
3015 /* Attempt to recover wrapped timestamps */
3016 unwrap_timestamp(fr
);
3018 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
3019 if ( !fromtrunk
&& !ast_tvzero(iaxs
[fr
->callno
]->rxcore
))
3020 fr
->af
.delivery
= ast_tvadd(iaxs
[fr
->callno
]->rxcore
, ast_samp2tv(fr
->ts
, 1000));
3023 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
3025 fr
->af
.delivery
= ast_tv(0,0);
3028 type
= JB_TYPE_CONTROL
;
3031 if(fr
->af
.frametype
== AST_FRAME_VOICE
) {
3032 type
= JB_TYPE_VOICE
;
3033 len
= ast_codec_get_samples(&fr
->af
) / 8;
3034 } else if(fr
->af
.frametype
== AST_FRAME_CNG
) {
3035 type
= JB_TYPE_SILENCE
;
3038 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_USEJITTERBUF
)) ) {
3045 if ((owner
= iaxs
[fr
->callno
]->owner
))
3046 bridge
= ast_bridged_channel(owner
);
3048 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
3049 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
3050 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_FORCEJITTERBUF
)) && owner
&& bridge
&& (bridge
->tech
->properties
& AST_CHAN_TP_WANTSJITTER
) ) {
3053 /* deliver any frames in the jb */
3054 while (jb_getall(iaxs
[fr
->callno
]->jb
, &frame
) == JB_OK
) {
3055 __do_deliver(frame
.data
);
3056 /* __do_deliver() can make the call disappear */
3057 if (!iaxs
[fr
->callno
])
3061 jb_reset(iaxs
[fr
->callno
]->jb
);
3063 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->jbid
);
3065 /* deliver this frame now */
3072 /* insert into jitterbuffer */
3073 /* TODO: Perhaps we could act immediately if it's not droppable and late */
3074 ret
= jb_put(iaxs
[fr
->callno
]->jb
, fr
, type
, len
, fr
->ts
,
3075 calc_rxstamp(iaxs
[fr
->callno
],fr
->ts
));
3076 if (ret
== JB_DROP
) {
3078 } else if (ret
== JB_SCHED
) {
3079 update_jbsched(iaxs
[fr
->callno
]);
3084 /* Free our iax frame */
3085 iax2_frame_free(fr
);
3091 static int iax2_transmit(struct iax_frame
*fr
)
3093 /* Lock the queue and place this packet at the end */
3094 /* By setting this to 0, the network thread will send it for us, and
3095 queue retransmission if necessary */
3097 AST_LIST_LOCK(&frame_queue
);
3098 AST_LIST_INSERT_TAIL(&frame_queue
, fr
, list
);
3099 AST_LIST_UNLOCK(&frame_queue
);
3100 /* Wake up the network and scheduler thread */
3101 if (netthreadid
!= AST_PTHREADT_NULL
)
3102 pthread_kill(netthreadid
, SIGURG
);
3103 signal_condition(&sched_lock
, &sched_cond
);
3109 static int iax2_digit_begin(struct ast_channel
*c
, char digit
)
3111 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_BEGIN
, digit
, 0, NULL
, 0, -1);
3114 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
)
3116 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_END
, digit
, 0, NULL
, 0, -1);
3119 static int iax2_sendtext(struct ast_channel
*c
, const char *text
)
3122 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_TEXT
,
3123 0, 0, (unsigned char *)text
, strlen(text
) + 1, -1);
3126 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
)
3128 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_IMAGE
, img
->subclass
, 0, img
->data
.ptr
, img
->datalen
, -1);
3131 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
)
3133 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_HTML
, subclass
, 0, (unsigned char *)data
, datalen
, -1);
3136 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
)
3138 unsigned short callno
= PTR_TO_CALLNO(newchan
->tech_pvt
);
3139 ast_mutex_lock(&iaxsl
[callno
]);
3141 iaxs
[callno
]->owner
= newchan
;
3143 ast_log(LOG_WARNING
, "Uh, this isn't a good sign...\n");
3144 ast_mutex_unlock(&iaxsl
[callno
]);
3149 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3150 * so do not call this with a pvt lock held.
3152 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
)
3154 struct ast_variable
*var
= NULL
;
3155 struct ast_variable
*tmp
;
3156 struct iax2_peer
*peer
=NULL
;
3157 time_t regseconds
= 0, nowtime
;
3161 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", "dynamic", SENTINEL
);
3163 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", ast_inet_ntoa(sin
->sin_addr
), SENTINEL
);
3166 sprintf(porta
, "%d", ntohs(sin
->sin_port
));
3167 var
= ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, SENTINEL
);
3169 /* We'll need the peer name in order to build the structure! */
3170 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
3171 if (!strcasecmp(tmp
->name
, "name"))
3172 peername
= tmp
->value
;
3176 if (!var
&& peername
) { /* Last ditch effort */
3177 var
= ast_load_realtime("iaxpeers", "name", peername
, SENTINEL
);
3179 * If this one loaded something, then we need to ensure that the host
3180 * field matched. The only reason why we can't have this as a criteria
3181 * is because we only have the IP address and the host field might be
3182 * set as a name (and the reverse PTR might not match).
3185 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
3186 if (!strcasecmp(tmp
->name
, "host")) {
3187 struct ast_hostent ahp
;
3189 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
3191 ast_variables_destroy(var
);
3202 peer
= build_peer(peername
, var
, NULL
, ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
) ? 0 : 1);
3205 ast_variables_destroy(var
);
3209 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
3210 /* Make sure it's not a user only... */
3211 if (!strcasecmp(tmp
->name
, "type")) {
3212 if (strcasecmp(tmp
->value
, "friend") &&
3213 strcasecmp(tmp
->value
, "peer")) {
3214 /* Whoops, we weren't supposed to exist! */
3215 peer
= peer_unref(peer
);
3218 } else if (!strcasecmp(tmp
->name
, "regseconds")) {
3219 ast_get_time_t(tmp
->value
, ®seconds
, 0, NULL
);
3220 } else if (!strcasecmp(tmp
->name
, "ipaddr")) {
3221 inet_aton(tmp
->value
, &(peer
->addr
.sin_addr
));
3222 } else if (!strcasecmp(tmp
->name
, "port")) {
3223 peer
->addr
.sin_port
= htons(atoi(tmp
->value
));
3224 } else if (!strcasecmp(tmp
->name
, "host")) {
3225 if (!strcasecmp(tmp
->value
, "dynamic"))
3230 ast_variables_destroy(var
);
3235 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
3236 ast_copy_flags(peer
, &globalflags
, IAX_RTAUTOCLEAR
|IAX_RTCACHEFRIENDS
);
3237 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
)) {
3238 if (peer
->expire
> -1) {
3239 if (!ast_sched_del(sched
, peer
->expire
)) {
3244 peer
->expire
= iax2_sched_add(sched
, (global_rtautoclear
) * 1000, expire_registry
, peer_ref(peer
));
3245 if (peer
->expire
== -1)
3248 ao2_link(peers
, peer
);
3249 if (ast_test_flag(peer
, IAX_DYNAMIC
))
3250 reg_source_db(peer
);
3252 ast_set_flag(peer
, IAX_TEMPONLY
);
3255 if (!ast_test_flag(&globalflags
, IAX_RTIGNOREREGEXPIRE
) && dynamic
) {
3257 if ((nowtime
- regseconds
) > IAX_DEFAULT_REG_EXPIRE
) {
3258 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
3259 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
3260 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3261 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
3264 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3265 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
3272 static struct iax2_user
*realtime_user(const char *username
, struct sockaddr_in
*sin
)
3274 struct ast_variable
*var
;
3275 struct ast_variable
*tmp
;
3276 struct iax2_user
*user
=NULL
;
3278 var
= ast_load_realtime("iaxusers", "name", username
, "host", "dynamic", SENTINEL
);
3280 var
= ast_load_realtime("iaxusers", "name", username
, "host", ast_inet_ntoa(sin
->sin_addr
), SENTINEL
);
3283 snprintf(porta
, sizeof(porta
), "%d", ntohs(sin
->sin_port
));
3284 var
= ast_load_realtime("iaxusers", "name", username
, "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, SENTINEL
);
3286 var
= ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, SENTINEL
);
3288 if (!var
) { /* Last ditch effort */
3289 var
= ast_load_realtime("iaxusers", "name", username
, SENTINEL
);
3291 * If this one loaded something, then we need to ensure that the host
3292 * field matched. The only reason why we can't have this as a criteria
3293 * is because we only have the IP address and the host field might be
3294 * set as a name (and the reverse PTR might not match).
3297 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
3298 if (!strcasecmp(tmp
->name
, "host")) {
3299 struct ast_hostent ahp
;
3301 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
3303 ast_variables_destroy(var
);
3316 /* Make sure it's not a peer only... */
3317 if (!strcasecmp(tmp
->name
, "type")) {
3318 if (strcasecmp(tmp
->value
, "friend") &&
3319 strcasecmp(tmp
->value
, "user")) {
3326 user
= build_user(username
, var
, NULL
, !ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
));
3328 ast_variables_destroy(var
);
3333 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
3334 ast_set_flag(user
, IAX_RTCACHEFRIENDS
);
3335 ao2_link(users
, user
);
3337 ast_set_flag(user
, IAX_TEMPONLY
);
3343 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
)
3346 char regseconds
[20];
3348 snprintf(regseconds
, sizeof(regseconds
), "%d", (int)regtime
);
3349 snprintf(port
, sizeof(port
), "%d", ntohs(sin
->sin_port
));
3350 ast_update_realtime("iaxpeers", "name", peername
,
3351 "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", port
,
3352 "regseconds", regseconds
, SENTINEL
);
3355 struct create_addr_info
{
3368 char context
[AST_MAX_CONTEXT
];
3369 char peercontext
[AST_MAX_CONTEXT
];
3370 char mohinterpret
[MAX_MUSICCLASS
];
3371 char mohsuggest
[MAX_MUSICCLASS
];
3374 static int create_addr(const char *peername
, struct ast_channel
*c
, struct sockaddr_in
*sin
, struct create_addr_info
*cai
)
3376 struct iax2_peer
*peer
;
3378 struct ast_codec_pref ourprefs
;
3380 ast_clear_flag(cai
, IAX_SENDANI
| IAX_TRUNK
);
3381 cai
->sockfd
= defaultsockfd
;
3383 sin
->sin_family
= AF_INET
;
3385 if (!(peer
= find_peer(peername
, 1))) {
3387 if (ast_get_ip_or_srv(sin
, peername
, srvlookup
? "_iax._udp" : NULL
)) {
3388 ast_log(LOG_WARNING
, "No such host: %s\n", peername
);
3391 sin
->sin_port
= htons(IAX_DEFAULT_PORTNO
);
3392 /* use global iax prefs for unknown peer/user */
3393 /* But move the calling channel's native codec to the top of the preference list */
3394 memcpy(&ourprefs
, &prefs
, sizeof(ourprefs
));
3396 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
3397 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
3403 /* if the peer has no address (current or default), return failure */
3404 if (!(peer
->addr
.sin_addr
.s_addr
|| peer
->defaddr
.sin_addr
.s_addr
))
3407 /* if the peer is being monitored and is currently unreachable, return failure */
3408 if (peer
->maxms
&& ((peer
->lastms
> peer
->maxms
) || (peer
->lastms
< 0)))
3411 ast_copy_flags(cai
, peer
, IAX_SENDANI
| IAX_TRUNK
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_NOKEYROTATE
);
3412 cai
->maxtime
= peer
->maxms
;
3413 cai
->capability
= peer
->capability
;
3414 cai
->encmethods
= peer
->encmethods
;
3415 cai
->sockfd
= peer
->sockfd
;
3416 cai
->adsi
= peer
->adsi
;
3417 memcpy(&ourprefs
, &peer
->prefs
, sizeof(ourprefs
));
3418 /* Move the calling channel's native codec to the top of the preference list */
3420 ast_log(LOG_DEBUG
, "prepending %x to prefs\n", c
->nativeformats
);
3421 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
3423 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
3424 ast_copy_string(cai
->context
, peer
->context
, sizeof(cai
->context
));
3425 ast_copy_string(cai
->peercontext
, peer
->peercontext
, sizeof(cai
->peercontext
));
3426 ast_copy_string(cai
->username
, peer
->username
, sizeof(cai
->username
));
3427 ast_copy_string(cai
->timezone
, peer
->zonetag
, sizeof(cai
->timezone
));
3428 ast_copy_string(cai
->outkey
, peer
->outkey
, sizeof(cai
->outkey
));
3429 ast_copy_string(cai
->mohinterpret
, peer
->mohinterpret
, sizeof(cai
->mohinterpret
));
3430 ast_copy_string(cai
->mohsuggest
, peer
->mohsuggest
, sizeof(cai
->mohsuggest
));
3431 if (ast_strlen_zero(peer
->dbsecret
)) {
3432 ast_copy_string(cai
->secret
, peer
->secret
, sizeof(cai
->secret
));
3437 family
= ast_strdupa(peer
->dbsecret
);
3438 key
= strchr(family
, '/');
3441 if (!key
|| ast_db_get(family
, key
, cai
->secret
, sizeof(cai
->secret
))) {
3442 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", peer
->dbsecret
);
3447 if (peer
->addr
.sin_addr
.s_addr
) {
3448 sin
->sin_addr
= peer
->addr
.sin_addr
;
3449 sin
->sin_port
= peer
->addr
.sin_port
;
3451 sin
->sin_addr
= peer
->defaddr
.sin_addr
;
3452 sin
->sin_port
= peer
->defaddr
.sin_port
;
3463 static void __auto_congest(const void *nothing
)
3465 int callno
= PTR_TO_CALLNO(nothing
);
3466 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_CONGESTION
};
3467 ast_mutex_lock(&iaxsl
[callno
]);
3469 iaxs
[callno
]->initid
= -1;
3470 iax2_queue_frame(callno
, &f
);
3471 ast_log(LOG_NOTICE
, "Auto-congesting call due to slow response\n");
3473 ast_mutex_unlock(&iaxsl
[callno
]);
3476 static int auto_congest(const void *data
)
3478 #ifdef SCHED_MULTITHREADED
3479 if (schedule_action(__auto_congest
, data
))
3481 __auto_congest(data
);
3485 static unsigned int iax2_datetime(const char *tz
)
3487 struct timeval t
= ast_tvnow();
3490 ast_localtime(&t
, &tm
, ast_strlen_zero(tz
) ? NULL
: tz
);
3491 tmp
= (tm
.tm_sec
>> 1) & 0x1f; /* 5 bits of seconds */
3492 tmp
|= (tm
.tm_min
& 0x3f) << 5; /* 6 bits of minutes */
3493 tmp
|= (tm
.tm_hour
& 0x1f) << 11; /* 5 bits of hours */
3494 tmp
|= (tm
.tm_mday
& 0x1f) << 16; /* 5 bits of day of month */
3495 tmp
|= ((tm
.tm_mon
+ 1) & 0xf) << 21; /* 4 bits of month */
3496 tmp
|= ((tm
.tm_year
- 100) & 0x7f) << 25; /* 7 bits of year */
3500 struct parsed_dial_string
{
3511 static int send_apathetic_reply(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int command
, int ts
, unsigned char seqno
)
3513 struct ast_iax2_full_hdr f
= { .scallno
= htons(0x8000 | callno
), .dcallno
= htons(dcallno
),
3514 .ts
= htonl(ts
), .iseqno
= seqno
, .oseqno
= seqno
, .type
= AST_FRAME_IAX
,
3515 .csub
= compress_subclass(command
) };
3517 return sendto(defaultsockfd
, &f
, sizeof(f
), 0, (struct sockaddr
*)sin
, sizeof(*sin
));
3521 * \brief Parses an IAX dial string into its component parts.
3522 * \param data the string to be parsed
3523 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3526 * This function parses the string and fills the structure
3527 * with pointers to its component parts. The input string
3530 * \note This function supports both plaintext passwords and RSA
3531 * key names; if the password string is formatted as '[keyname]',
3532 * then the keyname will be placed into the key field, and the
3533 * password field will be set to NULL.
3535 * \note The dial string format is:
3536 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3538 static void parse_dial_string(char *data
, struct parsed_dial_string
*pds
)
3540 if (ast_strlen_zero(data
))
3543 pds
->peer
= strsep(&data
, "/");
3544 pds
->exten
= strsep(&data
, "/");
3545 pds
->options
= data
;
3549 pds
->exten
= strsep(&data
, "@");
3550 pds
->context
= data
;
3553 if (strchr(pds
->peer
, '@')) {
3555 pds
->username
= strsep(&data
, "@");
3559 if (pds
->username
) {
3560 data
= pds
->username
;
3561 pds
->username
= strsep(&data
, ":");
3562 pds
->password
= data
;
3566 pds
->peer
= strsep(&data
, ":");
3569 /* check for a key name wrapped in [] in the secret position, if found,
3570 move it to the key field instead
3572 if (pds
->password
&& (pds
->password
[0] == '[')) {
3573 pds
->key
= ast_strip_quoted(pds
->password
, "[", "]");
3574 pds
->password
= NULL
;
3578 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
)
3580 struct sockaddr_in sin
;
3581 char *l
=NULL
, *n
=NULL
, *tmpstr
;
3582 struct iax_ie_data ied
;
3583 char *defaultrdest
= "s";
3584 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3585 struct parsed_dial_string pds
;
3586 struct create_addr_info cai
;
3587 struct ast_var_t
*var
;
3588 struct ast_datastore
*variablestore
= ast_channel_datastore_find(c
, &iax2_variable_datastore_info
, NULL
);
3589 const char* osp_token_ptr
;
3590 unsigned int osp_token_length
;
3591 unsigned char osp_block_index
;
3592 unsigned int osp_block_length
;
3593 unsigned char osp_buffer
[256];
3595 if ((c
->_state
!= AST_STATE_DOWN
) && (c
->_state
!= AST_STATE_RESERVED
)) {
3596 ast_log(LOG_WARNING
, "Channel is already in use (%s)?\n", c
->name
);
3600 memset(&cai
, 0, sizeof(cai
));
3601 cai
.encmethods
= iax2_encryption
;
3603 memset(&pds
, 0, sizeof(pds
));
3604 tmpstr
= ast_strdupa(dest
);
3605 parse_dial_string(tmpstr
, &pds
);
3607 if (ast_strlen_zero(pds
.peer
)) {
3608 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", dest
);
3613 pds
.exten
= defaultrdest
;
3616 if (create_addr(pds
.peer
, c
, &sin
, &cai
)) {
3617 ast_log(LOG_WARNING
, "No address associated with '%s'\n", pds
.peer
);
3621 if (!pds
.username
&& !ast_strlen_zero(cai
.username
))
3622 pds
.username
= cai
.username
;
3623 if (!pds
.password
&& !ast_strlen_zero(cai
.secret
))
3624 pds
.password
= cai
.secret
;
3625 if (!pds
.key
&& !ast_strlen_zero(cai
.outkey
))
3626 pds
.key
= cai
.outkey
;
3627 if (!pds
.context
&& !ast_strlen_zero(cai
.peercontext
))
3628 pds
.context
= cai
.peercontext
;
3630 /* Keep track of the context for outgoing calls too */
3631 ast_copy_string(c
->context
, cai
.context
, sizeof(c
->context
));
3634 sin
.sin_port
= htons(atoi(pds
.port
));
3637 n
= c
->cid
.cid_name
;
3639 /* Now build request */
3640 memset(&ied
, 0, sizeof(ied
));
3642 /* On new call, first IE MUST be IAX version of caller */
3643 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
3644 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, pds
.exten
);
3645 if (pds
.options
&& strchr(pds
.options
, 'a')) {
3646 /* Request auto answer */
3647 iax_ie_append(&ied
, IAX_IE_AUTOANSWER
);
3650 iax_ie_append_str(&ied
, IAX_IE_CODEC_PREFS
, cai
.prefs
);
3653 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, l
);
3654 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3657 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3659 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, AST_PRES_NUMBER_NOT_AVAILABLE
);
3662 iax_ie_append_byte(&ied
, IAX_IE_CALLINGTON
, c
->cid
.cid_ton
);
3663 iax_ie_append_short(&ied
, IAX_IE_CALLINGTNS
, c
->cid
.cid_tns
);
3666 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, n
);
3667 if (ast_test_flag(iaxs
[callno
], IAX_SENDANI
) && c
->cid
.cid_ani
)
3668 iax_ie_append_str(&ied
, IAX_IE_CALLING_ANI
, c
->cid
.cid_ani
);
3670 if (!ast_strlen_zero(c
->language
))
3671 iax_ie_append_str(&ied
, IAX_IE_LANGUAGE
, c
->language
);
3672 if (!ast_strlen_zero(c
->cid
.cid_dnid
))
3673 iax_ie_append_str(&ied
, IAX_IE_DNID
, c
->cid
.cid_dnid
);
3674 if (!ast_strlen_zero(c
->cid
.cid_rdnis
))
3675 iax_ie_append_str(&ied
, IAX_IE_RDNIS
, c
->cid
.cid_rdnis
);
3678 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.context
);
3681 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
3684 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, cai
.encmethods
);
3686 ast_mutex_lock(&iaxsl
[callno
]);
3688 if (!ast_strlen_zero(c
->context
))
3689 ast_string_field_set(iaxs
[callno
], context
, c
->context
);
3692 ast_string_field_set(iaxs
[callno
], username
, pds
.username
);
3694 iaxs
[callno
]->encmethods
= cai
.encmethods
;
3696 iaxs
[callno
]->adsi
= cai
.adsi
;
3698 ast_string_field_set(iaxs
[callno
], mohinterpret
, cai
.mohinterpret
);
3699 ast_string_field_set(iaxs
[callno
], mohsuggest
, cai
.mohsuggest
);
3702 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
3704 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
3706 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, c
->nativeformats
);
3707 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, iaxs
[callno
]->capability
);
3708 iax_ie_append_short(&ied
, IAX_IE_ADSICPE
, c
->adsicpe
);
3709 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(cai
.timezone
));
3711 if (iaxs
[callno
]->maxtime
) {
3712 /* Initialize pingtime and auto-congest time */
3713 iaxs
[callno
]->pingtime
= iaxs
[callno
]->maxtime
/ 2;
3714 iaxs
[callno
]->initid
= iax2_sched_add(sched
, iaxs
[callno
]->maxtime
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3715 } else if (autokill
) {
3716 iaxs
[callno
]->pingtime
= autokill
/ 2;
3717 iaxs
[callno
]->initid
= iax2_sched_add(sched
, autokill
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3720 /* Check if there is an OSP token set by IAXCHANINFO function */
3721 osp_token_ptr
= iaxs
[callno
]->osptoken
;
3722 if (!ast_strlen_zero(osp_token_ptr
)) {
3723 if ((osp_token_length
= strlen(osp_token_ptr
)) <= IAX_MAX_OSPTOKEN_SIZE
) {
3724 osp_block_index
= 0;
3725 while (osp_token_length
> 0) {
3726 osp_block_length
= IAX_MAX_OSPBLOCK_SIZE
< osp_token_length
? IAX_MAX_OSPBLOCK_SIZE
: osp_token_length
;
3727 osp_buffer
[0] = osp_block_index
;
3728 memcpy(osp_buffer
+ 1, osp_token_ptr
, osp_block_length
);
3729 iax_ie_append_raw(&ied
, IAX_IE_OSPTOKEN
, osp_buffer
, osp_block_length
+ 1);
3731 osp_token_ptr
+= osp_block_length
;
3732 osp_token_length
-= osp_block_length
;
3735 ast_log(LOG_WARNING
, "OSP token is too long\n");
3736 } else if (iaxdebug
)
3737 ast_debug(1, "OSP token is undefined\n");
3739 /* send the command using the appropriate socket for this peer */
3740 iaxs
[callno
]->sockfd
= cai
.sockfd
;
3742 /* Add remote vars */
3743 if (variablestore
) {
3744 AST_LIST_HEAD(, ast_var_t
) *variablelist
= variablestore
->data
;
3745 AST_LIST_LOCK(variablelist
);
3746 AST_LIST_TRAVERSE(variablelist
, var
, entries
) {
3749 /* Automatically divide the value up into sized chunks */
3750 for (i
= 0; i
< strlen(ast_var_value(var
)); i
+= 255 - (strlen(ast_var_name(var
)) + 1)) {
3751 snprintf(tmp
, sizeof(tmp
), "%s=%s", ast_var_name(var
), ast_var_value(var
) + i
);
3752 iax_ie_append_str(&ied
, IAX_IE_VARIABLE
, tmp
);
3755 AST_LIST_UNLOCK(variablelist
);
3758 /* Transmit the string in a "NEW" request */
3759 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
3761 ast_mutex_unlock(&iaxsl
[callno
]);
3762 ast_setstate(c
, AST_STATE_RINGING
);
3767 static int iax2_hangup(struct ast_channel
*c
)
3769 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3770 struct iax_ie_data ied
;
3771 memset(&ied
, 0, sizeof(ied
));
3772 ast_mutex_lock(&iaxsl
[callno
]);
3773 if (callno
&& iaxs
[callno
]) {
3774 ast_debug(1, "We're hanging up %s now...\n", c
->name
);
3775 /* Send the hangup unless we have had a transmission error or are already gone */
3776 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, (unsigned char)c
->hangupcause
);
3777 if (!iaxs
[callno
]->error
&& !ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
)) {
3778 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
3779 if (!iaxs
[callno
]) {
3780 ast_mutex_unlock(&iaxsl
[callno
]);
3784 /* Explicitly predestroy it */
3785 iax2_predestroy(callno
);
3786 /* If we were already gone to begin with, destroy us now */
3788 ast_debug(1, "Really destroying %s now...\n", c
->name
);
3789 iax2_destroy(callno
);
3791 } else if (c
->tech_pvt
) {
3792 /* If this call no longer exists, but the channel still
3793 * references it we need to set the channel's tech_pvt to null
3794 * to avoid ast_channel_free() trying to free it.
3798 ast_mutex_unlock(&iaxsl
[callno
]);
3799 ast_verb(3, "Hungup '%s'\n", c
->name
);
3803 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
)
3805 struct ast_option_header
*h
;
3809 case AST_OPTION_TXGAIN
:
3810 case AST_OPTION_RXGAIN
:
3811 /* these two cannot be sent, because they require a result */
3815 if (!(h
= ast_malloc(datalen
+ sizeof(*h
))))
3818 h
->flag
= AST_OPTION_FLAG_REQUEST
;
3819 h
->option
= htons(option
);
3820 memcpy(h
->data
, data
, datalen
);
3821 res
= send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_CONTROL
,
3822 AST_CONTROL_OPTION
, 0, (unsigned char *) h
,
3823 datalen
+ sizeof(*h
), -1);
3829 static struct ast_frame
*iax2_read(struct ast_channel
*c
)
3831 ast_log(LOG_NOTICE
, "I should never be called!\n");
3832 return &ast_null_frame
;
3835 static int iax2_key_rotate(const void *vpvt
)
3838 struct chan_iax2_pvt
*pvt
= (void *) vpvt
;
3839 struct MD5Context md5
;
3841 struct iax_ie_data ied
= {
3845 ast_mutex_lock(&iaxsl
[pvt
->callno
]);
3848 ast_sched_add(sched
, 120000 + (ast_random() % 180001), iax2_key_rotate
, vpvt
);
3850 snprintf(key
, sizeof(key
), "%lX", ast_random());
3853 MD5Update(&md5
, (unsigned char *) key
, strlen(key
));
3854 MD5Final((unsigned char *) key
, &md5
);
3856 IAX_DEBUGDIGEST("Sending", key
);
3858 iax_ie_append_raw(&ied
, IAX_IE_CHALLENGE
, key
, 16);
3860 res
= send_command(pvt
, AST_FRAME_IAX
, IAX_COMMAND_RTKEY
, 0, ied
.buf
, ied
.pos
, -1);
3862 ast_aes_encrypt_key((unsigned char *) key
, &pvt
->ecx
);
3864 ast_mutex_unlock(&iaxsl
[pvt
->callno
]);
3869 static int iax2_start_transfer(unsigned short callno0
, unsigned short callno1
, int mediaonly
)
3872 struct iax_ie_data ied0
;
3873 struct iax_ie_data ied1
;
3874 unsigned int transferid
= (unsigned int)ast_random();
3876 if (IAX_CALLENCRYPTED(iaxs
[callno0
]) || IAX_CALLENCRYPTED(iaxs
[callno1
])) {
3877 ast_debug(1, "transfers are not supported for encrypted calls at this time");
3878 ast_set_flag(iaxs
[callno0
], IAX_NOTRANSFER
);
3879 ast_set_flag(iaxs
[callno1
], IAX_NOTRANSFER
);
3883 memset(&ied0
, 0, sizeof(ied0
));
3884 iaxs
[callno0
]->transferid
= transferid
;
3885 iax_ie_append_addr(&ied0
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno1
]->addr
);
3886 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[callno1
]->peercallno
);
3887 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, transferid
);
3889 memset(&ied1
, 0, sizeof(ied1
));
3890 iaxs
[callno1
]->transferid
= transferid
;
3891 iax_ie_append_addr(&ied1
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno0
]->addr
);
3892 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[callno0
]->peercallno
);
3893 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, transferid
);
3895 if (iaxs
[callno0
]->mediareleased
) {
3896 res
= send_command_media(iaxs
[callno0
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied0
.buf
, ied0
.pos
);
3898 res
= send_command(iaxs
[callno0
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied0
.buf
, ied0
.pos
, -1);
3904 if (iaxs
[callno1
]->mediareleased
)
3905 res
= send_command_media(iaxs
[callno1
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied1
.buf
, ied1
.pos
);
3907 res
= send_command(iaxs
[callno1
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied1
.buf
, ied1
.pos
, -1);
3911 iaxs
[callno0
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3912 iaxs
[callno1
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3913 iaxs
[callno0
]->triedtransfer
= 1;
3914 iaxs
[callno1
]->triedtransfer
= 1;
3919 static void lock_both(unsigned short callno0
, unsigned short callno1
)
3921 ast_mutex_lock(&iaxsl
[callno0
]);
3922 while (ast_mutex_trylock(&iaxsl
[callno1
])) {
3923 DEADLOCK_AVOIDANCE(&iaxsl
[callno0
]);
3927 static void unlock_both(unsigned short callno0
, unsigned short callno1
)
3929 ast_mutex_unlock(&iaxsl
[callno1
]);
3930 ast_mutex_unlock(&iaxsl
[callno0
]);
3933 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
)
3935 struct ast_channel
*cs
[3];
3936 struct ast_channel
*who
, *other
;
3939 struct ast_frame
*f
;
3940 unsigned short callno0
= PTR_TO_CALLNO(c0
->tech_pvt
);
3941 unsigned short callno1
= PTR_TO_CALLNO(c1
->tech_pvt
);
3942 struct timeval waittimer
= {0, 0};
3944 /* We currently do not support native bridging if a timeoutms value has been provided */
3945 if (timeoutms
> 0) {
3946 return AST_BRIDGE_FAILED
;
3951 lock_both(callno0
, callno1
);
3952 if (!iaxs
[callno0
] || !iaxs
[callno1
]) {
3953 unlock_both(callno0
, callno1
);
3954 return AST_BRIDGE_FAILED
;
3956 /* Put them in native bridge mode */
3957 if (!flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) {
3958 iaxs
[callno0
]->bridgecallno
= callno1
;
3959 iaxs
[callno1
]->bridgecallno
= callno0
;
3961 unlock_both(callno0
, callno1
);
3963 /* If not, try to bridge until we can execute a transfer, if we can */
3966 for (/* ever */;;) {
3967 /* Check in case we got masqueraded into */
3968 if ((c0
->tech
!= &iax2_tech
) || (c1
->tech
!= &iax2_tech
)) {
3969 ast_verb(3, "Can't masquerade, we're different...\n");
3970 /* Remove from native mode */
3971 if (c0
->tech
== &iax2_tech
) {
3972 ast_mutex_lock(&iaxsl
[callno0
]);
3973 iaxs
[callno0
]->bridgecallno
= 0;
3974 ast_mutex_unlock(&iaxsl
[callno0
]);
3976 if (c1
->tech
== &iax2_tech
) {
3977 ast_mutex_lock(&iaxsl
[callno1
]);
3978 iaxs
[callno1
]->bridgecallno
= 0;
3979 ast_mutex_unlock(&iaxsl
[callno1
]);
3981 return AST_BRIDGE_FAILED_NOWARN
;
3983 if (c0
->nativeformats
!= c1
->nativeformats
) {
3986 ast_getformatname_multiple(buf0
, sizeof(buf0
) -1, c0
->nativeformats
);
3987 ast_getformatname_multiple(buf1
, sizeof(buf1
) -1, c1
->nativeformats
);
3988 ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0
->nativeformats
, buf0
, c1
->nativeformats
, buf1
);
3989 /* Remove from native mode */
3990 lock_both(callno0
, callno1
);
3992 iaxs
[callno0
]->bridgecallno
= 0;
3994 iaxs
[callno1
]->bridgecallno
= 0;
3995 unlock_both(callno0
, callno1
);
3996 return AST_BRIDGE_FAILED_NOWARN
;
3998 /* check if if we really want native bridging */
3999 if (!ast_test_flag(iaxs
[callno0
], IAX_NOTRANSFER
) && !ast_test_flag(iaxs
[callno1
], IAX_NOTRANSFER
)) {
4000 if (!iaxs
[callno0
]->triedtransfer
&& !iaxs
[callno1
]->triedtransfer
&&
4001 (iaxs
[callno0
]->transferring
== TRANSFER_NONE
) &&
4002 (iaxs
[callno1
]->transferring
== TRANSFER_NONE
)) {
4003 /* Try the transfer */
4004 if (iax2_start_transfer(callno0
, callno1
, (flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) ||
4005 ast_test_flag(iaxs
[callno0
], IAX_TRANSFERMEDIA
) | ast_test_flag(iaxs
[callno1
], IAX_TRANSFERMEDIA
))) {
4006 ast_log(LOG_WARNING
, "Unable to start the transfer\n");
4010 if ((iaxs
[callno0
]->transferring
== TRANSFER_RELEASED
) && (iaxs
[callno1
]->transferring
== TRANSFER_RELEASED
)) {
4011 /* Call has been transferred. We're no longer involved */
4012 struct timeval now
= ast_tvnow();
4013 if (ast_tvzero(waittimer
)) {
4015 } else if (now
.tv_sec
- waittimer
.tv_sec
> IAX_LINGER_TIMEOUT
) {
4016 c0
->_softhangup
|= AST_SOFTHANGUP_DEV
;
4017 c1
->_softhangup
|= AST_SOFTHANGUP_DEV
;
4020 res
= AST_BRIDGE_COMPLETE
;
4025 who
= ast_waitfor_n(cs
, 2, &to
);
4026 if (timeoutms
> -1) {
4027 timeoutms
-= (1000 - to
);
4033 res
= AST_BRIDGE_RETRY
;
4036 if (ast_check_hangup(c0
) || ast_check_hangup(c1
)) {
4037 res
= AST_BRIDGE_FAILED
;
4046 res
= AST_BRIDGE_COMPLETE
;
4049 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(flags
& AST_BRIDGE_IGNORE_SIGS
)) {
4052 res
= AST_BRIDGE_COMPLETE
;
4055 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
4056 if ((f
->frametype
== AST_FRAME_VOICE
) ||
4057 (f
->frametype
== AST_FRAME_TEXT
) ||
4058 (f
->frametype
== AST_FRAME_VIDEO
) ||
4059 (f
->frametype
== AST_FRAME_IMAGE
) ||
4060 (f
->frametype
== AST_FRAME_DTMF
)) {
4061 /* monitored dtmf take out of the bridge.
4062 * check if we monitor the specific source.
4064 int monitored_source
= (who
== c0
) ? AST_BRIDGE_DTMF_CHANNEL_0
: AST_BRIDGE_DTMF_CHANNEL_1
;
4065 if (f
->frametype
== AST_FRAME_DTMF
&& (flags
& monitored_source
)) {
4068 res
= AST_BRIDGE_COMPLETE
;
4069 /* Remove from native mode */
4072 /* everything else goes to the other side */
4073 ast_write(other
, f
);
4076 /* Swap who gets priority */
4081 lock_both(callno0
, callno1
);
4083 iaxs
[callno0
]->bridgecallno
= 0;
4085 iaxs
[callno1
]->bridgecallno
= 0;
4086 unlock_both(callno0
, callno1
);
4090 static int iax2_answer(struct ast_channel
*c
)
4092 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
4093 ast_debug(1, "Answering IAX2 call\n");
4094 ast_mutex_lock(&iaxsl
[callno
]);
4096 iax2_ami_channelupdate(iaxs
[callno
]);
4097 ast_mutex_unlock(&iaxsl
[callno
]);
4098 return send_command_locked(callno
, AST_FRAME_CONTROL
, AST_CONTROL_ANSWER
, 0, NULL
, 0, -1);
4101 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
)
4103 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
4104 struct chan_iax2_pvt
*pvt
;
4108 ast_debug(1, "Indicating condition %d\n", condition
);
4110 ast_mutex_lock(&iaxsl
[callno
]);
4113 if (!pvt
->peercallno
) {
4114 /* We don't know the remote side's call number, yet. :( */
4116 while (count
-- && pvt
&& !pvt
->peercallno
) {
4117 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
4120 if (!pvt
->peercallno
) {
4126 switch (condition
) {
4127 case AST_CONTROL_HOLD
:
4128 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
4129 ast_moh_start(c
, data
, pvt
->mohinterpret
);
4133 case AST_CONTROL_UNHOLD
:
4134 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
4140 res
= send_command(pvt
, AST_FRAME_CONTROL
, condition
, 0, data
, datalen
, -1);
4143 ast_mutex_unlock(&iaxsl
[callno
]);
4148 static int iax2_transfer(struct ast_channel
*c
, const char *dest
)
4150 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
4151 struct iax_ie_data ied
= { "", };
4152 char tmp
[256], *context
;
4153 ast_copy_string(tmp
, dest
, sizeof(tmp
));
4154 context
= strchr(tmp
, '@');
4159 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, tmp
);
4161 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, context
);
4162 ast_debug(1, "Transferring '%s' to '%s'\n", c
->name
, dest
);
4163 return send_command_locked(callno
, AST_FRAME_IAX
, IAX_COMMAND_TRANSFER
, 0, ied
.buf
, ied
.pos
, -1);
4166 static int iax2_getpeertrunk(struct sockaddr_in sin
)
4168 struct iax2_peer
*peer
;
4170 struct ao2_iterator i
;
4172 i
= ao2_iterator_init(peers
, 0);
4173 while ((peer
= ao2_iterator_next(&i
))) {
4174 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
4175 (peer
->addr
.sin_port
== sin
.sin_port
)) {
4176 res
= ast_test_flag(peer
, IAX_TRUNK
);
4186 /*! \brief Create new call, interface with the PBX core */
4187 static struct ast_channel
*ast_iax2_new(int callno
, int state
, int capability
)
4189 struct ast_channel
*tmp
;
4190 struct chan_iax2_pvt
*i
;
4191 struct ast_variable
*v
= NULL
;
4193 if (!(i
= iaxs
[callno
])) {
4194 ast_log(LOG_WARNING
, "No IAX2 pvt found for callno '%d' !\n", callno
);
4198 /* Don't hold call lock */
4199 ast_mutex_unlock(&iaxsl
[callno
]);
4200 tmp
= ast_channel_alloc(1, state
, i
->cid_num
, i
->cid_name
, i
->accountcode
, i
->exten
, i
->context
, i
->amaflags
, "IAX2/%s-%d", i
->host
, i
->callno
);
4201 ast_mutex_lock(&iaxsl
[callno
]);
4202 if (i
!= iaxs
[callno
]) {
4204 /* unlock and relock iaxsl[callno] to preserve locking order */
4205 ast_mutex_unlock(&iaxsl
[callno
]);
4206 ast_channel_free(tmp
);
4207 ast_mutex_lock(&iaxsl
[callno
]);
4211 iax2_ami_channelupdate(i
);
4214 tmp
->tech
= &iax2_tech
;
4215 /* We can support any format by default, until we get restricted */
4216 tmp
->nativeformats
= capability
;
4217 tmp
->readformat
= ast_best_codec(capability
);
4218 tmp
->writeformat
= ast_best_codec(capability
);
4219 tmp
->tech_pvt
= CALLNO_TO_PTR(i
->callno
);
4221 if (!ast_strlen_zero(i
->parkinglot
))
4222 ast_string_field_set(tmp
, parkinglot
, i
->parkinglot
);
4223 /* Don't use ast_set_callerid() here because it will
4224 * generate a NewCallerID event before the NewChannel event */
4225 if (!ast_strlen_zero(i
->ani
))
4226 tmp
->cid
.cid_ani
= ast_strdup(i
->ani
);
4228 tmp
->cid
.cid_ani
= ast_strdup(i
->cid_num
);
4229 tmp
->cid
.cid_dnid
= ast_strdup(i
->dnid
);
4230 tmp
->cid
.cid_rdnis
= ast_strdup(i
->rdnis
);
4231 tmp
->cid
.cid_pres
= i
->calling_pres
;
4232 tmp
->cid
.cid_ton
= i
->calling_ton
;
4233 tmp
->cid
.cid_tns
= i
->calling_tns
;
4234 if (!ast_strlen_zero(i
->language
))
4235 ast_string_field_set(tmp
, language
, i
->language
);
4236 if (!ast_strlen_zero(i
->accountcode
))
4237 ast_string_field_set(tmp
, accountcode
, i
->accountcode
);
4239 tmp
->amaflags
= i
->amaflags
;
4240 ast_copy_string(tmp
->context
, i
->context
, sizeof(tmp
->context
));
4241 ast_copy_string(tmp
->exten
, i
->exten
, sizeof(tmp
->exten
));
4243 tmp
->adsicpe
= i
->peeradsicpe
;
4245 tmp
->adsicpe
= AST_ADSI_UNAVAILABLE
;
4247 i
->capability
= capability
;
4249 /* Set inherited variables */
4251 for (v
= i
->vars
; v
; v
= v
->next
)
4252 pbx_builtin_setvar_helper(tmp
, v
->name
, v
->value
);
4255 if (state
!= AST_STATE_DOWN
) {
4256 if (ast_pbx_start(tmp
)) {
4257 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmp
->name
);
4264 ast_module_ref(ast_module_info
->self
);
4268 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer
*tpeer
, int sampms
, struct timeval
*now
)
4270 unsigned long int mssincetx
; /* unsigned to handle overflows */
4273 tpeer
->trunkact
= *now
;
4274 mssincetx
= ast_tvdiff_ms(*now
, tpeer
->lasttxtime
);
4275 if (mssincetx
> 5000 || ast_tvzero(tpeer
->txtrunktime
)) {
4276 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
4277 tpeer
->txtrunktime
= *now
;
4278 tpeer
->lastsent
= 999999;
4280 /* Update last transmit time now */
4281 tpeer
->lasttxtime
= *now
;
4283 /* Calculate ms offset */
4284 ms
= ast_tvdiff_ms(*now
, tpeer
->txtrunktime
);
4285 /* Predict from last value */
4286 pred
= tpeer
->lastsent
+ sampms
;
4287 if (abs(ms
- pred
) < MAX_TIMESTAMP_SKEW
)
4290 /* We never send the same timestamp twice, so fudge a little if we must */
4291 if (ms
== tpeer
->lastsent
)
4292 ms
= tpeer
->lastsent
+ 1;
4293 tpeer
->lastsent
= ms
;
4297 static unsigned int fix_peerts(struct timeval
*rxtrunktime
, int callno
, unsigned int ts
)
4299 long ms
; /* NOT unsigned */
4300 if (ast_tvzero(iaxs
[callno
]->rxcore
)) {
4301 /* Initialize rxcore time if appropriate */
4302 iaxs
[callno
]->rxcore
= ast_tvnow();
4303 /* Round to nearest 20ms so traces look pretty */
4304 iaxs
[callno
]->rxcore
.tv_usec
-= iaxs
[callno
]->rxcore
.tv_usec
% 20000;
4306 /* Calculate difference between trunk and channel */
4307 ms
= ast_tvdiff_ms(*rxtrunktime
, iaxs
[callno
]->rxcore
);
4308 /* Return as the sum of trunk time and the difference between trunk and real time */
4312 static unsigned int calc_timestamp(struct chan_iax2_pvt
*p
, unsigned int ts
, struct ast_frame
*f
)
4318 struct timeval
*delivery
= NULL
;
4321 /* What sort of frame do we have?: voice is self-explanatory
4322 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
4323 non-genuine frames are CONTROL frames [ringing etc], DTMF
4324 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
4325 the others need a timestamp slaved to the voice frames so that they go in sequence
4328 if (f
->frametype
== AST_FRAME_VOICE
) {
4330 delivery
= &f
->delivery
;
4331 } else if (f
->frametype
== AST_FRAME_IAX
) {
4333 } else if (f
->frametype
== AST_FRAME_CNG
) {
4337 if (ast_tvzero(p
->offset
)) {
4338 p
->offset
= ast_tvnow();
4339 /* Round to nearest 20ms for nice looking traces */
4340 p
->offset
.tv_usec
-= p
->offset
.tv_usec
% 20000;
4342 /* If the timestamp is specified, just send it as is */
4345 /* If we have a time that the frame arrived, always use it to make our timestamp */
4346 if (delivery
&& !ast_tvzero(*delivery
)) {
4347 ms
= ast_tvdiff_ms(*delivery
, p
->offset
);
4349 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p
->callno
, iaxs
[p
->callno
]->peercallno
);
4351 ms
= ast_tvdiff_ms(ast_tvnow(), p
->offset
);
4355 /* On a voice frame, use predicted values if appropriate */
4356 if (p
->notsilenttx
&& abs(ms
- p
->nextpred
) <= MAX_TIMESTAMP_SKEW
) {
4357 /* Adjust our txcore, keeping voice and non-voice synchronized */
4359 When we send voice, we usually send "calculated" timestamps worked out
4360 on the basis of the number of samples sent. When we send other frames,
4361 we usually send timestamps worked out from the real clock.
4362 The problem is that they can tend to drift out of step because the
4363 source channel's clock and our clock may not be exactly at the same rate.
4364 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
4365 for this call. Moving it adjusts timestamps for non-voice frames.
4366 We make the adjustment in the style of a moving average. Each time we
4367 adjust p->offset by 10% of the difference between our clock-derived
4368 timestamp and the predicted timestamp. That's why you see "10000"
4369 below even though IAX2 timestamps are in milliseconds.
4370 The use of a moving average avoids offset moving too radically.
4371 Generally, "adjust" roams back and forth around 0, with offset hardly
4372 changing at all. But if a consistent different starts to develop it
4373 will be eliminated over the course of 10 frames (200-300msecs)
4375 adjust
= (ms
- p
->nextpred
);
4377 p
->offset
= ast_tvsub(p
->offset
, ast_samp2tv(abs(adjust
), 10000));
4378 else if (adjust
> 0)
4379 p
->offset
= ast_tvadd(p
->offset
, ast_samp2tv(adjust
, 10000));
4382 p
->nextpred
= ms
; /*f->samples / 8;*/
4383 if (p
->nextpred
<= p
->lastsent
)
4384 p
->nextpred
= p
->lastsent
+ 3;
4388 /* in this case, just use the actual
4389 * time, since we're either way off
4390 * (shouldn't happen), or we're ending a
4391 * silent period -- and seed the next
4392 * predicted time. Also, round ms to the
4393 * next multiple of frame size (so our
4394 * silent periods are multiples of
4395 * frame size too) */
4397 if (iaxdebug
&& abs(ms
- p
->nextpred
) > MAX_TIMESTAMP_SKEW
)
4398 ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
4399 abs(ms
- p
->nextpred
), MAX_TIMESTAMP_SKEW
);
4401 if (f
->samples
>= 8) /* check to make sure we dont core dump */
4403 int diff
= ms
% (f
->samples
/ 8);
4405 ms
+= f
->samples
/8 - diff
;
4411 } else if ( f
->frametype
== AST_FRAME_VIDEO
) {
4413 * IAX2 draft 03 says that timestamps MUST be in order.
4414 * It does not say anything about several frames having the same timestamp
4415 * When transporting video, we can have a frame that spans multiple iax packets
4416 * (so called slices), so it would make sense to use the same timestamp for all of
4418 * We do want to make sure that frames don't go backwards though
4420 if ( (unsigned int)ms
< p
->lastsent
)
4423 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
4424 it's a genuine frame */
4426 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
4427 if (ms
<= p
->lastsent
)
4428 ms
= p
->lastsent
+ 3;
4429 } else if (abs(ms
- p
->lastsent
) <= MAX_TIMESTAMP_SKEW
) {
4430 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
4431 ms
= p
->lastsent
+ 3;
4437 p
->nextpred
= p
->nextpred
+ f
->samples
/ 8;
4441 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
)
4443 /* Returns where in "receive time" we are. That is, how many ms
4444 since we received (or would have received) the frame with timestamp 0 */
4448 #endif /* IAXTESTS */
4449 /* Setup rxcore if necessary */
4450 if (ast_tvzero(p
->rxcore
)) {
4451 p
->rxcore
= ast_tvnow();
4453 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
4454 p
->callno
, (int)(p
->rxcore
.tv_sec
), (int)(p
->rxcore
.tv_usec
), offset
);
4455 p
->rxcore
= ast_tvsub(p
->rxcore
, ast_samp2tv(offset
, 1000));
4458 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
4459 p
->callno
, (int)(p
->rxcore
.tv_sec
),(int)( p
->rxcore
.tv_usec
));
4463 ms
= ast_tvdiff_ms(ast_tvnow(), p
->rxcore
);
4466 if (!test_jitpct
|| ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_jitpct
)) {
4467 jit
= (int)((float)test_jit
* ast_random() / (RAND_MAX
+ 1.0));
4468 if ((int)(2.0 * ast_random() / (RAND_MAX
+ 1.0)))
4477 #endif /* IAXTESTS */
4481 static struct iax2_trunk_peer
*find_tpeer(struct sockaddr_in
*sin
, int fd
)
4483 struct iax2_trunk_peer
*tpeer
= NULL
;
4485 /* Finds and locks trunk peer */
4486 AST_LIST_LOCK(&tpeers
);
4488 AST_LIST_TRAVERSE(&tpeers
, tpeer
, list
) {
4489 if (!inaddrcmp(&tpeer
->addr
, sin
)) {
4490 ast_mutex_lock(&tpeer
->lock
);
4496 if ((tpeer
= ast_calloc(1, sizeof(*tpeer
)))) {
4497 ast_mutex_init(&tpeer
->lock
);
4498 tpeer
->lastsent
= 9999;
4499 memcpy(&tpeer
->addr
, sin
, sizeof(tpeer
->addr
));
4500 tpeer
->trunkact
= ast_tvnow();
4501 ast_mutex_lock(&tpeer
->lock
);
4504 setsockopt(tpeer
->sockfd
, SOL_SOCKET
, SO_NO_CHECK
, &nochecksums
, sizeof(nochecksums
));
4506 ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
));
4507 AST_LIST_INSERT_TAIL(&tpeers
, tpeer
, list
);
4511 AST_LIST_UNLOCK(&tpeers
);
4516 static int iax2_trunk_queue(struct chan_iax2_pvt
*pvt
, struct iax_frame
*fr
)
4518 struct ast_frame
*f
;
4519 struct iax2_trunk_peer
*tpeer
;
4523 struct ast_iax2_meta_trunk_entry
*met
;
4524 struct ast_iax2_meta_trunk_mini
*mtm
;
4527 tpeer
= find_tpeer(&pvt
->addr
, pvt
->sockfd
);
4529 if (tpeer
->trunkdatalen
+ f
->datalen
+ 4 >= tpeer
->trunkdataalloc
) {
4530 /* Need to reallocate space */
4531 if (tpeer
->trunkdataalloc
< trunkmaxsize
) {
4532 if (!(tmp
= ast_realloc(tpeer
->trunkdata
, tpeer
->trunkdataalloc
+ DEFAULT_TRUNKDATA
+ IAX2_TRUNK_PREFACE
))) {
4533 ast_mutex_unlock(&tpeer
->lock
);
4537 tpeer
->trunkdataalloc
+= DEFAULT_TRUNKDATA
;
4538 tpeer
->trunkdata
= tmp
;
4539 ast_debug(1, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
), tpeer
->trunkdataalloc
);
4541 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
));
4542 ast_mutex_unlock(&tpeer
->lock
);
4547 /* Append to meta frame */
4548 ptr
= tpeer
->trunkdata
+ IAX2_TRUNK_PREFACE
+ tpeer
->trunkdatalen
;
4549 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
)) {
4550 mtm
= (struct ast_iax2_meta_trunk_mini
*)ptr
;
4551 mtm
->len
= htons(f
->datalen
);
4552 mtm
->mini
.callno
= htons(pvt
->callno
);
4553 mtm
->mini
.ts
= htons(0xffff & fr
->ts
);
4554 ptr
+= sizeof(struct ast_iax2_meta_trunk_mini
);
4555 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_mini
);
4557 met
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
4558 /* Store call number and length in meta header */
4559 met
->callno
= htons(pvt
->callno
);
4560 met
->len
= htons(f
->datalen
);
4561 /* Advance pointers/decrease length past trunk entry header */
4562 ptr
+= sizeof(struct ast_iax2_meta_trunk_entry
);
4563 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_entry
);
4565 /* Copy actual trunk data */
4566 memcpy(ptr
, f
->data
.ptr
, f
->datalen
);
4567 tpeer
->trunkdatalen
+= f
->datalen
;
4571 /* track the largest mtu we actually have sent */
4572 if (tpeer
->trunkdatalen
+ f
->datalen
+ 4 > trunk_maxmtu
)
4573 trunk_maxmtu
= tpeer
->trunkdatalen
+ f
->datalen
+ 4 ;
4575 /* if we have enough for a full MTU, ship it now without waiting */
4576 if (global_max_trunk_mtu
> 0 && tpeer
->trunkdatalen
+ f
->datalen
+ 4 >= global_max_trunk_mtu
) {
4578 res
= send_trunk(tpeer
, &now
);
4582 ast_mutex_unlock(&tpeer
->lock
);
4587 static void build_enc_keys(const unsigned char *digest
, ast_aes_encrypt_key
*ecx
, ast_aes_decrypt_key
*dcx
)
4589 ast_aes_encrypt_key(digest
, ecx
);
4590 ast_aes_decrypt_key(digest
, dcx
);
4593 static void memcpy_decrypt(unsigned char *dst
, const unsigned char *src
, int len
, ast_aes_decrypt_key
*dcx
)
4596 /* Debug with "fake encryption" */
4599 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
4601 dst
[x
] = src
[x
] ^ 0xff;
4603 unsigned char lastblock
[16] = { 0 };
4606 ast_aes_decrypt(src
, dst
, dcx
);
4608 dst
[x
] ^= lastblock
[x
];
4609 memcpy(lastblock
, src
, sizeof(lastblock
));
4617 static void memcpy_encrypt(unsigned char *dst
, const unsigned char *src
, int len
, ast_aes_encrypt_key
*ecx
)
4620 /* Debug with "fake encryption" */
4623 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
4625 dst
[x
] = src
[x
] ^ 0xff;
4627 unsigned char curblock
[16] = { 0 };
4631 curblock
[x
] ^= src
[x
];
4632 ast_aes_encrypt(curblock
, dst
, ecx
);
4633 memcpy(curblock
, dst
, sizeof(curblock
));
4641 static int decode_frame(ast_aes_decrypt_key
*dcx
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4644 unsigned char *workspace
;
4646 workspace
= alloca(*datalen
);
4647 memset(f
, 0, sizeof(*f
));
4648 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4649 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4650 if (*datalen
< 16 + sizeof(struct ast_iax2_full_hdr
))
4653 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), dcx
);
4655 padding
= 16 + (workspace
[15] & 0xf);
4657 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen
, padding
, workspace
[15]);
4658 if (*datalen
< padding
+ sizeof(struct ast_iax2_full_hdr
))
4661 *datalen
-= padding
;
4662 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4663 f
->frametype
= fh
->type
;
4664 if (f
->frametype
== AST_FRAME_VIDEO
) {
4665 f
->subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
4667 f
->subclass
= uncompress_subclass(fh
->csub
);
4670 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4672 ast_debug(1, "Decoding mini with length %d\n", *datalen
);
4673 if (*datalen
< 16 + sizeof(struct ast_iax2_mini_hdr
))
4676 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), dcx
);
4677 padding
= 16 + (workspace
[15] & 0x0f);
4678 if (*datalen
< padding
+ sizeof(struct ast_iax2_mini_hdr
))
4680 *datalen
-= padding
;
4681 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4686 static int encrypt_frame(ast_aes_encrypt_key
*ecx
, struct ast_iax2_full_hdr
*fh
, unsigned char *poo
, int *datalen
)
4689 unsigned char *workspace
;
4690 workspace
= alloca(*datalen
+ 32);
4693 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4694 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4696 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh
->type
, fh
->csub
, *datalen
);
4697 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_full_enc_hdr
)) % 16);
4698 padding
= 16 + (padding
& 0xf);
4699 memcpy(workspace
, poo
, padding
);
4700 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4701 workspace
[15] &= 0xf0;
4702 workspace
[15] |= (padding
& 0xf);
4704 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh
->type
, fh
->csub
, *datalen
, padding
, workspace
[15]);
4705 *datalen
+= padding
;
4706 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), ecx
);
4707 if (*datalen
>= 32 + sizeof(struct ast_iax2_full_enc_hdr
))
4708 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4710 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4712 ast_debug(1, "Encoding mini frame with length %d\n", *datalen
);
4713 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_mini_enc_hdr
)) % 16);
4714 padding
= 16 + (padding
& 0xf);
4715 memcpy(workspace
, poo
, padding
);
4716 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4717 workspace
[15] &= 0xf0;
4718 workspace
[15] |= (padding
& 0x0f);
4719 *datalen
+= padding
;
4720 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), ecx
);
4721 if (*datalen
>= 32 + sizeof(struct ast_iax2_mini_enc_hdr
))
4722 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4727 static int decrypt_frame(int callno
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4730 if (!ast_test_flag(iaxs
[callno
], IAX_KEYPOPULATED
)) {
4731 /* Search for possible keys, given secrets */
4732 struct MD5Context md5
;
4733 unsigned char digest
[16];
4734 char *tmppw
, *stringp
;
4736 tmppw
= ast_strdupa(iaxs
[callno
]->secret
);
4738 while ((tmppw
= strsep(&stringp
, ";"))) {
4740 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
4741 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
4742 MD5Final(digest
, &md5
);
4743 build_enc_keys(digest
, &iaxs
[callno
]->ecx
, &iaxs
[callno
]->dcx
);
4744 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4746 ast_set_flag(iaxs
[callno
], IAX_KEYPOPULATED
);
4751 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4755 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
, int media
)
4757 /* Queue a packet for delivery on a given private structure. Use "ts" for
4758 timestamp, or calculate if ts is 0. Send immediately without retransmission
4759 or delayed, with retransmission */
4760 struct ast_iax2_full_hdr
*fh
;
4761 struct ast_iax2_mini_hdr
*mh
;
4762 struct ast_iax2_video_hdr
*vh
;
4764 struct iax_frame fr2
;
4765 unsigned char buffer
[4096];
4767 struct iax_frame
*fr
;
4770 unsigned int lastsent
;
4773 frb
.fr2
.afdatalen
= sizeof(frb
.buffer
);
4776 ast_log(LOG_WARNING
, "No private structure for packet?\n");
4780 lastsent
= pvt
->lastsent
;
4782 /* Calculate actual timestamp */
4783 fts
= calc_timestamp(pvt
, ts
, f
);
4785 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4786 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4787 * increment the "predicted timestamps" for voice, if we're predicting */
4788 if(f
->frametype
== AST_FRAME_VOICE
&& f
->datalen
== 0)
4792 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
4793 *("=!" + (f
->frametype
== AST_FRAME_VOICE
)),
4794 IAX_CALLENCRYPTED(pvt
) ? "" : "not ",
4795 pvt
->keyrotateid
!= -1 ? "" : "no "
4799 if (pvt
->keyrotateid
== -1 && f
->frametype
== AST_FRAME_VOICE
&& IAX_CALLENCRYPTED(pvt
)) {
4800 if (ast_test_flag(pvt
, IAX_NOKEYROTATE
)) {
4801 pvt
->keyrotateid
= -2;
4803 iax2_key_rotate(pvt
);
4807 if ((ast_test_flag(pvt
, IAX_TRUNK
) ||
4808 (((fts
& 0xFFFF0000L
) == (lastsent
& 0xFFFF0000L
)) ||
4809 ((fts
& 0xFFFF0000L
) == ((lastsent
+ 0x10000) & 0xFFFF0000L
))))
4810 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4811 (f
->frametype
== AST_FRAME_VOICE
)
4812 /* is a voice frame */ &&
4813 (f
->subclass
== pvt
->svoiceformat
)
4814 /* is the same type */ ) {
4815 /* Force immediate rather than delayed transmission */
4817 /* Mark that mini-style frame is appropriate */
4820 if ( f
->frametype
== AST_FRAME_VIDEO
) {
4822 * If the lower 15 bits of the timestamp roll over, or if
4823 * the video format changed then send a full frame.
4824 * Otherwise send a mini video frame
4826 if (((fts
& 0xFFFF8000L
) == (pvt
->lastvsent
& 0xFFFF8000L
)) &&
4827 ((f
->subclass
& ~0x1) == pvt
->svideoformat
)
4835 pvt
->lastvsent
= fts
;
4837 /* Allocate an iax_frame */
4841 fr
= iax_frame_new(DIRECTION_OUTGRESS
, ast_test_flag(pvt
, IAX_ENCRYPTED
) ? f
->datalen
+ 32 : f
->datalen
, (f
->frametype
== AST_FRAME_VOICE
) || (f
->frametype
== AST_FRAME_VIDEO
));
4843 ast_log(LOG_WARNING
, "Out of memory\n");
4846 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4847 iax_frame_wrap(fr
, f
);
4850 fr
->callno
= pvt
->callno
;
4851 fr
->transfer
= transfer
;
4855 /* We need a full frame */
4859 fr
->oseqno
= pvt
->oseqno
++;
4860 fr
->iseqno
= pvt
->iseqno
;
4861 fh
= (struct ast_iax2_full_hdr
*)(fr
->af
.data
.ptr
- sizeof(struct ast_iax2_full_hdr
));
4862 fh
->scallno
= htons(fr
->callno
| IAX_FLAG_FULL
);
4863 fh
->ts
= htonl(fr
->ts
);
4864 fh
->oseqno
= fr
->oseqno
;
4865 if (transfer
|| media
) {
4868 fh
->iseqno
= fr
->iseqno
;
4869 /* Keep track of the last thing we've acknowledged */
4870 if (!transfer
|| media
)
4871 pvt
->aseqno
= fr
->iseqno
;
4872 fh
->type
= fr
->af
.frametype
& 0xFF;
4873 if (fr
->af
.frametype
== AST_FRAME_VIDEO
)
4874 fh
->csub
= compress_subclass(fr
->af
.subclass
& ~0x1) | ((fr
->af
.subclass
& 0x1) << 6);
4876 fh
->csub
= compress_subclass(fr
->af
.subclass
);
4878 fr
->dcallno
= pvt
->transfercallno
;
4880 fr
->dcallno
= pvt
->peercallno
;
4881 fh
->dcallno
= htons(fr
->dcallno
);
4882 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_full_hdr
);
4885 /* Retry after 2x the ping time has passed */
4886 fr
->retrytime
= pvt
->pingtime
* 2;
4887 if (fr
->retrytime
< MIN_RETRY_TIME
)
4888 fr
->retrytime
= MIN_RETRY_TIME
;
4889 if (fr
->retrytime
> MAX_RETRY_TIME
)
4890 fr
->retrytime
= MAX_RETRY_TIME
;
4891 /* Acks' don't get retried */
4892 if ((f
->frametype
== AST_FRAME_IAX
) && (f
->subclass
== IAX_COMMAND_ACK
))
4894 else if (f
->frametype
== AST_FRAME_VOICE
)
4895 pvt
->svoiceformat
= f
->subclass
;
4896 else if (f
->frametype
== AST_FRAME_VIDEO
)
4897 pvt
->svideoformat
= f
->subclass
& ~0x1;
4898 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4899 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4901 iax_outputframe(fr
, NULL
, 2, &pvt
->transfer
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4903 iax_outputframe(fr
, NULL
, 2, &pvt
->media
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4905 iax_outputframe(fr
, NULL
, 2, &pvt
->addr
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4906 encrypt_frame(&pvt
->ecx
, fh
, pvt
->semirand
, &fr
->datalen
);
4908 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4912 res
= send_packet(fr
);
4914 res
= iax2_transmit(fr
);
4916 if (ast_test_flag(pvt
, IAX_TRUNK
)) {
4917 iax2_trunk_queue(pvt
, fr
);
4919 } else if (fr
->af
.frametype
== AST_FRAME_VIDEO
) {
4920 /* Video frame have no sequence number */
4923 vh
= (struct ast_iax2_video_hdr
*)(fr
->af
.data
.ptr
- sizeof(struct ast_iax2_video_hdr
));
4925 vh
->callno
= htons(0x8000 | fr
->callno
);
4926 vh
->ts
= htons((fr
->ts
& 0x7FFF) | (fr
->af
.subclass
& 0x1 ? 0x8000 : 0));
4927 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_video_hdr
);
4930 if (pvt
->mediareleased
) {
4933 res
= send_packet(fr
);
4935 /* Mini-frames have no sequence number */
4938 /* Mini frame will do */
4939 mh
= (struct ast_iax2_mini_hdr
*)(fr
->af
.data
.ptr
- sizeof(struct ast_iax2_mini_hdr
));
4940 mh
->callno
= htons(fr
->callno
);
4941 mh
->ts
= htons(fr
->ts
& 0xFFFF);
4942 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_mini_hdr
);
4945 if (pvt
->mediareleased
) {
4948 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4949 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4950 encrypt_frame(&pvt
->ecx
, (struct ast_iax2_full_hdr
*)mh
, pvt
->semirand
, &fr
->datalen
);
4952 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4954 res
= send_packet(fr
);
4960 static char *handle_cli_iax2_show_users(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4963 int havepattern
= 0;
4965 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4966 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4968 struct iax2_user
*user
= NULL
;
4971 struct ao2_iterator i
;
4975 e
->command
= "iax2 show users [like]";
4977 "Usage: iax2 show users [like <pattern>]\n"
4978 " Lists all known IAX2 users.\n"
4979 " Optional regular expression pattern is used to filter the user list.\n";
4987 if (!strcasecmp(a
->argv
[3], "like")) {
4988 if (regcomp(®exbuf
, a
->argv
[4], REG_EXTENDED
| REG_NOSUB
))
4989 return CLI_SHOWUSAGE
;
4992 return CLI_SHOWUSAGE
;
4996 return CLI_SHOWUSAGE
;
4999 ast_cli(a
->fd
, FORMAT
, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
5000 i
= ao2_iterator_init(users
, 0);
5001 for (user
= ao2_iterator_next(&i
); user
;
5002 user_unref(user
), user
= ao2_iterator_next(&i
)) {
5003 if (havepattern
&& regexec(®exbuf
, user
->name
, 0, NULL
, 0))
5006 if (!ast_strlen_zero(user
->secret
)) {
5007 ast_copy_string(auth
,user
->secret
, sizeof(auth
));
5008 } else if (!ast_strlen_zero(user
->inkeys
)) {
5009 snprintf(auth
, sizeof(auth
), "Key: %-15.15s ", user
->inkeys
);
5011 ast_copy_string(auth
, "-no secret-", sizeof(auth
));
5013 if(ast_test_flag(user
,IAX_CODEC_NOCAP
))
5015 else if(ast_test_flag(user
,IAX_CODEC_NOPREFS
))
5018 pstr
= ast_test_flag(user
,IAX_CODEC_USER_FIRST
) ? "Caller" : "Host";
5020 ast_cli(a
->fd
, FORMAT2
, user
->name
, auth
, user
->authmethods
,
5021 user
->contexts
? user
->contexts
->context
: DEFAULT_CONTEXT
,
5022 user
->ha
? "Yes" : "No", pstr
);
5033 static int __iax2_show_peers(int manager
, int fd
, struct mansession
*s
, int argc
, char *argv
[])
5036 int havepattern
= 0;
5037 int total_peers
= 0;
5038 int online_peers
= 0;
5039 int offline_peers
= 0;
5040 int unmonitored_peers
= 0;
5041 struct ao2_iterator i
;
5043 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
5044 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
5046 struct iax2_peer
*peer
= NULL
;
5048 int registeredonly
=0;
5049 char *term
= manager
? "\r\n" : "\n";
5050 char idtext
[256] = "";
5053 if (!strcasecmp(argv
[3], "registered"))
5056 return RESULT_SHOWUSAGE
;
5057 if (!strcasecmp(argv
[4], "like")) {
5058 if (regcomp(®exbuf
, argv
[5], REG_EXTENDED
| REG_NOSUB
))
5059 return RESULT_SHOWUSAGE
;
5062 return RESULT_SHOWUSAGE
;
5065 if (!strcasecmp(argv
[3], "like")) {
5066 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
5067 return RESULT_SHOWUSAGE
;
5070 return RESULT_SHOWUSAGE
;
5073 if (!strcasecmp(argv
[3], "registered"))
5076 return RESULT_SHOWUSAGE
;
5081 return RESULT_SHOWUSAGE
;
5086 ast_cli(fd
, FORMAT2
, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term
);
5088 i
= ao2_iterator_init(peers
, 0);
5089 for (peer
= ao2_iterator_next(&i
); peer
;
5090 peer_unref(peer
), peer
= ao2_iterator_next(&i
)) {
5096 if (registeredonly
&& !peer
->addr
.sin_addr
.s_addr
)
5098 if (havepattern
&& regexec(®exbuf
, peer
->name
, 0, NULL
, 0))
5101 if (!ast_strlen_zero(peer
->username
))
5102 snprintf(name
, sizeof(name
), "%s/%s", peer
->name
, peer
->username
);
5104 ast_copy_string(name
, peer
->name
, sizeof(name
));
5106 retstatus
= peer_status(peer
, status
, sizeof(status
));
5109 else if (!retstatus
)
5112 unmonitored_peers
++;
5114 ast_copy_string(nm
, ast_inet_ntoa(peer
->mask
), sizeof(nm
));
5116 snprintf(srch
, sizeof(srch
), FORMAT
, name
,
5117 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
5118 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
5120 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
5121 peer
->encmethods
? "(E)" : " ", status
, term
);
5125 "Event: PeerEntry\r\n%s"
5126 "Channeltype: IAX2\r\n"
5127 "ChanObjectType: peer\r\n"
5128 "ObjectName: %s\r\n"
5132 "Status: %s\r\n\r\n",
5135 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "-none-",
5136 ntohs(peer
->addr
.sin_port
),
5137 ast_test_flag(peer
, IAX_DYNAMIC
) ? "yes" : "no",
5141 ast_cli(fd
, FORMAT
, name
,
5142 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
5143 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
5145 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
5146 peer
->encmethods
? "(E)" : " ", status
, term
);
5151 ast_cli(fd
,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers
, online_peers
, offline_peers
, unmonitored_peers
, term
);
5156 return RESULT_SUCCESS
;
5161 static char *handle_cli_iax2_show_threads(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5163 struct iax2_thread
*thread
= NULL
;
5165 int threadcount
= 0, dynamiccount
= 0;
5170 e
->command
= "iax2 show threads";
5172 "Usage: iax2 show threads\n"
5173 " Lists status of IAX helper threads\n";
5179 return CLI_SHOWUSAGE
;
5181 ast_cli(a
->fd
, "IAX2 Thread Information\n");
5183 ast_cli(a
->fd
, "Idle Threads:\n");
5184 AST_LIST_LOCK(&idle_list
);
5185 AST_LIST_TRAVERSE(&idle_list
, thread
, list
) {
5186 #ifdef DEBUG_SCHED_MULTITHREAD
5187 ast_cli(a
->fd
, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
5188 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
5190 ast_cli(a
->fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
5191 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
5195 AST_LIST_UNLOCK(&idle_list
);
5196 ast_cli(a
->fd
, "Active Threads:\n");
5197 AST_LIST_LOCK(&active_list
);
5198 AST_LIST_TRAVERSE(&active_list
, thread
, list
) {
5199 if (thread
->type
== IAX_THREAD_TYPE_DYNAMIC
)
5203 #ifdef DEBUG_SCHED_MULTITHREAD
5204 ast_cli(a
->fd
, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
5205 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
5207 ast_cli(a
->fd
, "Thread %c%d: state=%d, update=%d, actions=%d\n",
5208 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
5212 AST_LIST_UNLOCK(&active_list
);
5213 ast_cli(a
->fd
, "Dynamic Threads:\n");
5214 AST_LIST_LOCK(&dynamic_list
);
5215 AST_LIST_TRAVERSE(&dynamic_list
, thread
, list
) {
5216 #ifdef DEBUG_SCHED_MULTITHREAD
5217 ast_cli(a
->fd
, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
5218 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
5220 ast_cli(a
->fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
5221 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
5225 AST_LIST_UNLOCK(&dynamic_list
);
5226 ast_cli(a
->fd
, "%d of %d threads accounted for with %d dynamic threads\n", threadcount
, iaxthreadcount
, dynamiccount
);
5230 static char *handle_cli_iax2_unregister(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5232 struct iax2_peer
*p
;
5236 e
->command
= "iax2 unregister";
5238 "Usage: iax2 unregister <peername>\n"
5239 " Unregister (force expiration) an IAX2 peer from the registry.\n";
5242 return complete_iax2_unregister(a
->line
, a
->word
, a
->pos
, a
->n
);
5246 return CLI_SHOWUSAGE
;
5248 p
= find_peer(a
->argv
[2], 1);
5250 if (p
->expire
> 0) {
5251 struct iax2_peer tmp_peer
= {
5254 struct iax2_peer
*peer
;
5256 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
5258 expire_registry(peer_ref(peer
)); /* will release its own reference when done */
5259 peer_unref(peer
); /* ref from ao2_find() */
5260 ast_cli(a
->fd
, "Peer %s unregistered\n", a
->argv
[2]);
5262 ast_cli(a
->fd
, "Peer %s not found\n", a
->argv
[2]);
5265 ast_cli(a
->fd
, "Peer %s not registered\n", a
->argv
[2]);
5268 ast_cli(a
->fd
, "Peer unknown: %s. Not unregistered\n", a
->argv
[2]);
5273 static char *complete_iax2_unregister(const char *line
, const char *word
, int pos
, int state
)
5276 struct iax2_peer
*p
= NULL
;
5278 int wordlen
= strlen(word
);
5280 /* 0 - iax2; 1 - unregister; 2 - <peername> */
5282 struct ao2_iterator i
= ao2_iterator_init(peers
, 0);
5283 while ((p
= ao2_iterator_next(&i
))) {
5284 if (!strncasecmp(p
->name
, word
, wordlen
) &&
5285 ++which
> state
&& p
->expire
> 0) {
5286 res
= ast_strdup(p
->name
);
5297 static char *handle_cli_iax2_show_peers(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5301 e
->command
= "iax2 show peers";
5303 "Usage: iax2 show peers [registered] [like <pattern>]\n"
5304 " Lists all known IAX2 peers.\n"
5305 " Optional 'registered' argument lists only peers with known addresses.\n"
5306 " Optional regular expression pattern is used to filter the peer list.\n";
5312 switch (__iax2_show_peers(0, a
->fd
, NULL
, a
->argc
, a
->argv
)) {
5313 case RESULT_SHOWUSAGE
:
5314 return CLI_SHOWUSAGE
;
5315 case RESULT_FAILURE
:
5322 static int manager_iax2_show_netstats(struct mansession
*s
, const struct message
*m
)
5324 ast_cli_netstats(s
, -1, 0);
5325 astman_append(s
, "\r\n");
5326 return RESULT_SUCCESS
;
5329 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5331 struct iax_firmware
*cur
= NULL
;
5335 e
->command
= "iax2 show firmware";
5337 "Usage: iax2 show firmware\n"
5338 " Lists all known IAX firmware images.\n";
5344 if (a
->argc
!= 3 && a
->argc
!= 4)
5345 return CLI_SHOWUSAGE
;
5347 ast_cli(a
->fd
, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
5348 AST_LIST_LOCK(&firmwares
);
5349 AST_LIST_TRAVERSE(&firmwares
, cur
, list
) {
5350 if ((a
->argc
== 3) || (!strcasecmp(a
->argv
[3], (char *) cur
->fwh
->devname
))) {
5351 ast_cli(a
->fd
, "%-15.15s %-15d %-15d\n", cur
->fwh
->devname
,
5352 ntohs(cur
->fwh
->version
), (int)ntohl(cur
->fwh
->datalen
));
5355 AST_LIST_UNLOCK(&firmwares
);
5360 /*! \brief callback to display iax peers in manager */
5361 static int manager_iax2_show_peers(struct mansession
*s
, const struct message
*m
)
5363 char *a
[] = { "iax2", "show", "users" };
5364 const char *id
= astman_get_header(m
,"ActionID");
5365 char idtext
[256] = "";
5367 if (!ast_strlen_zero(id
))
5368 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
5369 astman_send_ack(s
, m
, "Peer status list will follow");
5370 return __iax2_show_peers(1, -1, s
, 3, a
);
5373 /*! \brief callback to display iax peers in manager format */
5374 static int manager_iax2_show_peer_list(struct mansession
*s
, const struct message
*m
)
5376 struct iax2_peer
*peer
= NULL
;
5380 const char *id
= astman_get_header(m
,"ActionID");
5381 char idtext
[256] = "";
5382 struct ao2_iterator i
;
5384 if (!ast_strlen_zero(id
))
5385 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
5387 astman_append(s
, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext
);
5390 i
= ao2_iterator_init(peers
, 0);
5391 for (peer
= ao2_iterator_next(&i
); peer
; peer_unref(peer
), peer
= ao2_iterator_next(&i
)) {
5393 astman_append(s
, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext
);
5394 if (!ast_strlen_zero(peer
->username
)) {
5395 astman_append(s
, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer
->name
, peer
->username
);
5397 astman_append(s
, "ObjectName: %s\r\n", peer
->name
);
5399 astman_append(s
, "ChanObjectType: peer\r\n");
5400 astman_append(s
, "IPaddress: %s\r\n", peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "-none-");
5401 ast_copy_string(nm
, ast_inet_ntoa(peer
->mask
), sizeof(nm
));
5402 astman_append(s
, "Mask: %s\r\n", nm
);
5403 astman_append(s
, "Port: %d\r\n", ntohs(peer
->addr
.sin_port
));
5404 astman_append(s
, "Dynamic: %s\r\n", ast_test_flag(peer
, IAX_DYNAMIC
) ? "Yes" : "No");
5405 peer_status(peer
, status
, sizeof(status
));
5406 astman_append(s
, "Status: %s\r\n\r\n", status
);
5410 astman_append(s
, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext
, peer_count
);
5411 return RESULT_SUCCESS
;
5415 static char *regstate2str(int regstate
)
5418 case REG_STATE_UNREGISTERED
:
5419 return "Unregistered";
5420 case REG_STATE_REGSENT
:
5421 return "Request Sent";
5422 case REG_STATE_AUTHSENT
:
5423 return "Auth. Sent";
5424 case REG_STATE_REGISTERED
:
5425 return "Registered";
5426 case REG_STATE_REJECTED
:
5428 case REG_STATE_TIMEOUT
:
5430 case REG_STATE_NOAUTH
:
5431 return "No Authentication";
5437 static char *handle_cli_iax2_show_registry(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5439 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
5440 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
5441 struct iax2_registry
*reg
= NULL
;
5448 e
->command
= "iax2 show registry";
5450 "Usage: iax2 show registry\n"
5451 " Lists all registration requests and status.\n";
5457 return CLI_SHOWUSAGE
;
5458 ast_cli(a
->fd
, FORMAT2
, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
5459 AST_LIST_LOCK(®istrations
);
5460 AST_LIST_TRAVERSE(®istrations
, reg
, entry
) {
5461 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(reg
->addr
.sin_addr
), ntohs(reg
->addr
.sin_port
));
5462 if (reg
->us
.sin_addr
.s_addr
)
5463 snprintf(perceived
, sizeof(perceived
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
5465 ast_copy_string(perceived
, "<Unregistered>", sizeof(perceived
));
5466 ast_cli(a
->fd
, FORMAT
, host
,
5467 (reg
->dnsmgr
) ? "Y" : "N",
5468 reg
->username
, perceived
, reg
->refresh
, regstate2str(reg
->regstate
));
5471 AST_LIST_UNLOCK(®istrations
);
5472 ast_cli(a
->fd
, "%d IAX2 registrations.\n", counter
);
5478 static char *handle_cli_iax2_show_channels(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5480 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
5481 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
5482 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
5488 e
->command
= "iax2 show channels";
5490 "Usage: iax2 show channels\n"
5491 " Lists all currently active IAX channels.\n";
5498 return CLI_SHOWUSAGE
;
5499 ast_cli(a
->fd
, FORMAT2
, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
5500 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
5501 ast_mutex_lock(&iaxsl
[x
]);
5503 int lag
, jitter
, localdelay
;
5506 if (ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
5507 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
5508 jitter
= jbinfo
.jitter
;
5509 localdelay
= jbinfo
.current
- jbinfo
.min
;
5514 lag
= iaxs
[x
]->remote_rr
.delay
;
5515 ast_cli(a
->fd
, FORMAT
,
5516 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
5517 ast_inet_ntoa(iaxs
[x
]->addr
.sin_addr
),
5518 S_OR(iaxs
[x
]->username
, "(None)"),
5519 iaxs
[x
]->callno
, iaxs
[x
]->peercallno
,
5520 iaxs
[x
]->oseqno
, iaxs
[x
]->iseqno
,
5524 ast_getformatname(iaxs
[x
]->voiceformat
) );
5527 ast_mutex_unlock(&iaxsl
[x
]);
5529 ast_cli(a
->fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
5536 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
)
5540 #define ACN_FORMAT1 "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n"
5541 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n"
5542 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
5543 ast_mutex_lock(&iaxsl
[x
]);
5545 int localjitter
, localdelay
, locallost
, locallosspct
, localdropped
, localooo
;
5548 if(ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
5549 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
5550 localjitter
= jbinfo
.jitter
;
5551 localdelay
= jbinfo
.current
- jbinfo
.min
;
5552 locallost
= jbinfo
.frames_lost
;
5553 locallosspct
= jbinfo
.losspct
/1000;
5554 localdropped
= jbinfo
.frames_dropped
;
5555 localooo
= jbinfo
.frames_ooo
;
5566 astman_append(s
, limit_fmt
? ACN_FORMAT1
: ACN_FORMAT2
,
5567 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
5575 iaxs
[x
]->frames_received
/1000,
5576 iaxs
[x
]->remote_rr
.jitter
,
5577 iaxs
[x
]->remote_rr
.delay
,
5578 iaxs
[x
]->remote_rr
.losscnt
,
5579 iaxs
[x
]->remote_rr
.losspct
,
5580 iaxs
[x
]->remote_rr
.dropped
,
5581 iaxs
[x
]->remote_rr
.ooo
,
5582 iaxs
[x
]->remote_rr
.packets
/1000);
5584 ast_cli(fd
, limit_fmt
? ACN_FORMAT1
: ACN_FORMAT2
,
5585 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
5593 iaxs
[x
]->frames_received
/1000,
5594 iaxs
[x
]->remote_rr
.jitter
,
5595 iaxs
[x
]->remote_rr
.delay
,
5596 iaxs
[x
]->remote_rr
.losscnt
,
5597 iaxs
[x
]->remote_rr
.losspct
,
5598 iaxs
[x
]->remote_rr
.dropped
,
5599 iaxs
[x
]->remote_rr
.ooo
,
5600 iaxs
[x
]->remote_rr
.packets
/1000
5604 ast_mutex_unlock(&iaxsl
[x
]);
5610 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5616 e
->command
= "iax2 show netstats";
5618 "Usage: iax2 show netstats\n"
5619 " Lists network status for all currently active IAX channels.\n";
5625 return CLI_SHOWUSAGE
;
5626 ast_cli(a
->fd
, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
5627 ast_cli(a
->fd
, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
5628 numchans
= ast_cli_netstats(NULL
, a
->fd
, 1);
5629 ast_cli(a
->fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
5635 static char *handle_cli_iax2_set_debug(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5639 e
->command
= "iax2 set debug {on|off|peer}";
5641 "Usage: iax2 set debug {on|off|peer peername}\n"
5642 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
5646 return complete_iax2_peers(a
->line
, a
->word
, a
->pos
, a
->n
);
5650 if (a
->argc
< e
->args
|| a
->argc
> e
->args
+ 1)
5651 return CLI_SHOWUSAGE
;
5653 if (!strcasecmp(a
->argv
[3], "peer")) {
5654 struct iax2_peer
*peer
;
5656 if (a
->argc
!= e
->args
+ 1)
5657 return CLI_SHOWUSAGE
;
5659 peer
= find_peer(a
->argv
[4], 1);
5662 ast_cli(a
->fd
, "IAX2 peer '%s' does not exist\n", a
->argv
[e
->args
-1]);
5666 debugaddr
.sin_addr
= peer
->addr
.sin_addr
;
5667 debugaddr
.sin_port
= peer
->addr
.sin_port
;
5669 ast_cli(a
->fd
, "IAX2 Debugging Enabled for IP: %s:%d\n",
5670 ast_inet_ntoa(debugaddr
.sin_addr
), ntohs(debugaddr
.sin_port
));
5673 } else if (!strncasecmp(a
->argv
[3], "on", 2)) {
5675 ast_cli(a
->fd
, "IAX2 Debugging Enabled\n");
5678 memset(&debugaddr
, 0, sizeof(debugaddr
));
5679 ast_cli(a
->fd
, "IAX2 Debugging Disabled\n");
5684 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5688 e
->command
= "iax2 set debug trunk {on|off}";
5690 "Usage: iax2 set debug trunk {on|off}\n"
5691 " Enables/Disables debugging of IAX trunking\n";
5697 if (a
->argc
!= e
->args
)
5698 return CLI_SHOWUSAGE
;
5700 if (!strncasecmp(a
->argv
[e
->args
- 1], "on", 2)) {
5702 ast_cli(a
->fd
, "IAX2 Trunk Debugging Enabled\n");
5705 ast_cli(a
->fd
, "IAX2 Trunk Debugging Disabled\n");
5710 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5714 e
->command
= "iax2 set debug jb {on|off}";
5716 "Usage: iax2 set debug jb {on|off}\n"
5717 " Enables/Disables jitterbuffer debugging information\n";
5723 if (a
->argc
!= e
->args
)
5724 return CLI_SHOWUSAGE
;
5726 if (!strncasecmp(a
->argv
[e
->args
-1], "on", 2)) {
5727 jb_setoutput(jb_error_output
, jb_warning_output
, jb_debug_output
);
5728 ast_cli(a
->fd
, "IAX2 Jitterbuffer Debugging Enabled\n");
5730 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
5731 ast_cli(a
->fd
, "IAX2 Jitterbuffer Debugging Disabled\n");
5736 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
)
5738 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
5740 ast_mutex_lock(&iaxsl
[callno
]);
5742 /* If there's an outstanding error, return failure now */
5743 if (!iaxs
[callno
]->error
) {
5744 if (ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
))
5746 /* Don't waste bandwidth sending null frames */
5747 else if (f
->frametype
== AST_FRAME_NULL
)
5749 else if ((f
->frametype
== AST_FRAME_VOICE
) && ast_test_flag(iaxs
[callno
], IAX_QUELCH
))
5751 else if (!ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
5754 /* Simple, just queue for transmission */
5755 res
= iax2_send(iaxs
[callno
], f
, 0, -1, 0, 0, 0, 0);
5757 ast_debug(1, "Write error: %s\n", strerror(errno
));
5760 /* If it's already gone, just return */
5761 ast_mutex_unlock(&iaxsl
[callno
]);
5765 static int __send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
,
5766 int now
, int transfer
, int final
, int media
)
5768 struct ast_frame f
= { 0, };
5771 f
.subclass
= command
;
5772 f
.datalen
= datalen
;
5773 f
.src
= __FUNCTION__
;
5774 f
.data
.ptr
= (void *) data
;
5776 return iax2_send(i
, &f
, ts
, seqno
, now
, transfer
, final
, media
);
5779 static int send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5781 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 0, 0);
5784 static int send_command_locked(unsigned short callno
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5787 ast_mutex_lock(&iaxsl
[callno
]);
5788 res
= send_command(iaxs
[callno
], type
, command
, ts
, data
, datalen
, seqno
);
5789 ast_mutex_unlock(&iaxsl
[callno
]);
5794 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5795 * the pvt struct for the given call number may disappear during its
5798 static int send_command_final(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5800 int call_num
= i
->callno
;
5801 /* It is assumed that the callno has already been locked */
5802 iax2_predestroy(i
->callno
);
5803 if (!iaxs
[call_num
])
5805 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 1, 0);
5808 static int send_command_immediate(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5810 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 1, 0, 0, 0);
5813 static int send_command_transfer(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
)
5815 return __send_command(i
, type
, command
, ts
, data
, datalen
, 0, 0, 1, 0, 0);
5818 static int send_command_media(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
)
5820 return __send_command(i
, type
, command
, ts
, data
, datalen
, 0, 0, 0, 0, 1);
5823 static int apply_context(struct iax2_context
*con
, const char *context
)
5826 if (!strcmp(con
->context
, context
) || !strcmp(con
->context
, "*"))
5834 static int check_access(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
5836 /* Start pessimistic */
5839 struct iax2_user
*user
= NULL
, *best
= NULL
;
5841 int gotcapability
= 0;
5842 struct ast_variable
*v
= NULL
, *tmpvar
= NULL
;
5843 struct ao2_iterator i
;
5847 if (ies
->called_number
)
5848 ast_string_field_set(iaxs
[callno
], exten
, ies
->called_number
);
5849 if (ies
->calling_number
) {
5850 ast_shrink_phone_number(ies
->calling_number
);
5851 ast_string_field_set(iaxs
[callno
], cid_num
, ies
->calling_number
);
5853 if (ies
->calling_name
)
5854 ast_string_field_set(iaxs
[callno
], cid_name
, ies
->calling_name
);
5855 if (ies
->calling_ani
)
5856 ast_string_field_set(iaxs
[callno
], ani
, ies
->calling_ani
);
5858 ast_string_field_set(iaxs
[callno
], dnid
, ies
->dnid
);
5860 ast_string_field_set(iaxs
[callno
], rdnis
, ies
->rdnis
);
5861 if (ies
->called_context
)
5862 ast_string_field_set(iaxs
[callno
], context
, ies
->called_context
);
5864 ast_string_field_set(iaxs
[callno
], language
, ies
->language
);
5866 ast_string_field_set(iaxs
[callno
], username
, ies
->username
);
5867 if (ies
->calling_ton
> -1)
5868 iaxs
[callno
]->calling_ton
= ies
->calling_ton
;
5869 if (ies
->calling_tns
> -1)
5870 iaxs
[callno
]->calling_tns
= ies
->calling_tns
;
5871 if (ies
->calling_pres
> -1)
5872 iaxs
[callno
]->calling_pres
= ies
->calling_pres
;
5874 iaxs
[callno
]->peerformat
= ies
->format
;
5876 iaxs
[callno
]->peeradsicpe
= ies
->adsicpe
;
5877 if (ies
->capability
) {
5879 iaxs
[callno
]->peercapability
= ies
->capability
;
5882 version
= ies
->version
;
5884 /* Use provided preferences until told otherwise for actual preferences */
5885 if(ies
->codec_prefs
) {
5886 ast_codec_pref_convert(&iaxs
[callno
]->rprefs
, ies
->codec_prefs
, 32, 0);
5887 ast_codec_pref_convert(&iaxs
[callno
]->prefs
, ies
->codec_prefs
, 32, 0);
5891 iaxs
[callno
]->peercapability
= iaxs
[callno
]->peerformat
;
5892 if (version
> IAX_PROTO_VERSION
) {
5893 ast_log(LOG_WARNING
, "Peer '%s' has too new a protocol version (%d) for me\n",
5894 ast_inet_ntoa(sin
->sin_addr
), version
);
5897 /* Search the userlist for a compatible entry, and fill in the rest */
5898 i
= ao2_iterator_init(users
, 0);
5899 while ((user
= ao2_iterator_next(&i
))) {
5900 if ((ast_strlen_zero(iaxs
[callno
]->username
) || /* No username specified */
5901 !strcmp(iaxs
[callno
]->username
, user
->name
)) /* Or this username specified */
5902 && ast_apply_ha(user
->ha
, sin
) /* Access is permitted from this IP */
5903 && (ast_strlen_zero(iaxs
[callno
]->context
) || /* No context specified */
5904 apply_context(user
->contexts
, iaxs
[callno
]->context
))) { /* Context is permitted */
5905 if (!ast_strlen_zero(iaxs
[callno
]->username
)) {
5906 /* Exact match, stop right now. */
5911 } else if (ast_strlen_zero(user
->secret
) && ast_strlen_zero(user
->dbsecret
) && ast_strlen_zero(user
->inkeys
)) {
5912 /* No required authentication */
5914 /* There was host authentication and we passed, bonus! */
5915 if (bestscore
< 4) {
5923 /* No host access, but no secret, either, not bad */
5924 if (bestscore
< 3) {
5934 /* Authentication, but host access too, eh, it's something.. */
5935 if (bestscore
< 2) {
5943 /* Authentication and no host access... This is our baseline */
5944 if (bestscore
< 1) {
5957 if (!user
&& !ast_strlen_zero(iaxs
[callno
]->username
)) {
5958 user
= realtime_user(iaxs
[callno
]->username
, sin
);
5959 if (user
&& !ast_strlen_zero(iaxs
[callno
]->context
) && /* No context specified */
5960 !apply_context(user
->contexts
, iaxs
[callno
]->context
)) { /* Context is permitted */
5961 user
= user_unref(user
);
5965 /* We found our match (use the first) */
5967 for (v
= user
->vars
; v
; v
= v
->next
) {
5968 if((tmpvar
= ast_variable_new(v
->name
, v
->value
, v
->file
))) {
5969 tmpvar
->next
= iaxs
[callno
]->vars
;
5970 iaxs
[callno
]->vars
= tmpvar
;
5973 /* If a max AUTHREQ restriction is in place, activate it */
5974 if (user
->maxauthreq
> 0)
5975 ast_set_flag(iaxs
[callno
], IAX_MAXAUTHREQ
);
5976 iaxs
[callno
]->prefs
= user
->prefs
;
5977 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_USER_FIRST
);
5978 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOPREFS
);
5979 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOCAP
);
5980 ast_copy_flags(iaxs
[callno
], user
, IAX_NOKEYROTATE
);
5981 iaxs
[callno
]->encmethods
= user
->encmethods
;
5982 /* Store the requested username if not specified */
5983 if (ast_strlen_zero(iaxs
[callno
]->username
))
5984 ast_string_field_set(iaxs
[callno
], username
, user
->name
);
5985 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5986 ast_copy_flags(iaxs
[callno
], user
, IAX_TRUNK
);
5987 iaxs
[callno
]->capability
= user
->capability
;
5988 /* And use the default context */
5989 if (ast_strlen_zero(iaxs
[callno
]->context
)) {
5991 ast_string_field_set(iaxs
[callno
], context
, user
->contexts
->context
);
5993 ast_string_field_set(iaxs
[callno
], context
, DEFAULT_CONTEXT
);
5995 /* And any input keys */
5996 ast_string_field_set(iaxs
[callno
], inkeys
, user
->inkeys
);
5997 /* And the permitted authentication methods */
5998 iaxs
[callno
]->authmethods
= user
->authmethods
;
5999 iaxs
[callno
]->adsi
= user
->adsi
;
6000 /* If the user has callerid, override the remote caller id. */
6001 if (ast_test_flag(user
, IAX_HASCALLERID
)) {
6002 iaxs
[callno
]->calling_tns
= 0;
6003 iaxs
[callno
]->calling_ton
= 0;
6004 ast_string_field_set(iaxs
[callno
], cid_num
, user
->cid_num
);
6005 ast_string_field_set(iaxs
[callno
], cid_name
, user
->cid_name
);
6006 ast_string_field_set(iaxs
[callno
], ani
, user
->cid_num
);
6007 iaxs
[callno
]->calling_pres
= AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
;
6008 } else if (ast_strlen_zero(iaxs
[callno
]->cid_num
) && ast_strlen_zero(iaxs
[callno
]->cid_name
)) {
6009 iaxs
[callno
]->calling_pres
= AST_PRES_NUMBER_NOT_AVAILABLE
;
6010 } /* else user is allowed to set their own CID settings */
6011 if (!ast_strlen_zero(user
->accountcode
))
6012 ast_string_field_set(iaxs
[callno
], accountcode
, user
->accountcode
);
6013 if (!ast_strlen_zero(user
->mohinterpret
))
6014 ast_string_field_set(iaxs
[callno
], mohinterpret
, user
->mohinterpret
);
6015 if (!ast_strlen_zero(user
->mohsuggest
))
6016 ast_string_field_set(iaxs
[callno
], mohsuggest
, user
->mohsuggest
);
6017 if (!ast_strlen_zero(user
->parkinglot
))
6018 ast_string_field_set(iaxs
[callno
], parkinglot
, user
->parkinglot
);
6020 iaxs
[callno
]->amaflags
= user
->amaflags
;
6021 if (!ast_strlen_zero(user
->language
))
6022 ast_string_field_set(iaxs
[callno
], language
, user
->language
);
6023 ast_copy_flags(iaxs
[callno
], user
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
6024 /* Keep this check last */
6025 if (!ast_strlen_zero(user
->dbsecret
)) {
6026 char *family
, *key
=NULL
;
6028 family
= ast_strdupa(user
->dbsecret
);
6029 key
= strchr(family
, '/');
6034 if (!key
|| ast_db_get(family
, key
, buf
, sizeof(buf
)))
6035 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", user
->dbsecret
);
6037 ast_string_field_set(iaxs
[callno
], secret
, buf
);
6039 ast_string_field_set(iaxs
[callno
], secret
, user
->secret
);
6041 user
= user_unref(user
);
6043 ast_set2_flag(iaxs
[callno
], iax2_getpeertrunk(*sin
), IAX_TRUNK
);
6047 static int raw_hangup(struct sockaddr_in
*sin
, unsigned short src
, unsigned short dst
, int sockfd
)
6049 struct ast_iax2_full_hdr fh
;
6050 fh
.scallno
= htons(src
| IAX_FLAG_FULL
);
6051 fh
.dcallno
= htons(dst
);
6055 fh
.type
= AST_FRAME_IAX
;
6056 fh
.csub
= compress_subclass(IAX_COMMAND_INVAL
);
6057 iax_outputframe(NULL
, &fh
, 0, sin
, 0);
6061 ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
6062 ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), src
, dst
);
6063 return sendto(sockfd
, &fh
, sizeof(fh
), 0, (struct sockaddr
*)sin
, sizeof(*sin
));
6066 static void merge_encryption(struct chan_iax2_pvt
*p
, unsigned int enc
)
6068 /* Select exactly one common encryption if there are any */
6069 p
->encmethods
&= enc
;
6070 if (p
->encmethods
) {
6071 if (p
->encmethods
& IAX_ENCRYPT_AES128
)
6072 p
->encmethods
= IAX_ENCRYPT_AES128
;
6079 * \pre iaxsl[call_num] is locked
6081 * \note Since this function calls send_command_final(), the pvt struct for the given
6082 * call number may disappear while executing this function.
6084 static int authenticate_request(int call_num
)
6086 struct iax_ie_data ied
;
6087 int res
= -1, authreq_restrict
= 0;
6089 struct chan_iax2_pvt
*p
= iaxs
[call_num
];
6091 memset(&ied
, 0, sizeof(ied
));
6093 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
6094 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
6095 struct iax2_user
*user
, tmp_user
= {
6096 .name
= p
->username
,
6099 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
6101 if (user
->curauthreq
== user
->maxauthreq
)
6102 authreq_restrict
= 1;
6105 user
= user_unref(user
);
6109 /* If the AUTHREQ limit test failed, send back an error */
6110 if (authreq_restrict
) {
6111 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Unauthenticated call limit reached");
6112 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_CALL_REJECTED
);
6113 send_command_final(p
, AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied
.buf
, ied
.pos
, -1);
6117 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
6118 if (p
->authmethods
& (IAX_AUTH_MD5
| IAX_AUTH_RSA
)) {
6119 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
6120 ast_string_field_set(p
, challenge
, challenge
);
6121 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
6122 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, p
->challenge
);
6125 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, p
->encmethods
);
6127 iax_ie_append_str(&ied
,IAX_IE_USERNAME
, p
->username
);
6129 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREQ
, 0, ied
.buf
, ied
.pos
, -1);
6132 ast_set_flag(p
, IAX_ENCRYPTED
);
6137 static int authenticate_verify(struct chan_iax2_pvt
*p
, struct iax_ies
*ies
)
6139 char requeststr
[256];
6140 char md5secret
[256] = "";
6141 char secret
[256] = "";
6142 char rsasecret
[256] = "";
6145 struct iax2_user
*user
, tmp_user
= {
6146 .name
= p
->username
,
6149 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
6151 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
6152 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
6153 ast_clear_flag(p
, IAX_MAXAUTHREQ
);
6155 ast_string_field_set(p
, host
, user
->name
);
6156 user
= user_unref(user
);
6159 if (!ast_test_flag(&p
->state
, IAX_STATE_AUTHENTICATED
))
6162 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
6163 if (ies
->md5_result
)
6164 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
6165 if (ies
->rsa_result
)
6166 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
6167 if ((p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(rsasecret
) && !ast_strlen_zero(p
->inkeys
)) {
6168 struct ast_key
*key
;
6172 ast_copy_string(tmpkey
, p
->inkeys
, sizeof(tmpkey
));
6174 keyn
= strsep(&stringp
, ":");
6176 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
6177 if (key
&& !ast_check_signature(key
, p
->challenge
, rsasecret
)) {
6181 ast_log(LOG_WARNING
, "requested inkey '%s' for RSA authentication does not exist\n", keyn
);
6182 keyn
= strsep(&stringp
, ":");
6184 } else if (p
->authmethods
& IAX_AUTH_MD5
) {
6185 struct MD5Context md5
;
6186 unsigned char digest
[16];
6187 char *tmppw
, *stringp
;
6189 tmppw
= ast_strdupa(p
->secret
);
6191 while((tmppw
= strsep(&stringp
, ";"))) {
6193 MD5Update(&md5
, (unsigned char *)p
->challenge
, strlen(p
->challenge
));
6194 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
6195 MD5Final(digest
, &md5
);
6196 /* If they support md5, authenticate with it. */
6198 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
6199 if (!strcasecmp(requeststr
, md5secret
)) {
6204 } else if (p
->authmethods
& IAX_AUTH_PLAINTEXT
) {
6205 if (!strcmp(secret
, p
->secret
))
6211 /*! \brief Verify inbound registration */
6212 static int register_verify(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
6214 char requeststr
[256] = "";
6215 char peer
[256] = "";
6216 char md5secret
[256] = "";
6217 char rsasecret
[256] = "";
6218 char secret
[256] = "";
6219 struct iax2_peer
*p
= NULL
;
6220 struct ast_key
*key
;
6226 ast_clear_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
);
6227 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
6229 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
6231 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
6232 if (ies
->md5_result
)
6233 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
6234 if (ies
->rsa_result
)
6235 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
6237 expire
= ies
->refresh
;
6239 if (ast_strlen_zero(peer
)) {
6240 ast_log(LOG_NOTICE
, "Empty registration from %s\n", ast_inet_ntoa(sin
->sin_addr
));
6244 /* SLD: first call to lookup peer during registration */
6245 ast_mutex_unlock(&iaxsl
[callno
]);
6246 p
= find_peer(peer
, 1);
6247 ast_mutex_lock(&iaxsl
[callno
]);
6248 if (!p
|| !iaxs
[callno
]) {
6249 if (authdebug
&& !p
)
6250 ast_log(LOG_NOTICE
, "No registration for peer '%s' (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
6254 if (!ast_test_flag(p
, IAX_DYNAMIC
)) {
6256 ast_log(LOG_NOTICE
, "Peer '%s' is not dynamic (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
6260 if (!ast_apply_ha(p
->ha
, sin
)) {
6262 ast_log(LOG_NOTICE
, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
6265 if (!inaddrcmp(&p
->addr
, sin
))
6266 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_UNCHANGED
);
6267 ast_string_field_set(iaxs
[callno
], secret
, p
->secret
);
6268 ast_string_field_set(iaxs
[callno
], inkeys
, p
->inkeys
);
6269 /* Check secret against what we have on file */
6270 if (!ast_strlen_zero(rsasecret
) && (p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
6271 if (!ast_strlen_zero(p
->inkeys
)) {
6274 ast_copy_string(tmpkeys
, p
->inkeys
, sizeof(tmpkeys
));
6276 keyn
= strsep(&stringp
, ":");
6278 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
6279 if (key
&& !ast_check_signature(key
, iaxs
[callno
]->challenge
, rsasecret
)) {
6280 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
6283 ast_log(LOG_WARNING
, "requested inkey '%s' does not exist\n", keyn
);
6284 keyn
= strsep(&stringp
, ":");
6288 ast_log(LOG_NOTICE
, "Host %s failed RSA authentication with inkeys '%s'\n", peer
, p
->inkeys
);
6293 ast_log(LOG_NOTICE
, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer
);
6296 } else if (!ast_strlen_zero(md5secret
) && (p
->authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
6297 struct MD5Context md5
;
6298 unsigned char digest
[16];
6299 char *tmppw
, *stringp
;
6301 tmppw
= ast_strdupa(p
->secret
);
6303 while((tmppw
= strsep(&stringp
, ";"))) {
6305 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
6306 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
6307 MD5Final(digest
, &md5
);
6309 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
6310 if (!strcasecmp(requeststr
, md5secret
))
6314 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
6317 ast_log(LOG_NOTICE
, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
, requeststr
, md5secret
);
6320 } else if (!ast_strlen_zero(secret
) && (p
->authmethods
& IAX_AUTH_PLAINTEXT
)) {
6321 /* They've provided a plain text password and we support that */
6322 if (strcmp(secret
, p
->secret
)) {
6324 ast_log(LOG_NOTICE
, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
6327 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
6328 } else if (!ast_strlen_zero(md5secret
) || !ast_strlen_zero(secret
)) {
6330 ast_log(LOG_NOTICE
, "Inappropriate authentication received\n");
6333 ast_string_field_set(iaxs
[callno
], peer
, peer
);
6334 /* Choose lowest expiry number */
6335 if (expire
&& (expire
< iaxs
[callno
]->expiry
))
6336 iaxs
[callno
]->expiry
= expire
;
6338 ast_devstate_changed(AST_DEVICE_UNKNOWN
, "IAX2/%s", p
->name
); /* Activate notification */
6349 static int authenticate(const char *challenge
, const char *secret
, const char *keyn
, int authmethods
, struct iax_ie_data
*ied
, struct sockaddr_in
*sin
, ast_aes_encrypt_key
*ecx
, ast_aes_decrypt_key
*dcx
)
6353 if (!ast_strlen_zero(keyn
)) {
6354 if (!(authmethods
& IAX_AUTH_RSA
)) {
6355 if (ast_strlen_zero(secret
))
6356 ast_log(LOG_NOTICE
, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin
->sin_addr
));
6357 } else if (ast_strlen_zero(challenge
)) {
6358 ast_log(LOG_NOTICE
, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin
->sin_addr
));
6361 struct ast_key
*key
;
6362 key
= ast_key_get(keyn
, AST_KEY_PRIVATE
);
6364 ast_log(LOG_NOTICE
, "Unable to find private key '%s'\n", keyn
);
6366 if (ast_sign(key
, (char*)challenge
, sig
)) {
6367 ast_log(LOG_NOTICE
, "Unable to sign challenge with key\n");
6370 iax_ie_append_str(ied
, IAX_IE_RSA_RESULT
, sig
);
6377 if (res
&& !ast_strlen_zero(secret
)) {
6378 if ((authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(challenge
)) {
6379 struct MD5Context md5
;
6380 unsigned char digest
[16];
6383 MD5Update(&md5
, (unsigned char *)challenge
, strlen(challenge
));
6384 MD5Update(&md5
, (unsigned char *)secret
, strlen(secret
));
6385 MD5Final(digest
, &md5
);
6386 /* If they support md5, authenticate with it. */
6388 sprintf(digres
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
6390 build_enc_keys(digest
, ecx
, dcx
);
6391 iax_ie_append_str(ied
, IAX_IE_MD5_RESULT
, digres
);
6393 } else if (authmethods
& IAX_AUTH_PLAINTEXT
) {
6394 iax_ie_append_str(ied
, IAX_IE_PASSWORD
, secret
);
6397 ast_log(LOG_NOTICE
, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin
->sin_addr
), authmethods
);
6403 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
6404 * so do not call this function with a pvt lock held.
6406 static int authenticate_reply(struct chan_iax2_pvt
*p
, struct sockaddr_in
*sin
, struct iax_ies
*ies
, const char *override
, const char *okey
)
6408 struct iax2_peer
*peer
= NULL
;
6409 /* Start pessimistic */
6411 int authmethods
= 0;
6412 struct iax_ie_data ied
;
6413 uint16_t callno
= p
->callno
;
6415 memset(&ied
, 0, sizeof(ied
));
6418 ast_string_field_set(p
, username
, ies
->username
);
6420 ast_string_field_set(p
, challenge
, ies
->challenge
);
6421 if (ies
->authmethods
)
6422 authmethods
= ies
->authmethods
;
6423 if (authmethods
& IAX_AUTH_MD5
)
6424 merge_encryption(p
, ies
->encmethods
);
6428 /* Check for override RSA authentication first */
6429 if (!ast_strlen_zero(override
) || !ast_strlen_zero(okey
)) {
6430 /* Normal password authentication */
6431 res
= authenticate(p
->challenge
, override
, okey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
6433 struct ao2_iterator i
= ao2_iterator_init(peers
, 0);
6434 while ((peer
= ao2_iterator_next(&i
))) {
6435 if ((ast_strlen_zero(p
->peer
) || !strcmp(p
->peer
, peer
->name
))
6436 /* No peer specified at our end, or this is the peer */
6437 && (ast_strlen_zero(peer
->username
) || (!strcmp(peer
->username
, p
->username
)))
6438 /* No username specified in peer rule, or this is the right username */
6439 && (!peer
->addr
.sin_addr
.s_addr
|| ((sin
->sin_addr
.s_addr
& peer
->mask
.s_addr
) == (peer
->addr
.sin_addr
.s_addr
& peer
->mask
.s_addr
)))
6440 /* No specified host, or this is our host */
6442 res
= authenticate(p
->challenge
, peer
->secret
, peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
6451 /* We checked our list and didn't find one. It's unlikely, but possible,
6452 that we're trying to authenticate *to* a realtime peer */
6453 const char *peer_name
= ast_strdupa(p
->peer
);
6454 ast_mutex_unlock(&iaxsl
[callno
]);
6455 if ((peer
= realtime_peer(peer_name
, NULL
))) {
6456 ast_mutex_lock(&iaxsl
[callno
]);
6457 if (!(p
= iaxs
[callno
])) {
6461 res
= authenticate(p
->challenge
, peer
->secret
,peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
6465 ast_mutex_lock(&iaxsl
[callno
]);
6466 if (!(p
= iaxs
[callno
]))
6471 if (ies
->encmethods
)
6472 ast_set_flag(p
, IAX_ENCRYPTED
| IAX_KEYPOPULATED
);
6474 struct ast_datastore
*variablestore
;
6475 struct ast_variable
*var
, *prev
= NULL
;
6476 AST_LIST_HEAD(, ast_var_t
) *varlist
;
6477 varlist
= ast_calloc(1, sizeof(*varlist
));
6478 variablestore
= ast_datastore_alloc(&iax2_variable_datastore_info
, NULL
);
6479 if (variablestore
&& varlist
&& p
->owner
) {
6480 variablestore
->data
= varlist
;
6481 variablestore
->inheritance
= DATASTORE_INHERIT_FOREVER
;
6482 AST_LIST_HEAD_INIT(varlist
);
6483 for (var
= ies
->vars
; var
; var
= var
->next
) {
6484 struct ast_var_t
*newvar
= ast_var_assign(var
->name
, var
->value
);
6489 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
6490 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
6492 AST_LIST_INSERT_TAIL(varlist
, newvar
, entries
);
6498 ast_channel_datastore_add(p
->owner
, variablestore
);
6501 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
6503 ast_datastore_free(variablestore
);
6510 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREP
, 0, ied
.buf
, ied
.pos
, -1);
6514 static int iax2_do_register(struct iax2_registry
*reg
);
6516 static void __iax2_do_register_s(const void *data
)
6518 struct iax2_registry
*reg
= (struct iax2_registry
*)data
;
6520 iax2_do_register(reg
);
6523 static int iax2_do_register_s(const void *data
)
6525 #ifdef SCHED_MULTITHREADED
6526 if (schedule_action(__iax2_do_register_s
, data
))
6528 __iax2_do_register_s(data
);
6532 static int try_transfer(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
6536 struct iax_ie_data ied
;
6537 struct sockaddr_in
new;
6540 memset(&ied
, 0, sizeof(ied
));
6541 if (ies
->apparent_addr
)
6542 bcopy(ies
->apparent_addr
, &new, sizeof(new));
6544 newcall
= ies
->callno
;
6545 if (!newcall
|| !new.sin_addr
.s_addr
|| !new.sin_port
) {
6546 ast_log(LOG_WARNING
, "Invalid transfer request\n");
6549 pvt
->transfercallno
= newcall
;
6550 memcpy(&pvt
->transfer
, &new, sizeof(pvt
->transfer
));
6551 inet_aton(newip
, &pvt
->transfer
.sin_addr
);
6552 pvt
->transfer
.sin_family
= AF_INET
;
6553 pvt
->transferring
= TRANSFER_BEGIN
;
6554 pvt
->transferid
= ies
->transferid
;
6555 if (ies
->transferid
)
6556 iax_ie_append_int(&ied
, IAX_IE_TRANSFERID
, ies
->transferid
);
6557 send_command_transfer(pvt
, AST_FRAME_IAX
, IAX_COMMAND_TXCNT
, 0, ied
.buf
, ied
.pos
);
6561 static int complete_dpreply(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
6563 char exten
[256] = "";
6564 int status
= CACHE_FLAG_UNKNOWN
, expiry
= iaxdefaultdpcache
, x
, matchmore
= 0;
6565 struct iax2_dpcache
*dp
= NULL
;
6567 if (ies
->called_number
)
6568 ast_copy_string(exten
, ies
->called_number
, sizeof(exten
));
6570 if (ies
->dpstatus
& IAX_DPSTATUS_EXISTS
)
6571 status
= CACHE_FLAG_EXISTS
;
6572 else if (ies
->dpstatus
& IAX_DPSTATUS_CANEXIST
)
6573 status
= CACHE_FLAG_CANEXIST
;
6574 else if (ies
->dpstatus
& IAX_DPSTATUS_NONEXISTENT
)
6575 status
= CACHE_FLAG_NONEXISTENT
;
6578 expiry
= ies
->refresh
;
6579 if (ies
->dpstatus
& IAX_DPSTATUS_MATCHMORE
)
6580 matchmore
= CACHE_FLAG_MATCHMORE
;
6582 AST_LIST_LOCK(&dpcache
);
6583 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache
, dp
, peer_list
) {
6584 if (strcmp(dp
->exten
, exten
))
6586 AST_LIST_REMOVE_CURRENT(peer_list
);
6588 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ expiry
;
6589 if (dp
->flags
& CACHE_FLAG_PENDING
) {
6590 dp
->flags
&= ~CACHE_FLAG_PENDING
;
6591 dp
->flags
|= status
;
6592 dp
->flags
|= matchmore
;
6594 /* Wake up waiters */
6595 for (x
= 0; x
< ARRAY_LEN(dp
->waiters
); x
++) {
6596 if (dp
->waiters
[x
] > -1)
6597 write(dp
->waiters
[x
], "asdf", 4);
6600 AST_LIST_TRAVERSE_SAFE_END
;
6601 AST_LIST_UNLOCK(&dpcache
);
6606 static int complete_transfer(int callno
, struct iax_ies
*ies
)
6609 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
6610 struct iax_frame
*cur
;
6614 peercallno
= ies
->callno
;
6616 if (peercallno
< 1) {
6617 ast_log(LOG_WARNING
, "Invalid transfer request\n");
6620 memcpy(&pvt
->addr
, &pvt
->transfer
, sizeof(pvt
->addr
));
6621 memset(&pvt
->transfer
, 0, sizeof(pvt
->transfer
));
6622 pvt
->mediareleased
= 0;
6623 memset(&pvt
->media
, 0, sizeof(pvt
->media
));
6624 /* Reset sequence numbers */
6630 if (pvt
->peercallno
) {
6631 remove_by_peercallno(pvt
);
6633 pvt
->peercallno
= peercallno
;
6634 store_by_peercallno(pvt
);
6636 pvt
->transferring
= TRANSFER_NONE
;
6637 pvt
->svoiceformat
= -1;
6638 pvt
->voiceformat
= 0;
6639 pvt
->svideoformat
= -1;
6640 pvt
->videoformat
= 0;
6641 pvt
->transfercallno
= -1;
6642 memset(&pvt
->rxcore
, 0, sizeof(pvt
->rxcore
));
6643 memset(&pvt
->offset
, 0, sizeof(pvt
->offset
));
6644 /* reset jitterbuffer */
6645 while(jb_getall(pvt
->jb
,&frame
) == JB_OK
)
6646 iax2_frame_free(frame
.data
);
6652 pvt
->pingtime
= DEFAULT_RETRY_TIME
;
6653 AST_LIST_LOCK(&frame_queue
);
6654 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
6655 /* We must cancel any packets that would have been transmitted
6656 because now we're talking to someone new. It's okay, they
6657 were transmitted to someone that didn't care anyway. */
6658 if (callno
== cur
->callno
)
6661 AST_LIST_UNLOCK(&frame_queue
);
6665 /*! \brief Acknowledgment received for OUR registration */
6666 static int iax2_ack_registry(struct iax_ies
*ies
, struct sockaddr_in
*sin
, int callno
)
6668 struct iax2_registry
*reg
;
6669 /* Start pessimistic */
6670 char peer
[256] = "";
6673 char ourip
[256] = "<Unspecified>";
6674 struct sockaddr_in oldus
;
6675 struct sockaddr_in us
;
6678 memset(&us
, 0, sizeof(us
));
6679 if (ies
->apparent_addr
)
6680 bcopy(ies
->apparent_addr
, &us
, sizeof(us
));
6682 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
6684 refresh
= ies
->refresh
;
6685 if (ies
->calling_number
) {
6686 /* We don't do anything with it really, but maybe we should */
6688 reg
= iaxs
[callno
]->reg
;
6690 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registry '%s'\n", peer
);
6693 memcpy(&oldus
, ®
->us
, sizeof(oldus
));
6694 oldmsgs
= reg
->messages
;
6695 if (inaddrcmp(®
->addr
, sin
)) {
6696 ast_log(LOG_WARNING
, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
6699 memcpy(®
->us
, &us
, sizeof(reg
->us
));
6700 if (ies
->msgcount
>= 0)
6701 reg
->messages
= ies
->msgcount
& 0xffff; /* only low 16 bits are used in the transmission of the IE */
6702 /* always refresh the registration at the interval requested by the server
6703 we are registering to
6705 reg
->refresh
= refresh
;
6706 reg
->expire
= iax2_sched_replace(reg
->expire
, sched
,
6707 (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
6708 if (inaddrcmp(&oldus
, ®
->us
) || (reg
->messages
!= oldmsgs
)) {
6709 if (reg
->messages
> 255)
6710 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new and %d old messages waiting", reg
->messages
& 0xff, reg
->messages
>> 8);
6711 else if (reg
->messages
> 1)
6712 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new messages waiting\n", reg
->messages
);
6713 else if (reg
->messages
> 0)
6714 ast_copy_string(msgstatus
, " with 1 new message waiting\n", sizeof(msgstatus
));
6716 ast_copy_string(msgstatus
, " with no messages waiting\n", sizeof(msgstatus
));
6717 snprintf(ourip
, sizeof(ourip
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
6718 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin
->sin_addr
), ourip
, msgstatus
);
6719 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin
->sin_addr
));
6721 reg
->regstate
= REG_STATE_REGISTERED
;
6725 static int iax2_append_register(const char *hostname
, const char *username
,
6726 const char *secret
, const char *porta
)
6728 struct iax2_registry
*reg
;
6730 if (!(reg
= ast_calloc(1, sizeof(*reg
))))
6733 if (ast_dnsmgr_lookup(hostname
, ®
->addr
, ®
->dnsmgr
, srvlookup
? "_iax._udp" : NULL
) < 0) {
6738 ast_copy_string(reg
->username
, username
, sizeof(reg
->username
));
6741 ast_copy_string(reg
->secret
, secret
, sizeof(reg
->secret
));
6744 reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
6745 reg
->addr
.sin_family
= AF_INET
;
6746 reg
->addr
.sin_port
= porta
? htons(atoi(porta
)) : htons(IAX_DEFAULT_PORTNO
);
6748 AST_LIST_LOCK(®istrations
);
6749 AST_LIST_INSERT_HEAD(®istrations
, reg
, entry
);
6750 AST_LIST_UNLOCK(®istrations
);
6755 static int iax2_register(const char *value
, int lineno
)
6758 char *username
, *hostname
, *secret
;
6765 ast_copy_string(copy
, value
, sizeof(copy
));
6767 username
= strsep(&stringp
, "@");
6768 hostname
= strsep(&stringp
, "@");
6771 ast_log(LOG_WARNING
, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno
);
6776 username
= strsep(&stringp
, ":");
6777 secret
= strsep(&stringp
, ":");
6779 hostname
= strsep(&stringp
, ":");
6780 porta
= strsep(&stringp
, ":");
6782 if (porta
&& !atoi(porta
)) {
6783 ast_log(LOG_WARNING
, "%s is not a valid port number at line %d\n", porta
, lineno
);
6787 return iax2_append_register(hostname
, username
, secret
, porta
);
6791 static void register_peer_exten(struct iax2_peer
*peer
, int onoff
)
6794 char *stringp
, *ext
;
6795 if (!ast_strlen_zero(regcontext
)) {
6796 ast_copy_string(multi
, S_OR(peer
->regexten
, peer
->name
), sizeof(multi
));
6798 while((ext
= strsep(&stringp
, "&"))) {
6800 if (!ast_exists_extension(NULL
, regcontext
, ext
, 1, NULL
))
6801 ast_add_extension(regcontext
, 1, ext
, 1, NULL
, NULL
,
6802 "Noop", ast_strdup(peer
->name
), ast_free_ptr
, "IAX2");
6804 ast_context_remove_extension(regcontext
, ext
, 1, NULL
);
6808 static void prune_peers(void);
6810 static void unlink_peer(struct iax2_peer
*peer
)
6812 if (peer
->expire
> -1) {
6813 if (!ast_sched_del(sched
, peer
->expire
)) {
6819 if (peer
->pokeexpire
> -1) {
6820 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
6821 peer
->pokeexpire
= -1;
6826 ao2_unlink(peers
, peer
);
6829 static void __expire_registry(const void *data
)
6831 struct iax2_peer
*peer
= (struct iax2_peer
*) data
;
6838 ast_debug(1, "Expiring registration for peer '%s'\n", peer
->name
);
6839 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(peer
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
)))
6840 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
6841 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer
->name
);
6842 /* Reset the address */
6843 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
6844 /* Reset expiry value */
6845 peer
->expiry
= min_reg_expire
;
6846 if (!ast_test_flag(peer
, IAX_TEMPONLY
))
6847 ast_db_del("IAX/Registry", peer
->name
);
6848 register_peer_exten(peer
, 0);
6849 ast_devstate_changed(AST_DEVICE_UNAVAILABLE
, "IAX2/%s", peer
->name
); /* Activate notification */
6851 iax2_regfunk(peer
->name
, 0);
6853 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
))
6859 static int expire_registry(const void *data
)
6861 #ifdef SCHED_MULTITHREADED
6862 if (schedule_action(__expire_registry
, data
))
6864 __expire_registry(data
);
6868 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
6870 static void reg_source_db(struct iax2_peer
*p
)
6875 if (!ast_test_flag(p
, IAX_TEMPONLY
) && (!ast_db_get("IAX/Registry", p
->name
, data
, sizeof(data
)))) {
6876 c
= strchr(data
, ':');
6880 if (inet_aton(data
, &in
)) {
6885 ast_verb(3, "Seeding '%s' at %s:%d for %d\n", p
->name
,
6886 ast_inet_ntoa(in
), atoi(c
), atoi(d
));
6887 iax2_poke_peer(p
, 0);
6888 p
->expiry
= atoi(d
);
6889 memset(&p
->addr
, 0, sizeof(p
->addr
));
6890 p
->addr
.sin_family
= AF_INET
;
6891 p
->addr
.sin_addr
= in
;
6892 p
->addr
.sin_port
= htons(atoi(c
));
6893 if (p
->expire
> -1) {
6894 if (!ast_sched_del(sched
, p
->expire
)) {
6899 ast_devstate_changed(AST_DEVICE_UNKNOWN
, "IAX2/%s", p
->name
); /* Activate notification */
6900 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
6901 if (p
->expire
== -1)
6904 iax2_regfunk(p
->name
, 1);
6905 register_peer_exten(p
, 1);
6914 * \pre iaxsl[callno] is locked
6916 * \note Since this function calls send_command_final(), the pvt struct for
6917 * the given call number may disappear while executing this function.
6919 static int update_registry(struct sockaddr_in
*sin
, int callno
, char *devtype
, int fd
, unsigned short refresh
)
6921 /* Called from IAX thread only, with proper iaxsl lock */
6922 struct iax_ie_data ied
;
6923 struct iax2_peer
*p
;
6927 const char *peer_name
;
6930 memset(&ied
, 0, sizeof(ied
));
6932 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
6934 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6935 ast_mutex_unlock(&iaxsl
[callno
]);
6936 if (!(p
= find_peer(peer_name
, 1))) {
6937 ast_mutex_lock(&iaxsl
[callno
]);
6938 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
6941 ast_mutex_lock(&iaxsl
[callno
]);
6945 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(p
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
))) {
6946 if (sin
->sin_addr
.s_addr
) {
6949 realtime_update_peer(peer_name
, sin
, nowtime
);
6951 realtime_update_peer(peer_name
, sin
, 0);
6954 if (inaddrcmp(&p
->addr
, sin
)) {
6956 iax2_regfunk(p
->name
, 1);
6957 /* Stash the IP address from which they registered */
6958 memcpy(&p
->addr
, sin
, sizeof(p
->addr
));
6959 snprintf(data
, sizeof(data
), "%s:%d:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), p
->expiry
);
6960 if (!ast_test_flag(p
, IAX_TEMPONLY
) && sin
->sin_addr
.s_addr
) {
6961 ast_db_put("IAX/Registry", p
->name
, data
);
6962 ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p
->name
,
6963 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
6964 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p
->name
);
6965 register_peer_exten(p
, 1);
6966 ast_devstate_changed(AST_DEVICE_UNKNOWN
, "IAX2/%s", p
->name
); /* Activate notification */
6967 } else if (!ast_test_flag(p
, IAX_TEMPONLY
)) {
6968 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p
->name
,
6969 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6970 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p
->name
);
6971 register_peer_exten(p
, 0);
6972 ast_db_del("IAX/Registry", p
->name
);
6973 ast_devstate_changed(AST_DEVICE_UNAVAILABLE
, "IAX2/%s", p
->name
); /* Activate notification */
6975 /* Update the host */
6976 /* Verify that the host is really there */
6977 iax2_poke_peer(p
, callno
);
6980 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6981 if (!iaxs
[callno
]) {
6986 /* Store socket fd */
6988 /* Setup the expiry */
6989 if (p
->expire
> -1) {
6990 if (!ast_sched_del(sched
, p
->expire
)) {
6995 /* treat an unspecified refresh interval as the minimum */
6997 refresh
= min_reg_expire
;
6998 if (refresh
> max_reg_expire
) {
6999 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
7000 p
->name
, max_reg_expire
, refresh
);
7001 p
->expiry
= max_reg_expire
;
7002 } else if (refresh
< min_reg_expire
) {
7003 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
7004 p
->name
, min_reg_expire
, refresh
);
7005 p
->expiry
= min_reg_expire
;
7007 p
->expiry
= refresh
;
7009 if (p
->expiry
&& sin
->sin_addr
.s_addr
) {
7010 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
7011 if (p
->expire
== -1)
7014 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, p
->name
);
7015 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(p
->zonetag
));
7016 if (sin
->sin_addr
.s_addr
) {
7017 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, p
->expiry
);
7018 iax_ie_append_addr(&ied
, IAX_IE_APPARENT_ADDR
, &p
->addr
);
7019 if (!ast_strlen_zero(p
->mailbox
)) {
7020 struct ast_event
*event
;
7022 char *mailbox
, *context
;
7024 context
= mailbox
= ast_strdupa(p
->mailbox
);
7025 strsep(&context
, "@");
7026 if (ast_strlen_zero(context
))
7027 context
= "default";
7029 event
= ast_event_get_cached(AST_EVENT_MWI
,
7030 AST_EVENT_IE_MAILBOX
, AST_EVENT_IE_PLTYPE_STR
, mailbox
,
7031 AST_EVENT_IE_CONTEXT
, AST_EVENT_IE_PLTYPE_STR
, context
,
7032 AST_EVENT_IE_NEWMSGS
, AST_EVENT_IE_PLTYPE_EXISTS
,
7033 AST_EVENT_IE_OLDMSGS
, AST_EVENT_IE_PLTYPE_EXISTS
,
7036 new = ast_event_get_ie_uint(event
, AST_EVENT_IE_NEWMSGS
);
7037 old
= ast_event_get_ie_uint(event
, AST_EVENT_IE_OLDMSGS
);
7038 ast_event_destroy(event
);
7039 } else { /* Fall back on checking the mailbox directly */
7040 ast_app_inboxcount(p
->mailbox
, &new, &old
);
7049 msgcount
= (old
<< 8) | new;
7051 iax_ie_append_short(&ied
, IAX_IE_MSGCOUNT
, msgcount
);
7053 if (ast_test_flag(p
, IAX_HASCALLERID
)) {
7054 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, p
->cid_num
);
7055 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, p
->cid_name
);
7058 version
= iax_check_version(devtype
);
7060 iax_ie_append_short(&ied
, IAX_IE_FIRMWAREVER
, version
);
7067 return res
? res
: send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGACK
, 0, ied
.buf
, ied
.pos
, -1);
7070 static int registry_authrequest(int callno
)
7072 struct iax_ie_data ied
;
7073 struct iax2_peer
*p
;
7075 const char *peer_name
;
7078 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
7080 /* SLD: third call to find_peer in registration */
7081 ast_mutex_unlock(&iaxsl
[callno
]);
7082 p
= find_peer(peer_name
, 1);
7083 ast_mutex_lock(&iaxsl
[callno
]);
7087 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
7091 memset(&ied
, 0, sizeof(ied
));
7092 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
7093 if (p
->authmethods
& (IAX_AUTH_RSA
| IAX_AUTH_MD5
)) {
7094 /* Build the challenge */
7095 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
7096 ast_string_field_set(iaxs
[callno
], challenge
, challenge
);
7097 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, iaxs
[callno
]->challenge
);
7099 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, peer_name
);
7106 return res
? res
: send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGAUTH
, 0, ied
.buf
, ied
.pos
, -1);;
7109 static int registry_rerequest(struct iax_ies
*ies
, int callno
, struct sockaddr_in
*sin
)
7111 struct iax2_registry
*reg
;
7112 /* Start pessimistic */
7113 struct iax_ie_data ied
;
7114 char peer
[256] = "";
7115 char challenge
[256] = "";
7117 int authmethods
= 0;
7118 if (ies
->authmethods
)
7119 authmethods
= ies
->authmethods
;
7121 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
7123 ast_copy_string(challenge
, ies
->challenge
, sizeof(challenge
));
7124 memset(&ied
, 0, sizeof(ied
));
7125 reg
= iaxs
[callno
]->reg
;
7127 if (inaddrcmp(®
->addr
, sin
)) {
7128 ast_log(LOG_WARNING
, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
7131 if (ast_strlen_zero(reg
->secret
)) {
7132 ast_log(LOG_NOTICE
, "No secret associated with peer '%s'\n", reg
->username
);
7133 reg
->regstate
= REG_STATE_NOAUTH
;
7136 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
7137 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
7138 if (reg
->secret
[0] == '[') {
7140 ast_copy_string(tmpkey
, reg
->secret
+ 1, sizeof(tmpkey
));
7141 tmpkey
[strlen(tmpkey
) - 1] = '\0';
7142 res
= authenticate(challenge
, NULL
, tmpkey
, authmethods
, &ied
, sin
, NULL
, NULL
);
7144 res
= authenticate(challenge
, reg
->secret
, NULL
, authmethods
, &ied
, sin
, NULL
, NULL
);
7146 reg
->regstate
= REG_STATE_AUTHSENT
;
7147 return send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
7150 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registery '%s'\n", peer
);
7152 ast_log(LOG_NOTICE
, "Can't reregister without a reg\n");
7156 static void stop_stuff(int callno
)
7158 iax2_destroy_helper(iaxs
[callno
]);
7161 static void __auth_reject(const void *nothing
)
7163 /* Called from IAX thread only, without iaxs lock */
7164 int callno
= (int)(long)(nothing
);
7165 struct iax_ie_data ied
;
7166 ast_mutex_lock(&iaxsl
[callno
]);
7168 memset(&ied
, 0, sizeof(ied
));
7169 if (iaxs
[callno
]->authfail
== IAX_COMMAND_REGREJ
) {
7170 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Registration Refused");
7171 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_REJECTED
);
7172 } else if (iaxs
[callno
]->authfail
== IAX_COMMAND_REJECT
) {
7173 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "No authority found");
7174 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
7176 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, iaxs
[callno
]->authfail
, 0, ied
.buf
, ied
.pos
, -1);
7178 ast_mutex_unlock(&iaxsl
[callno
]);
7181 static int auth_reject(const void *data
)
7183 int callno
= (int)(long)(data
);
7184 ast_mutex_lock(&iaxsl
[callno
]);
7186 iaxs
[callno
]->authid
= -1;
7187 ast_mutex_unlock(&iaxsl
[callno
]);
7188 #ifdef SCHED_MULTITHREADED
7189 if (schedule_action(__auth_reject
, data
))
7191 __auth_reject(data
);
7195 static int auth_fail(int callno
, int failcode
)
7197 /* Schedule sending the authentication failure in one second, to prevent
7200 iaxs
[callno
]->authfail
= failcode
;
7202 iaxs
[callno
]->authid
= iax2_sched_replace(iaxs
[callno
]->authid
,
7203 sched
, 1000, auth_reject
, (void *)(long)callno
);
7205 auth_reject((void *)(long)callno
);
7210 static void __auto_hangup(const void *nothing
)
7212 /* Called from IAX thread only, without iaxs lock */
7213 int callno
= (int)(long)(nothing
);
7214 struct iax_ie_data ied
;
7215 ast_mutex_lock(&iaxsl
[callno
]);
7217 memset(&ied
, 0, sizeof(ied
));
7218 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Timeout");
7219 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_USER_RESPONSE
);
7220 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
7222 ast_mutex_unlock(&iaxsl
[callno
]);
7225 static int auto_hangup(const void *data
)
7227 int callno
= (int)(long)(data
);
7228 ast_mutex_lock(&iaxsl
[callno
]);
7230 iaxs
[callno
]->autoid
= -1;
7232 ast_mutex_unlock(&iaxsl
[callno
]);
7233 #ifdef SCHED_MULTITHREADED
7234 if (schedule_action(__auto_hangup
, data
))
7236 __auto_hangup(data
);
7240 static void iax2_dprequest(struct iax2_dpcache
*dp
, int callno
)
7242 struct iax_ie_data ied
;
7243 /* Auto-hangup with 30 seconds of inactivity */
7244 iaxs
[callno
]->autoid
= iax2_sched_replace(iaxs
[callno
]->autoid
,
7245 sched
, 30000, auto_hangup
, (void *)(long)callno
);
7246 memset(&ied
, 0, sizeof(ied
));
7247 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, dp
->exten
);
7248 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREQ
, 0, ied
.buf
, ied
.pos
, -1);
7249 dp
->flags
|= CACHE_FLAG_TRANSMITTED
;
7252 static int iax2_vnak(int callno
)
7254 return send_command_immediate(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_VNAK
, 0, NULL
, 0, iaxs
[callno
]->iseqno
);
7257 static void vnak_retransmit(int callno
, int last
)
7259 struct iax_frame
*f
;
7261 AST_LIST_LOCK(&frame_queue
);
7262 AST_LIST_TRAVERSE(&frame_queue
, f
, list
) {
7263 /* Send a copy immediately */
7264 if ((f
->callno
== callno
) && iaxs
[f
->callno
] &&
7265 ((unsigned char ) (f
->oseqno
- last
) < 128) &&
7266 (f
->retries
>= 0)) {
7270 AST_LIST_UNLOCK(&frame_queue
);
7273 static void __iax2_poke_peer_s(const void *data
)
7275 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
7276 iax2_poke_peer(peer
, 0);
7280 static int iax2_poke_peer_s(const void *data
)
7282 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
7283 peer
->pokeexpire
= -1;
7284 #ifdef SCHED_MULTITHREADED
7285 if (schedule_action(__iax2_poke_peer_s
, data
))
7287 __iax2_poke_peer_s(data
);
7291 static int send_trunk(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
7294 struct iax_frame
*fr
;
7295 struct ast_iax2_meta_hdr
*meta
;
7296 struct ast_iax2_meta_trunk_hdr
*mth
;
7299 /* Point to frame */
7300 fr
= (struct iax_frame
*)tpeer
->trunkdata
;
7301 /* Point to meta data */
7302 meta
= (struct ast_iax2_meta_hdr
*)fr
->afdata
;
7303 mth
= (struct ast_iax2_meta_trunk_hdr
*)meta
->data
;
7304 if (tpeer
->trunkdatalen
) {
7305 /* We're actually sending a frame, so fill the meta trunk header and meta header */
7307 meta
->metacmd
= IAX_META_TRUNK
;
7308 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
))
7309 meta
->cmddata
= IAX_META_TRUNK_MINI
;
7311 meta
->cmddata
= IAX_META_TRUNK_SUPERMINI
;
7312 mth
->ts
= htonl(calc_txpeerstamp(tpeer
, trunkfreq
, now
));
7313 /* And the rest of the ast_iax2 header */
7314 fr
->direction
= DIRECTION_OUTGRESS
;
7317 /* Any appropriate call will do */
7318 fr
->data
= fr
->afdata
;
7319 fr
->datalen
= tpeer
->trunkdatalen
+ sizeof(struct ast_iax2_meta_hdr
) + sizeof(struct ast_iax2_meta_trunk_hdr
);
7320 res
= transmit_trunk(fr
, &tpeer
->addr
, tpeer
->sockfd
);
7321 calls
= tpeer
->calls
;
7323 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls
, fr
->datalen
, ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
), ntohl(mth
->ts
));
7325 /* Reset transmit trunk side data */
7326 tpeer
->trunkdatalen
= 0;
7334 static inline int iax2_trunk_expired(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
7336 /* Drop when trunk is about 5 seconds idle */
7337 if (now
->tv_sec
> tpeer
->trunkact
.tv_sec
+ 5)
7342 static int timing_read(int *id
, int fd
, short events
, void *cbdata
)
7344 int res
, processed
= 0, totalcalls
= 0;
7345 struct iax2_trunk_peer
*tpeer
= NULL
, *drop
= NULL
;
7346 struct timeval now
= ast_tvnow();
7349 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize
);
7351 if (timingfd
> -1) {
7352 ast_timer_ack(timingfd
, 1);
7355 /* For each peer that supports trunking... */
7356 AST_LIST_LOCK(&tpeers
);
7357 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers
, tpeer
, list
) {
7360 ast_mutex_lock(&tpeer
->lock
);
7361 /* We can drop a single tpeer per pass. That makes all this logic
7362 substantially easier */
7363 if (!drop
&& iax2_trunk_expired(tpeer
, &now
)) {
7364 /* Take it out of the list, but don't free it yet, because it
7366 AST_LIST_REMOVE_CURRENT(list
);
7369 res
= send_trunk(tpeer
, &now
);
7372 ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
), res
, (res
!= 1) ? "s" : "", tpeer
->trunkdatalen
, tpeer
->trunkdataalloc
);
7376 ast_mutex_unlock(&tpeer
->lock
);
7378 AST_LIST_TRAVERSE_SAFE_END
;
7379 AST_LIST_UNLOCK(&tpeers
);
7382 ast_mutex_lock(&drop
->lock
);
7383 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
7384 because by the time they could get tpeerlock, we've already grabbed it */
7385 ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop
->addr
.sin_addr
), ntohs(drop
->addr
.sin_port
));
7386 if (drop
->trunkdata
) {
7387 ast_free(drop
->trunkdata
);
7388 drop
->trunkdata
= NULL
;
7390 ast_mutex_unlock(&drop
->lock
);
7391 ast_mutex_destroy(&drop
->lock
);
7397 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed
, totalcalls
);
7405 char context
[AST_MAX_EXTENSION
];
7406 char callednum
[AST_MAX_EXTENSION
];
7410 static void dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
, int skiplock
)
7412 unsigned short dpstatus
= 0;
7413 struct iax_ie_data ied1
;
7416 memset(&ied1
, 0, sizeof(ied1
));
7417 mm
= ast_matchmore_extension(NULL
, context
, callednum
, 1, callerid
);
7418 /* Must be started */
7419 if (!strcmp(callednum
, ast_parking_ext()) || ast_exists_extension(NULL
, context
, callednum
, 1, callerid
)) {
7420 dpstatus
= IAX_DPSTATUS_EXISTS
;
7421 } else if (ast_canmatch_extension(NULL
, context
, callednum
, 1, callerid
)) {
7422 dpstatus
= IAX_DPSTATUS_CANEXIST
;
7424 dpstatus
= IAX_DPSTATUS_NONEXISTENT
;
7426 if (ast_ignore_pattern(context
, callednum
))
7427 dpstatus
|= IAX_DPSTATUS_IGNOREPAT
;
7429 dpstatus
|= IAX_DPSTATUS_MATCHMORE
;
7431 ast_mutex_lock(&iaxsl
[callno
]);
7433 iax_ie_append_str(&ied1
, IAX_IE_CALLED_NUMBER
, callednum
);
7434 iax_ie_append_short(&ied1
, IAX_IE_DPSTATUS
, dpstatus
);
7435 iax_ie_append_short(&ied1
, IAX_IE_REFRESH
, iaxdefaultdpcache
);
7436 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREP
, 0, ied1
.buf
, ied1
.pos
, -1);
7439 ast_mutex_unlock(&iaxsl
[callno
]);
7442 static void *dp_lookup_thread(void *data
)
7444 /* Look up for dpreq */
7445 struct dpreq_data
*dpr
= data
;
7446 dp_lookup(dpr
->callno
, dpr
->context
, dpr
->callednum
, dpr
->callerid
, 0);
7448 ast_free(dpr
->callerid
);
7453 static void spawn_dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
)
7455 pthread_t newthread
;
7456 struct dpreq_data
*dpr
;
7458 if (!(dpr
= ast_calloc(1, sizeof(*dpr
))))
7461 dpr
->callno
= callno
;
7462 ast_copy_string(dpr
->context
, context
, sizeof(dpr
->context
));
7463 ast_copy_string(dpr
->callednum
, callednum
, sizeof(dpr
->callednum
));
7465 dpr
->callerid
= ast_strdup(callerid
);
7466 if (ast_pthread_create_detached(&newthread
, NULL
, dp_lookup_thread
, dpr
)) {
7467 ast_log(LOG_WARNING
, "Unable to start lookup thread!\n");
7472 struct ast_channel
*chan1
;
7473 struct ast_channel
*chan2
;
7476 static void *iax_park_thread(void *stuff
)
7478 struct ast_channel
*chan1
, *chan2
;
7480 struct ast_frame
*f
;
7487 f
= ast_read(chan1
);
7490 res
= ast_park_call(chan1
, chan2
, 0, &ext
);
7492 ast_log(LOG_NOTICE
, "Parked on extension '%d'\n", ext
);
7496 static int iax_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
)
7499 struct ast_channel
*chan1m
, *chan2m
;
7501 chan1m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan1
->exten
, chan1
->context
, chan1
->amaflags
, "Parking/%s", chan1
->name
);
7502 chan2m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan2
->exten
, chan2
->context
, chan2
->amaflags
, "IAXPeer/%s",chan2
->name
);
7503 if (chan2m
&& chan1m
) {
7504 /* Make formats okay */
7505 chan1m
->readformat
= chan1
->readformat
;
7506 chan1m
->writeformat
= chan1
->writeformat
;
7507 ast_channel_masquerade(chan1m
, chan1
);
7508 /* Setup the extensions and such */
7509 ast_copy_string(chan1m
->context
, chan1
->context
, sizeof(chan1m
->context
));
7510 ast_copy_string(chan1m
->exten
, chan1
->exten
, sizeof(chan1m
->exten
));
7511 chan1m
->priority
= chan1
->priority
;
7513 /* We make a clone of the peer channel too, so we can play
7514 back the announcement */
7515 /* Make formats okay */
7516 chan2m
->readformat
= chan2
->readformat
;
7517 chan2m
->writeformat
= chan2
->writeformat
;
7518 ast_channel_masquerade(chan2m
, chan2
);
7519 /* Setup the extensions and such */
7520 ast_copy_string(chan2m
->context
, chan2
->context
, sizeof(chan2m
->context
));
7521 ast_copy_string(chan2m
->exten
, chan2
->exten
, sizeof(chan2m
->exten
));
7522 chan2m
->priority
= chan2
->priority
;
7523 if (ast_do_masquerade(chan2m
)) {
7524 ast_log(LOG_WARNING
, "Masquerade failed :(\n");
7535 if ((d
= ast_calloc(1, sizeof(*d
)))) {
7538 if (!ast_pthread_create_detached_background(&th
, NULL
, iax_park_thread
, d
)) {
7547 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
7549 static int check_provisioning(struct sockaddr_in
*sin
, int sockfd
, char *si
, unsigned int ver
)
7551 unsigned int ourver
;
7553 snprintf(rsi
, sizeof(rsi
), "si-%s", si
);
7554 if (iax_provision_version(&ourver
, rsi
, 1))
7556 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si
, ourver
, ver
);
7558 iax2_provision(sin
, sockfd
, NULL
, rsi
, 1);
7562 static void construct_rr(struct chan_iax2_pvt
*pvt
, struct iax_ie_data
*iep
)
7565 jb_getinfo(pvt
->jb
, &stats
);
7567 memset(iep
, 0, sizeof(*iep
));
7569 iax_ie_append_int(iep
,IAX_IE_RR_JITTER
, stats
.jitter
);
7570 if(stats
.frames_in
== 0) stats
.frames_in
= 1;
7571 iax_ie_append_int(iep
,IAX_IE_RR_LOSS
, ((0xff & (stats
.losspct
/1000)) << 24 | (stats
.frames_lost
& 0x00ffffff)));
7572 iax_ie_append_int(iep
,IAX_IE_RR_PKTS
, stats
.frames_in
);
7573 iax_ie_append_short(iep
,IAX_IE_RR_DELAY
, stats
.current
- stats
.min
);
7574 iax_ie_append_int(iep
,IAX_IE_RR_DROPPED
, stats
.frames_dropped
);
7575 iax_ie_append_int(iep
,IAX_IE_RR_OOO
, stats
.frames_ooo
);
7578 static void save_rr(struct iax_frame
*fr
, struct iax_ies
*ies
)
7580 iaxs
[fr
->callno
]->remote_rr
.jitter
= ies
->rr_jitter
;
7581 iaxs
[fr
->callno
]->remote_rr
.losspct
= ies
->rr_loss
>> 24;
7582 iaxs
[fr
->callno
]->remote_rr
.losscnt
= ies
->rr_loss
& 0xffffff;
7583 iaxs
[fr
->callno
]->remote_rr
.packets
= ies
->rr_pkts
;
7584 iaxs
[fr
->callno
]->remote_rr
.delay
= ies
->rr_delay
;
7585 iaxs
[fr
->callno
]->remote_rr
.dropped
= ies
->rr_dropped
;
7586 iaxs
[fr
->callno
]->remote_rr
.ooo
= ies
->rr_ooo
;
7589 static void save_osptoken(struct iax_frame
*fr
, struct iax_ies
*ies
)
7592 unsigned int length
, offset
= 0;
7593 char full_osptoken
[IAX_MAX_OSPBUFF_SIZE
];
7595 for (i
= 0; i
< IAX_MAX_OSPBLOCK_NUM
; i
++) {
7596 length
= ies
->ospblocklength
[i
];
7598 if (length
> IAX_MAX_OSPBLOCK_SIZE
) {
7599 /* OSP token block length wrong, clear buffer */
7603 memcpy(full_osptoken
+ offset
, ies
->osptokenblock
[i
], length
);
7610 *(full_osptoken
+ offset
) = '\0';
7611 if (strlen(full_osptoken
) != offset
) {
7612 /* OSP token length wrong, clear buffer */
7613 *full_osptoken
= '\0';
7616 ast_string_field_set(iaxs
[fr
->callno
], osptoken
, full_osptoken
);
7619 static void log_jitterstats(unsigned short callno
)
7621 int localjitter
= -1, localdelay
= 0, locallost
= -1, locallosspct
= -1, localdropped
= 0, localooo
= -1, localpackets
= -1;
7624 ast_mutex_lock(&iaxsl
[callno
]);
7625 if (iaxs
[callno
] && iaxs
[callno
]->owner
&& iaxs
[callno
]->owner
->name
) {
7626 if(ast_test_flag(iaxs
[callno
], IAX_USEJITTERBUF
)) {
7627 jb_getinfo(iaxs
[callno
]->jb
, &jbinfo
);
7628 localjitter
= jbinfo
.jitter
;
7629 localdelay
= jbinfo
.current
- jbinfo
.min
;
7630 locallost
= jbinfo
.frames_lost
;
7631 locallosspct
= jbinfo
.losspct
/1000;
7632 localdropped
= jbinfo
.frames_dropped
;
7633 localooo
= jbinfo
.frames_ooo
;
7634 localpackets
= jbinfo
.frames_in
;
7636 ast_debug(3, "JB STATS:%s ping=%d ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
7637 iaxs
[callno
]->owner
->name
,
7638 iaxs
[callno
]->pingtime
,
7646 iaxs
[callno
]->remote_rr
.jitter
,
7647 iaxs
[callno
]->remote_rr
.delay
,
7648 iaxs
[callno
]->remote_rr
.losscnt
,
7649 iaxs
[callno
]->remote_rr
.losspct
/1000,
7650 iaxs
[callno
]->remote_rr
.dropped
,
7651 iaxs
[callno
]->remote_rr
.ooo
,
7652 iaxs
[callno
]->remote_rr
.packets
);
7653 manager_event(EVENT_FLAG_REPORTING
, "JitterBufStats", "Owner: %s\r\nPing: %d\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
7654 iaxs
[callno
]->owner
->name
,
7655 iaxs
[callno
]->pingtime
,
7663 iaxs
[callno
]->remote_rr
.jitter
,
7664 iaxs
[callno
]->remote_rr
.delay
,
7665 iaxs
[callno
]->remote_rr
.losscnt
,
7666 iaxs
[callno
]->remote_rr
.losspct
/1000,
7667 iaxs
[callno
]->remote_rr
.dropped
,
7668 iaxs
[callno
]->remote_rr
.ooo
,
7669 iaxs
[callno
]->remote_rr
.packets
);
7671 ast_mutex_unlock(&iaxsl
[callno
]);
7674 static int socket_process(struct iax2_thread
*thread
);
7677 * \brief Handle any deferred full frames for this thread
7679 static void handle_deferred_full_frames(struct iax2_thread
*thread
)
7681 struct iax2_pkt_buf
*pkt_buf
;
7683 ast_mutex_lock(&thread
->lock
);
7685 while ((pkt_buf
= AST_LIST_REMOVE_HEAD(&thread
->full_frames
, entry
))) {
7686 ast_mutex_unlock(&thread
->lock
);
7688 thread
->buf
= pkt_buf
->buf
;
7689 thread
->buf_len
= pkt_buf
->len
;
7690 thread
->buf_size
= pkt_buf
->len
+ 1;
7692 socket_process(thread
);
7697 ast_mutex_lock(&thread
->lock
);
7700 ast_mutex_unlock(&thread
->lock
);
7704 * \brief Queue the last read full frame for processing by a certain thread
7706 * If there are already any full frames queued, they are sorted
7707 * by sequence number.
7709 static void defer_full_frame(struct iax2_thread
*from_here
, struct iax2_thread
*to_here
)
7711 struct iax2_pkt_buf
*pkt_buf
, *cur_pkt_buf
;
7712 struct ast_iax2_full_hdr
*fh
, *cur_fh
;
7714 if (!(pkt_buf
= ast_calloc(1, sizeof(*pkt_buf
) + from_here
->buf_len
)))
7717 pkt_buf
->len
= from_here
->buf_len
;
7718 memcpy(pkt_buf
->buf
, from_here
->buf
, pkt_buf
->len
);
7720 fh
= (struct ast_iax2_full_hdr
*) pkt_buf
->buf
;
7721 ast_mutex_lock(&to_here
->lock
);
7722 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here
->full_frames
, cur_pkt_buf
, entry
) {
7723 cur_fh
= (struct ast_iax2_full_hdr
*) cur_pkt_buf
->buf
;
7724 if (fh
->oseqno
< cur_fh
->oseqno
) {
7725 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf
, entry
);
7729 AST_LIST_TRAVERSE_SAFE_END
7732 AST_LIST_INSERT_TAIL(&to_here
->full_frames
, pkt_buf
, entry
);
7734 ast_mutex_unlock(&to_here
->lock
);
7737 static int socket_read(int *id
, int fd
, short events
, void *cbdata
)
7739 struct iax2_thread
*thread
;
7742 static time_t last_errtime
= 0;
7743 struct ast_iax2_full_hdr
*fh
;
7745 if (!(thread
= find_idle_thread())) {
7747 if (t
!= last_errtime
)
7748 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
7754 len
= sizeof(thread
->iosin
);
7756 thread
->buf_len
= recvfrom(fd
, thread
->readbuf
, sizeof(thread
->readbuf
), 0, (struct sockaddr
*) &thread
->iosin
, &len
);
7757 thread
->buf_size
= sizeof(thread
->readbuf
);
7758 thread
->buf
= thread
->readbuf
;
7759 if (thread
->buf_len
< 0) {
7760 if (errno
!= ECONNREFUSED
&& errno
!= EAGAIN
)
7761 ast_log(LOG_WARNING
, "Error: %s\n", strerror(errno
));
7763 thread
->iostate
= IAX_IOSTATE_IDLE
;
7764 signal_condition(&thread
->lock
, &thread
->cond
);
7767 if (test_losspct
&& ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_losspct
)) { /* simulate random loss condition */
7768 thread
->iostate
= IAX_IOSTATE_IDLE
;
7769 signal_condition(&thread
->lock
, &thread
->cond
);
7773 /* Determine if this frame is a full frame; if so, and any thread is currently
7774 processing a full frame for the same callno from this peer, then drop this
7775 frame (and the peer will retransmit it) */
7776 fh
= (struct ast_iax2_full_hdr
*) thread
->buf
;
7777 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
7778 struct iax2_thread
*cur
= NULL
;
7779 uint16_t callno
= ntohs(fh
->scallno
) & ~IAX_FLAG_FULL
;
7781 AST_LIST_LOCK(&active_list
);
7782 AST_LIST_TRAVERSE(&active_list
, cur
, list
) {
7783 if ((cur
->ffinfo
.callno
== callno
) &&
7784 !inaddrcmp(&cur
->ffinfo
.sin
, &thread
->iosin
))
7788 /* we found another thread processing a full frame for this call,
7789 so queue it up for processing later. */
7790 defer_full_frame(thread
, cur
);
7791 AST_LIST_UNLOCK(&active_list
);
7792 thread
->iostate
= IAX_IOSTATE_IDLE
;
7793 signal_condition(&thread
->lock
, &thread
->cond
);
7796 /* this thread is going to process this frame, so mark it */
7797 thread
->ffinfo
.callno
= callno
;
7798 memcpy(&thread
->ffinfo
.sin
, &thread
->iosin
, sizeof(thread
->ffinfo
.sin
));
7799 thread
->ffinfo
.type
= fh
->type
;
7800 thread
->ffinfo
.csub
= fh
->csub
;
7802 AST_LIST_UNLOCK(&active_list
);
7805 /* Mark as ready and send on its way */
7806 thread
->iostate
= IAX_IOSTATE_READY
;
7807 #ifdef DEBUG_SCHED_MULTITHREAD
7808 ast_copy_string(thread
->curfunc
, "socket_process", sizeof(thread
->curfunc
));
7810 signal_condition(&thread
->lock
, &thread
->cond
);
7815 static int socket_process_meta(int packet_len
, struct ast_iax2_meta_hdr
*meta
, struct sockaddr_in
*sin
, int sockfd
,
7816 struct iax_frame
*fr
)
7818 unsigned char metatype
;
7819 struct ast_iax2_meta_trunk_mini
*mtm
;
7820 struct ast_iax2_meta_trunk_hdr
*mth
;
7821 struct ast_iax2_meta_trunk_entry
*mte
;
7822 struct iax2_trunk_peer
*tpeer
;
7825 struct timeval rxtrunktime
;
7826 struct ast_frame f
= { 0, };
7828 if (packet_len
< sizeof(*meta
)) {
7829 ast_log(LOG_WARNING
, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
7830 ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
7834 if (meta
->metacmd
!= IAX_META_TRUNK
)
7837 if (packet_len
< (sizeof(*meta
) + sizeof(*mth
))) {
7838 ast_log(LOG_WARNING
, "midget meta trunk packet received (%d of %d min)\n", packet_len
,
7839 (int) (sizeof(*meta
) + sizeof(*mth
)));
7842 mth
= (struct ast_iax2_meta_trunk_hdr
*)(meta
->data
);
7843 ts
= ntohl(mth
->ts
);
7844 metatype
= meta
->cmddata
;
7845 packet_len
-= (sizeof(*meta
) + sizeof(*mth
));
7847 tpeer
= find_tpeer(sin
, sockfd
);
7849 ast_log(LOG_WARNING
, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
7850 ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
7853 tpeer
->trunkact
= ast_tvnow();
7854 if (!ts
|| ast_tvzero(tpeer
->rxtrunktime
))
7855 tpeer
->rxtrunktime
= tpeer
->trunkact
;
7856 rxtrunktime
= tpeer
->rxtrunktime
;
7857 ast_mutex_unlock(&tpeer
->lock
);
7858 while (packet_len
>= sizeof(*mte
)) {
7859 /* Process channels */
7860 unsigned short callno
, trunked_ts
, len
;
7862 if (metatype
== IAX_META_TRUNK_MINI
) {
7863 mtm
= (struct ast_iax2_meta_trunk_mini
*) ptr
;
7864 ptr
+= sizeof(*mtm
);
7865 packet_len
-= sizeof(*mtm
);
7866 len
= ntohs(mtm
->len
);
7867 callno
= ntohs(mtm
->mini
.callno
);
7868 trunked_ts
= ntohs(mtm
->mini
.ts
);
7869 } else if (metatype
== IAX_META_TRUNK_SUPERMINI
) {
7870 mte
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
7871 ptr
+= sizeof(*mte
);
7872 packet_len
-= sizeof(*mte
);
7873 len
= ntohs(mte
->len
);
7874 callno
= ntohs(mte
->callno
);
7877 ast_log(LOG_WARNING
, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
7880 /* Stop if we don't have enough data */
7881 if (len
> packet_len
)
7883 fr
->callno
= find_callno_locked(callno
& ~IAX_FLAG_FULL
, 0, sin
, NEW_PREVENT
, sockfd
, 0);
7887 /* If it's a valid call, deliver the contents. If not, we
7888 drop it, since we don't have a scallno to use for an INVAL */
7889 /* Process as a mini frame */
7890 memset(&f
, 0, sizeof(f
));
7891 f
.frametype
= AST_FRAME_VOICE
;
7892 if (!iaxs
[fr
->callno
]) {
7894 } else if (iaxs
[fr
->callno
]->voiceformat
== 0) {
7895 ast_log(LOG_WARNING
, "Received trunked frame before first full voice frame\n");
7896 iax2_vnak(fr
->callno
);
7898 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
7900 if (f
.datalen
>= 0) {
7906 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | (trunked_ts
& 0xffff);
7908 fr
->ts
= fix_peerts(&rxtrunktime
, fr
->callno
, ts
);
7909 /* Don't pass any packets until we're started */
7910 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7911 struct iax_frame
*duped_fr
;
7917 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
))
7918 f
.samples
= ast_codec_get_samples(&f
);
7922 iax_frame_wrap(fr
, &f
);
7923 duped_fr
= iaxfrdup2(fr
);
7925 schedule_delivery(duped_fr
, 1, 1, &fr
->ts
);
7926 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
)
7927 iaxs
[fr
->callno
]->last
= fr
->ts
;
7930 ast_log(LOG_WARNING
, "Datalen < 0?\n");
7933 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7941 static int acf_iaxvar_read(struct ast_channel
*chan
, const char *cmd
, char *data
, char *buf
, size_t len
)
7943 struct ast_datastore
*variablestore
= ast_channel_datastore_find(chan
, &iax2_variable_datastore_info
, NULL
);
7944 AST_LIST_HEAD(, ast_var_t
) *varlist
;
7945 struct ast_var_t
*var
;
7947 if (!variablestore
) {
7951 varlist
= variablestore
->data
;
7953 AST_LIST_LOCK(varlist
);
7954 AST_LIST_TRAVERSE(varlist
, var
, entries
) {
7955 if (strcmp(var
->name
, data
) == 0) {
7956 ast_copy_string(buf
, var
->value
, len
);
7960 AST_LIST_UNLOCK(varlist
);
7964 static int acf_iaxvar_write(struct ast_channel
*chan
, const char *cmd
, char *data
, const char *value
)
7966 struct ast_datastore
*variablestore
= ast_channel_datastore_find(chan
, &iax2_variable_datastore_info
, NULL
);
7967 AST_LIST_HEAD(, ast_var_t
) *varlist
;
7968 struct ast_var_t
*var
;
7970 if (!variablestore
) {
7971 variablestore
= ast_datastore_alloc(&iax2_variable_datastore_info
, NULL
);
7972 if (!variablestore
) {
7973 ast_log(LOG_ERROR
, "Memory allocation error\n");
7976 varlist
= ast_calloc(1, sizeof(*varlist
));
7978 ast_log(LOG_ERROR
, "Unable to assign new variable '%s'\n", data
);
7982 AST_LIST_HEAD_INIT(varlist
);
7983 variablestore
->data
= varlist
;
7984 variablestore
->inheritance
= DATASTORE_INHERIT_FOREVER
;
7985 ast_channel_datastore_add(chan
, variablestore
);
7987 varlist
= variablestore
->data
;
7989 AST_LIST_LOCK(varlist
);
7990 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist
, var
, entries
) {
7991 if (strcmp(var
->name
, data
) == 0) {
7992 AST_LIST_REMOVE_CURRENT(entries
);
7993 ast_var_delete(var
);
7997 AST_LIST_TRAVERSE_SAFE_END
;
7998 var
= ast_var_assign(data
, value
);
8000 AST_LIST_INSERT_TAIL(varlist
, var
, entries
);
8002 ast_log(LOG_ERROR
, "Unable to assign new variable '%s'\n", data
);
8003 AST_LIST_UNLOCK(varlist
);
8007 static struct ast_custom_function iaxvar_function
= {
8009 .synopsis
= "Sets or retrieves a remote variable",
8010 .syntax
= "IAXVAR(<varname>)",
8011 .read
= acf_iaxvar_read
,
8012 .write
= acf_iaxvar_write
,
8015 static int socket_process(struct iax2_thread
*thread
)
8017 struct sockaddr_in sin
;
8019 int updatehistory
=1;
8020 int new = NEW_PREVENT
;
8022 struct ast_iax2_full_hdr
*fh
= (struct ast_iax2_full_hdr
*)thread
->buf
;
8023 struct ast_iax2_mini_hdr
*mh
= (struct ast_iax2_mini_hdr
*)thread
->buf
;
8024 struct ast_iax2_meta_hdr
*meta
= (struct ast_iax2_meta_hdr
*)thread
->buf
;
8025 struct ast_iax2_video_hdr
*vh
= (struct ast_iax2_video_hdr
*)thread
->buf
;
8026 struct iax_frame
*fr
;
8027 struct iax_frame
*cur
;
8028 struct ast_frame f
= { 0, };
8029 struct ast_channel
*c
= NULL
;
8030 struct iax2_dpcache
*dp
;
8031 struct iax2_peer
*peer
;
8033 struct iax_ie_data ied0
, ied1
;
8038 char empty
[32]=""; /* Safety measure */
8039 struct iax_frame
*duped_fr
;
8040 char host_pref_buf
[128];
8041 char caller_pref_buf
[128];
8042 struct ast_codec_pref pref
;
8043 char *using_prefs
= "mine";
8045 /* allocate an iax_frame with 4096 bytes of data buffer */
8046 fr
= alloca(sizeof(*fr
) + 4096);
8047 memset(fr
, 0, sizeof(*fr
));
8048 fr
->afdatalen
= 4096; /* From alloca() above */
8050 /* Copy frequently used parameters to the stack */
8051 res
= thread
->buf_len
;
8053 memcpy(&sin
, &thread
->iosin
, sizeof(sin
));
8055 if (res
< sizeof(*mh
)) {
8056 ast_log(LOG_WARNING
, "midget packet received (%d of %d min)\n", res
, (int) sizeof(*mh
));
8059 if ((vh
->zeros
== 0) && (ntohs(vh
->callno
) & 0x8000)) {
8060 if (res
< sizeof(*vh
)) {
8061 ast_log(LOG_WARNING
, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
8065 /* This is a video frame, get call number */
8066 fr
->callno
= find_callno(ntohs(vh
->callno
) & ~0x8000, dcallno
, &sin
, new, fd
, 0);
8068 } else if ((meta
->zeros
== 0) && !(ntohs(meta
->metacmd
) & 0x8000))
8069 return socket_process_meta(res
, meta
, &sin
, fd
, fr
);
8071 #ifdef DEBUG_SUPPORT
8072 if (res
>= sizeof(*fh
))
8073 iax_outputframe(NULL
, fh
, 1, &sin
, res
- sizeof(*fh
));
8075 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
8076 if (res
< sizeof(*fh
)) {
8077 ast_log(LOG_WARNING
, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
8081 /* Get the destination call number */
8082 dcallno
= ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
;
8083 /* Retrieve the type and subclass */
8084 f
.frametype
= fh
->type
;
8085 if (f
.frametype
== AST_FRAME_VIDEO
) {
8086 f
.subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
8088 f
.subclass
= uncompress_subclass(fh
->csub
);
8091 /* Deal with POKE/PONG without allocating a callno */
8092 if (f
.frametype
== AST_FRAME_IAX
&& f
.subclass
== IAX_COMMAND_POKE
) {
8093 /* Reply back with a PONG, but don't care about the result. */
8094 send_apathetic_reply(1, ntohs(fh
->scallno
), &sin
, IAX_COMMAND_PONG
, ntohs(fh
->ts
), fh
->oseqno
);
8096 } else if (f
.frametype
== AST_FRAME_IAX
&& f
.subclass
== IAX_COMMAND_ACK
&& dcallno
== 1) {
8101 if ((f
.frametype
== AST_FRAME_IAX
) && ((f
.subclass
== IAX_COMMAND_NEW
) || (f
.subclass
== IAX_COMMAND_REGREQ
) ||
8102 (f
.subclass
== IAX_COMMAND_POKE
) || (f
.subclass
== IAX_COMMAND_FWDOWNL
) ||
8103 (f
.subclass
== IAX_COMMAND_REGREL
)))
8106 /* Don't know anything about it yet */
8107 f
.frametype
= AST_FRAME_NULL
;
8112 int check_dcallno
= 0;
8115 * We enforce accurate destination call numbers for all full frames except
8116 * LAGRQ and PING commands. This is because older versions of Asterisk
8117 * schedule these commands to get sent very quickly, and they will sometimes
8118 * be sent before they receive the first frame from the other side. When
8119 * that happens, it doesn't contain the destination call number. However,
8120 * not checking it for these frames is safe.
8122 * Discussed in the following thread:
8123 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
8126 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
8127 check_dcallno
= f
.frametype
== AST_FRAME_IAX
? (f
.subclass
!= IAX_COMMAND_PING
&& f
.subclass
!= IAX_COMMAND_LAGRQ
) : 1;
8130 fr
->callno
= find_callno(ntohs(mh
->callno
) & ~IAX_FLAG_FULL
, dcallno
, &sin
, new, fd
, check_dcallno
);
8134 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8136 if (!fr
->callno
|| !iaxs
[fr
->callno
]) {
8137 /* A call arrived for a nonexistent destination. Unless it's an "inval"
8138 frame, reply with an inval */
8139 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
8140 /* We can only raw hangup control frames */
8141 if (((f
.subclass
!= IAX_COMMAND_INVAL
) &&
8142 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8143 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
8144 (f
.subclass
!= IAX_COMMAND_FWDOWNL
))||
8145 (f
.frametype
!= AST_FRAME_IAX
))
8146 raw_hangup(&sin
, ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
, ntohs(mh
->callno
) & ~IAX_FLAG_FULL
,
8150 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8153 if (ast_test_flag(iaxs
[fr
->callno
], IAX_ENCRYPTED
)) {
8154 if (decrypt_frame(fr
->callno
, fh
, &f
, &res
)) {
8155 ast_log(LOG_NOTICE
, "Packet Decrypt Failed!\n");
8156 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8159 #ifdef DEBUG_SUPPORT
8161 iax_outputframe(NULL
, fh
, 3, &sin
, res
- sizeof(*fh
));
8165 /* count this frame */
8166 iaxs
[fr
->callno
]->frames_received
++;
8168 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) && !minivid
&&
8169 f
.subclass
!= IAX_COMMAND_TXCNT
&& /* for attended transfer */
8170 f
.subclass
!= IAX_COMMAND_TXACC
) { /* for attended transfer */
8171 unsigned short new_peercallno
;
8173 new_peercallno
= (unsigned short) (ntohs(mh
->callno
) & ~IAX_FLAG_FULL
);
8174 if (new_peercallno
&& new_peercallno
!= iaxs
[fr
->callno
]->peercallno
) {
8175 if (iaxs
[fr
->callno
]->peercallno
) {
8176 remove_by_peercallno(iaxs
[fr
->callno
]);
8178 iaxs
[fr
->callno
]->peercallno
= new_peercallno
;
8179 store_by_peercallno(iaxs
[fr
->callno
]);
8182 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
8184 ast_debug(1, "Received packet %d, (%d, %d)\n", fh
->oseqno
, f
.frametype
, f
.subclass
);
8185 /* Check if it's out of order (and not an ACK or INVAL) */
8186 fr
->oseqno
= fh
->oseqno
;
8187 fr
->iseqno
= fh
->iseqno
;
8188 fr
->ts
= ntohl(fh
->ts
);
8191 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr
->ts
, fr
->ts
+ test_resync
);
8192 fr
->ts
+= test_resync
;
8194 #endif /* IAXTESTS */
8196 if ( (ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) ||
8197 ( (f
.frametype
!= AST_FRAME_VOICE
) && ! (f
.frametype
== AST_FRAME_IAX
&&
8198 (f
.subclass
== IAX_COMMAND_NEW
||
8199 f
.subclass
== IAX_COMMAND_AUTHREQ
||
8200 f
.subclass
== IAX_COMMAND_ACCEPT
||
8201 f
.subclass
== IAX_COMMAND_REJECT
)) ) )
8203 if ((ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) || (f
.frametype
!= AST_FRAME_VOICE
))
8205 if ((iaxs
[fr
->callno
]->iseqno
!= fr
->oseqno
) &&
8206 (iaxs
[fr
->callno
]->iseqno
||
8207 ((f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8208 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
8209 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
8210 (f
.subclass
!= IAX_COMMAND_TXMEDIA
) && /* for attended transfer */
8211 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
8212 (f
.subclass
!= IAX_COMMAND_TXACC
)) ||
8213 (f
.frametype
!= AST_FRAME_IAX
))) {
8215 ((f
.subclass
!= IAX_COMMAND_ACK
) &&
8216 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
8217 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8218 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
8219 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
8220 (f
.subclass
!= IAX_COMMAND_TXMEDIA
) && /* for attended transfer */
8221 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
8222 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
8223 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
8224 (f
.frametype
!= AST_FRAME_IAX
)) {
8225 /* If it's not an ACK packet, it's out of order. */
8226 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
8227 iaxs
[fr
->callno
]->iseqno
, fr
->oseqno
, f
.frametype
, f
.subclass
);
8228 /* Check to see if we need to request retransmission,
8229 * and take sequence number wraparound into account */
8230 if ((unsigned char) (iaxs
[fr
->callno
]->iseqno
- fr
->oseqno
) < 128) {
8231 /* If we've already seen it, ack it XXX There's a border condition here XXX */
8232 if ((f
.frametype
!= AST_FRAME_IAX
) ||
8233 ((f
.subclass
!= IAX_COMMAND_ACK
) && (f
.subclass
!= IAX_COMMAND_INVAL
))) {
8234 ast_debug(1, "Acking anyway\n");
8235 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
8236 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
8237 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8240 /* Send a VNAK requesting retransmission */
8241 iax2_vnak(fr
->callno
);
8243 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8247 /* Increment unless it's an ACK or VNAK */
8248 if (((f
.subclass
!= IAX_COMMAND_ACK
) &&
8249 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
8250 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8251 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
8252 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
8253 (f
.frametype
!= AST_FRAME_IAX
))
8254 iaxs
[fr
->callno
]->iseqno
++;
8257 if (res
< sizeof(*fh
)) {
8258 ast_log(LOG_WARNING
, "midget packet received (%d of %d min)\n", res
, (int) sizeof(*fh
));
8259 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8262 /* Ensure text frames are NULL-terminated */
8263 if (f
.frametype
== AST_FRAME_TEXT
&& thread
->buf
[res
- 1] != '\0') {
8264 if (res
< thread
->buf_size
)
8265 thread
->buf
[res
++] = '\0';
8266 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
8267 thread
->buf
[res
- 1] = '\0';
8269 f
.datalen
= res
- sizeof(*fh
);
8271 /* Handle implicit ACKing unless this is an INVAL, and only if this is
8272 from the real peer, not the transfer peer */
8273 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) &&
8274 ((f
.subclass
!= IAX_COMMAND_INVAL
) ||
8275 (f
.frametype
!= AST_FRAME_IAX
))) {
8277 int call_to_destroy
;
8278 /* First we have to qualify that the ACKed value is within our window */
8279 if (iaxs
[fr
->callno
]->rseqno
>= iaxs
[fr
->callno
]->oseqno
|| (fr
->iseqno
>= iaxs
[fr
->callno
]->rseqno
&& fr
->iseqno
< iaxs
[fr
->callno
]->oseqno
))
8282 x
= iaxs
[fr
->callno
]->oseqno
;
8283 if ((x
!= iaxs
[fr
->callno
]->oseqno
) || (iaxs
[fr
->callno
]->oseqno
== fr
->iseqno
)) {
8284 /* The acknowledgement is within our window. Time to acknowledge everything
8286 for (x
=iaxs
[fr
->callno
]->rseqno
; x
!= fr
->iseqno
; x
++) {
8287 /* Ack the packet with the given timestamp */
8289 ast_debug(1, "Cancelling transmission of packet %d\n", x
);
8290 call_to_destroy
= 0;
8291 AST_LIST_LOCK(&frame_queue
);
8292 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
8293 /* If it's our call, and our timestamp, mark -1 retries */
8294 if ((fr
->callno
== cur
->callno
) && (x
== cur
->oseqno
)) {
8296 /* Destroy call if this is the end */
8298 call_to_destroy
= fr
->callno
;
8301 AST_LIST_UNLOCK(&frame_queue
);
8302 if (call_to_destroy
) {
8304 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy
);
8305 ast_mutex_lock(&iaxsl
[call_to_destroy
]);
8306 iax2_destroy(call_to_destroy
);
8307 ast_mutex_unlock(&iaxsl
[call_to_destroy
]);
8310 /* Note how much we've received acknowledgement for */
8311 if (iaxs
[fr
->callno
])
8312 iaxs
[fr
->callno
]->rseqno
= fr
->iseqno
;
8314 /* Stop processing now */
8315 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8319 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr
->iseqno
, iaxs
[fr
->callno
]->rseqno
, iaxs
[fr
->callno
]->oseqno
);
8322 if (inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) && inaddrcmp(&sin
, &iaxs
[fr
->callno
]->media
) &&
8323 ((f
.frametype
!= AST_FRAME_IAX
) ||
8324 ((f
.subclass
!= IAX_COMMAND_TXACC
) &&
8325 (f
.subclass
!= IAX_COMMAND_TXCNT
)))) {
8326 /* Only messages we accept from a transfer host are TXACC and TXCNT */
8327 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8332 if (f
.frametype
== AST_FRAME_IAX
) {
8333 if (iax_parse_ies(&ies
, thread
->buf
+ sizeof(*fh
), f
.datalen
)) {
8334 ast_log(LOG_WARNING
, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin
.sin_addr
));
8335 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8341 f
.data
.ptr
= thread
->buf
+ sizeof(*fh
);
8343 if (f
.frametype
== AST_FRAME_IAX
)
8347 memset(&ies
, 0, sizeof(ies
));
8350 /* when we receive the first full frame for a new incoming channel,
8351 it is safe to start the PBX on the channel because we have now
8352 completed a 3-way handshake with the peer */
8353 if ((f
.frametype
== AST_FRAME_VOICE
) ||
8354 (f
.frametype
== AST_FRAME_VIDEO
) ||
8355 (f
.frametype
== AST_FRAME_IAX
)) {
8356 if (ast_test_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
)) {
8357 ast_clear_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
8358 if (!ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->chosenformat
)) {
8359 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8361 } else if (ies
.vars
) {
8362 struct ast_datastore
*variablestore
;
8363 struct ast_variable
*var
, *prev
= NULL
;
8364 AST_LIST_HEAD(, ast_var_t
) *varlist
;
8365 varlist
= ast_calloc(1, sizeof(*varlist
));
8366 variablestore
= ast_datastore_alloc(&iax2_variable_datastore_info
, NULL
);
8367 if (variablestore
&& varlist
) {
8368 variablestore
->data
= varlist
;
8369 variablestore
->inheritance
= DATASTORE_INHERIT_FOREVER
;
8370 AST_LIST_HEAD_INIT(varlist
);
8371 for (var
= ies
.vars
; var
; var
= var
->next
) {
8372 struct ast_var_t
*newvar
= ast_var_assign(var
->name
, var
->value
);
8377 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
8378 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
8380 AST_LIST_INSERT_TAIL(varlist
, newvar
, entries
);
8386 ast_channel_datastore_add(c
, variablestore
);
8388 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
8390 ast_datastore_free(variablestore
);
8398 if (f
.frametype
== AST_FRAME_VOICE
) {
8399 if (f
.subclass
!= iaxs
[fr
->callno
]->voiceformat
) {
8400 iaxs
[fr
->callno
]->voiceformat
= f
.subclass
;
8401 ast_debug(1, "Ooh, voice format changed to %d\n", f
.subclass
);
8402 if (iaxs
[fr
->callno
]->owner
) {
8405 if (ast_channel_trylock(iaxs
[fr
->callno
]->owner
)) {
8406 DEADLOCK_AVOIDANCE(&iaxsl
[fr
->callno
]);
8407 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner
;
8409 if (iaxs
[fr
->callno
]) {
8410 if (iaxs
[fr
->callno
]->owner
) {
8411 orignative
= iaxs
[fr
->callno
]->owner
->nativeformats
;
8412 iaxs
[fr
->callno
]->owner
->nativeformats
= f
.subclass
;
8413 if (iaxs
[fr
->callno
]->owner
->readformat
)
8414 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
8415 iaxs
[fr
->callno
]->owner
->nativeformats
= orignative
;
8416 ast_channel_unlock(iaxs
[fr
->callno
]->owner
);
8419 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
8420 /* Free remote variables (if any) */
8422 ast_variables_destroy(ies
.vars
);
8423 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8429 if (f
.frametype
== AST_FRAME_VIDEO
) {
8430 if (f
.subclass
!= iaxs
[fr
->callno
]->videoformat
) {
8431 ast_debug(1, "Ooh, video format changed to %d\n", f
.subclass
& ~0x1);
8432 iaxs
[fr
->callno
]->videoformat
= f
.subclass
& ~0x1;
8435 if (f
.frametype
== AST_FRAME_IAX
) {
8436 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->initid
);
8437 /* Handle the IAX pseudo frame itself */
8439 ast_debug(1, "IAX subclass %d received\n", f
.subclass
);
8441 /* Update last ts unless the frame's timestamp originated with us. */
8442 if (iaxs
[fr
->callno
]->last
< fr
->ts
&&
8443 f
.subclass
!= IAX_COMMAND_ACK
&&
8444 f
.subclass
!= IAX_COMMAND_PONG
&&
8445 f
.subclass
!= IAX_COMMAND_LAGRP
) {
8446 iaxs
[fr
->callno
]->last
= fr
->ts
;
8448 ast_debug(1, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
8451 switch(f
.subclass
) {
8452 case IAX_COMMAND_ACK
:
8455 case IAX_COMMAND_QUELCH
:
8456 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
8457 /* Generate Manager Hold event, if necessary*/
8458 if (iaxs
[fr
->callno
]->owner
) {
8459 manager_event(EVENT_FLAG_CALL
, "Hold",
8463 iaxs
[fr
->callno
]->owner
->name
,
8464 iaxs
[fr
->callno
]->owner
->uniqueid
);
8467 ast_set_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
8468 if (ies
.musiconhold
) {
8469 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
8470 const char *moh_suggest
= iaxs
[fr
->callno
]->mohsuggest
;
8471 iax2_queue_control_data(fr
->callno
, AST_CONTROL_HOLD
,
8472 S_OR(moh_suggest
, NULL
),
8473 !ast_strlen_zero(moh_suggest
) ? strlen(moh_suggest
) + 1 : 0);
8474 if (!iaxs
[fr
->callno
]) {
8475 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8482 case IAX_COMMAND_UNQUELCH
:
8483 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
8484 /* Generate Manager Unhold event, if necessary*/
8485 if (iaxs
[fr
->callno
]->owner
&& ast_test_flag(iaxs
[fr
->callno
], IAX_QUELCH
)) {
8486 manager_event(EVENT_FLAG_CALL
, "Hold",
8490 iaxs
[fr
->callno
]->owner
->name
,
8491 iaxs
[fr
->callno
]->owner
->uniqueid
);
8494 ast_clear_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
8495 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
8496 iax2_queue_control_data(fr
->callno
, AST_CONTROL_UNHOLD
, NULL
, 0);
8497 if (!iaxs
[fr
->callno
]) {
8498 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8504 case IAX_COMMAND_TXACC
:
8505 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) &&
8506 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
8507 /* Cancel any outstanding txcnt's */
8508 AST_LIST_LOCK(&frame_queue
);
8509 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
8510 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
))
8513 AST_LIST_UNLOCK(&frame_queue
);
8514 memset(&ied1
, 0, sizeof(ied1
));
8515 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->callno
);
8516 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, iaxs
[fr
->callno
]->transferid
);
8517 if (iaxs
[fr
->callno
]->mediareleased
) {
8518 send_command_media(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREADY
, 0, ied1
.buf
, ied1
.pos
);
8520 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREADY
, 0, ied1
.buf
, ied1
.pos
, -1);
8522 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
8525 case IAX_COMMAND_NEW
:
8526 /* Ignore if it's already up */
8527 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
))
8529 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
8530 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8531 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
8532 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8533 if (!iaxs
[fr
->callno
]) {
8534 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8538 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
8539 if (ast_test_flag(iaxs
[fr
->callno
], IAX_TRUNK
)) {
8541 if ((new_callno
= make_trunk(fr
->callno
, 1)) != -1)
8542 fr
->callno
= new_callno
;
8544 /* For security, always ack immediately */
8546 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8547 if (check_access(fr
->callno
, &sin
, &ies
)) {
8548 /* They're not allowed on */
8549 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
8551 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->exten
, iaxs
[fr
->callno
]->context
);
8554 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
8555 const char *context
, *exten
, *cid_num
;
8557 context
= ast_strdupa(iaxs
[fr
->callno
]->context
);
8558 exten
= ast_strdupa(iaxs
[fr
->callno
]->exten
);
8559 cid_num
= ast_strdupa(iaxs
[fr
->callno
]->cid_num
);
8561 /* This might re-enter the IAX code and need the lock */
8562 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8563 exists
= ast_exists_extension(NULL
, context
, exten
, 1, cid_num
);
8564 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8566 if (!iaxs
[fr
->callno
]) {
8567 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8572 /* Get OSP token if it does exist */
8573 save_osptoken(fr
, &ies
);
8574 if (ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) {
8575 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
8576 memset(&ied0
, 0, sizeof(ied0
));
8577 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
8578 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
8579 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8580 if (!iaxs
[fr
->callno
]) {
8581 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8585 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->exten
, iaxs
[fr
->callno
]->context
);
8587 /* Select an appropriate format */
8589 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
8590 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
8591 using_prefs
= "reqonly";
8593 using_prefs
= "disabled";
8595 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
8596 memset(&pref
, 0, sizeof(pref
));
8597 strcpy(caller_pref_buf
, "disabled");
8598 strcpy(host_pref_buf
, "disabled");
8600 using_prefs
= "mine";
8601 /* If the information elements are in here... use them */
8602 if (ies
.codec_prefs
)
8603 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
8604 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
8605 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
8606 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
8607 pref
= iaxs
[fr
->callno
]->rprefs
;
8608 using_prefs
= "caller";
8610 pref
= iaxs
[fr
->callno
]->prefs
;
8613 pref
= iaxs
[fr
->callno
]->prefs
;
8615 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
8616 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
8617 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
8620 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
8621 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
8623 memset(&ied0
, 0, sizeof(ied0
));
8624 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
8625 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
8626 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8627 if (!iaxs
[fr
->callno
]) {
8628 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8632 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
8633 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->capability
);
8635 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->peercapability
, iaxs
[fr
->callno
]->capability
);
8639 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
8640 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
8643 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
8644 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
8645 memset(&pref
, 0, sizeof(pref
));
8646 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8647 strcpy(caller_pref_buf
,"disabled");
8648 strcpy(host_pref_buf
,"disabled");
8650 using_prefs
= "mine";
8651 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
8652 /* Do the opposite of what we tried above. */
8653 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
8654 pref
= iaxs
[fr
->callno
]->prefs
;
8656 pref
= iaxs
[fr
->callno
]->rprefs
;
8657 using_prefs
= "caller";
8659 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
8661 } else /* if no codec_prefs IE do it the old way */
8662 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8667 memset(&ied0
, 0, sizeof(ied0
));
8668 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
8669 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
8670 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8671 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8672 if (!iaxs
[fr
->callno
]) {
8673 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8677 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->peercapability
, iaxs
[fr
->callno
]->capability
);
8678 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
8684 /* No authentication required, let them in */
8685 memset(&ied1
, 0, sizeof(ied1
));
8686 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
8687 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
8688 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
8689 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8690 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
8691 "%srequested format = %s,\n"
8692 "%srequested prefs = %s,\n"
8693 "%sactual format = %s,\n"
8694 "%shost prefs = %s,\n"
8695 "%spriority = %s\n",
8696 ast_inet_ntoa(sin
.sin_addr
),
8698 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
8702 ast_getformatname(format
),
8708 iaxs
[fr
->callno
]->chosenformat
= format
;
8709 ast_set_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
8711 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
8712 /* If this is a TBD call, we're ready but now what... */
8713 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
8719 if (iaxs
[fr
->callno
]->authmethods
& IAX_AUTH_MD5
)
8720 merge_encryption(iaxs
[fr
->callno
],ies
.encmethods
);
8722 iaxs
[fr
->callno
]->encmethods
= 0;
8723 if (!authenticate_request(fr
->callno
) && iaxs
[fr
->callno
])
8724 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
);
8725 if (!iaxs
[fr
->callno
]) {
8726 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8730 case IAX_COMMAND_DPREQ
:
8731 /* Request status in the dialplan */
8732 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
) &&
8733 !ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
) && ies
.called_number
) {
8735 /* Spawn a thread for the lookup */
8736 spawn_dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
);
8738 /* Just look it up */
8739 dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
, 1);
8743 case IAX_COMMAND_HANGUP
:
8744 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
8745 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr
->callno
);
8746 /* Set hangup cause according to remote */
8747 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
8748 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
8749 /* Send ack immediately, before we destroy */
8750 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8751 iax2_destroy(fr
->callno
);
8753 case IAX_COMMAND_REJECT
:
8754 /* Set hangup cause according to remote */
8755 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
8756 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
8758 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
8759 if (iaxs
[fr
->callno
]->owner
&& authdebug
)
8760 ast_log(LOG_WARNING
, "Call rejected by %s: %s\n",
8761 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
),
8762 ies
.cause
? ies
.cause
: "<Unknown>");
8763 ast_debug(1, "Immediately destroying %d, having received reject\n",
8766 /* Send ack immediately, before we destroy */
8767 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
,
8768 fr
->ts
, NULL
, 0, fr
->iseqno
);
8769 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
))
8770 iaxs
[fr
->callno
]->error
= EPERM
;
8771 iax2_destroy(fr
->callno
);
8773 case IAX_COMMAND_TRANSFER
:
8775 struct ast_channel
*bridged_chan
;
8777 if (iaxs
[fr
->callno
]->owner
&& (bridged_chan
= ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) && ies
.called_number
) {
8778 /* Set BLINDTRANSFER channel variables */
8780 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8781 pbx_builtin_setvar_helper(iaxs
[fr
->callno
]->owner
, "BLINDTRANSFER", bridged_chan
->name
);
8782 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8783 if (!iaxs
[fr
->callno
]) {
8784 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8788 pbx_builtin_setvar_helper(bridged_chan
, "BLINDTRANSFER", iaxs
[fr
->callno
]->owner
->name
);
8789 if (!strcmp(ies
.called_number
, ast_parking_ext())) {
8790 struct ast_channel
*saved_channel
= iaxs
[fr
->callno
]->owner
;
8791 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8792 if (iax_park(bridged_chan
, saved_channel
)) {
8793 ast_log(LOG_WARNING
, "Failed to park call on '%s'\n", bridged_chan
->name
);
8795 ast_debug(1, "Parked call on '%s'\n", ast_bridged_channel(iaxs
[fr
->callno
]->owner
)->name
);
8797 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8799 if (ast_async_goto(bridged_chan
, iaxs
[fr
->callno
]->context
, ies
.called_number
, 1))
8800 ast_log(LOG_WARNING
, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan
->name
,
8801 ies
.called_number
, iaxs
[fr
->callno
]->context
);
8803 ast_debug(1, "Async goto of '%s' to '%s@%s' started\n", bridged_chan
->name
,
8804 ies
.called_number
, iaxs
[fr
->callno
]->context
);
8808 ast_debug(1, "Async goto not applicable on call %d\n", fr
->callno
);
8813 case IAX_COMMAND_ACCEPT
:
8814 /* Ignore if call is already up or needs authentication or is a TBD */
8815 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
| IAX_STATE_AUTHENTICATED
))
8817 if (ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
8818 /* Send ack immediately, before we destroy */
8819 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8820 iax2_destroy(fr
->callno
);
8824 iaxs
[fr
->callno
]->peerformat
= ies
.format
;
8826 if (iaxs
[fr
->callno
]->owner
)
8827 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->owner
->nativeformats
;
8829 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->capability
;
8831 ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), ast_getformatname(iaxs
[fr
->callno
]->peerformat
));
8832 if (!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
)) {
8833 memset(&ied0
, 0, sizeof(ied0
));
8834 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
8835 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
8836 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8837 if (!iaxs
[fr
->callno
]) {
8838 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8842 ast_log(LOG_NOTICE
, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->capability
);
8844 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8845 if (iaxs
[fr
->callno
]->owner
) {
8846 /* Switch us to use a compatible format */
8847 iaxs
[fr
->callno
]->owner
->nativeformats
= iaxs
[fr
->callno
]->peerformat
;
8848 ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs
[fr
->callno
]->owner
->nativeformats
));
8850 if (ast_channel_trylock(iaxs
[fr
->callno
]->owner
)) {
8851 DEADLOCK_AVOIDANCE(&iaxsl
[fr
->callno
]);
8852 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner2
;
8855 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) {
8856 /* Setup read/write formats properly. */
8857 if (iaxs
[fr
->callno
]->owner
->writeformat
)
8858 ast_set_write_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->writeformat
);
8859 if (iaxs
[fr
->callno
]->owner
->readformat
)
8860 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
8861 ast_channel_unlock(iaxs
[fr
->callno
]->owner
);
8865 if (iaxs
[fr
->callno
]) {
8866 AST_LIST_LOCK(&dpcache
);
8867 AST_LIST_TRAVERSE(&iaxs
[fr
->callno
]->dpentries
, dp
, peer_list
)
8868 if (!(dp
->flags
& CACHE_FLAG_TRANSMITTED
))
8869 iax2_dprequest(dp
, fr
->callno
);
8870 AST_LIST_UNLOCK(&dpcache
);
8873 case IAX_COMMAND_POKE
:
8874 /* Send back a pong packet with the original timestamp */
8875 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, NULL
, 0, -1);
8876 if (!iaxs
[fr
->callno
]) {
8877 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8881 case IAX_COMMAND_PING
:
8883 struct iax_ie_data pingied
;
8884 construct_rr(iaxs
[fr
->callno
], &pingied
);
8885 /* Send back a pong packet with the original timestamp */
8886 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, pingied
.buf
, pingied
.pos
, -1);
8889 case IAX_COMMAND_PONG
:
8890 /* Calculate ping time */
8891 iaxs
[fr
->callno
]->pingtime
= calc_timestamp(iaxs
[fr
->callno
], 0, &f
) - fr
->ts
;
8895 /* Good time to write jb stats for this call */
8896 log_jitterstats(fr
->callno
);
8898 if (iaxs
[fr
->callno
]->peerpoke
) {
8899 peer
= iaxs
[fr
->callno
]->peerpoke
;
8900 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
)) {
8901 if (iaxs
[fr
->callno
]->pingtime
<= peer
->maxms
) {
8902 ast_log(LOG_NOTICE
, "Peer '%s' is now REACHABLE! Time: %d\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
8903 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
8904 ast_devstate_changed(AST_DEVICE_NOT_INUSE
, "IAX2/%s", peer
->name
); /* Activate notification */
8906 } else if ((peer
->historicms
> 0) && (peer
->historicms
<= peer
->maxms
)) {
8907 if (iaxs
[fr
->callno
]->pingtime
> peer
->maxms
) {
8908 ast_log(LOG_NOTICE
, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
8909 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
8910 ast_devstate_changed(AST_DEVICE_UNAVAILABLE
, "IAX2/%s", peer
->name
); /* Activate notification */
8913 peer
->lastms
= iaxs
[fr
->callno
]->pingtime
;
8914 if (peer
->smoothing
&& (peer
->lastms
> -1))
8915 peer
->historicms
= (iaxs
[fr
->callno
]->pingtime
+ peer
->historicms
) / 2;
8916 else if (peer
->smoothing
&& peer
->lastms
< 0)
8917 peer
->historicms
= (0 + peer
->historicms
) / 2;
8919 peer
->historicms
= iaxs
[fr
->callno
]->pingtime
;
8921 /* Remove scheduled iax2_poke_noanswer */
8922 if (peer
->pokeexpire
> -1) {
8923 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
8925 peer
->pokeexpire
= -1;
8928 /* Schedule the next cycle */
8929 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
))
8930 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
8932 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqok
, iax2_poke_peer_s
, peer_ref(peer
));
8933 if (peer
->pokeexpire
== -1)
8935 /* and finally send the ack */
8936 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8937 /* And wrap up the qualify call */
8938 iax2_destroy(fr
->callno
);
8940 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer
->name
, peer
->lastms
, peer
->historicms
, peer
->maxms
);
8943 case IAX_COMMAND_LAGRQ
:
8944 case IAX_COMMAND_LAGRP
:
8949 iax_frame_wrap(fr
, &f
);
8950 if(f
.subclass
== IAX_COMMAND_LAGRQ
) {
8951 /* Received a LAGRQ - echo back a LAGRP */
8952 fr
->af
.subclass
= IAX_COMMAND_LAGRP
;
8953 iax2_send(iaxs
[fr
->callno
], &fr
->af
, fr
->ts
, -1, 0, 0, 0, 0);
8955 /* Received LAGRP in response to our LAGRQ */
8957 /* This is a reply we've been given, actually measure the difference */
8958 ts
= calc_timestamp(iaxs
[fr
->callno
], 0, &fr
->af
);
8959 iaxs
[fr
->callno
]->lag
= ts
- fr
->ts
;
8961 ast_debug(1, "Peer %s lag measured as %dms\n",
8962 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), iaxs
[fr
->callno
]->lag
);
8965 case IAX_COMMAND_AUTHREQ
:
8966 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
8967 ast_log(LOG_WARNING
, "Call on %s is already up, can't start on it\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8970 if (authenticate_reply(iaxs
[fr
->callno
], &iaxs
[fr
->callno
]->addr
, &ies
, iaxs
[fr
->callno
]->secret
, iaxs
[fr
->callno
]->outkey
)) {
8971 struct ast_frame hangup_fr
= { .frametype
= AST_FRAME_CONTROL
,
8972 .subclass
= AST_CONTROL_HANGUP
,
8974 ast_log(LOG_WARNING
,
8975 "I don't know how to authenticate %s to %s\n",
8976 ies
.username
? ies
.username
: "<unknown>", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
));
8977 iax2_queue_frame(fr
->callno
, &hangup_fr
);
8979 if (!iaxs
[fr
->callno
]) {
8980 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8984 case IAX_COMMAND_AUTHREP
:
8985 /* For security, always ack immediately */
8987 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8988 /* Ignore once we've started */
8989 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
8990 ast_log(LOG_WARNING
, "Call on %s is already up, can't start on it\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8993 if (authenticate_verify(iaxs
[fr
->callno
], &ies
)) {
8995 ast_log(LOG_NOTICE
, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), iaxs
[fr
->callno
]->username
);
8996 memset(&ied0
, 0, sizeof(ied0
));
8997 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
9000 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
9001 /* This might re-enter the IAX code and need the lock */
9002 exists
= ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
);
9005 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
9007 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->exten
, iaxs
[fr
->callno
]->context
);
9008 memset(&ied0
, 0, sizeof(ied0
));
9009 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
9010 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
9011 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9012 if (!iaxs
[fr
->callno
]) {
9013 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9017 /* Select an appropriate format */
9018 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
9019 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
9020 using_prefs
= "reqonly";
9022 using_prefs
= "disabled";
9024 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
9025 memset(&pref
, 0, sizeof(pref
));
9026 strcpy(caller_pref_buf
, "disabled");
9027 strcpy(host_pref_buf
, "disabled");
9029 using_prefs
= "mine";
9030 if (ies
.codec_prefs
)
9031 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
9032 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
9033 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
9034 pref
= iaxs
[fr
->callno
]->rprefs
;
9035 using_prefs
= "caller";
9037 pref
= iaxs
[fr
->callno
]->prefs
;
9039 } else /* if no codec_prefs IE do it the old way */
9040 pref
= iaxs
[fr
->callno
]->prefs
;
9042 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
9043 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
9044 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
9047 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
9048 ast_debug(1, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs
[fr
->callno
]->peerformat
), iaxs
[fr
->callno
]->peercapability
);
9049 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
9053 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
9054 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->capability
);
9056 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->peercapability
, iaxs
[fr
->callno
]->capability
);
9058 memset(&ied0
, 0, sizeof(ied0
));
9059 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
9060 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
9061 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9062 if (!iaxs
[fr
->callno
]) {
9063 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9068 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
9069 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
9072 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
9073 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
9074 memset(&pref
, 0, sizeof(pref
));
9075 format
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ?
9076 iaxs
[fr
->callno
]->peerformat
: ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
9077 strcpy(caller_pref_buf
,"disabled");
9078 strcpy(host_pref_buf
,"disabled");
9080 using_prefs
= "mine";
9081 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
9082 /* Do the opposite of what we tried above. */
9083 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
9084 pref
= iaxs
[fr
->callno
]->prefs
;
9086 pref
= iaxs
[fr
->callno
]->rprefs
;
9087 using_prefs
= "caller";
9089 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
9090 } else /* if no codec_prefs IE do it the old way */
9091 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
9095 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
9097 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
9098 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->capability
);
9100 ast_log(LOG_NOTICE
, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
, iaxs
[fr
->callno
]->peercapability
, iaxs
[fr
->callno
]->capability
);
9102 memset(&ied0
, 0, sizeof(ied0
));
9103 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
9104 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
9105 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9106 if (!iaxs
[fr
->callno
]) {
9107 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9114 /* Authentication received */
9115 memset(&ied1
, 0, sizeof(ied1
));
9116 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
9117 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
9118 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
9119 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
9120 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
9121 "%srequested format = %s,\n"
9122 "%srequested prefs = %s,\n"
9123 "%sactual format = %s,\n"
9124 "%shost prefs = %s,\n"
9125 "%spriority = %s\n",
9126 ast_inet_ntoa(sin
.sin_addr
),
9128 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
9132 ast_getformatname(format
),
9138 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
9139 if (!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, format
)))
9140 iax2_destroy(fr
->callno
);
9141 else if (ies
.vars
) {
9142 struct ast_datastore
*variablestore
;
9143 struct ast_variable
*var
, *prev
= NULL
;
9144 AST_LIST_HEAD(, ast_var_t
) *varlist
;
9145 varlist
= ast_calloc(1, sizeof(*varlist
));
9146 variablestore
= ast_datastore_alloc(&iax2_variable_datastore_info
, NULL
);
9147 if (variablestore
&& varlist
) {
9148 variablestore
->data
= varlist
;
9149 variablestore
->inheritance
= DATASTORE_INHERIT_FOREVER
;
9150 AST_LIST_HEAD_INIT(varlist
);
9151 for (var
= ies
.vars
; var
; var
= var
->next
) {
9152 struct ast_var_t
*newvar
= ast_var_assign(var
->name
, var
->value
);
9157 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
9158 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
9160 AST_LIST_INSERT_TAIL(varlist
, newvar
, entries
);
9166 ast_channel_datastore_add(c
, variablestore
);
9168 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
9170 ast_datastore_free(variablestore
);
9176 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
9177 /* If this is a TBD call, we're ready but now what... */
9178 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
9183 case IAX_COMMAND_DIAL
:
9184 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
)) {
9185 ast_clear_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
9186 ast_string_field_set(iaxs
[fr
->callno
], exten
, ies
.called_number
? ies
.called_number
: "s");
9187 if (!ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
)) {
9189 ast_log(LOG_NOTICE
, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->exten
, iaxs
[fr
->callno
]->context
);
9190 memset(&ied0
, 0, sizeof(ied0
));
9191 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
9192 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
9193 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9194 if (!iaxs
[fr
->callno
]) {
9195 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9199 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
9200 ast_verb(3, "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
);
9201 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
9202 send_command(iaxs
[fr
->callno
], AST_FRAME_CONTROL
, AST_CONTROL_PROGRESS
, 0, NULL
, 0, -1);
9203 if (!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->peerformat
)))
9204 iax2_destroy(fr
->callno
);
9205 else if (ies
.vars
) {
9206 struct ast_datastore
*variablestore
;
9207 struct ast_variable
*var
, *prev
= NULL
;
9208 AST_LIST_HEAD(, ast_var_t
) *varlist
;
9209 varlist
= ast_calloc(1, sizeof(*varlist
));
9210 variablestore
= ast_datastore_alloc(&iax2_variable_datastore_info
, NULL
);
9211 if (variablestore
&& varlist
) {
9212 variablestore
->data
= varlist
;
9213 variablestore
->inheritance
= DATASTORE_INHERIT_FOREVER
;
9214 AST_LIST_HEAD_INIT(varlist
);
9215 for (var
= ies
.vars
; var
; var
= var
->next
) {
9216 struct ast_var_t
*newvar
= ast_var_assign(var
->name
, var
->value
);
9221 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
9222 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
9224 AST_LIST_INSERT_TAIL(varlist
, newvar
, entries
);
9230 ast_channel_datastore_add(c
, variablestore
);
9232 ast_log(LOG_ERROR
, "Memory allocation error while processing IAX2 variables\n");
9234 ast_datastore_free(variablestore
);
9242 case IAX_COMMAND_INVAL
:
9243 iaxs
[fr
->callno
]->error
= ENOTCONN
;
9244 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr
->callno
);
9245 iax2_destroy(fr
->callno
);
9246 ast_debug(1, "Destroying call %d\n", fr
->callno
);
9248 case IAX_COMMAND_VNAK
:
9249 ast_debug(1, "Received VNAK: resending outstanding frames\n");
9250 /* Force retransmission */
9251 vnak_retransmit(fr
->callno
, fr
->iseqno
);
9253 case IAX_COMMAND_REGREQ
:
9254 case IAX_COMMAND_REGREL
:
9255 /* For security, always ack immediately */
9257 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9258 if (register_verify(fr
->callno
, &sin
, &ies
)) {
9259 if (!iaxs
[fr
->callno
]) {
9260 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9263 /* Send delayed failure */
9264 auth_fail(fr
->callno
, IAX_COMMAND_REGREJ
);
9267 if (!iaxs
[fr
->callno
]) {
9268 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9271 if ((ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) ||
9272 ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
)) {
9273 if (f
.subclass
== IAX_COMMAND_REGREL
)
9274 memset(&sin
, 0, sizeof(sin
));
9275 if (update_registry(&sin
, fr
->callno
, ies
.devicetype
, fd
, ies
.refresh
))
9276 ast_log(LOG_WARNING
, "Registry error\n");
9277 if (!iaxs
[fr
->callno
]) {
9278 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9281 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
9282 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9283 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
9284 ast_mutex_lock(&iaxsl
[fr
->callno
]);
9285 if (!iaxs
[fr
->callno
]) {
9286 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9292 registry_authrequest(fr
->callno
);
9293 if (!iaxs
[fr
->callno
]) {
9294 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9298 case IAX_COMMAND_REGACK
:
9299 if (iax2_ack_registry(&ies
, &sin
, fr
->callno
))
9300 ast_log(LOG_WARNING
, "Registration failure\n");
9301 /* Send ack immediately, before we destroy */
9302 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9303 iax2_destroy(fr
->callno
);
9305 case IAX_COMMAND_REGREJ
:
9306 if (iaxs
[fr
->callno
]->reg
) {
9308 ast_log(LOG_NOTICE
, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs
[fr
->callno
]->reg
->username
, ies
.cause
? ies
.cause
: "<unknown>", ast_inet_ntoa(sin
.sin_addr
));
9309 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs
[fr
->callno
]->reg
->username
, ies
.cause
? ies
.cause
: "<unknown>");
9311 iaxs
[fr
->callno
]->reg
->regstate
= REG_STATE_REJECTED
;
9313 /* Send ack immediately, before we destroy */
9314 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9315 iax2_destroy(fr
->callno
);
9317 case IAX_COMMAND_REGAUTH
:
9318 /* Authentication request */
9319 if (registry_rerequest(&ies
, fr
->callno
, &sin
)) {
9320 memset(&ied0
, 0, sizeof(ied0
));
9321 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No authority found");
9322 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
9323 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9324 if (!iaxs
[fr
->callno
]) {
9325 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9330 case IAX_COMMAND_TXREJ
:
9331 if ((iaxs
[fr
->callno
]->transferring
!= TRANSFER_NONE
) &&
9332 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
9333 iaxs
[fr
->callno
]->transferring
= TRANSFER_NONE
;
9334 ast_verb(3, "Channel '%s' transfer rejected\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
9335 memset(&iaxs
[fr
->callno
]->transfer
, 0, sizeof(iaxs
[fr
->callno
]->transfer
));
9336 if (iaxs
[fr
->callno
]->bridgecallno
&&
9337 (iaxs
[fr
->callno
]->transferid
== iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
)) {
9338 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_NONE
;
9339 memset(&ied0
, 0, sizeof(ied0
));
9340 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
);
9341 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->mediareleased
) {
9342 send_command_media(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied0
.buf
, ied0
.pos
);
9344 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied0
.buf
, ied0
.pos
, -1);
9349 case IAX_COMMAND_TXREADY
:
9350 if (((iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) ||
9351 (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)) &&
9352 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
9353 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)
9354 iaxs
[fr
->callno
]->transferring
= TRANSFER_MREADY
;
9356 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
9357 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
9358 if (iaxs
[fr
->callno
]->bridgecallno
) {
9359 if ((iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_READY
) ||
9360 (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_MREADY
)) {
9361 /* They're both ready, now release them. */
9362 /* If a peer is media released, we must also do a media release as there may be peers in between */
9363 if (iaxs
[fr
->callno
]->mediareleased
||
9364 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->mediareleased
||
9365 (iaxs
[fr
->callno
]->transferring
== TRANSFER_MREADY
)) {
9367 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
9368 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
9370 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_MRELEASED
;
9371 iaxs
[fr
->callno
]->transferring
= TRANSFER_MRELEASED
;
9373 memset(&ied0
, 0, sizeof(ied0
));
9374 memset(&ied1
, 0, sizeof(ied1
));
9375 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
9376 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
);
9377 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
9378 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, iaxs
[fr
->callno
]->transferid
);
9379 if (iaxs
[fr
->callno
]->mediareleased
) {
9380 send_command_media(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied0
.buf
, ied0
.pos
);
9382 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied0
.buf
, ied0
.pos
, -1);
9384 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->mediareleased
) {
9385 send_command_media(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied1
.buf
, ied1
.pos
);
9387 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied1
.buf
, ied1
.pos
, -1);
9390 ast_verb(3, "Releasing %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
9391 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
9393 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_RELEASED
;
9394 iaxs
[fr
->callno
]->transferring
= TRANSFER_RELEASED
;
9395 ast_set_flag(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], IAX_ALREADYGONE
);
9396 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
9398 /* Stop doing lag & ping requests */
9399 stop_stuff(fr
->callno
);
9400 stop_stuff(iaxs
[fr
->callno
]->bridgecallno
);
9402 memset(&ied0
, 0, sizeof(ied0
));
9403 memset(&ied1
, 0, sizeof(ied1
));
9404 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
9405 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
);
9406 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
9407 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, iaxs
[fr
->callno
]->transferid
);
9408 if (iaxs
[fr
->callno
]->mediareleased
) {
9409 send_command_media(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied0
.buf
, ied0
.pos
);
9411 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied0
.buf
, ied0
.pos
, -1);
9413 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->mediareleased
) {
9414 send_command_media(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied1
.buf
, ied1
.pos
);
9416 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied1
.buf
, ied1
.pos
, -1);
9424 case IAX_COMMAND_TXREQ
:
9425 /* Try transfer only if none in progress, or use the transferid to resolve contention */
9426 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_NONE
) ||
9427 (iaxs
[fr
->callno
]->transferid
<= ies
.transferid
)) {
9428 /* If there is a bridged channel and it is the same transfer, reject it */
9429 if (iaxs
[fr
->callno
]->bridgecallno
&&
9430 (iaxs
[fr
->callno
]->transferid
== iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
)) {
9431 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_NONE
;
9432 memset(&ied0
, 0, sizeof(ied0
));
9433 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferid
);
9434 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->mediareleased
) {
9435 send_command_media(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied0
.buf
, ied0
.pos
);
9437 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, ied0
.buf
, ied0
.pos
, -1);
9439 /* Start our transfer again later */
9440 iaxs
[fr
->callno
]->triedtransfer
= 0;
9441 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->triedtransfer
= 0;
9443 try_transfer(iaxs
[fr
->callno
], &ies
);
9447 case IAX_COMMAND_TXCNT
:
9448 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) &&
9449 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
9450 memcpy(&iaxs
[fr
->callno
]->transfer
, &sin
, sizeof(iaxs
[fr
->callno
]->transfer
));
9451 memset(&ied0
, 0, sizeof(ied0
));
9452 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, iaxs
[fr
->callno
]->transferid
);
9453 send_command_transfer(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXACC
, 0, ied0
.buf
, ied0
.pos
);
9456 case IAX_COMMAND_TXREL
:
9457 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_READY
) &&
9458 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
9459 /* Send ack immediately, rather than waiting until we've changed addresses */
9460 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9461 complete_transfer(fr
->callno
, &ies
);
9462 stop_stuff(fr
->callno
); /* for attended transfer to work with libiax */
9465 case IAX_COMMAND_TXMEDIA
:
9466 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_READY
) &&
9467 (iaxs
[fr
->callno
]->transferid
== ies
.transferid
)) {
9469 AST_LIST_LOCK(&frame_queue
);
9470 AST_LIST_TRAVERSE(&frame_queue
, cur
, list
) {
9471 /* Cancel any outstanding frames and start anew */
9472 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
))
9475 AST_LIST_UNLOCK(&frame_queue
);
9476 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
9477 memcpy(&iaxs
[fr
->callno
]->media
, &iaxs
[fr
->callno
]->transfer
, sizeof(iaxs
[fr
->callno
]->addr
));
9478 memset(&iaxs
[fr
->callno
]->transfer
, 0, sizeof(iaxs
[fr
->callno
]->transfer
));
9479 iaxs
[fr
->callno
]->transferring
= TRANSFER_NONE
;
9480 iaxs
[fr
->callno
]->mediareleased
= 1;
9483 case IAX_COMMAND_RTKEY
:
9484 if (!IAX_CALLENCRYPTED(iaxs
[fr
->callno
])) {
9485 ast_log(LOG_WARNING
,
9486 "we've been told to rotate our encryption key, "
9487 "but this isn't an encrypted call. bad things will happen.\n"
9492 IAX_DEBUGDIGEST("Receiving", ies
.challenge
);
9494 ast_aes_decrypt_key((unsigned char *) ies
.challenge
, &iaxs
[fr
->callno
]->dcx
);
9496 case IAX_COMMAND_DPREP
:
9497 complete_dpreply(iaxs
[fr
->callno
], &ies
);
9499 case IAX_COMMAND_UNSUPPORT
:
9500 ast_log(LOG_NOTICE
, "Peer did not understand our iax command '%d'\n", ies
.iax_unknown
);
9502 case IAX_COMMAND_FWDOWNL
:
9503 /* Firmware download */
9504 if (!ast_test_flag(&globalflags
, IAX_ALLOWFWDOWNLOAD
)) {
9505 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_UNSUPPORT
, 0, NULL
, 0, -1);
9508 memset(&ied0
, 0, sizeof(ied0
));
9509 res
= iax_firmware_append(&ied0
, (unsigned char *)ies
.devicetype
, ies
.fwdesc
);
9511 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
9513 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
9515 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
9516 if (!iaxs
[fr
->callno
]) {
9517 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9522 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f
.subclass
, fr
->callno
, iaxs
[fr
->callno
]->peercallno
);
9523 memset(&ied0
, 0, sizeof(ied0
));
9524 iax_ie_append_byte(&ied0
, IAX_IE_IAX_UNKNOWN
, f
.subclass
);
9525 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_UNSUPPORT
, 0, ied0
.buf
, ied0
.pos
, -1);
9527 /* Free remote variables (if any) */
9529 ast_variables_destroy(ies
.vars
);
9531 /* Don't actually pass these frames along */
9532 if ((f
.subclass
!= IAX_COMMAND_ACK
) &&
9533 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
9534 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
9535 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
9536 (f
.subclass
!= IAX_COMMAND_VNAK
)) {
9537 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
9538 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9540 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9543 /* Unless this is an ACK or INVAL frame, ack it */
9544 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
9545 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
9546 } else if (minivid
) {
9547 f
.frametype
= AST_FRAME_VIDEO
;
9548 if (iaxs
[fr
->callno
]->videoformat
> 0)
9549 f
.subclass
= iaxs
[fr
->callno
]->videoformat
| (ntohs(vh
->ts
) & 0x8000 ? 1 : 0);
9551 ast_log(LOG_WARNING
, "Received mini frame before first full video frame\n");
9552 iax2_vnak(fr
->callno
);
9553 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9556 f
.datalen
= res
- sizeof(*vh
);
9558 f
.data
.ptr
= thread
->buf
+ sizeof(*vh
);
9563 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | ((ntohs(vh
->ts
) + test_resync
) & 0x7fff);
9565 #endif /* IAXTESTS */
9566 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | (ntohs(vh
->ts
) & 0x7fff);
9569 f
.frametype
= AST_FRAME_VOICE
;
9570 if (iaxs
[fr
->callno
]->voiceformat
> 0)
9571 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
9573 ast_debug(1, "Received mini frame before first full voice frame\n");
9574 iax2_vnak(fr
->callno
);
9575 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9578 f
.datalen
= res
- sizeof(struct ast_iax2_mini_hdr
);
9579 if (f
.datalen
< 0) {
9580 ast_log(LOG_WARNING
, "Datalen < 0?\n");
9581 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9585 f
.data
.ptr
= thread
->buf
+ sizeof(*mh
);
9590 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ((ntohs(mh
->ts
) + test_resync
) & 0xffff);
9592 #endif /* IAXTESTS */
9593 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ntohs(mh
->ts
);
9594 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
9596 /* Don't pass any packets until we're started */
9597 if (!ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
9598 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9606 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
)) {
9607 f
.samples
= ast_codec_get_samples(&f
);
9608 /* We need to byteswap incoming slinear samples from network byte order */
9609 if (f
.subclass
== AST_FORMAT_SLINEAR
)
9610 ast_frame_byteswap_be(&f
);
9613 iax_frame_wrap(fr
, &f
);
9615 /* If this is our most recent packet, use it as our basis for timestamping */
9616 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
9617 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
9620 if (iaxdebug
&& iaxs
[fr
->callno
])
9621 ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f
.frametype
, f
.subclass
, fr
->ts
, iaxs
[fr
->callno
]->last
);
9622 fr
->outoforder
= -1;
9624 fr
->cacheable
= ((f
.frametype
== AST_FRAME_VOICE
) || (f
.frametype
== AST_FRAME_VIDEO
));
9625 duped_fr
= iaxfrdup2(fr
);
9627 schedule_delivery(duped_fr
, updatehistory
, 0, &fr
->ts
);
9629 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
9630 iaxs
[fr
->callno
]->last
= fr
->ts
;
9633 ast_debug(1, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
9636 /* Always run again */
9637 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
9641 /* Function to clean up process thread if it is cancelled */
9642 static void iax2_process_thread_cleanup(void *data
)
9644 struct iax2_thread
*thread
= data
;
9645 ast_mutex_destroy(&thread
->lock
);
9646 ast_cond_destroy(&thread
->cond
);
9648 ast_atomic_dec_and_test(&iaxactivethreadcount
);
9651 static void *iax2_process_thread(void *data
)
9653 struct iax2_thread
*thread
= data
;
9654 struct timeval wait
;
9656 int put_into_idle
= 0;
9658 ast_atomic_fetchadd_int(&iaxactivethreadcount
,1);
9659 pthread_cleanup_push(iax2_process_thread_cleanup
, data
);
9661 /* Wait for something to signal us to be awake */
9662 ast_mutex_lock(&thread
->lock
);
9664 /* Flag that we're ready to accept signals */
9665 thread
->ready_for_signal
= 1;
9667 /* Put into idle list if applicable */
9669 insert_idle_thread(thread
);
9671 if (thread
->type
== IAX_THREAD_TYPE_DYNAMIC
) {
9672 struct iax2_thread
*t
= NULL
;
9673 /* Wait to be signalled or time out */
9674 wait
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
9675 ts
.tv_sec
= wait
.tv_sec
;
9676 ts
.tv_nsec
= wait
.tv_usec
* 1000;
9677 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
) {
9678 /* This thread was never put back into the available dynamic
9679 * thread list, so just go away. */
9680 if (!put_into_idle
) {
9681 ast_mutex_unlock(&thread
->lock
);
9684 AST_LIST_LOCK(&dynamic_list
);
9685 /* Account for the case where this thread is acquired *right* after a timeout */
9686 if ((t
= AST_LIST_REMOVE(&dynamic_list
, thread
, list
)))
9687 ast_atomic_fetchadd_int(&iaxdynamicthreadcount
, -1);
9688 AST_LIST_UNLOCK(&dynamic_list
);
9690 /* This dynamic thread timed out waiting for a task and was
9691 * not acquired immediately after the timeout,
9692 * so it's time to go away. */
9693 ast_mutex_unlock(&thread
->lock
);
9696 /* Someone grabbed our thread *right* after we timed out.
9697 * Wait for them to set us up with something to do and signal
9698 * us to continue. */
9699 wait
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
9700 ts
.tv_sec
= wait
.tv_sec
;
9701 ts
.tv_nsec
= wait
.tv_usec
* 1000;
9702 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
)
9704 ast_mutex_unlock(&thread
->lock
);
9709 ast_cond_wait(&thread
->cond
, &thread
->lock
);
9712 /* Go back into our respective list */
9715 ast_mutex_unlock(&thread
->lock
);
9717 if (thread
->iostate
== IAX_IOSTATE_IDLE
)
9720 /* Add ourselves to the active list now */
9721 AST_LIST_LOCK(&active_list
);
9722 AST_LIST_INSERT_HEAD(&active_list
, thread
, list
);
9723 AST_LIST_UNLOCK(&active_list
);
9725 /* See what we need to do */
9726 switch(thread
->iostate
) {
9727 case IAX_IOSTATE_READY
:
9729 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
9730 socket_process(thread
);
9731 handle_deferred_full_frames(thread
);
9733 case IAX_IOSTATE_SCHEDREADY
:
9735 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
9736 #ifdef SCHED_MULTITHREADED
9737 thread
->schedfunc(thread
->scheddata
);
9742 time(&thread
->checktime
);
9743 thread
->iostate
= IAX_IOSTATE_IDLE
;
9744 #ifdef DEBUG_SCHED_MULTITHREAD
9745 thread
->curfunc
[0]='\0';
9748 /* Now... remove ourselves from the active list, and return to the idle list */
9749 AST_LIST_LOCK(&active_list
);
9750 AST_LIST_REMOVE(&active_list
, thread
, list
);
9751 AST_LIST_UNLOCK(&active_list
);
9753 /* Make sure another frame didn't sneak in there after we thought we were done. */
9754 handle_deferred_full_frames(thread
);
9757 /*!\note For some reason, idle threads are exiting without being removed
9758 * from an idle list, which is causing memory corruption. Forcibly remove
9759 * it from the list, if it's there.
9761 AST_LIST_LOCK(&idle_list
);
9762 AST_LIST_REMOVE(&idle_list
, thread
, list
);
9763 AST_LIST_UNLOCK(&idle_list
);
9765 AST_LIST_LOCK(&dynamic_list
);
9766 AST_LIST_REMOVE(&dynamic_list
, thread
, list
);
9767 AST_LIST_UNLOCK(&dynamic_list
);
9769 /* I am exiting here on my own volition, I need to clean up my own data structures
9770 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
9772 pthread_cleanup_pop(1);
9776 static int iax2_do_register(struct iax2_registry
*reg
)
9778 struct iax_ie_data ied
;
9780 ast_debug(1, "Sending registration request for '%s'\n", reg
->username
);
9783 ((reg
->regstate
== REG_STATE_TIMEOUT
) || !reg
->addr
.sin_addr
.s_addr
)) {
9784 /* Maybe the IP has changed, force DNS refresh */
9785 ast_dnsmgr_refresh(reg
->dnsmgr
);
9789 * if IP has Changed, free allocated call to create a new one with new IP
9790 * call has the pointer to IP and must be updated to the new one
9792 if (reg
->dnsmgr
&& ast_dnsmgr_changed(reg
->dnsmgr
) && (reg
->callno
> 0)) {
9793 int callno
= reg
->callno
;
9794 ast_mutex_lock(&iaxsl
[callno
]);
9795 iax2_destroy(callno
);
9796 ast_mutex_unlock(&iaxsl
[callno
]);
9799 if (!reg
->addr
.sin_addr
.s_addr
) {
9801 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg
->username
);
9802 /* Setup the next registration attempt */
9803 reg
->expire
= iax2_sched_replace(reg
->expire
, sched
,
9804 (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
9809 ast_debug(3, "Allocate call number\n");
9810 reg
->callno
= find_callno_locked(0, 0, ®
->addr
, NEW_FORCE
, defaultsockfd
, 0);
9811 if (reg
->callno
< 1) {
9812 ast_log(LOG_WARNING
, "Unable to create call for registration\n");
9815 ast_debug(3, "Registration created on call %d\n", reg
->callno
);
9816 iaxs
[reg
->callno
]->reg
= reg
;
9817 ast_mutex_unlock(&iaxsl
[reg
->callno
]);
9819 /* Setup the next registration a little early */
9820 reg
->expire
= iax2_sched_replace(reg
->expire
, sched
,
9821 (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
9822 /* Send the request */
9823 memset(&ied
, 0, sizeof(ied
));
9824 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
9825 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
9826 send_command(iaxs
[reg
->callno
],AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
9827 reg
->regstate
= REG_STATE_REGSENT
;
9831 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
)
9833 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
9834 is found for template */
9835 struct iax_ie_data provdata
;
9836 struct iax_ie_data ied
;
9838 struct sockaddr_in sin
;
9840 struct create_addr_info cai
;
9842 memset(&cai
, 0, sizeof(cai
));
9844 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest
, template);
9846 if (iax_provision_build(&provdata
, &sig
, template, force
)) {
9847 ast_debug(1, "No provisioning found for template '%s'\n", template);
9852 memcpy(&sin
, end
, sizeof(sin
));
9853 cai
.sockfd
= sockfd
;
9854 } else if (create_addr(dest
, NULL
, &sin
, &cai
))
9857 /* Build the rest of the message */
9858 memset(&ied
, 0, sizeof(ied
));
9859 iax_ie_append_raw(&ied
, IAX_IE_PROVISIONING
, provdata
.buf
, provdata
.pos
);
9861 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
9866 /* Schedule autodestruct in case they don't ever give us anything back */
9867 iaxs
[callno
]->autoid
= iax2_sched_replace(iaxs
[callno
]->autoid
,
9868 sched
, 15000, auto_hangup
, (void *)(long)callno
);
9869 ast_set_flag(iaxs
[callno
], IAX_PROVISION
);
9870 /* Got a call number now, so go ahead and send the provisioning information */
9871 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PROVISION
, 0, ied
.buf
, ied
.pos
, -1);
9873 ast_mutex_unlock(&iaxsl
[callno
]);
9878 static char *papp
= "IAX2Provision";
9879 static char *psyn
= "Provision a calling IAXy with a given template";
9880 static char *pdescrip
=
9881 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
9882 "the calling entity is in fact an IAXy) with the given template or\n"
9883 "default if one is not specified. Returns -1 on error or 0 on success.\n";
9886 \ingroup applications
9888 static int iax2_prov_app(struct ast_channel
*chan
, void *data
)
9894 unsigned short callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
9895 if (ast_strlen_zero(data
))
9897 sdata
= ast_strdupa(data
);
9898 opts
= strchr(sdata
, '|');
9902 if (chan
->tech
!= &iax2_tech
) {
9903 ast_log(LOG_NOTICE
, "Can't provision a non-IAX device!\n");
9906 if (!callno
|| !iaxs
[callno
] || !iaxs
[callno
]->addr
.sin_addr
.s_addr
) {
9907 ast_log(LOG_NOTICE
, "Can't provision something with no IP?\n");
9910 res
= iax2_provision(&iaxs
[callno
]->addr
, iaxs
[callno
]->sockfd
, NULL
, sdata
, force
);
9911 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
9912 ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
),
9917 static char *handle_cli_iax2_provision(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
9924 e
->command
= "iax2 provision";
9926 "Usage: iax2 provision <host> <template> [forced]\n"
9927 " Provisions the given peer or IP address using a template\n"
9928 " matching either 'template' or '*' if the template is not\n"
9929 " found. If 'forced' is specified, even empty provisioning\n"
9930 " fields will be provisioned as empty fields.\n";
9934 return iax_prov_complete_template(a
->line
, a
->word
, a
->pos
, a
->n
);
9939 return CLI_SHOWUSAGE
;
9941 if (!strcasecmp(a
->argv
[4], "forced"))
9944 return CLI_SHOWUSAGE
;
9946 res
= iax2_provision(NULL
, -1, a
->argv
[2], a
->argv
[3], force
);
9948 ast_cli(a
->fd
, "Unable to find peer/address '%s'\n", a
->argv
[2]);
9950 ast_cli(a
->fd
, "No template (including wildcard) matching '%s'\n", a
->argv
[3]);
9952 ast_cli(a
->fd
, "Provisioning '%s' with template '%s'%s\n", a
->argv
[2], a
->argv
[3], force
? ", forced" : "");
9956 static void __iax2_poke_noanswer(const void *data
)
9958 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
9961 if (peer
->lastms
> -1) {
9962 ast_log(LOG_NOTICE
, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer
->name
, peer
->lastms
);
9963 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer
->name
, peer
->lastms
);
9964 ast_devstate_changed(AST_DEVICE_UNAVAILABLE
, "IAX2/%s", peer
->name
); /* Activate notification */
9966 if ((callno
= peer
->callno
) > 0) {
9967 ast_mutex_lock(&iaxsl
[callno
]);
9968 iax2_destroy(callno
);
9969 ast_mutex_unlock(&iaxsl
[callno
]);
9973 /* Try again quickly */
9974 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
9975 if (peer
->pokeexpire
== -1)
9979 static int iax2_poke_noanswer(const void *data
)
9981 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
9982 peer
->pokeexpire
= -1;
9983 #ifdef SCHED_MULTITHREADED
9984 if (schedule_action(__iax2_poke_noanswer
, data
))
9986 __iax2_poke_noanswer(data
);
9991 static int iax2_poke_peer_cb(void *obj
, void *arg
, int flags
)
9993 struct iax2_peer
*peer
= obj
;
9995 iax2_poke_peer(peer
, 0);
10000 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
)
10003 if (!peer
->maxms
|| (!peer
->addr
.sin_addr
.s_addr
&& !peer
->dnsmgr
)) {
10004 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
10005 immediately after clearing things out */
10007 peer
->historicms
= 0;
10008 peer
->pokeexpire
= -1;
10013 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
10014 if ((callno
= peer
->callno
) > 0) {
10015 ast_log(LOG_NOTICE
, "Still have a callno...\n");
10016 ast_mutex_lock(&iaxsl
[callno
]);
10017 iax2_destroy(callno
);
10018 ast_mutex_unlock(&iaxsl
[callno
]);
10021 ast_mutex_unlock(&iaxsl
[heldcall
]);
10022 callno
= peer
->callno
= find_callno(0, 0, &peer
->addr
, NEW_FORCE
, peer
->sockfd
, 0);
10024 ast_mutex_lock(&iaxsl
[heldcall
]);
10025 if (peer
->callno
< 1) {
10026 ast_log(LOG_WARNING
, "Unable to allocate call for poking peer '%s'\n", peer
->name
);
10030 /* Speed up retransmission times for this qualify call */
10031 iaxs
[peer
->callno
]->pingtime
= peer
->maxms
/ 4 + 1;
10032 iaxs
[peer
->callno
]->peerpoke
= peer
;
10034 if (peer
->pokeexpire
> -1) {
10035 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
10036 peer
->pokeexpire
= -1;
10041 /* Queue up a new task to handle no reply */
10042 /* If the host is already unreachable then use the unreachable interval instead */
10043 if (peer
->lastms
< 0)
10044 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_noanswer
, peer_ref(peer
));
10046 peer
->pokeexpire
= iax2_sched_add(sched
, DEFAULT_MAXMS
* 2, iax2_poke_noanswer
, peer_ref(peer
));
10048 if (peer
->pokeexpire
== -1)
10051 /* And send the poke */
10052 ast_mutex_lock(&iaxsl
[callno
]);
10053 if (iaxs
[callno
]) {
10054 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_POKE
, 0, NULL
, 0, -1);
10056 ast_mutex_unlock(&iaxsl
[callno
]);
10061 static void free_context(struct iax2_context
*con
)
10063 struct iax2_context
*conl
;
10071 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
)
10076 struct sockaddr_in sin
;
10077 struct ast_channel
*c
;
10078 struct parsed_dial_string pds
;
10079 struct create_addr_info cai
;
10082 memset(&pds
, 0, sizeof(pds
));
10083 tmpstr
= ast_strdupa(data
);
10084 parse_dial_string(tmpstr
, &pds
);
10086 if (ast_strlen_zero(pds
.peer
)) {
10087 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
10091 memset(&cai
, 0, sizeof(cai
));
10092 cai
.capability
= iax2_capability
;
10094 ast_copy_flags(&cai
, &globalflags
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_NOKEYROTATE
);
10096 /* Populate our address from the given */
10097 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
)) {
10098 *cause
= AST_CAUSE_UNREGISTERED
;
10103 sin
.sin_port
= htons(atoi(pds
.port
));
10105 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
10107 ast_log(LOG_WARNING
, "Unable to create call\n");
10108 *cause
= AST_CAUSE_CONGESTION
;
10112 /* If this is a trunk, update it now */
10113 ast_copy_flags(iaxs
[callno
], &cai
, IAX_TRUNK
| IAX_SENDANI
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_NOKEYROTATE
);
10114 if (ast_test_flag(&cai
, IAX_TRUNK
)) {
10116 if ((new_callno
= make_trunk(callno
, 1)) != -1)
10117 callno
= new_callno
;
10119 iaxs
[callno
]->maxtime
= cai
.maxtime
;
10121 ast_string_field_set(iaxs
[callno
], host
, pds
.peer
);
10123 c
= ast_iax2_new(callno
, AST_STATE_DOWN
, cai
.capability
);
10125 ast_mutex_unlock(&iaxsl
[callno
]);
10128 /* Choose a format we can live with */
10129 if (c
->nativeformats
& format
)
10130 c
->nativeformats
&= format
;
10132 native
= c
->nativeformats
;
10134 res
= ast_translator_best_choice(&fmt
, &native
);
10136 ast_log(LOG_WARNING
, "Unable to create translator path for %s to %s on %s\n",
10137 ast_getformatname(c
->nativeformats
), ast_getformatname(fmt
), c
->name
);
10141 c
->nativeformats
= native
;
10143 c
->readformat
= ast_best_codec(c
->nativeformats
);
10144 c
->writeformat
= c
->readformat
;
10150 static void *sched_thread(void *ignore
)
10154 struct timeval wait
;
10155 struct timespec ts
;
10158 pthread_testcancel();
10159 ast_mutex_lock(&sched_lock
);
10160 res
= ast_sched_wait(sched
);
10161 if ((res
> 1000) || (res
< 0))
10163 wait
= ast_tvadd(ast_tvnow(), ast_samp2tv(res
, 1000));
10164 ts
.tv_sec
= wait
.tv_sec
;
10165 ts
.tv_nsec
= wait
.tv_usec
* 1000;
10166 ast_cond_timedwait(&sched_cond
, &sched_lock
, &ts
);
10167 ast_mutex_unlock(&sched_lock
);
10168 pthread_testcancel();
10170 count
= ast_sched_runq(sched
);
10172 ast_debug(1, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count
);
10178 static void *network_thread(void *ignore
)
10180 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
10181 from the network, and queue them for delivery to the channels */
10182 int res
, count
, wakeup
;
10183 struct iax_frame
*f
;
10186 ast_io_add(io
, timingfd
, timing_read
, AST_IO_IN
| AST_IO_PRI
, NULL
);
10189 pthread_testcancel();
10191 /* Go through the queue, sending messages which have not yet been
10192 sent, and scheduling retransmissions if appropriate */
10193 AST_LIST_LOCK(&frame_queue
);
10196 AST_LIST_TRAVERSE_SAFE_BEGIN(&frame_queue
, f
, list
) {
10200 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
10201 if (ast_mutex_trylock(&iaxsl
[f
->callno
])) {
10208 if (iaxs
[f
->callno
]) {
10213 ast_mutex_unlock(&iaxsl
[f
->callno
]);
10215 if (f
->retries
< 0) {
10216 /* This is not supposed to be retransmitted */
10217 AST_LIST_REMOVE_CURRENT(list
);
10218 /* Free the iax frame */
10221 /* We need reliable delivery. Schedule a retransmission */
10223 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
10226 AST_LIST_TRAVERSE_SAFE_END
;
10227 AST_LIST_UNLOCK(&frame_queue
);
10229 pthread_testcancel();
10231 ast_debug(1, "chan_iax2: Sent %d queued outbound frames all at once\n", count
);
10233 /* Now do the IO, and run scheduled tasks */
10234 res
= ast_io_wait(io
, wakeup
);
10237 ast_debug(1, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res
);
10243 static int start_network_thread(void)
10245 struct iax2_thread
*thread
;
10246 int threadcount
= 0;
10248 for (x
= 0; x
< iaxthreadcount
; x
++) {
10249 thread
= ast_calloc(1, sizeof(*thread
));
10251 thread
->type
= IAX_THREAD_TYPE_POOL
;
10252 thread
->threadnum
= ++threadcount
;
10253 ast_mutex_init(&thread
->lock
);
10254 ast_cond_init(&thread
->cond
, NULL
);
10255 if (ast_pthread_create_detached(&thread
->threadid
, NULL
, iax2_process_thread
, thread
)) {
10256 ast_log(LOG_WARNING
, "Failed to create new thread!\n");
10260 AST_LIST_LOCK(&idle_list
);
10261 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
10262 AST_LIST_UNLOCK(&idle_list
);
10265 ast_pthread_create_background(&schedthreadid
, NULL
, sched_thread
, NULL
);
10266 ast_pthread_create_background(&netthreadid
, NULL
, network_thread
, NULL
);
10267 ast_verb(2, "%d helper threads started\n", threadcount
);
10271 static struct iax2_context
*build_context(const char *context
)
10273 struct iax2_context
*con
;
10275 if ((con
= ast_calloc(1, sizeof(*con
))))
10276 ast_copy_string(con
->context
, context
, sizeof(con
->context
));
10281 static int get_auth_methods(const char *value
)
10284 if (strstr(value
, "rsa"))
10285 methods
|= IAX_AUTH_RSA
;
10286 if (strstr(value
, "md5"))
10287 methods
|= IAX_AUTH_MD5
;
10288 if (strstr(value
, "plaintext"))
10289 methods
|= IAX_AUTH_PLAINTEXT
;
10294 /*! \brief Check if address can be used as packet source.
10295 \return 0 address available, 1 address unavailable, -1 error
10297 static int check_srcaddr(struct sockaddr
*sa
, socklen_t salen
)
10302 sd
= socket(AF_INET
, SOCK_DGRAM
, 0);
10304 ast_log(LOG_ERROR
, "Socket: %s\n", strerror(errno
));
10308 res
= bind(sd
, sa
, salen
);
10310 ast_debug(1, "Can't bind: %s\n", strerror(errno
));
10319 /*! \brief Parse the "sourceaddress" value,
10320 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
10322 static int peer_set_srcaddr(struct iax2_peer
*peer
, const char *srcaddr
)
10324 struct sockaddr_in sin
;
10326 int port
= IAX_DEFAULT_PORTNO
;
10327 int sockfd
= defaultsockfd
;
10332 if (!(tmp
= ast_strdupa(srcaddr
)))
10335 addr
= strsep(&tmp
, ":");
10339 port
= atoi(portstr
);
10341 port
= IAX_DEFAULT_PORTNO
;
10344 if (!ast_get_ip(&sin
, addr
)) {
10345 struct ast_netsock
*sock
;
10349 sin
.sin_family
= AF_INET
;
10350 res
= check_srcaddr((struct sockaddr
*) &sin
, sizeof(sin
));
10352 /* ip address valid. */
10353 sin
.sin_port
= htons(port
);
10354 if (!(sock
= ast_netsock_find(netsock
, &sin
)))
10355 sock
= ast_netsock_find(outsock
, &sin
);
10357 sockfd
= ast_netsock_sockfd(sock
);
10360 unsigned int orig_saddr
= sin
.sin_addr
.s_addr
;
10361 /* INADDR_ANY matches anyway! */
10362 sin
.sin_addr
.s_addr
= INADDR_ANY
;
10363 if (ast_netsock_find(netsock
, &sin
)) {
10364 sin
.sin_addr
.s_addr
= orig_saddr
;
10365 sock
= ast_netsock_bind(outsock
, io
, srcaddr
, port
, qos
.tos
, qos
.cos
, socket_read
, NULL
);
10367 sockfd
= ast_netsock_sockfd(sock
);
10368 ast_netsock_unref(sock
);
10378 peer
->sockfd
= sockfd
;
10380 if (nonlocal
== 1) {
10381 ast_log(LOG_WARNING
, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
10382 srcaddr
, peer
->name
);
10384 } else if (nonlocal
== 2) {
10385 ast_log(LOG_WARNING
, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
10386 srcaddr
, peer
->name
);
10389 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr
, peer
->name
);
10394 static void peer_destructor(void *obj
)
10396 struct iax2_peer
*peer
= obj
;
10397 int callno
= peer
->callno
;
10399 ast_free_ha(peer
->ha
);
10402 ast_mutex_lock(&iaxsl
[callno
]);
10403 iax2_destroy(callno
);
10404 ast_mutex_unlock(&iaxsl
[callno
]);
10407 register_peer_exten(peer
, 0);
10410 ast_dnsmgr_release(peer
->dnsmgr
);
10412 if (peer
->mwi_event_sub
)
10413 ast_event_unsubscribe(peer
->mwi_event_sub
);
10415 ast_string_field_free_memory(peer
);
10418 /*! \brief Create peer structure based on configuration */
10419 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
10421 struct iax2_peer
*peer
= NULL
;
10422 struct ast_ha
*oldha
= NULL
;
10426 struct iax2_peer tmp_peer
= {
10431 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
10432 if (peer
&& !ast_test_flag(peer
, IAX_DELME
))
10443 } else if ((peer
= ao2_alloc(sizeof(*peer
), peer_destructor
))) {
10445 peer
->pokeexpire
= -1;
10446 peer
->sockfd
= defaultsockfd
;
10447 if (ast_string_field_init(peer
, 32))
10448 peer
= peer_unref(peer
);
10453 if (ast_test_flag(&globalflags
, IAX_NOKEYROTATE
)) {
10454 ast_copy_flags(peer
, &globalflags
, IAX_NOKEYROTATE
);
10456 ast_copy_flags(peer
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
10457 peer
->encmethods
= iax2_encryption
;
10459 ast_string_field_set(peer
,secret
,"");
10461 ast_string_field_set(peer
, name
, name
);
10462 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
10463 peer
->expiry
= min_reg_expire
;
10465 peer
->prefs
= prefs
;
10466 peer
->capability
= iax2_capability
;
10467 peer
->smoothing
= 0;
10468 peer
->pokefreqok
= DEFAULT_FREQ_OK
;
10469 peer
->pokefreqnotok
= DEFAULT_FREQ_NOTOK
;
10470 ast_string_field_set(peer
,context
,"");
10471 ast_string_field_set(peer
,peercontext
,"");
10472 ast_clear_flag(peer
, IAX_HASCALLERID
);
10473 ast_string_field_set(peer
, cid_name
, "");
10474 ast_string_field_set(peer
, cid_num
, "");
10482 if (!strcasecmp(v
->name
, "secret")) {
10483 ast_string_field_set(peer
, secret
, v
->value
);
10484 } else if (!strcasecmp(v
->name
, "mailbox")) {
10485 ast_string_field_set(peer
, mailbox
, v
->value
);
10486 } else if (!strcasecmp(v
->name
, "hasvoicemail")) {
10487 if (ast_true(v
->value
) && ast_strlen_zero(peer
->mailbox
)) {
10488 ast_string_field_set(peer
, mailbox
, name
);
10490 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
10491 ast_string_field_set(peer
, mohinterpret
, v
->value
);
10492 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
10493 ast_string_field_set(peer
, mohsuggest
, v
->value
);
10494 } else if (!strcasecmp(v
->name
, "dbsecret")) {
10495 ast_string_field_set(peer
, dbsecret
, v
->value
);
10496 } else if (!strcasecmp(v
->name
, "trunk")) {
10497 ast_set2_flag(peer
, ast_true(v
->value
), IAX_TRUNK
);
10498 if (ast_test_flag(peer
, IAX_TRUNK
) && (timingfd
< 0)) {
10499 ast_log(LOG_WARNING
, "Unable to support trunking on peer '%s' without DAHDI timing\n", peer
->name
);
10500 ast_clear_flag(peer
, IAX_TRUNK
);
10502 } else if (!strcasecmp(v
->name
, "auth")) {
10503 peer
->authmethods
= get_auth_methods(v
->value
);
10504 } else if (!strcasecmp(v
->name
, "encryption")) {
10505 peer
->encmethods
= get_encrypt_methods(v
->value
);
10506 } else if (!strcasecmp(v
->name
, "keyrotate")) {
10507 if (ast_false(v
->value
))
10508 ast_set_flag(peer
, IAX_NOKEYROTATE
);
10510 ast_clear_flag(peer
, IAX_NOKEYROTATE
);
10511 } else if (!strcasecmp(v
->name
, "transfer")) {
10512 if (!strcasecmp(v
->value
, "mediaonly")) {
10513 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
10514 } else if (ast_true(v
->value
)) {
10515 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
10517 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
10518 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
10519 ast_set2_flag(peer
, ast_true(v
->value
), IAX_USEJITTERBUF
);
10520 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
10521 ast_set2_flag(peer
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
10522 } else if (!strcasecmp(v
->name
, "host")) {
10523 if (!strcasecmp(v
->value
, "dynamic")) {
10524 /* They'll register with us */
10525 ast_set_flag(peer
, IAX_DYNAMIC
);
10527 /* Initialize stuff iff we're not found, otherwise
10528 we keep going with what we had */
10529 memset(&peer
->addr
.sin_addr
, 0, 4);
10530 if (peer
->addr
.sin_port
) {
10531 /* If we've already got a port, make it the default rather than absolute */
10532 peer
->defaddr
.sin_port
= peer
->addr
.sin_port
;
10533 peer
->addr
.sin_port
= 0;
10537 /* Non-dynamic. Make sure we become that way if we're not */
10538 AST_SCHED_DEL(sched
, peer
->expire
);
10539 ast_clear_flag(peer
, IAX_DYNAMIC
);
10540 if (ast_dnsmgr_lookup(v
->value
, &peer
->addr
, &peer
->dnsmgr
, srvlookup
? "_iax._udp" : NULL
))
10541 return peer_unref(peer
);
10542 if (!peer
->addr
.sin_port
)
10543 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
10546 inet_aton("255.255.255.255", &peer
->mask
);
10547 } else if (!strcasecmp(v
->name
, "defaultip")) {
10548 if (ast_get_ip(&peer
->defaddr
, v
->value
))
10549 return peer_unref(peer
);
10550 } else if (!strcasecmp(v
->name
, "sourceaddress")) {
10551 peer_set_srcaddr(peer
, v
->value
);
10552 } else if (!strcasecmp(v
->name
, "permit") ||
10553 !strcasecmp(v
->name
, "deny")) {
10554 peer
->ha
= ast_append_ha(v
->name
, v
->value
, peer
->ha
, NULL
);
10555 } else if (!strcasecmp(v
->name
, "mask")) {
10557 inet_aton(v
->value
, &peer
->mask
);
10558 } else if (!strcasecmp(v
->name
, "context")) {
10559 ast_string_field_set(peer
, context
, v
->value
);
10560 } else if (!strcasecmp(v
->name
, "regexten")) {
10561 ast_string_field_set(peer
, regexten
, v
->value
);
10562 } else if (!strcasecmp(v
->name
, "peercontext")) {
10563 ast_string_field_set(peer
, peercontext
, v
->value
);
10564 } else if (!strcasecmp(v
->name
, "port")) {
10565 if (ast_test_flag(peer
, IAX_DYNAMIC
))
10566 peer
->defaddr
.sin_port
= htons(atoi(v
->value
));
10568 peer
->addr
.sin_port
= htons(atoi(v
->value
));
10569 } else if (!strcasecmp(v
->name
, "username")) {
10570 ast_string_field_set(peer
, username
, v
->value
);
10571 } else if (!strcasecmp(v
->name
, "allow")) {
10572 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 1);
10573 } else if (!strcasecmp(v
->name
, "disallow")) {
10574 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 0);
10575 } else if (!strcasecmp(v
->name
, "callerid")) {
10576 if (!ast_strlen_zero(v
->value
)) {
10579 ast_callerid_split(v
->value
, name2
, sizeof(name2
), num2
, sizeof(num2
));
10580 ast_string_field_set(peer
, cid_name
, name2
);
10581 ast_string_field_set(peer
, cid_num
, num2
);
10583 ast_string_field_set(peer
, cid_name
, "");
10584 ast_string_field_set(peer
, cid_num
, "");
10586 ast_set_flag(peer
, IAX_HASCALLERID
);
10587 } else if (!strcasecmp(v
->name
, "fullname")) {
10588 ast_string_field_set(peer
, cid_name
, S_OR(v
->value
, ""));
10589 ast_set_flag(peer
, IAX_HASCALLERID
);
10590 } else if (!strcasecmp(v
->name
, "cid_number")) {
10591 ast_string_field_set(peer
, cid_num
, S_OR(v
->value
, ""));
10592 ast_set_flag(peer
, IAX_HASCALLERID
);
10593 } else if (!strcasecmp(v
->name
, "sendani")) {
10594 ast_set2_flag(peer
, ast_true(v
->value
), IAX_SENDANI
);
10595 } else if (!strcasecmp(v
->name
, "inkeys")) {
10596 ast_string_field_set(peer
, inkeys
, v
->value
);
10597 } else if (!strcasecmp(v
->name
, "outkey")) {
10598 ast_string_field_set(peer
, outkey
, v
->value
);
10599 } else if (!strcasecmp(v
->name
, "qualify")) {
10600 if (!strcasecmp(v
->value
, "no")) {
10602 } else if (!strcasecmp(v
->value
, "yes")) {
10603 peer
->maxms
= DEFAULT_MAXMS
;
10604 } else if (sscanf(v
->value
, "%d", &peer
->maxms
) != 1) {
10605 ast_log(LOG_WARNING
, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer
->name
, v
->lineno
);
10608 } else if (!strcasecmp(v
->name
, "qualifysmoothing")) {
10609 peer
->smoothing
= ast_true(v
->value
);
10610 } else if (!strcasecmp(v
->name
, "qualifyfreqok")) {
10611 if (sscanf(v
->value
, "%d", &peer
->pokefreqok
) != 1) {
10612 ast_log(LOG_WARNING
, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer
->name
, v
->lineno
);
10614 } else if (!strcasecmp(v
->name
, "qualifyfreqnotok")) {
10615 if (sscanf(v
->value
, "%d", &peer
->pokefreqnotok
) != 1) {
10616 ast_log(LOG_WARNING
, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer
->name
, v
->lineno
);
10617 } else ast_log(LOG_WARNING
, "Set peer->pokefreqnotok to %d\n", peer
->pokefreqnotok
);
10618 } else if (!strcasecmp(v
->name
, "timezone")) {
10619 ast_string_field_set(peer
, zonetag
, v
->value
);
10620 } else if (!strcasecmp(v
->name
, "adsi")) {
10621 peer
->adsi
= ast_true(v
->value
);
10622 }/* else if (strcasecmp(v->name,"type")) */
10623 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10630 if (!peer
->authmethods
)
10631 peer
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
10632 ast_clear_flag(peer
, IAX_DELME
);
10633 /* Make sure these are IPv4 addresses */
10634 peer
->addr
.sin_family
= AF_INET
;
10638 ast_free_ha(oldha
);
10640 if (!ast_strlen_zero(peer
->mailbox
)) {
10641 char *mailbox
, *context
;
10642 context
= mailbox
= ast_strdupa(peer
->mailbox
);
10643 strsep(&context
, "@");
10644 if (ast_strlen_zero(context
))
10645 context
= "default";
10646 peer
->mwi_event_sub
= ast_event_subscribe(AST_EVENT_MWI
, mwi_event_cb
, NULL
,
10647 AST_EVENT_IE_MAILBOX
, AST_EVENT_IE_PLTYPE_STR
, mailbox
,
10648 AST_EVENT_IE_CONTEXT
, AST_EVENT_IE_PLTYPE_STR
, context
,
10655 static void user_destructor(void *obj
)
10657 struct iax2_user
*user
= obj
;
10659 ast_free_ha(user
->ha
);
10660 free_context(user
->contexts
);
10662 ast_variables_destroy(user
->vars
);
10665 ast_string_field_free_memory(user
);
10668 /*! \brief Create in-memory user structure from configuration */
10669 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
10671 struct iax2_user
*user
= NULL
;
10672 struct iax2_context
*con
, *conl
= NULL
;
10673 struct ast_ha
*oldha
= NULL
;
10674 struct iax2_context
*oldcon
= NULL
;
10677 int oldcurauthreq
= 0;
10678 char *varname
= NULL
, *varval
= NULL
;
10679 struct ast_variable
*tmpvar
= NULL
;
10680 struct iax2_user tmp_user
= {
10685 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
10686 if (user
&& !ast_test_flag(user
, IAX_DELME
))
10692 oldcurauthreq
= user
->curauthreq
;
10694 oldcon
= user
->contexts
;
10696 user
->contexts
= NULL
;
10698 /* Already in the list, remove it and it will be added back (or FREE'd) */
10699 ao2_unlink(users
, user
);
10701 user
= ao2_alloc(sizeof(*user
), user_destructor
);
10706 ast_string_field_free_memory(user
);
10707 memset(user
, 0, sizeof(struct iax2_user
));
10708 if (ast_string_field_init(user
, 32)) {
10709 user
= user_unref(user
);
10712 user
->maxauthreq
= maxauthreq
;
10713 user
->curauthreq
= oldcurauthreq
;
10714 user
->prefs
= prefs
;
10715 user
->capability
= iax2_capability
;
10716 user
->encmethods
= iax2_encryption
;
10718 ast_string_field_set(user
, name
, name
);
10719 ast_string_field_set(user
, language
, language
);
10720 ast_copy_flags(user
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_CODEC_USER_FIRST
| IAX_CODEC_NOPREFS
| IAX_CODEC_NOCAP
| IAX_NOKEYROTATE
);
10721 ast_clear_flag(user
, IAX_HASCALLERID
);
10722 ast_string_field_set(user
, cid_name
, "");
10723 ast_string_field_set(user
, cid_num
, "");
10730 if (!strcasecmp(v
->name
, "context")) {
10731 con
= build_context(v
->value
);
10736 user
->contexts
= con
;
10739 } else if (!strcasecmp(v
->name
, "permit") ||
10740 !strcasecmp(v
->name
, "deny")) {
10741 user
->ha
= ast_append_ha(v
->name
, v
->value
, user
->ha
, NULL
);
10742 } else if (!strcasecmp(v
->name
, "setvar")) {
10743 varname
= ast_strdupa(v
->value
);
10744 if (varname
&& (varval
= strchr(varname
,'='))) {
10747 if((tmpvar
= ast_variable_new(varname
, varval
, ""))) {
10748 tmpvar
->next
= user
->vars
;
10749 user
->vars
= tmpvar
;
10752 } else if (!strcasecmp(v
->name
, "allow")) {
10753 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 1);
10754 } else if (!strcasecmp(v
->name
, "disallow")) {
10755 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
,v
->value
, 0);
10756 } else if (!strcasecmp(v
->name
, "trunk")) {
10757 ast_set2_flag(user
, ast_true(v
->value
), IAX_TRUNK
);
10758 if (ast_test_flag(user
, IAX_TRUNK
) && (timingfd
< 0)) {
10759 ast_log(LOG_WARNING
, "Unable to support trunking on user '%s' without DAHDI timing\n", user
->name
);
10760 ast_clear_flag(user
, IAX_TRUNK
);
10762 } else if (!strcasecmp(v
->name
, "auth")) {
10763 user
->authmethods
= get_auth_methods(v
->value
);
10764 } else if (!strcasecmp(v
->name
, "encryption")) {
10765 user
->encmethods
= get_encrypt_methods(v
->value
);
10766 } else if (!strcasecmp(v
->name
, "keyrotate")) {
10767 if (ast_false(v
->value
))
10768 ast_set_flag(user
, IAX_NOKEYROTATE
);
10770 ast_clear_flag(user
, IAX_NOKEYROTATE
);
10771 } else if (!strcasecmp(v
->name
, "transfer")) {
10772 if (!strcasecmp(v
->value
, "mediaonly")) {
10773 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
10774 } else if (ast_true(v
->value
)) {
10775 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
10777 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
10778 } else if (!strcasecmp(v
->name
, "codecpriority")) {
10779 if(!strcasecmp(v
->value
, "caller"))
10780 ast_set_flag(user
, IAX_CODEC_USER_FIRST
);
10781 else if(!strcasecmp(v
->value
, "disabled"))
10782 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
10783 else if(!strcasecmp(v
->value
, "reqonly")) {
10784 ast_set_flag(user
, IAX_CODEC_NOCAP
);
10785 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
10787 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
10788 ast_set2_flag(user
, ast_true(v
->value
), IAX_USEJITTERBUF
);
10789 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
10790 ast_set2_flag(user
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
10791 } else if (!strcasecmp(v
->name
, "dbsecret")) {
10792 ast_string_field_set(user
, dbsecret
, v
->value
);
10793 } else if (!strcasecmp(v
->name
, "secret")) {
10794 if (!ast_strlen_zero(user
->secret
)) {
10795 char *old
= ast_strdupa(user
->secret
);
10797 ast_string_field_build(user
, secret
, "%s;%s", old
, v
->value
);
10799 ast_string_field_set(user
, secret
, v
->value
);
10800 } else if (!strcasecmp(v
->name
, "callerid")) {
10801 if (!ast_strlen_zero(v
->value
) && strcasecmp(v
->value
, "asreceived")) {
10804 ast_callerid_split(v
->value
, name2
, sizeof(name2
), num2
, sizeof(num2
));
10805 ast_string_field_set(user
, cid_name
, name2
);
10806 ast_string_field_set(user
, cid_num
, num2
);
10807 ast_set_flag(user
, IAX_HASCALLERID
);
10809 ast_clear_flag(user
, IAX_HASCALLERID
);
10810 ast_string_field_set(user
, cid_name
, "");
10811 ast_string_field_set(user
, cid_num
, "");
10813 } else if (!strcasecmp(v
->name
, "fullname")) {
10814 if (!ast_strlen_zero(v
->value
)) {
10815 ast_string_field_set(user
, cid_name
, v
->value
);
10816 ast_set_flag(user
, IAX_HASCALLERID
);
10818 ast_string_field_set(user
, cid_name
, "");
10819 if (ast_strlen_zero(user
->cid_num
))
10820 ast_clear_flag(user
, IAX_HASCALLERID
);
10822 } else if (!strcasecmp(v
->name
, "cid_number")) {
10823 if (!ast_strlen_zero(v
->value
)) {
10824 ast_string_field_set(user
, cid_num
, v
->value
);
10825 ast_set_flag(user
, IAX_HASCALLERID
);
10827 ast_string_field_set(user
, cid_num
, "");
10828 if (ast_strlen_zero(user
->cid_name
))
10829 ast_clear_flag(user
, IAX_HASCALLERID
);
10831 } else if (!strcasecmp(v
->name
, "accountcode")) {
10832 ast_string_field_set(user
, accountcode
, v
->value
);
10833 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
10834 ast_string_field_set(user
, mohinterpret
, v
->value
);
10835 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
10836 ast_string_field_set(user
, mohsuggest
, v
->value
);
10837 } else if (!strcasecmp(v
->name
, "parkinglot")) {
10838 ast_string_field_set(user
, parkinglot
, v
->value
);
10839 } else if (!strcasecmp(v
->name
, "language")) {
10840 ast_string_field_set(user
, language
, v
->value
);
10841 } else if (!strcasecmp(v
->name
, "amaflags")) {
10842 format
= ast_cdr_amaflags2int(v
->value
);
10844 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
10846 user
->amaflags
= format
;
10848 } else if (!strcasecmp(v
->name
, "inkeys")) {
10849 ast_string_field_set(user
, inkeys
, v
->value
);
10850 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
10851 user
->maxauthreq
= atoi(v
->value
);
10852 if (user
->maxauthreq
< 0)
10853 user
->maxauthreq
= 0;
10854 } else if (!strcasecmp(v
->name
, "adsi")) {
10855 user
->adsi
= ast_true(v
->value
);
10856 }/* else if (strcasecmp(v->name,"type")) */
10857 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10864 if (!user
->authmethods
) {
10865 if (!ast_strlen_zero(user
->secret
)) {
10866 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
10867 if (!ast_strlen_zero(user
->inkeys
))
10868 user
->authmethods
|= IAX_AUTH_RSA
;
10869 } else if (!ast_strlen_zero(user
->inkeys
)) {
10870 user
->authmethods
= IAX_AUTH_RSA
;
10872 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
10875 ast_clear_flag(user
, IAX_DELME
);
10879 ast_free_ha(oldha
);
10881 free_context(oldcon
);
10885 static int peer_delme_cb(void *obj
, void *arg
, int flags
)
10887 struct iax2_peer
*peer
= obj
;
10889 ast_set_flag(peer
, IAX_DELME
);
10894 static int user_delme_cb(void *obj
, void *arg
, int flags
)
10896 struct iax2_user
*user
= obj
;
10898 ast_set_flag(user
, IAX_DELME
);
10903 static void delete_users(void)
10905 struct iax2_registry
*reg
;
10907 ao2_callback(users
, 0, user_delme_cb
, NULL
);
10909 AST_LIST_LOCK(®istrations
);
10910 while ((reg
= AST_LIST_REMOVE_HEAD(®istrations
, entry
))) {
10911 AST_SCHED_DEL(sched
, reg
->expire
);
10913 int callno
= reg
->callno
;
10914 ast_mutex_lock(&iaxsl
[callno
]);
10915 if (iaxs
[callno
]) {
10916 iaxs
[callno
]->reg
= NULL
;
10917 iax2_destroy(callno
);
10919 ast_mutex_unlock(&iaxsl
[callno
]);
10922 ast_dnsmgr_release(reg
->dnsmgr
);
10925 AST_LIST_UNLOCK(®istrations
);
10927 ao2_callback(peers
, 0, peer_delme_cb
, NULL
);
10930 static void prune_users(void)
10932 struct iax2_user
*user
;
10933 struct ao2_iterator i
;
10935 i
= ao2_iterator_init(users
, 0);
10936 while ((user
= ao2_iterator_next(&i
))) {
10937 if (ast_test_flag(user
, IAX_DELME
))
10938 ao2_unlink(users
, user
);
10943 /* Prune peers who still are supposed to be deleted */
10944 static void prune_peers(void)
10946 struct iax2_peer
*peer
;
10947 struct ao2_iterator i
;
10949 i
= ao2_iterator_init(peers
, 0);
10950 while ((peer
= ao2_iterator_next(&i
))) {
10951 if (ast_test_flag(peer
, IAX_DELME
))
10957 static void set_config_destroy(void)
10959 strcpy(accountcode
, "");
10960 strcpy(language
, "");
10961 strcpy(mohinterpret
, "default");
10962 strcpy(mohsuggest
, "");
10963 global_max_trunk_mtu
= MAX_TRUNK_MTU
;
10964 trunkmaxsize
= MAX_TRUNKDATA
;
10967 ast_clear_flag((&globalflags
), IAX_NOTRANSFER
);
10968 ast_clear_flag((&globalflags
), IAX_TRANSFERMEDIA
);
10969 ast_clear_flag((&globalflags
), IAX_USEJITTERBUF
);
10970 ast_clear_flag((&globalflags
), IAX_FORCEJITTERBUF
);
10974 /*! \brief Load configuration */
10975 static int set_config(char *config_file
, int reload
)
10977 struct ast_config
*cfg
, *ucfg
;
10978 int capability
=iax2_capability
;
10979 struct ast_variable
*v
;
10982 const char *tosval
;
10984 int portno
= IAX_DEFAULT_PORTNO
;
10987 struct iax2_user
*user
;
10988 struct iax2_peer
*peer
;
10989 struct ast_netsock
*ns
;
10990 struct ast_flags config_flags
= { reload
? CONFIG_FLAG_FILEUNCHANGED
: 0 };
10992 static unsigned short int last_port
=0;
10995 cfg
= ast_config_load(config_file
, config_flags
);
10998 ast_log(LOG_ERROR
, "Unable to load config %s\n", config_file
);
11000 } else if (cfg
== CONFIG_STATUS_FILEUNCHANGED
) {
11001 ucfg
= ast_config_load("users.conf", config_flags
);
11002 if (ucfg
== CONFIG_STATUS_FILEUNCHANGED
)
11004 /* Otherwise we need to reread both files */
11005 ast_clear_flag(&config_flags
, CONFIG_FLAG_FILEUNCHANGED
);
11006 cfg
= ast_config_load(config_file
, config_flags
);
11007 } else { /* iax.conf changed, gotta reread users.conf, too */
11008 ast_clear_flag(&config_flags
, CONFIG_FLAG_FILEUNCHANGED
);
11009 ucfg
= ast_config_load("users.conf", config_flags
);
11013 set_config_destroy();
11016 /* Reset global codec prefs */
11017 memset(&prefs
, 0 , sizeof(struct ast_codec_pref
));
11019 /* Reset Global Flags */
11020 memset(&globalflags
, 0, sizeof(globalflags
));
11021 ast_set_flag(&globalflags
, IAX_RTUPDATE
);
11026 /* Reset default parking lot */
11027 default_parkinglot
[0] = '\0';
11029 min_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
11030 max_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
11036 v
= ast_variable_browse(cfg
, "general");
11038 /* Seed initial tos value */
11039 tosval
= ast_variable_retrieve(cfg
, "general", "tos");
11041 if (ast_str2tos(tosval
, &qos
.tos
))
11042 ast_log(LOG_WARNING
, "Invalid tos value, refer to QoS documentation\n");
11044 /* Seed initial cos value */
11045 tosval
= ast_variable_retrieve(cfg
, "general", "cos");
11047 if (ast_str2cos(tosval
, &qos
.cos
))
11048 ast_log(LOG_WARNING
, "Invalid cos value, refer to QoS documentation\n");
11051 if (!strcasecmp(v
->name
, "bindport")){
11053 ast_log(LOG_NOTICE
, "Ignoring bindport on reload\n");
11055 portno
= atoi(v
->value
);
11056 } else if (!strcasecmp(v
->name
, "pingtime"))
11057 ping_time
= atoi(v
->value
);
11058 else if (!strcasecmp(v
->name
, "iaxthreadcount")) {
11060 if (atoi(v
->value
) != iaxthreadcount
)
11061 ast_log(LOG_NOTICE
, "Ignoring any changes to iaxthreadcount during reload\n");
11063 iaxthreadcount
= atoi(v
->value
);
11064 if (iaxthreadcount
< 1) {
11065 ast_log(LOG_NOTICE
, "iaxthreadcount must be at least 1.\n");
11066 iaxthreadcount
= 1;
11067 } else if (iaxthreadcount
> 256) {
11068 ast_log(LOG_NOTICE
, "limiting iaxthreadcount to 256\n");
11069 iaxthreadcount
= 256;
11072 } else if (!strcasecmp(v
->name
, "iaxmaxthreadcount")) {
11074 AST_LIST_LOCK(&dynamic_list
);
11075 iaxmaxthreadcount
= atoi(v
->value
);
11076 AST_LIST_UNLOCK(&dynamic_list
);
11078 iaxmaxthreadcount
= atoi(v
->value
);
11079 if (iaxmaxthreadcount
< 0) {
11080 ast_log(LOG_NOTICE
, "iaxmaxthreadcount must be at least 0.\n");
11081 iaxmaxthreadcount
= 0;
11082 } else if (iaxmaxthreadcount
> 256) {
11083 ast_log(LOG_NOTICE
, "Limiting iaxmaxthreadcount to 256\n");
11084 iaxmaxthreadcount
= 256;
11087 } else if (!strcasecmp(v
->name
, "nochecksums")) {
11089 if (ast_true(v
->value
))
11094 if (ast_true(v
->value
))
11095 ast_log(LOG_WARNING
, "Disabling RTP checksums is not supported on this operating system!\n");
11098 else if (!strcasecmp(v
->name
, "maxjitterbuffer"))
11099 maxjitterbuffer
= atoi(v
->value
);
11100 else if (!strcasecmp(v
->name
, "resyncthreshold"))
11101 resyncthreshold
= atoi(v
->value
);
11102 else if (!strcasecmp(v
->name
, "maxjitterinterps"))
11103 maxjitterinterps
= atoi(v
->value
);
11104 else if (!strcasecmp(v
->name
, "jittertargetextra"))
11105 jittertargetextra
= atoi(v
->value
);
11106 else if (!strcasecmp(v
->name
, "lagrqtime"))
11107 lagrq_time
= atoi(v
->value
);
11108 else if (!strcasecmp(v
->name
, "maxregexpire"))
11109 max_reg_expire
= atoi(v
->value
);
11110 else if (!strcasecmp(v
->name
, "minregexpire"))
11111 min_reg_expire
= atoi(v
->value
);
11112 else if (!strcasecmp(v
->name
, "bindaddr")) {
11114 ast_log(LOG_NOTICE
, "Ignoring bindaddr on reload\n");
11116 if (!(ns
= ast_netsock_bind(netsock
, io
, v
->value
, portno
, qos
.tos
, qos
.cos
, socket_read
, NULL
))) {
11117 ast_log(LOG_WARNING
, "Unable apply binding to '%s' at line %d\n", v
->value
, v
->lineno
);
11119 if (strchr(v
->value
, ':'))
11120 ast_verb(2, "Binding IAX2 to '%s'\n", v
->value
);
11122 ast_verb(2, "Binding IAX2 to '%s:%d'\n", v
->value
, portno
);
11123 if (defaultsockfd
< 0)
11124 defaultsockfd
= ast_netsock_sockfd(ns
);
11125 ast_netsock_unref(ns
);
11128 } else if (!strcasecmp(v
->name
, "authdebug"))
11129 authdebug
= ast_true(v
->value
);
11130 else if (!strcasecmp(v
->name
, "encryption"))
11131 iax2_encryption
= get_encrypt_methods(v
->value
);
11132 else if (!strcasecmp(v
->name
, "keyrotate")) {
11133 if (ast_false(v
->value
))
11134 ast_set_flag((&globalflags
), IAX_NOKEYROTATE
);
11136 ast_clear_flag((&globalflags
), IAX_NOKEYROTATE
);
11137 } else if (!strcasecmp(v
->name
, "transfer")) {
11138 if (!strcasecmp(v
->value
, "mediaonly")) {
11139 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
11140 } else if (ast_true(v
->value
)) {
11141 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
11143 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
11144 } else if (!strcasecmp(v
->name
, "codecpriority")) {
11145 if(!strcasecmp(v
->value
, "caller"))
11146 ast_set_flag((&globalflags
), IAX_CODEC_USER_FIRST
);
11147 else if(!strcasecmp(v
->value
, "disabled"))
11148 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
11149 else if(!strcasecmp(v
->value
, "reqonly")) {
11150 ast_set_flag((&globalflags
), IAX_CODEC_NOCAP
);
11151 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
11153 } else if (!strcasecmp(v
->name
, "jitterbuffer"))
11154 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_USEJITTERBUF
);
11155 else if (!strcasecmp(v
->name
, "forcejitterbuffer"))
11156 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_FORCEJITTERBUF
);
11157 else if (!strcasecmp(v
->name
, "delayreject"))
11158 delayreject
= ast_true(v
->value
);
11159 else if (!strcasecmp(v
->name
, "allowfwdownload"))
11160 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_ALLOWFWDOWNLOAD
);
11161 else if (!strcasecmp(v
->name
, "rtcachefriends"))
11162 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTCACHEFRIENDS
);
11163 else if (!strcasecmp(v
->name
, "rtignoreregexpire"))
11164 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTIGNOREREGEXPIRE
);
11165 else if (!strcasecmp(v
->name
, "rtupdate"))
11166 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTUPDATE
);
11167 else if (!strcasecmp(v
->name
, "trunktimestamps"))
11168 ast_set2_flag(&globalflags
, ast_true(v
->value
), IAX_TRUNKTIMESTAMPS
);
11169 else if (!strcasecmp(v
->name
, "rtautoclear")) {
11170 int i
= atoi(v
->value
);
11172 global_rtautoclear
= i
;
11175 ast_set2_flag((&globalflags
), i
|| ast_true(v
->value
), IAX_RTAUTOCLEAR
);
11176 } else if (!strcasecmp(v
->name
, "trunkfreq")) {
11177 trunkfreq
= atoi(v
->value
);
11178 if (trunkfreq
< 10)
11180 } else if (!strcasecmp(v
->name
, "trunkmtu")) {
11181 mtuv
= atoi(v
->value
);
11183 global_max_trunk_mtu
= 0;
11184 else if (mtuv
>= 172 && mtuv
< 4000)
11185 global_max_trunk_mtu
= mtuv
;
11187 ast_log(LOG_NOTICE
, "trunkmtu value out of bounds (%d) at line %d\n",
11189 } else if (!strcasecmp(v
->name
, "trunkmaxsize")) {
11190 trunkmaxsize
= atoi(v
->value
);
11191 if (trunkmaxsize
== 0)
11192 trunkmaxsize
= MAX_TRUNKDATA
;
11193 } else if (!strcasecmp(v
->name
, "autokill")) {
11194 if (sscanf(v
->value
, "%d", &x
) == 1) {
11198 ast_log(LOG_NOTICE
, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v
->lineno
);
11199 } else if (ast_true(v
->value
)) {
11200 autokill
= DEFAULT_MAXMS
;
11204 } else if (!strcasecmp(v
->name
, "bandwidth")) {
11205 if (!strcasecmp(v
->value
, "low")) {
11206 capability
= IAX_CAPABILITY_LOWBANDWIDTH
;
11207 } else if (!strcasecmp(v
->value
, "medium")) {
11208 capability
= IAX_CAPABILITY_MEDBANDWIDTH
;
11209 } else if (!strcasecmp(v
->value
, "high")) {
11210 capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
11212 ast_log(LOG_WARNING
, "bandwidth must be either low, medium, or high\n");
11213 } else if (!strcasecmp(v
->name
, "allow")) {
11214 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 1);
11215 } else if (!strcasecmp(v
->name
, "disallow")) {
11216 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 0);
11217 } else if (!strcasecmp(v
->name
, "register")) {
11218 iax2_register(v
->value
, v
->lineno
);
11219 } else if (!strcasecmp(v
->name
, "iaxcompat")) {
11220 iaxcompat
= ast_true(v
->value
);
11221 } else if (!strcasecmp(v
->name
, "regcontext")) {
11222 ast_copy_string(regcontext
, v
->value
, sizeof(regcontext
));
11223 /* Create context if it doesn't exist already */
11224 ast_context_find_or_create(NULL
, NULL
, regcontext
, "IAX2");
11225 } else if (!strcasecmp(v
->name
, "tos")) {
11226 if (ast_str2tos(v
->value
, &qos
.tos
))
11227 ast_log(LOG_WARNING
, "Invalid tos value at line %d, refer to QoS documentation\n", v
->lineno
);
11228 } else if (!strcasecmp(v
->name
, "cos")) {
11229 if (ast_str2cos(v
->value
, &qos
.cos
))
11230 ast_log(LOG_WARNING
, "Invalid cos value at line %d, refer to QoS documentation\n", v
->lineno
);
11231 } else if (!strcasecmp(v
->name
, "parkinglot")) {
11232 ast_copy_string(default_parkinglot
, v
->value
, sizeof(default_parkinglot
));
11233 } else if (!strcasecmp(v
->name
, "accountcode")) {
11234 ast_copy_string(accountcode
, v
->value
, sizeof(accountcode
));
11235 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
11236 ast_copy_string(mohinterpret
, v
->value
, sizeof(user
->mohinterpret
));
11237 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
11238 ast_copy_string(mohsuggest
, v
->value
, sizeof(user
->mohsuggest
));
11239 } else if (!strcasecmp(v
->name
, "amaflags")) {
11240 format
= ast_cdr_amaflags2int(v
->value
);
11242 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
11246 } else if (!strcasecmp(v
->name
, "language")) {
11247 ast_copy_string(language
, v
->value
, sizeof(language
));
11248 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
11249 maxauthreq
= atoi(v
->value
);
11250 if (maxauthreq
< 0)
11252 } else if (!strcasecmp(v
->name
, "adsi")) {
11253 adsi
= ast_true(v
->value
);
11254 } else if (!strcasecmp(v
->name
, "srvlookup")) {
11255 srvlookup
= ast_true(v
->value
);
11256 } /*else if (strcasecmp(v->name,"type")) */
11257 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
11261 if (defaultsockfd
< 0) {
11262 if (!(ns
= ast_netsock_bind(netsock
, io
, "0.0.0.0", portno
, qos
.tos
, qos
.cos
, socket_read
, NULL
))) {
11263 ast_log(LOG_ERROR
, "Unable to create network socket: %s\n", strerror(errno
));
11265 ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno
);
11266 defaultsockfd
= ast_netsock_sockfd(ns
);
11267 ast_netsock_unref(ns
);
11271 ast_netsock_release(outsock
);
11272 outsock
= ast_netsock_list_alloc();
11274 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
11277 ast_netsock_init(outsock
);
11280 if (min_reg_expire
> max_reg_expire
) {
11281 ast_log(LOG_WARNING
, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
11282 min_reg_expire
, max_reg_expire
, max_reg_expire
);
11283 min_reg_expire
= max_reg_expire
;
11285 iax2_capability
= capability
;
11288 struct ast_variable
*gen
;
11290 int genregisteriax
;
11291 const char *hasiax
, *registeriax
;
11293 genhasiax
= ast_true(ast_variable_retrieve(ucfg
, "general", "hasiax"));
11294 genregisteriax
= ast_true(ast_variable_retrieve(ucfg
, "general", "registeriax"));
11295 gen
= ast_variable_browse(ucfg
, "general");
11296 cat
= ast_category_browse(ucfg
, NULL
);
11298 if (strcasecmp(cat
, "general")) {
11299 hasiax
= ast_variable_retrieve(ucfg
, cat
, "hasiax");
11300 registeriax
= ast_variable_retrieve(ucfg
, cat
, "registeriax");
11301 if (ast_true(hasiax
) || (!hasiax
&& genhasiax
)) {
11302 /* Start with general parameters, then specific parameters, user and peer */
11303 user
= build_user(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
11305 ao2_link(users
, user
);
11306 user
= user_unref(user
);
11308 peer
= build_peer(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
11310 if (ast_test_flag(peer
, IAX_DYNAMIC
))
11311 reg_source_db(peer
);
11312 ao2_link(peers
, peer
);
11313 peer
= peer_unref(peer
);
11316 if (ast_true(registeriax
) || (!registeriax
&& genregisteriax
)) {
11318 const char *host
= ast_variable_retrieve(ucfg
, cat
, "host");
11319 const char *username
= ast_variable_retrieve(ucfg
, cat
, "username");
11320 const char *secret
= ast_variable_retrieve(ucfg
, cat
, "secret");
11322 host
= ast_variable_retrieve(ucfg
, "general", "host");
11324 username
= ast_variable_retrieve(ucfg
, "general", "username");
11326 secret
= ast_variable_retrieve(ucfg
, "general", "secret");
11327 if (!ast_strlen_zero(username
) && !ast_strlen_zero(host
)) {
11328 if (!ast_strlen_zero(secret
))
11329 snprintf(tmp
, sizeof(tmp
), "%s:%s@%s", username
, secret
, host
);
11331 snprintf(tmp
, sizeof(tmp
), "%s@%s", username
, host
);
11332 iax2_register(tmp
, 0);
11336 cat
= ast_category_browse(ucfg
, cat
);
11338 ast_config_destroy(ucfg
);
11341 cat
= ast_category_browse(cfg
, NULL
);
11343 if (strcasecmp(cat
, "general")) {
11344 utype
= ast_variable_retrieve(cfg
, cat
, "type");
11346 if (!strcasecmp(utype
, "user") || !strcasecmp(utype
, "friend")) {
11347 user
= build_user(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
11349 ao2_link(users
, user
);
11350 user
= user_unref(user
);
11353 if (!strcasecmp(utype
, "peer") || !strcasecmp(utype
, "friend")) {
11354 peer
= build_peer(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
11356 if (ast_test_flag(peer
, IAX_DYNAMIC
))
11357 reg_source_db(peer
);
11358 ao2_link(peers
, peer
);
11359 peer
= peer_unref(peer
);
11361 } else if (strcasecmp(utype
, "user")) {
11362 ast_log(LOG_WARNING
, "Unknown type '%s' for '%s' in %s\n", utype
, cat
, config_file
);
11365 ast_log(LOG_WARNING
, "Section '%s' lacks type\n", cat
);
11367 cat
= ast_category_browse(cfg
, cat
);
11369 ast_config_destroy(cfg
);
11373 static void poke_all_peers(void)
11375 struct ao2_iterator i
;
11376 struct iax2_peer
*peer
;
11378 i
= ao2_iterator_init(peers
, 0);
11379 while ((peer
= ao2_iterator_next(&i
))) {
11380 iax2_poke_peer(peer
, 0);
11384 static int reload_config(void)
11386 char *config
= "iax.conf";
11387 struct iax2_registry
*reg
;
11389 if (set_config(config
, 1) > 0) {
11392 trunk_timed
= trunk_untimed
= 0;
11393 trunk_nmaxmtu
= trunk_maxmtu
= 0;
11394 memset(&debugaddr
, '\0', sizeof(debugaddr
));
11396 AST_LIST_LOCK(®istrations
);
11397 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
11398 iax2_do_register(reg
);
11399 AST_LIST_UNLOCK(®istrations
);
11401 /* Qualify hosts, too */
11405 reload_firmware(0);
11406 iax_provision_reload(1);
11407 ast_unload_realtime("iaxpeers");
11412 static char *handle_cli_iax2_reload(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
11416 e
->command
= "iax2 reload";
11418 "Usage: iax2 reload\n"
11419 " Reloads IAX configuration from iax.conf\n";
11427 return CLI_SUCCESS
;
11430 static int reload(void)
11432 return reload_config();
11435 static int cache_get_callno_locked(const char *data
)
11437 struct sockaddr_in sin
;
11440 struct iax_ie_data ied
;
11441 struct create_addr_info cai
;
11442 struct parsed_dial_string pds
;
11445 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
11446 /* Look for an *exact match* call. Once a call is negotiated, it can only
11447 look up entries for a single context */
11448 if (!ast_mutex_trylock(&iaxsl
[x
])) {
11449 if (iaxs
[x
] && !strcasecmp(data
, iaxs
[x
]->dproot
))
11451 ast_mutex_unlock(&iaxsl
[x
]);
11455 /* No match found, we need to create a new one */
11457 memset(&cai
, 0, sizeof(cai
));
11458 memset(&ied
, 0, sizeof(ied
));
11459 memset(&pds
, 0, sizeof(pds
));
11461 tmpstr
= ast_strdupa(data
);
11462 parse_dial_string(tmpstr
, &pds
);
11464 if (ast_strlen_zero(pds
.peer
)) {
11465 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", data
);
11469 /* Populate our address from the given */
11470 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
))
11473 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
11474 pds
.peer
, pds
.username
, pds
.password
, pds
.context
);
11476 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
11478 ast_log(LOG_WARNING
, "Unable to create call\n");
11482 ast_string_field_set(iaxs
[callno
], dproot
, data
);
11483 iaxs
[callno
]->capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
11485 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
11486 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, "TBD");
11487 /* the string format is slightly different from a standard dial string,
11488 because the context appears in the 'exten' position
11491 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.exten
);
11493 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
11494 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, IAX_CAPABILITY_FULLBANDWIDTH
);
11495 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, IAX_CAPABILITY_FULLBANDWIDTH
);
11496 /* Keep password handy */
11498 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
11500 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
11501 /* Start the call going */
11502 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
11507 static struct iax2_dpcache
*find_cache(struct ast_channel
*chan
, const char *data
, const char *context
, const char *exten
, int priority
)
11509 struct iax2_dpcache
*dp
= NULL
;
11510 struct timeval now
= ast_tvnow();
11511 int x
, com
[2], timeout
, old
= 0, outfd
, doabort
, callno
;
11512 struct ast_channel
*c
= NULL
;
11513 struct ast_frame
*f
= NULL
;
11515 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache
, dp
, cache_list
) {
11516 if (ast_tvcmp(now
, dp
->expiry
) > 0) {
11517 AST_LIST_REMOVE_CURRENT(cache_list
);
11518 if ((dp
->flags
& CACHE_FLAG_PENDING
) || dp
->callno
)
11519 ast_log(LOG_WARNING
, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp
->flags
, dp
->callno
);
11524 if (!strcmp(dp
->peercontext
, data
) && !strcmp(dp
->exten
, exten
))
11527 AST_LIST_TRAVERSE_SAFE_END
;
11530 /* No matching entry. Create a new one. */
11531 /* First, can we make a callno? */
11532 if ((callno
= cache_get_callno_locked(data
)) < 0) {
11533 ast_log(LOG_WARNING
, "Unable to generate call for '%s'\n", data
);
11536 if (!(dp
= ast_calloc(1, sizeof(*dp
)))) {
11537 ast_mutex_unlock(&iaxsl
[callno
]);
11540 ast_copy_string(dp
->peercontext
, data
, sizeof(dp
->peercontext
));
11541 ast_copy_string(dp
->exten
, exten
, sizeof(dp
->exten
));
11542 dp
->expiry
= ast_tvnow();
11543 dp
->orig
= dp
->expiry
;
11544 /* Expires in 30 mins by default */
11545 dp
->expiry
.tv_sec
+= iaxdefaultdpcache
;
11546 dp
->flags
= CACHE_FLAG_PENDING
;
11547 for (x
= 0; x
< ARRAY_LEN(dp
->waiters
); x
++)
11548 dp
->waiters
[x
] = -1;
11549 /* Insert into the lists */
11550 AST_LIST_INSERT_TAIL(&dpcache
, dp
, cache_list
);
11551 AST_LIST_INSERT_TAIL(&iaxs
[callno
]->dpentries
, dp
, peer_list
);
11552 /* Send the request if we're already up */
11553 if (ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
11554 iax2_dprequest(dp
, callno
);
11555 ast_mutex_unlock(&iaxsl
[callno
]);
11558 /* By here we must have a dp */
11559 if (dp
->flags
& CACHE_FLAG_PENDING
) {
11560 /* Okay, here it starts to get nasty. We need a pipe now to wait
11561 for a reply to come back so long as it's pending */
11562 for (x
= 0; x
< ARRAY_LEN(dp
->waiters
); x
++) {
11563 /* Find an empty slot */
11564 if (dp
->waiters
[x
] < 0)
11567 if (x
>= ARRAY_LEN(dp
->waiters
)) {
11568 ast_log(LOG_WARNING
, "No more waiter positions available\n");
11572 ast_log(LOG_WARNING
, "Unable to create pipe for comm\n");
11575 dp
->waiters
[x
] = com
[1];
11576 /* Okay, now we wait */
11577 timeout
= iaxdefaulttimeout
* 1000;
11578 /* Temporarily unlock */
11579 AST_LIST_UNLOCK(&dpcache
);
11580 /* Defer any dtmf */
11582 old
= ast_channel_defer_dtmf(chan
);
11585 c
= ast_waitfor_nandfds(&chan
, chan
? 1 : 0, &com
[0], 1, NULL
, &outfd
, &timeout
);
11590 if (!(f
= ast_read(c
))) {
11597 ast_log(LOG_WARNING
, "Timeout waiting for %s exten %s\n", data
, exten
);
11599 AST_LIST_LOCK(&dpcache
);
11600 dp
->waiters
[x
] = -1;
11604 /* Don't interpret anything, just abort. Not sure what th epoint
11605 of undeferring dtmf on a hung up channel is but hey whatever */
11607 ast_channel_undefer_dtmf(chan
);
11610 if (!(dp
->flags
& CACHE_FLAG_TIMEOUT
)) {
11611 /* Now to do non-independent analysis the results of our wait */
11612 if (dp
->flags
& CACHE_FLAG_PENDING
) {
11613 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
11614 pending. Don't let it take as long to timeout. */
11615 dp
->flags
&= ~CACHE_FLAG_PENDING
;
11616 dp
->flags
|= CACHE_FLAG_TIMEOUT
;
11617 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
11618 systems without leaving it unavailable once the server comes back online */
11619 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ 60;
11620 for (x
= 0; x
< ARRAY_LEN(dp
->waiters
); x
++) {
11621 if (dp
->waiters
[x
] > -1)
11622 write(dp
->waiters
[x
], "asdf", 4);
11626 /* Our caller will obtain the rest */
11628 ast_channel_undefer_dtmf(chan
);
11633 /*! \brief Part of the IAX2 switch interface */
11634 static int iax2_exists(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
11637 struct iax2_dpcache
*dp
= NULL
;
11639 ast_log(LOG_NOTICE
, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
11641 if ((priority
!= 1) && (priority
!= 2))
11644 AST_LIST_LOCK(&dpcache
);
11645 if ((dp
= find_cache(chan
, data
, context
, exten
, priority
))) {
11646 if (dp
->flags
& CACHE_FLAG_EXISTS
)
11649 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
11651 AST_LIST_UNLOCK(&dpcache
);
11656 /*! \brief part of the IAX2 dial plan switch interface */
11657 static int iax2_canmatch(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
11660 struct iax2_dpcache
*dp
= NULL
;
11662 ast_log(LOG_NOTICE
, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
11664 if ((priority
!= 1) && (priority
!= 2))
11667 AST_LIST_LOCK(&dpcache
);
11668 if ((dp
= find_cache(chan
, data
, context
, exten
, priority
))) {
11669 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
11672 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
11674 AST_LIST_UNLOCK(&dpcache
);
11679 /*! \brief Part of the IAX2 Switch interface */
11680 static int iax2_matchmore(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
11683 struct iax2_dpcache
*dp
= NULL
;
11685 ast_log(LOG_NOTICE
, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
11687 if ((priority
!= 1) && (priority
!= 2))
11690 AST_LIST_LOCK(&dpcache
);
11691 if ((dp
= find_cache(chan
, data
, context
, exten
, priority
))) {
11692 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
11695 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
11697 AST_LIST_UNLOCK(&dpcache
);
11702 /*! \brief Execute IAX2 dialplan switch */
11703 static int iax2_exec(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
11708 struct iax2_dpcache
*dp
= NULL
;
11709 struct ast_app
*dial
= NULL
;
11711 ast_log(LOG_NOTICE
, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
, newstack
);
11713 if (priority
== 2) {
11714 /* Indicate status, can be overridden in dialplan */
11715 const char *dialstatus
= pbx_builtin_getvar_helper(chan
, "DIALSTATUS");
11717 dial
= pbx_findapp(dialstatus
);
11719 pbx_exec(chan
, dial
, "");
11722 } else if (priority
!= 1)
11725 AST_LIST_LOCK(&dpcache
);
11726 if ((dp
= find_cache(chan
, data
, context
, exten
, priority
))) {
11727 if (dp
->flags
& CACHE_FLAG_EXISTS
) {
11728 ast_copy_string(odata
, data
, sizeof(odata
));
11729 ncontext
= strchr(odata
, '/');
11733 snprintf(req
, sizeof(req
), "IAX2/%s/%s@%s", odata
, exten
, ncontext
);
11735 snprintf(req
, sizeof(req
), "IAX2/%s/%s", odata
, exten
);
11737 ast_verb(3, "Executing Dial('%s')\n", req
);
11739 AST_LIST_UNLOCK(&dpcache
);
11740 ast_log(LOG_WARNING
, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten
, context
, data
);
11744 AST_LIST_UNLOCK(&dpcache
);
11746 if ((dial
= pbx_findapp("Dial")))
11747 return pbx_exec(chan
, dial
, req
);
11749 ast_log(LOG_WARNING
, "No dial application registered\n");
11754 static int function_iaxpeer(struct ast_channel
*chan
, const char *cmd
, char *data
, char *buf
, size_t len
)
11756 struct iax2_peer
*peer
;
11757 char *peername
, *colname
;
11759 peername
= ast_strdupa(data
);
11761 /* if our channel, return the IP address of the endpoint of current channel */
11762 if (!strcmp(peername
,"CURRENTCHANNEL")) {
11763 unsigned short callno
;
11764 if (chan
->tech
!= &iax2_tech
)
11766 callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
11767 ast_copy_string(buf
, iaxs
[callno
]->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
) : "", len
);
11771 if ((colname
= strchr(peername
, ',')))
11776 if (!(peer
= find_peer(peername
, 1)))
11779 if (!strcasecmp(colname
, "ip")) {
11780 ast_copy_string(buf
, peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", len
);
11781 } else if (!strcasecmp(colname
, "status")) {
11782 peer_status(peer
, buf
, len
);
11783 } else if (!strcasecmp(colname
, "mailbox")) {
11784 ast_copy_string(buf
, peer
->mailbox
, len
);
11785 } else if (!strcasecmp(colname
, "context")) {
11786 ast_copy_string(buf
, peer
->context
, len
);
11787 } else if (!strcasecmp(colname
, "expire")) {
11788 snprintf(buf
, len
, "%d", peer
->expire
);
11789 } else if (!strcasecmp(colname
, "dynamic")) {
11790 ast_copy_string(buf
, (ast_test_flag(peer
, IAX_DYNAMIC
) ? "yes" : "no"), len
);
11791 } else if (!strcasecmp(colname
, "callerid_name")) {
11792 ast_copy_string(buf
, peer
->cid_name
, len
);
11793 } else if (!strcasecmp(colname
, "callerid_num")) {
11794 ast_copy_string(buf
, peer
->cid_num
, len
);
11795 } else if (!strcasecmp(colname
, "codecs")) {
11796 ast_getformatname_multiple(buf
, len
-1, peer
->capability
);
11797 } else if (!strncasecmp(colname
, "codec[", 6)) {
11798 char *codecnum
, *ptr
;
11801 codecnum
= strchr(colname
, '[');
11804 if ((ptr
= strchr(codecnum
, ']'))) {
11807 if((codec
= ast_codec_pref_index(&peer
->prefs
, atoi(codecnum
)))) {
11808 ast_copy_string(buf
, ast_getformatname(codec
), len
);
11817 struct ast_custom_function iaxpeer_function
= {
11819 .synopsis
= "Gets IAX peer information",
11820 .syntax
= "IAXPEER(<peername|CURRENTCHANNEL>[,item])",
11821 .read
= function_iaxpeer
,
11822 .desc
= "If peername specified, valid items are:\n"
11823 "- ip (default) The IP address.\n"
11824 "- status The peer's status (if qualify=yes)\n"
11825 "- mailbox The configured mailbox.\n"
11826 "- context The configured context.\n"
11827 "- expire The epoch time of the next expire.\n"
11828 "- dynamic Is it dynamic? (yes/no).\n"
11829 "- callerid_name The configured Caller ID name.\n"
11830 "- callerid_num The configured Caller ID number.\n"
11831 "- codecs The configured codecs.\n"
11832 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11834 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
11838 static int acf_channel_write(struct ast_channel
*chan
, const char *function
, char *args
, const char *value
)
11840 struct chan_iax2_pvt
*pvt
;
11841 unsigned int callno
;
11844 if (!chan
|| chan
->tech
!= &iax2_tech
) {
11845 ast_log(LOG_ERROR
, "This function requires a valid IAX2 channel\n");
11849 callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
11850 ast_mutex_lock(&iaxsl
[callno
]);
11851 if (!(pvt
= iaxs
[callno
])) {
11852 ast_mutex_unlock(&iaxsl
[callno
]);
11856 if (!strcasecmp(args
, "osptoken"))
11857 ast_string_field_set(pvt
, osptoken
, value
);
11861 ast_mutex_unlock(&iaxsl
[callno
]);
11866 static int acf_channel_read(struct ast_channel
*chan
, const char *funcname
, char *args
, char *buf
, size_t buflen
)
11868 struct chan_iax2_pvt
*pvt
;
11869 unsigned int callno
;
11872 if (!chan
|| chan
->tech
!= &iax2_tech
) {
11873 ast_log(LOG_ERROR
, "This function requires a valid IAX2 channel\n");
11877 callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
11878 ast_mutex_lock(&iaxsl
[callno
]);
11879 if (!(pvt
= iaxs
[callno
])) {
11880 ast_mutex_unlock(&iaxsl
[callno
]);
11884 if (!strcasecmp(args
, "osptoken")) {
11885 ast_copy_string(buf
, pvt
->osptoken
, buflen
);
11886 } else if (!strcasecmp(args
, "peerip")) {
11887 ast_copy_string(buf
, pvt
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(pvt
->addr
.sin_addr
) : "", buflen
);
11888 } else if (!strcasecmp(args
, "peername")) {
11889 ast_copy_string(buf
, pvt
->username
, buflen
);
11894 ast_mutex_unlock(&iaxsl
[callno
]);
11899 /*! \brief Part of the device state notification system ---*/
11900 static int iax2_devicestate(void *data
)
11902 struct parsed_dial_string pds
;
11903 char *tmp
= ast_strdupa(data
);
11904 struct iax2_peer
*p
;
11905 int res
= AST_DEVICE_INVALID
;
11907 memset(&pds
, 0, sizeof(pds
));
11908 parse_dial_string(tmp
, &pds
);
11910 if (ast_strlen_zero(pds
.peer
)) {
11911 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
11915 ast_debug(3, "Checking device state for device %s\n", pds
.peer
);
11917 /* SLD: FIXME: second call to find_peer during registration */
11918 if (!(p
= find_peer(pds
.peer
, 1)))
11921 res
= AST_DEVICE_UNAVAILABLE
;
11922 ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
11923 pds
.peer
, p
->addr
.sin_addr
.s_addr
, p
->defaddr
.sin_addr
.s_addr
, p
->maxms
, p
->lastms
);
11925 if ((p
->addr
.sin_addr
.s_addr
|| p
->defaddr
.sin_addr
.s_addr
) &&
11926 (!p
->maxms
|| ((p
->lastms
> -1) && (p
->historicms
<= p
->maxms
)))) {
11927 /* Peer is registered, or have default IP address
11928 and a valid registration */
11929 if (p
->historicms
== 0 || p
->historicms
<= p
->maxms
)
11930 /* let the core figure out whether it is in use or not */
11931 res
= AST_DEVICE_UNKNOWN
;
11939 static struct ast_switch iax2_switch
=
11942 description
: "IAX Remote Dialplan Switch",
11943 exists
: iax2_exists
,
11944 canmatch
: iax2_canmatch
,
11946 matchmore
: iax2_matchmore
,
11950 { { "iax2", "show", "cache", NULL },
11951 iax2_show_cache, "Display IAX cached dialplan",
11952 show_cache_usage },
11954 { { "iax2", "show", "channels", NULL },
11955 iax2_show_channels, "List active IAX channels",
11956 show_channels_usage },
11958 { { "iax2", "show", "firmware", NULL },
11959 iax2_show_firmware, "List available IAX firmwares",
11960 show_firmware_usage },
11962 { { "iax2", "show", "netstats", NULL },
11963 iax2_show_netstats, "List active IAX channel netstats",
11964 show_netstats_usage },
11966 { { "iax2", "show", "peers", NULL },
11967 iax2_show_peers, "List defined IAX peers",
11968 show_peers_usage },
11970 { { "iax2", "show", "registry", NULL },
11971 iax2_show_registry, "Display IAX registration status",
11974 { { "iax2", "show", "stats", NULL },
11975 iax2_show_stats, "Display IAX statistics",
11976 show_stats_usage },
11978 { { "iax2", "show", "threads", NULL },
11979 iax2_show_threads, "Display IAX helper thread info",
11980 show_threads_usage },
11982 { { "iax2", "unregister", NULL },
11983 iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
11984 unregister_usage, complete_iax2_unregister },
11986 { { "iax2", "set", "mtu", NULL },
11987 iax2_set_mtu, "Set the IAX systemwide trunking MTU",
11988 set_mtu_usage, NULL, NULL },
11990 { { "iax2", "show", "users", NULL },
11991 iax2_show_users, "List defined IAX users",
11992 show_users_usage },
11994 { { "iax2", "prune", "realtime", NULL },
11995 iax2_prune_realtime, "Prune a cached realtime lookup",
11996 prune_realtime_usage, complete_iax2_show_peer },
11998 { { "iax2", "reload", NULL },
11999 iax2_reload, "Reload IAX configuration",
12000 iax2_reload_usage },
12002 { { "iax2", "show", "peer", NULL },
12003 iax2_show_peer, "Show details on specific IAX peer",
12004 show_peer_usage, complete_iax2_show_peer },
12006 { { "iax2", "set", "debug", NULL },
12007 iax2_do_debug, "Enable IAX debugging",
12010 { { "iax2", "set", "debug", "trunk", NULL },
12011 iax2_do_trunk_debug, "Enable IAX trunk debugging",
12012 debug_trunk_usage },
12014 { { "iax2", "set", "debug", "jb", NULL },
12015 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
12018 { { "iax2", "set", "debug", "off", NULL },
12019 iax2_no_debug, "Disable IAX debugging",
12022 { { "iax2", "set", "debug", "trunk", "off", NULL },
12023 iax2_no_trunk_debug, "Disable IAX trunk debugging",
12024 no_debug_trunk_usage },
12026 { { "iax2", "set", "debug", "jb", "off", NULL },
12027 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
12028 no_debug_jb_usage },
12030 { { "iax2", "test", "losspct", NULL },
12031 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
12032 iax2_test_losspct_usage },
12034 { { "iax2", "provision", NULL },
12035 iax2_prov_cmd, "Provision an IAX device",
12036 show_prov_usage, iax2_prov_complete_template_3rd },
12039 { { "iax2", "test", "late", NULL },
12040 iax2_test_late, "Test the receipt of a late frame",
12041 iax2_test_late_usage },
12043 { { "iax2", "test", "resync", NULL },
12044 iax2_test_resync, "Test a resync in received timestamps",
12045 iax2_test_resync_usage },
12047 { { "iax2", "test", "jitter", NULL },
12048 iax2_test_jitter, "Simulates jitter for testing",
12049 iax2_test_jitter_usage },
12053 static struct ast_cli_entry cli_iax2
[] = {
12054 AST_CLI_DEFINE(handle_cli_iax2_provision
, "Provision an IAX device"),
12055 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime
, "Prune a cached realtime lookup"),
12056 AST_CLI_DEFINE(handle_cli_iax2_reload
, "Reload IAX configuration"),
12057 AST_CLI_DEFINE(handle_cli_iax2_set_mtu
, "Set the IAX systemwide trunking MTU"),
12058 AST_CLI_DEFINE(handle_cli_iax2_set_debug
, "Enable/Disable IAX debugging"),
12059 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk
, "Enable/Disable IAX trunk debugging"),
12060 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb
, "Enable/Disable IAX jitterbuffer debugging"),
12061 AST_CLI_DEFINE(handle_cli_iax2_show_cache
, "Display IAX cached dialplan"),
12062 AST_CLI_DEFINE(handle_cli_iax2_show_channels
, "List active IAX channels"),
12063 AST_CLI_DEFINE(handle_cli_iax2_show_firmware
, "List available IAX firmware"),
12064 AST_CLI_DEFINE(handle_cli_iax2_show_netstats
, "List active IAX channel netstats"),
12065 AST_CLI_DEFINE(handle_cli_iax2_show_peer
, "Show details on specific IAX peer"),
12066 AST_CLI_DEFINE(handle_cli_iax2_show_peers
, "List defined IAX peers"),
12067 AST_CLI_DEFINE(handle_cli_iax2_show_registry
, "Display IAX registration status"),
12068 AST_CLI_DEFINE(handle_cli_iax2_show_stats
, "Display IAX statistics"),
12069 AST_CLI_DEFINE(handle_cli_iax2_show_threads
, "Display IAX helper thread info"),
12070 AST_CLI_DEFINE(handle_cli_iax2_show_users
, "List defined IAX users"),
12071 AST_CLI_DEFINE(handle_cli_iax2_test_losspct
, "Set IAX2 incoming frame loss percentage"),
12072 AST_CLI_DEFINE(handle_cli_iax2_unregister
, "Unregister (force expiration) an IAX2 peer from the registry"),
12074 AST_CLI_DEFINE(handle_cli_iax2_test_jitter
, "Simulates jitter for testing"),
12075 AST_CLI_DEFINE(handle_cli_iax2_test_late
, "Test the receipt of a late frame"),
12076 AST_CLI_DEFINE(handle_cli_iax2_test_resync
, "Test a resync in received timestamps"),
12077 #endif /* IAXTESTS */
12080 static int __unload_module(void)
12082 struct iax2_thread
*thread
= NULL
;
12083 struct ast_context
*con
;
12086 /* Make sure threads do not hold shared resources when they are canceled */
12088 /* Grab the sched lock resource to keep it away from threads about to die */
12089 /* Cancel the network thread, close the net socket */
12090 if (netthreadid
!= AST_PTHREADT_NULL
) {
12091 AST_LIST_LOCK(&frame_queue
);
12092 ast_mutex_lock(&sched_lock
);
12093 pthread_cancel(netthreadid
);
12094 ast_cond_signal(&sched_cond
);
12095 ast_mutex_unlock(&sched_lock
); /* Release the schedule lock resource */
12096 AST_LIST_UNLOCK(&frame_queue
);
12097 pthread_join(netthreadid
, NULL
);
12099 if (schedthreadid
!= AST_PTHREADT_NULL
) {
12100 ast_mutex_lock(&sched_lock
);
12101 pthread_cancel(schedthreadid
);
12102 ast_cond_signal(&sched_cond
);
12103 ast_mutex_unlock(&sched_lock
);
12104 pthread_join(schedthreadid
, NULL
);
12107 /* Call for all threads to halt */
12108 AST_LIST_LOCK(&idle_list
);
12109 while ((thread
= AST_LIST_REMOVE_HEAD(&idle_list
, list
)))
12110 pthread_cancel(thread
->threadid
);
12111 AST_LIST_UNLOCK(&idle_list
);
12113 AST_LIST_LOCK(&active_list
);
12114 while ((thread
= AST_LIST_REMOVE_HEAD(&active_list
, list
)))
12115 pthread_cancel(thread
->threadid
);
12116 AST_LIST_UNLOCK(&active_list
);
12118 AST_LIST_LOCK(&dynamic_list
);
12119 while ((thread
= AST_LIST_REMOVE_HEAD(&dynamic_list
, list
)))
12120 pthread_cancel(thread
->threadid
);
12121 AST_LIST_UNLOCK(&dynamic_list
);
12123 /* Wait for threads to exit */
12124 while(0 < iaxactivethreadcount
)
12127 ast_netsock_release(netsock
);
12128 ast_netsock_release(outsock
);
12129 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
12134 ast_manager_unregister( "IAXpeers" );
12135 ast_manager_unregister( "IAXpeerlist" );
12136 ast_manager_unregister( "IAXnetstats" );
12137 ast_unregister_application(papp
);
12138 ast_cli_unregister_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
12139 ast_unregister_switch(&iax2_switch
);
12140 ast_channel_unregister(&iax2_tech
);
12142 iax_provision_unload();
12143 sched_context_destroy(sched
);
12144 reload_firmware(1);
12146 for (x
= 0; x
< ARRAY_LEN(iaxsl
); x
++) {
12147 ast_mutex_destroy(&iaxsl
[x
]);
12150 ao2_ref(peers
, -1);
12151 ao2_ref(users
, -1);
12152 ao2_ref(iax_peercallno_pvts
, -1);
12154 if (timingfd
> -1) {
12155 ast_timer_close(timingfd
);
12158 con
= ast_context_find(regcontext
);
12160 ast_context_destroy(con
, "IAX2");
12161 ast_unload_realtime("iaxpeers");
12165 static int unload_module(void)
12167 ast_custom_function_unregister(&iaxpeer_function
);
12168 ast_custom_function_unregister(&iaxvar_function
);
12169 return __unload_module();
12172 static int peer_set_sock_cb(void *obj
, void *arg
, int flags
)
12174 struct iax2_peer
*peer
= obj
;
12176 if (peer
->sockfd
< 0)
12177 peer
->sockfd
= defaultsockfd
;
12182 static int pvt_hash_cb(const void *obj
, const int flags
)
12184 const struct chan_iax2_pvt
*pvt
= obj
;
12186 return pvt
->peercallno
;
12189 static int pvt_cmp_cb(void *obj
, void *arg
, int flags
)
12191 struct chan_iax2_pvt
*pvt
= obj
, *pvt2
= arg
;
12193 /* The frames_received field is used to hold whether we're matching
12194 * against a full frame or not ... */
12196 return match(&pvt2
->addr
, pvt2
->peercallno
, pvt2
->callno
, pvt
,
12197 pvt2
->frames_received
) ? CMP_MATCH
| CMP_STOP
: 0;
12200 /*! \brief Load IAX2 module, load configuraiton ---*/
12201 static int load_module(void)
12203 char *config
= "iax.conf";
12205 struct iax2_registry
*reg
= NULL
;
12207 peers
= ao2_container_alloc(MAX_PEER_BUCKETS
, peer_hash_cb
, peer_cmp_cb
);
12209 return AST_MODULE_LOAD_FAILURE
;
12210 users
= ao2_container_alloc(MAX_USER_BUCKETS
, user_hash_cb
, user_cmp_cb
);
12212 ao2_ref(peers
, -1);
12213 return AST_MODULE_LOAD_FAILURE
;
12215 iax_peercallno_pvts
= ao2_container_alloc(IAX_MAX_CALLS
, pvt_hash_cb
, pvt_cmp_cb
);
12216 if (!iax_peercallno_pvts
) {
12217 ao2_ref(peers
, -1);
12218 ao2_ref(users
, -1);
12219 return AST_MODULE_LOAD_FAILURE
;
12222 ast_custom_function_register(&iaxpeer_function
);
12223 ast_custom_function_register(&iaxvar_function
);
12225 iax_set_output(iax_debug_output
);
12226 iax_set_error(iax_error_output
);
12227 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
12229 memset(iaxs
, 0, sizeof(iaxs
));
12231 for (x
= 0; x
< ARRAY_LEN(iaxsl
); x
++) {
12232 ast_mutex_init(&iaxsl
[x
]);
12235 ast_cond_init(&sched_cond
, NULL
);
12237 if (!(sched
= sched_context_create())) {
12238 ast_log(LOG_ERROR
, "Failed to create scheduler context\n");
12239 return AST_MODULE_LOAD_FAILURE
;
12242 if (!(io
= io_context_create())) {
12243 ast_log(LOG_ERROR
, "Failed to create I/O context\n");
12244 sched_context_destroy(sched
);
12245 return AST_MODULE_LOAD_FAILURE
;
12248 if (!(netsock
= ast_netsock_list_alloc())) {
12249 ast_log(LOG_ERROR
, "Failed to create netsock list\n");
12250 io_context_destroy(io
);
12251 sched_context_destroy(sched
);
12252 return AST_MODULE_LOAD_FAILURE
;
12254 ast_netsock_init(netsock
);
12256 outsock
= ast_netsock_list_alloc();
12258 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
12259 io_context_destroy(io
);
12260 sched_context_destroy(sched
);
12261 return AST_MODULE_LOAD_FAILURE
;
12263 ast_netsock_init(outsock
);
12265 ast_cli_register_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
12267 ast_register_application(papp
, iax2_prov_app
, psyn
, pdescrip
);
12269 ast_manager_register( "IAXpeers", EVENT_FLAG_SYSTEM
| EVENT_FLAG_REPORTING
, manager_iax2_show_peers
, "List IAX Peers" );
12270 ast_manager_register( "IAXpeerlist", EVENT_FLAG_SYSTEM
| EVENT_FLAG_REPORTING
, manager_iax2_show_peer_list
, "List IAX Peers" );
12271 ast_manager_register( "IAXnetstats", EVENT_FLAG_SYSTEM
| EVENT_FLAG_REPORTING
, manager_iax2_show_netstats
, "Show IAX Netstats" );
12273 if(set_config(config
, 0) == -1)
12274 return AST_MODULE_LOAD_DECLINE
;
12276 timingfd
= ast_timer_open();
12277 if (timingfd
> -1) {
12278 ast_timer_set_rate(timingfd
, trunkfreq
);
12281 if (ast_channel_register(&iax2_tech
)) {
12282 ast_log(LOG_ERROR
, "Unable to register channel class %s\n", "IAX2");
12284 return AST_MODULE_LOAD_FAILURE
;
12287 if (ast_register_switch(&iax2_switch
))
12288 ast_log(LOG_ERROR
, "Unable to register IAX switch\n");
12290 if (start_network_thread()) {
12291 ast_log(LOG_ERROR
, "Unable to start network thread\n");
12293 return AST_MODULE_LOAD_FAILURE
;
12295 ast_verb(2, "IAX Ready and Listening\n");
12297 AST_LIST_LOCK(®istrations
);
12298 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
12299 iax2_do_register(reg
);
12300 AST_LIST_UNLOCK(®istrations
);
12302 ao2_callback(peers
, 0, peer_set_sock_cb
, NULL
);
12303 ao2_callback(peers
, 0, iax2_poke_peer_cb
, NULL
);
12306 reload_firmware(0);
12307 iax_provision_reload(0);
12309 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR
, 10, "ipaddr", RQ_CHAR
, 15, "port", RQ_UINTEGER2
, 5, "regseconds", RQ_UINTEGER2
, 6, SENTINEL
);
12311 return AST_MODULE_LOAD_SUCCESS
;
12314 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Inter Asterisk eXchange (Ver 2)",
12315 .load
= load_module
,
12316 .unload
= unload_module
,