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
33 <depend>res_features</depend>
38 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
42 #include <sys/types.h>
45 #include <sys/socket.h>
46 #include <netinet/in.h>
47 #include <arpa/inet.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
51 #include <sys/signal.h>
63 #include <sys/ioctl.h>
64 #include <zaptel/zaptel.h>
67 #include "asterisk/lock.h"
68 #include "asterisk/frame.h"
69 #include "asterisk/channel.h"
70 #include "asterisk/logger.h"
71 #include "asterisk/module.h"
72 #include "asterisk/pbx.h"
73 #include "asterisk/sched.h"
74 #include "asterisk/io.h"
75 #include "asterisk/config.h"
76 #include "asterisk/options.h"
77 #include "asterisk/cli.h"
78 #include "asterisk/translate.h"
79 #include "asterisk/md5.h"
80 #include "asterisk/cdr.h"
81 #include "asterisk/crypto.h"
82 #include "asterisk/acl.h"
83 #include "asterisk/manager.h"
84 #include "asterisk/callerid.h"
85 #include "asterisk/app.h"
86 #include "asterisk/astdb.h"
87 #include "asterisk/musiconhold.h"
88 #include "asterisk/features.h"
89 #include "asterisk/utils.h"
90 #include "asterisk/causes.h"
91 #include "asterisk/localtime.h"
92 #include "asterisk/aes.h"
93 #include "asterisk/dnsmgr.h"
94 #include "asterisk/devicestate.h"
95 #include "asterisk/netsock.h"
96 #include "asterisk/stringfields.h"
97 #include "asterisk/linkedlists.h"
98 #include "asterisk/astobj2.h"
101 #include "iax2-parser.h"
102 #include "iax2-provision.h"
103 #include "jitterbuf.h"
105 /* Define SCHED_MULTITHREADED to run the scheduler in a special
106 multithreaded mode. */
107 #define SCHED_MULTITHREADED
109 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
110 thread is actually doing. */
111 #define DEBUG_SCHED_MULTITHREAD
113 #ifndef IPTOS_MINCOST
114 #define IPTOS_MINCOST 0x02
118 static int nochecksums
= 0;
122 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
123 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
125 #define DEFAULT_THREAD_COUNT 10
126 #define DEFAULT_MAX_THREAD_COUNT 100
127 #define DEFAULT_RETRY_TIME 1000
128 #define MEMORY_SIZE 100
129 #define DEFAULT_DROP 3
130 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
131 but keeps the division between trunked and non-trunked better. */
132 #define TRUNK_CALL_START 0x4000
134 #define DEBUG_SUPPORT
136 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
138 /* Sample over last 100 units to determine historic jitter */
141 static struct ast_codec_pref prefs
;
143 static const char tdesc
[] = "Inter Asterisk eXchange Driver (Ver 2)";
145 static char context
[80] = "default";
147 static char language
[MAX_LANGUAGE
] = "";
148 static char regcontext
[AST_MAX_CONTEXT
] = "";
150 static int maxauthreq
= 3;
151 static int max_retries
= 4;
152 static int ping_time
= 21;
153 static int lagrq_time
= 10;
154 static int maxtrunkcall
= TRUNK_CALL_START
;
155 static int maxnontrunkcall
= 1;
156 static int maxjitterbuffer
=1000;
157 static int resyncthreshold
=1000;
158 static int maxjitterinterps
=10;
159 static int trunkfreq
= 20;
160 static int authdebug
= 1;
161 static int autokill
= 0;
162 static int iaxcompat
= 0;
164 static int iaxdefaultdpcache
=10 * 60; /* Cache dialplan entries for 10 minutes by default */
166 static int iaxdefaulttimeout
= 5; /* Default to wait no more than 5 seconds for a reply to come back */
168 static unsigned int tos
= 0;
170 static int min_reg_expire
;
171 static int max_reg_expire
;
173 static int timingfd
= -1; /* Timing file descriptor */
175 static struct ast_netsock_list
*netsock
;
176 static struct ast_netsock_list
*outsock
; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
177 static int defaultsockfd
= -1;
179 int (*iax2_regfunk
)(const char *username
, int onoff
) = NULL
;
182 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
184 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
185 ~AST_FORMAT_SLINEAR & \
190 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
192 ~AST_FORMAT_G726_AAL2 & \
195 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
199 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
200 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
201 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
203 static struct io_context
*io
;
204 static struct sched_context
*sched
;
206 static int iax2_capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
208 static int iaxdebug
= 0;
210 static int iaxtrunkdebug
= 0;
212 static int test_losspct
= 0;
214 static int test_late
= 0;
215 static int test_resync
= 0;
216 static int test_jit
= 0;
217 static int test_jitpct
= 0;
218 #endif /* IAXTESTS */
220 static char accountcode
[AST_MAX_ACCOUNT_CODE
];
221 static char mohinterpret
[MAX_MUSICCLASS
];
222 static char mohsuggest
[MAX_MUSICCLASS
];
223 static int amaflags
= 0;
225 static int delayreject
= 0;
226 static int iax2_encryption
= 0;
228 static struct ast_flags globalflags
= { 0 };
230 static pthread_t netthreadid
= AST_PTHREADT_NULL
;
231 static pthread_t schedthreadid
= AST_PTHREADT_NULL
;
232 AST_MUTEX_DEFINE_STATIC(sched_lock
);
233 static ast_cond_t sched_cond
;
236 IAX_STATE_STARTED
= (1 << 0),
237 IAX_STATE_AUTHENTICATED
= (1 << 1),
238 IAX_STATE_TBD
= (1 << 2),
239 IAX_STATE_UNCHANGED
= (1 << 3),
242 struct iax2_context
{
243 char context
[AST_MAX_CONTEXT
];
244 struct iax2_context
*next
;
248 IAX_HASCALLERID
= (1 << 0), /*!< CallerID has been specified */
249 IAX_DELME
= (1 << 1), /*!< Needs to be deleted */
250 IAX_TEMPONLY
= (1 << 2), /*!< Temporary (realtime) */
251 IAX_TRUNK
= (1 << 3), /*!< Treat as a trunk */
252 IAX_NOTRANSFER
= (1 << 4), /*!< Don't native bridge */
253 IAX_USEJITTERBUF
= (1 << 5), /*!< Use jitter buffer */
254 IAX_DYNAMIC
= (1 << 6), /*!< dynamic peer */
255 IAX_SENDANI
= (1 << 7), /*!< Send ANI along with CallerID */
256 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
257 IAX_ALREADYGONE
= (1 << 9), /*!< Already disconnected */
258 IAX_PROVISION
= (1 << 10), /*!< This is a provisioning request */
259 IAX_QUELCH
= (1 << 11), /*!< Whether or not we quelch audio */
260 IAX_ENCRYPTED
= (1 << 12), /*!< Whether we should assume encrypted tx/rx */
261 IAX_KEYPOPULATED
= (1 << 13), /*!< Whether we have a key populated */
262 IAX_CODEC_USER_FIRST
= (1 << 14), /*!< are we willing to let the other guy choose the codec? */
263 IAX_CODEC_NOPREFS
= (1 << 15), /*!< Force old behaviour by turning off prefs */
264 IAX_CODEC_NOCAP
= (1 << 16), /*!< only consider requested format and ignore capabilities*/
265 IAX_RTCACHEFRIENDS
= (1 << 17), /*!< let realtime stay till your reload */
266 IAX_RTUPDATE
= (1 << 18), /*!< Send a realtime update */
267 IAX_RTAUTOCLEAR
= (1 << 19), /*!< erase me on expire */
268 IAX_FORCEJITTERBUF
= (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
269 IAX_RTIGNOREREGEXPIRE
= (1 << 21), /*!< When using realtime, ignore registration expiration */
270 IAX_TRUNKTIMESTAMPS
= (1 << 22), /*!< Send trunk timestamps */
271 IAX_TRANSFERMEDIA
= (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
272 IAX_MAXAUTHREQ
= (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
273 IAX_DELAYPBXSTART
= (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
274 response, so that we've achieved a three-way handshake with
275 them before sending voice or anything else*/
278 static int global_rtautoclear
= 120;
280 static int reload_config(void);
281 static int iax2_reload(int fd
, int argc
, char *argv
[]);
285 AST_DECLARE_STRING_FIELDS(
286 AST_STRING_FIELD(name
);
287 AST_STRING_FIELD(secret
);
288 AST_STRING_FIELD(dbsecret
);
289 AST_STRING_FIELD(accountcode
);
290 AST_STRING_FIELD(mohinterpret
);
291 AST_STRING_FIELD(mohsuggest
);
292 AST_STRING_FIELD(inkeys
); /*!< Key(s) this user can use to authenticate to us */
293 AST_STRING_FIELD(language
);
294 AST_STRING_FIELD(cid_num
);
295 AST_STRING_FIELD(cid_name
);
304 int maxauthreq
; /*!< Maximum allowed outstanding AUTHREQs */
305 int curauthreq
; /*!< Current number of outstanding AUTHREQs */
306 struct ast_codec_pref prefs
;
308 struct iax2_context
*contexts
;
309 struct ast_variable
*vars
;
313 AST_DECLARE_STRING_FIELDS(
314 AST_STRING_FIELD(name
);
315 AST_STRING_FIELD(username
);
316 AST_STRING_FIELD(secret
);
317 AST_STRING_FIELD(dbsecret
);
318 AST_STRING_FIELD(outkey
); /*!< What key we use to talk to this peer */
320 AST_STRING_FIELD(regexten
); /*!< Extension to register (if regcontext is used) */
321 AST_STRING_FIELD(context
); /*!< For transfers only */
322 AST_STRING_FIELD(peercontext
); /*!< Context to pass to peer */
323 AST_STRING_FIELD(mailbox
); /*!< Mailbox */
324 AST_STRING_FIELD(mohinterpret
);
325 AST_STRING_FIELD(mohsuggest
);
326 AST_STRING_FIELD(inkeys
); /*!< Key(s) this peer can use to authenticate to us */
327 /* Suggested caller id if registering */
328 AST_STRING_FIELD(cid_num
); /*!< Default context (for transfer really) */
329 AST_STRING_FIELD(cid_name
); /*!< Default context (for transfer really) */
330 AST_STRING_FIELD(zonetag
); /*!< Time Zone */
332 struct ast_codec_pref prefs
;
333 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
334 struct sockaddr_in addr
;
336 int sockfd
; /*!< Socket to use for transmission */
341 /* Dynamic Registration fields */
342 struct sockaddr_in defaddr
; /*!< Default address if there is one */
343 int authmethods
; /*!< Authentication methods (IAX_AUTH_*) */
344 int encmethods
; /*!< Encryption methods (IAX_ENCRYPT_*) */
346 int expire
; /*!< Schedule entry for expiry */
347 int expiry
; /*!< How soon to expire */
348 int capability
; /*!< Capability */
351 int callno
; /*!< Call number of POKE request */
352 int pokeexpire
; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
353 int lastms
; /*!< How long last response took (in ms), or -1 for no response */
354 int maxms
; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
356 int pokefreqok
; /*!< How often to check if the host is up */
357 int pokefreqnotok
; /*!< How often to check when the host has been determined to be down */
358 int historicms
; /*!< How long recent average responses took */
359 int smoothing
; /*!< Sample over how many units to determine historic ms */
364 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
366 static struct iax2_trunk_peer
{
369 struct sockaddr_in addr
;
370 struct timeval txtrunktime
; /*!< Transmit trunktime */
371 struct timeval rxtrunktime
; /*!< Receive trunktime */
372 struct timeval lasttxtime
; /*!< Last transmitted trunktime */
373 struct timeval trunkact
; /*!< Last trunk activity */
374 unsigned int lastsent
; /*!< Last sent time */
375 /* Trunk data and length */
376 unsigned char *trunkdata
;
377 unsigned int trunkdatalen
;
378 unsigned int trunkdataalloc
;
379 struct iax2_trunk_peer
*next
;
384 AST_MUTEX_DEFINE_STATIC(tpeerlock
);
386 struct iax_firmware
{
387 struct iax_firmware
*next
;
391 struct ast_iax2_firmware_header
*fwh
;
396 REG_STATE_UNREGISTERED
= 0,
399 REG_STATE_REGISTERED
,
405 enum iax_transfer_state
{
410 TRANSFER_PASSTHROUGH
,
414 TRANSFER_MPASSTHROUGH
,
419 struct iax2_registry
{
420 struct sockaddr_in addr
; /*!< Who we connect to for registration purposes */
422 char secret
[80]; /*!< Password or key name in []'s */
424 int expire
; /*!< Sched ID of expiration */
425 int refresh
; /*!< How often to refresh */
426 enum iax_reg_state regstate
;
427 int messages
; /*!< Message count, low 8 bits = new, high 8 bits = old */
428 int callno
; /*!< Associated call number if applicable */
429 struct sockaddr_in us
; /*!< Who the server thinks we are */
430 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
431 AST_LIST_ENTRY(iax2_registry
) entry
;
434 static AST_LIST_HEAD_STATIC(registrations
, iax2_registry
);
436 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
437 #define MIN_RETRY_TIME 100
438 #define MAX_RETRY_TIME 10000
440 #define MAX_JITTER_BUFFER 50
441 #define MIN_JITTER_BUFFER 10
443 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
444 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
446 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
448 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
449 #define TS_GAP_FOR_JB_RESYNC 5000
451 static int iaxthreadcount
= DEFAULT_THREAD_COUNT
;
452 static int iaxmaxthreadcount
= DEFAULT_MAX_THREAD_COUNT
;
453 static int iaxdynamicthreadcount
= 0;
454 static int iaxactivethreadcount
= 0;
466 struct chan_iax2_pvt
{
467 /*! Socket to send/receive on for this call */
469 /*! Last received voice format */
471 /*! Last received video format */
473 /*! Last sent voice format */
475 /*! Last sent video format */
477 /*! What we are capable of sending */
479 /*! Last received timestamp */
481 /*! Last sent timestamp - never send the same timestamp twice in a single call */
482 unsigned int lastsent
;
483 /*! Timestamp of the last video frame sent */
484 unsigned int lastvsent
;
485 /*! Next outgoing timestamp if everything is good */
486 unsigned int nextpred
;
487 /*! True if the last voice we transmitted was not silence/CNG */
490 unsigned int pingtime
;
491 /*! Max time for initial response */
494 struct sockaddr_in addr
;
495 /*! Actual used codec preferences */
496 struct ast_codec_pref prefs
;
497 /*! Requested codec preferences */
498 struct ast_codec_pref rprefs
;
499 /*! Our call number */
500 unsigned short callno
;
502 unsigned short peercallno
;
503 /*! Negotiated format, this is only used to remember what format was
504 chosen for an unauthenticated call so that the channel can get
505 created later using the right format */
507 /*! Peer selected format */
509 /*! Peer capability */
511 /*! timeval that we base our transmission on */
512 struct timeval offset
;
513 /*! timeval that we base our delivery on */
514 struct timeval rxcore
;
515 /*! The jitterbuffer */
517 /*! active jb read scheduler id */
521 /*! Error, as discovered by the manager */
523 /*! Owner if we have one */
524 struct ast_channel
*owner
;
525 /*! What's our state? */
526 struct ast_flags state
;
527 /*! Expiry (optional) */
529 /*! Next outgoing sequence number */
530 unsigned char oseqno
;
531 /*! Next sequence number they have not yet acknowledged */
532 unsigned char rseqno
;
533 /*! Next incoming sequence number */
534 unsigned char iseqno
;
535 /*! Last incoming sequence number we have acknowledged */
536 unsigned char aseqno
;
538 AST_DECLARE_STRING_FIELDS(
540 AST_STRING_FIELD(peer
);
541 /*! Default Context */
542 AST_STRING_FIELD(context
);
543 /*! Caller ID if available */
544 AST_STRING_FIELD(cid_num
);
545 AST_STRING_FIELD(cid_name
);
546 /*! Hidden Caller ID (i.e. ANI) if appropriate */
547 AST_STRING_FIELD(ani
);
549 AST_STRING_FIELD(dnid
);
551 AST_STRING_FIELD(rdnis
);
552 /*! Requested Extension */
553 AST_STRING_FIELD(exten
);
554 /*! Expected Username */
555 AST_STRING_FIELD(username
);
556 /*! Expected Secret */
557 AST_STRING_FIELD(secret
);
559 AST_STRING_FIELD(challenge
);
560 /*! Public keys permitted keys for incoming authentication */
561 AST_STRING_FIELD(inkeys
);
562 /*! Private key for outgoing authentication */
563 AST_STRING_FIELD(outkey
);
564 /*! Preferred language */
565 AST_STRING_FIELD(language
);
566 /*! Hostname/peername for naming purposes */
567 AST_STRING_FIELD(host
);
569 AST_STRING_FIELD(dproot
);
570 AST_STRING_FIELD(accountcode
);
571 AST_STRING_FIELD(mohinterpret
);
572 AST_STRING_FIELD(mohsuggest
);
575 /*! permitted authentication methods */
577 /*! permitted encryption methods */
579 /*! Encryption AES-128 Key */
581 /*! Decryption AES-128 Key */
583 /*! 32 bytes of semi-random data */
584 unsigned char semirand
[32];
585 /*! Associated registry */
586 struct iax2_registry
*reg
;
587 /*! Associated peer for poking */
588 struct iax2_peer
*peerpoke
;
593 /*! Transferring status */
594 enum iax_transfer_state transferring
;
595 /*! Transfer identifier */
597 /*! Who we are IAX transfering to */
598 struct sockaddr_in transfer
;
599 /*! What's the new call number for the transfer */
600 unsigned short transfercallno
;
601 /*! Transfer decrypt AES-128 Key */
602 aes_encrypt_ctx tdcx
;
604 /*! Status of knowledge of peer ADSI capability */
607 /*! Who we are bridged to */
608 unsigned short bridgecallno
;
610 int pingid
; /*!< Transmit PING request */
611 int lagid
; /*!< Retransmit lag request */
612 int autoid
; /*!< Auto hangup for Dialplan requestor */
613 int authid
; /*!< Authentication rejection ID */
614 int authfail
; /*!< Reason to report failure */
615 int initid
; /*!< Initial peer auto-congest ID (based on qualified peers) */
620 struct iax2_dpcache
*dpentries
;
621 struct ast_variable
*vars
;
622 /*! last received remote rr */
623 struct iax_rr remote_rr
;
624 /*! Current base time: (just for stats) */
626 /*! Dropped frame count: (just for stats) */
628 /*! received frame count: (just for stats) */
632 static struct ast_iax2_queue
{
633 AST_LIST_HEAD(, iax_frame
) queue
;
638 * This module will get much higher performance when doing a lot of
639 * user and peer lookups if the number of buckets is increased from 1.
640 * However, to maintain old behavior for Asterisk 1.4, these are set to
641 * 1 by default. When using multiple buckets, search order through these
642 * containers is considered random, so you will not be able to depend on
643 * the order the entires are specified in iax.conf for matching order. */
645 #define MAX_PEER_BUCKETS 1
646 /* #define MAX_PEER_BUCKETS 17 */
648 #define MAX_PEER_BUCKETS 1
649 /* #define MAX_PEER_BUCKETS 563 */
651 static struct ao2_container
*peers
;
653 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
654 static struct ao2_container
*users
;
656 static struct ast_firmware_list
{
657 struct iax_firmware
*wares
;
661 /*! Extension exists */
662 #define CACHE_FLAG_EXISTS (1 << 0)
663 /*! Extension is nonexistent */
664 #define CACHE_FLAG_NONEXISTENT (1 << 1)
665 /*! Extension can exist */
666 #define CACHE_FLAG_CANEXIST (1 << 2)
667 /*! Waiting to hear back response */
668 #define CACHE_FLAG_PENDING (1 << 3)
670 #define CACHE_FLAG_TIMEOUT (1 << 4)
671 /*! Request transmitted */
672 #define CACHE_FLAG_TRANSMITTED (1 << 5)
674 #define CACHE_FLAG_UNKNOWN (1 << 6)
676 #define CACHE_FLAG_MATCHMORE (1 << 7)
678 static struct iax2_dpcache
{
679 char peercontext
[AST_MAX_CONTEXT
];
680 char exten
[AST_MAX_EXTENSION
];
682 struct timeval expiry
;
684 unsigned short callno
;
686 struct iax2_dpcache
*next
;
687 struct iax2_dpcache
*peer
; /*!< For linking in peers */
690 AST_MUTEX_DEFINE_STATIC(dpcache_lock
);
692 static void reg_source_db(struct iax2_peer
*p
);
693 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
);
695 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
);
697 #define IAX_IOSTATE_IDLE 0
698 #define IAX_IOSTATE_READY 1
699 #define IAX_IOSTATE_PROCESSING 2
700 #define IAX_IOSTATE_SCHEDREADY 3
702 #define IAX_TYPE_POOL 1
703 #define IAX_TYPE_DYNAMIC 2
705 struct iax2_pkt_buf
{
706 AST_LIST_ENTRY(iax2_pkt_buf
) entry
;
708 unsigned char buf
[1];
712 AST_LIST_ENTRY(iax2_thread
) list
;
715 #ifdef SCHED_MULTITHREADED
716 void (*schedfunc
)(const void *);
717 const void *scheddata
;
719 #ifdef DEBUG_SCHED_MULTITHREAD
725 struct sockaddr_in iosin
;
726 unsigned char readbuf
[4096];
734 unsigned int ready_for_signal
:1;
735 /*! if this thread is processing a full frame,
736 some information about that frame will be stored
737 here, so we can avoid dispatching any more full
738 frames for that callno to other threads */
740 unsigned short callno
;
741 struct sockaddr_in sin
;
745 /*! Queued up full frames for processing. If more full frames arrive for
746 * a call which this thread is already processing a full frame for, they
747 * are queued up here. */
748 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf
) full_frames
;
752 static AST_LIST_HEAD_STATIC(idle_list
, iax2_thread
);
753 static AST_LIST_HEAD_STATIC(active_list
, iax2_thread
);
754 static AST_LIST_HEAD_STATIC(dynamic_list
, iax2_thread
);
756 static void *iax2_process_thread(void *data
);
758 static void signal_condition(ast_mutex_t
*lock
, ast_cond_t
*cond
)
760 ast_mutex_lock(lock
);
761 ast_cond_signal(cond
);
762 ast_mutex_unlock(lock
);
765 static void iax_debug_output(const char *data
)
768 ast_verbose("%s", data
);
771 static void iax_error_output(const char *data
)
773 ast_log(LOG_WARNING
, "%s", data
);
776 static void jb_error_output(const char *fmt
, ...)
782 vsnprintf(buf
, 1024, fmt
, args
);
785 ast_log(LOG_ERROR
, buf
);
788 static void jb_warning_output(const char *fmt
, ...)
794 vsnprintf(buf
, 1024, fmt
, args
);
797 ast_log(LOG_WARNING
, buf
);
800 static void jb_debug_output(const char *fmt
, ...)
806 vsnprintf(buf
, 1024, fmt
, args
);
812 /* XXX We probably should use a mutex when working with this XXX */
813 static struct chan_iax2_pvt
*iaxs
[IAX_MAX_CALLS
];
814 static ast_mutex_t iaxsl
[IAX_MAX_CALLS
];
815 static struct timeval lastused
[IAX_MAX_CALLS
];
817 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
);
818 static int expire_registry(const void *data
);
819 static int iax2_answer(struct ast_channel
*c
);
820 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
);
821 static int iax2_devicestate(void *data
);
822 static int iax2_digit_begin(struct ast_channel
*c
, char digit
);
823 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
);
824 static int iax2_do_register(struct iax2_registry
*reg
);
825 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
);
826 static int iax2_hangup(struct ast_channel
*c
);
827 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
);
828 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
829 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
830 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
);
831 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
);
832 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
);
833 static int iax2_sendtext(struct ast_channel
*c
, const char *text
);
834 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
);
835 static int iax2_transfer(struct ast_channel
*c
, const char *dest
);
836 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
);
837 static int send_command(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
838 static int send_command_final(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
839 static int send_command_immediate(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
840 static int send_command_locked(unsigned short callno
, char, int, unsigned int, const unsigned char *, int, int);
841 static int send_command_transfer(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int);
842 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
);
843 static struct ast_frame
*iax2_read(struct ast_channel
*c
);
844 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
845 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
846 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
);
847 static void prune_peers(void);
849 static const struct ast_channel_tech iax2_tech
= {
851 .description
= tdesc
,
852 .capabilities
= IAX_CAPABILITY_FULLBANDWIDTH
,
853 .properties
= AST_CHAN_TP_WANTSJITTER
,
854 .requester
= iax2_request
,
855 .devicestate
= iax2_devicestate
,
856 .send_digit_begin
= iax2_digit_begin
,
857 .send_digit_end
= iax2_digit_end
,
858 .send_text
= iax2_sendtext
,
859 .send_image
= iax2_sendimage
,
860 .send_html
= iax2_sendhtml
,
862 .hangup
= iax2_hangup
,
863 .answer
= iax2_answer
,
866 .write_video
= iax2_write
,
867 .indicate
= iax2_indicate
,
868 .setoption
= iax2_setoption
,
869 .bridge
= iax2_bridge
,
870 .transfer
= iax2_transfer
,
874 /* WARNING: insert_idle_thread should only ever be called within the
875 * context of an iax2_process_thread() thread.
877 static void insert_idle_thread(struct iax2_thread
*thread
)
879 if (thread
->type
== IAX_TYPE_DYNAMIC
) {
880 AST_LIST_LOCK(&dynamic_list
);
881 AST_LIST_INSERT_TAIL(&dynamic_list
, thread
, list
);
882 AST_LIST_UNLOCK(&dynamic_list
);
884 AST_LIST_LOCK(&idle_list
);
885 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
886 AST_LIST_UNLOCK(&idle_list
);
892 static struct iax2_thread
*find_idle_thread(void)
895 struct iax2_thread
*thread
= NULL
;
897 /* Pop the head of the list off */
898 AST_LIST_LOCK(&idle_list
);
899 thread
= AST_LIST_REMOVE_HEAD(&idle_list
, list
);
900 AST_LIST_UNLOCK(&idle_list
);
902 /* If no idle thread is available from the regular list, try dynamic */
903 if (thread
== NULL
) {
904 AST_LIST_LOCK(&dynamic_list
);
905 thread
= AST_LIST_REMOVE_HEAD(&dynamic_list
, list
);
906 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
907 if (thread
== NULL
&& iaxmaxthreadcount
> iaxdynamicthreadcount
) {
908 /* We need to MAKE a thread! */
909 if ((thread
= ast_calloc(1, sizeof(*thread
)))) {
910 thread
->threadnum
= iaxdynamicthreadcount
;
911 thread
->type
= IAX_TYPE_DYNAMIC
;
912 ast_mutex_init(&thread
->lock
);
913 ast_cond_init(&thread
->cond
, NULL
);
914 pthread_attr_init(&attr
);
915 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
916 if (ast_pthread_create(&thread
->threadid
, &attr
, iax2_process_thread
, thread
)) {
920 /* All went well and the thread is up, so increment our count */
921 iaxdynamicthreadcount
++;
923 /* Wait for the thread to be ready before returning it to the caller */
924 while (!thread
->ready_for_signal
)
929 AST_LIST_UNLOCK(&dynamic_list
);
932 /* this thread is not processing a full frame (since it is idle),
933 so ensure that the field for the full frame call number is empty */
935 memset(&thread
->ffinfo
, 0, sizeof(thread
->ffinfo
));
940 #ifdef SCHED_MULTITHREADED
941 static int __schedule_action(void (*func
)(const void *data
), const void *data
, const char *funcname
)
943 struct iax2_thread
*thread
= NULL
;
944 static time_t lasterror
;
947 thread
= find_idle_thread();
949 if (thread
!= NULL
) {
950 thread
->schedfunc
= func
;
951 thread
->scheddata
= data
;
952 thread
->iostate
= IAX_IOSTATE_SCHEDREADY
;
953 #ifdef DEBUG_SCHED_MULTITHREAD
954 ast_copy_string(thread
->curfunc
, funcname
, sizeof(thread
->curfunc
));
956 signal_condition(&thread
->lock
, &thread
->cond
);
960 if (t
!= lasterror
&& option_debug
)
961 ast_log(LOG_DEBUG
, "Out of idle IAX2 threads for scheduling!\n");
966 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
969 static int iax2_sched_add(struct sched_context
*con
, int when
, ast_sched_cb callback
, const void *data
)
973 res
= ast_sched_add(con
, when
, callback
, data
);
974 signal_condition(&sched_lock
, &sched_cond
);
979 static int send_ping(const void *data
);
981 static void __send_ping(const void *data
)
983 int callno
= (long)data
;
984 ast_mutex_lock(&iaxsl
[callno
]);
985 if (iaxs
[callno
] && iaxs
[callno
]->pingid
!= -1) {
986 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PING
, 0, NULL
, 0, -1);
987 iaxs
[callno
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, data
);
989 ast_mutex_unlock(&iaxsl
[callno
]);
992 static int send_ping(const void *data
)
994 #ifdef SCHED_MULTITHREADED
995 if (schedule_action(__send_ping
, data
))
1001 static int get_encrypt_methods(const char *s
)
1004 if (!strcasecmp(s
, "aes128"))
1005 e
= IAX_ENCRYPT_AES128
;
1006 else if (ast_true(s
))
1007 e
= IAX_ENCRYPT_AES128
;
1013 static int send_lagrq(const void *data
);
1015 static void __send_lagrq(const void *data
)
1017 int callno
= (long)data
;
1018 /* Ping only if it's real not if it's bridged */
1019 ast_mutex_lock(&iaxsl
[callno
]);
1020 if (iaxs
[callno
] && iaxs
[callno
]->lagid
> -1) {
1021 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_LAGRQ
, 0, NULL
, 0, -1);
1022 iaxs
[callno
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, data
);
1024 ast_mutex_unlock(&iaxsl
[callno
]);
1027 static int send_lagrq(const void *data
)
1029 #ifdef SCHED_MULTITHREADED
1030 if (schedule_action(__send_lagrq
, data
))
1036 static unsigned char compress_subclass(int subclass
)
1040 /* If it's 128 or smaller, just return it */
1041 if (subclass
< IAX_FLAG_SC_LOG
)
1043 /* Otherwise find its power */
1044 for (x
= 0; x
< IAX_MAX_SHIFT
; x
++) {
1045 if (subclass
& (1 << x
)) {
1047 ast_log(LOG_WARNING
, "Can't compress subclass %d\n", subclass
);
1053 return power
| IAX_FLAG_SC_LOG
;
1056 static int uncompress_subclass(unsigned char csub
)
1058 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1059 if (csub
& IAX_FLAG_SC_LOG
) {
1060 /* special case for 'compressed' -1 */
1064 return 1 << (csub
& ~IAX_FLAG_SC_LOG
& IAX_MAX_SHIFT
);
1071 * \note The only member of the peer passed here guaranteed to be set is the name field
1073 static int peer_hash_cb(const void *obj
, const int flags
)
1075 const struct iax2_peer
*peer
= obj
;
1077 return ast_str_hash(peer
->name
);
1081 * \note The only member of the peer passed here guaranteed to be set is the name field
1083 static int peer_cmp_cb(void *obj
, void *arg
, int flags
)
1085 struct iax2_peer
*peer
= obj
, *peer2
= arg
;
1087 return !strcasecmp(peer
->name
, peer2
->name
) ? CMP_MATCH
: 0;
1091 * \note The only member of the user passed here guaranteed to be set is the name field
1093 static int user_hash_cb(const void *obj
, const int flags
)
1095 const struct iax2_user
*user
= obj
;
1097 return ast_str_hash(user
->name
);
1101 * \note The only member of the user passed here guaranteed to be set is the name field
1103 static int user_cmp_cb(void *obj
, void *arg
, int flags
)
1105 struct iax2_user
*user
= obj
, *user2
= arg
;
1107 return !strcasecmp(user
->name
, user2
->name
) ? CMP_MATCH
: 0;
1111 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1112 * so do not call it with a pvt lock held.
1114 static struct iax2_peer
*find_peer(const char *name
, int realtime
)
1116 struct iax2_peer
*peer
= NULL
;
1117 struct iax2_peer tmp_peer
= {
1121 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
1123 /* Now go for realtime if applicable */
1124 if(!peer
&& realtime
)
1125 peer
= realtime_peer(name
, NULL
);
1130 static struct iax2_peer
*peer_ref(struct iax2_peer
*peer
)
1136 static inline struct iax2_peer
*peer_unref(struct iax2_peer
*peer
)
1142 static inline struct iax2_user
*user_ref(struct iax2_user
*user
)
1148 static inline struct iax2_user
*user_unref(struct iax2_user
*user
)
1154 static int iax2_getpeername(struct sockaddr_in sin
, char *host
, int len
)
1156 struct iax2_peer
*peer
= NULL
;
1158 struct ao2_iterator i
;
1160 i
= ao2_iterator_init(peers
, 0);
1161 while ((peer
= ao2_iterator_next(&i
))) {
1162 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
1163 (peer
->addr
.sin_port
== sin
.sin_port
)) {
1164 ast_copy_string(host
, peer
->name
, len
);
1173 peer
= realtime_peer(NULL
, &sin
);
1175 ast_copy_string(host
, peer
->name
, len
);
1184 static struct chan_iax2_pvt
*new_iax(struct sockaddr_in
*sin
, const char *host
)
1186 struct chan_iax2_pvt
*tmp
;
1189 if (!(tmp
= ast_calloc(1, sizeof(*tmp
))))
1192 if (ast_string_field_init(tmp
, 32)) {
1200 tmp
->peercallno
= 0;
1201 tmp
->transfercallno
= 0;
1202 tmp
->bridgecallno
= 0;
1209 ast_string_field_set(tmp
,exten
, "s");
1210 ast_string_field_set(tmp
,host
, host
);
1214 jbconf
.max_jitterbuf
= maxjitterbuffer
;
1215 jbconf
.resync_threshold
= resyncthreshold
;
1216 jbconf
.max_contig_interp
= maxjitterinterps
;
1217 jb_setconf(tmp
->jb
,&jbconf
);
1222 static struct iax_frame
*iaxfrdup2(struct iax_frame
*fr
)
1224 struct iax_frame
*new = iax_frame_new(DIRECTION_INGRESS
, fr
->af
.datalen
, fr
->cacheable
);
1226 size_t afdatalen
= new->afdatalen
;
1227 memcpy(new, fr
, sizeof(*new));
1228 iax_frame_wrap(new, &fr
->af
);
1229 new->afdatalen
= afdatalen
;
1232 new->direction
= DIRECTION_INGRESS
;
1238 #define NEW_PREVENT 0
1242 static int match(struct sockaddr_in
*sin
, unsigned short callno
, unsigned short dcallno
, struct chan_iax2_pvt
*cur
)
1244 if ((cur
->addr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1245 (cur
->addr
.sin_port
== sin
->sin_port
)) {
1246 /* This is the main host */
1247 if ((cur
->peercallno
== callno
) ||
1248 ((dcallno
== cur
->callno
) && !cur
->peercallno
)) {
1249 /* That's us. Be sure we keep track of the peer call number */
1253 if ((cur
->transfer
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1254 (cur
->transfer
.sin_port
== sin
->sin_port
) && (cur
->transferring
)) {
1255 /* We're transferring */
1256 if ((dcallno
== cur
->callno
) || (cur
->transferring
== TRANSFER_MEDIAPASS
&& cur
->transfercallno
== callno
))
1262 static void update_max_trunk(void)
1264 int max
= TRUNK_CALL_START
;
1266 /* XXX Prolly don't need locks here XXX */
1267 for (x
=TRUNK_CALL_START
;x
<IAX_MAX_CALLS
- 1; x
++) {
1272 if (option_debug
&& iaxdebug
)
1273 ast_log(LOG_DEBUG
, "New max trunk callno is %d\n", max
);
1276 static void update_max_nontrunk(void)
1280 /* XXX Prolly don't need locks here XXX */
1281 for (x
=1;x
<TRUNK_CALL_START
- 1; x
++) {
1285 maxnontrunkcall
= max
;
1286 if (option_debug
&& iaxdebug
)
1287 ast_log(LOG_DEBUG
, "New max nontrunk callno is %d\n", max
);
1290 static int make_trunk(unsigned short callno
, int locked
)
1295 if (iaxs
[callno
]->oseqno
) {
1296 ast_log(LOG_WARNING
, "Can't make trunk once a call has started!\n");
1299 if (callno
& TRUNK_CALL_START
) {
1300 ast_log(LOG_WARNING
, "Call %d is already a trunk\n", callno
);
1303 gettimeofday(&now
, NULL
);
1304 for (x
=TRUNK_CALL_START
;x
<IAX_MAX_CALLS
- 1; x
++) {
1305 ast_mutex_lock(&iaxsl
[x
]);
1306 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) {
1307 iaxs
[x
] = iaxs
[callno
];
1308 iaxs
[x
]->callno
= x
;
1309 iaxs
[callno
] = NULL
;
1310 /* Update the two timers that should have been started */
1311 AST_SCHED_DEL(sched
, iaxs
[x
]->pingid
);
1312 AST_SCHED_DEL(sched
, iaxs
[x
]->lagid
);
1313 iaxs
[x
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, (void *)(long)x
);
1314 iaxs
[x
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1316 ast_mutex_unlock(&iaxsl
[callno
]);
1319 ast_mutex_unlock(&iaxsl
[x
]);
1322 ast_mutex_unlock(&iaxsl
[x
]);
1324 if (x
>= IAX_MAX_CALLS
- 1) {
1325 ast_log(LOG_WARNING
, "Unable to trunk call: Insufficient space\n");
1329 ast_log(LOG_DEBUG
, "Made call %d into trunk call %d\n", callno
, x
);
1330 /* We move this call from a non-trunked to a trunked call */
1332 update_max_nontrunk();
1337 * \note Calling this function while holding another pvt lock can cause a deadlock.
1339 static int __find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int return_locked
)
1346 if (new <= NEW_ALLOW
) {
1347 /* Look for an existing connection first */
1348 for (x
=1;(res
< 1) && (x
<maxnontrunkcall
);x
++) {
1349 ast_mutex_lock(&iaxsl
[x
]);
1351 /* Look for an exact match */
1352 if (match(sin
, callno
, dcallno
, iaxs
[x
])) {
1356 ast_mutex_unlock(&iaxsl
[x
]);
1358 for (x
=TRUNK_CALL_START
;(res
< 1) && (x
<maxtrunkcall
);x
++) {
1359 ast_mutex_lock(&iaxsl
[x
]);
1361 /* Look for an exact match */
1362 if (match(sin
, callno
, dcallno
, iaxs
[x
])) {
1366 ast_mutex_unlock(&iaxsl
[x
]);
1369 if ((res
< 1) && (new >= NEW_ALLOW
)) {
1370 /* It may seem odd that we look through the peer list for a name for
1371 * this *incoming* call. Well, it is weird. However, users don't
1372 * have an IP address/port number that we can match against. So,
1373 * this is just checking for a peer that has that IP/port and
1374 * assuming that we have a user of the same name. This isn't always
1375 * correct, but it will be changed if needed after authentication. */
1376 if (!iax2_getpeername(*sin
, host
, sizeof(host
)))
1377 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
1378 gettimeofday(&now
, NULL
);
1379 for (x
=1;x
<TRUNK_CALL_START
;x
++) {
1380 /* Find first unused call number that hasn't been used in a while */
1381 ast_mutex_lock(&iaxsl
[x
]);
1382 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) break;
1383 ast_mutex_unlock(&iaxsl
[x
]);
1385 /* We've still got lock held if we found a spot */
1386 if (x
>= TRUNK_CALL_START
) {
1387 ast_log(LOG_WARNING
, "No more space\n");
1390 iaxs
[x
] = new_iax(sin
, host
);
1391 update_max_nontrunk();
1393 if (option_debug
&& iaxdebug
)
1394 ast_log(LOG_DEBUG
, "Creating new call structure %d\n", x
);
1395 iaxs
[x
]->sockfd
= sockfd
;
1396 iaxs
[x
]->addr
.sin_port
= sin
->sin_port
;
1397 iaxs
[x
]->addr
.sin_family
= sin
->sin_family
;
1398 iaxs
[x
]->addr
.sin_addr
.s_addr
= sin
->sin_addr
.s_addr
;
1399 iaxs
[x
]->peercallno
= callno
;
1400 iaxs
[x
]->callno
= x
;
1401 iaxs
[x
]->pingtime
= DEFAULT_RETRY_TIME
;
1402 iaxs
[x
]->expiry
= min_reg_expire
;
1403 iaxs
[x
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, (void *)(long)x
);
1404 iaxs
[x
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1405 iaxs
[x
]->amaflags
= amaflags
;
1406 ast_copy_flags(iaxs
[x
], (&globalflags
), IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
1408 ast_string_field_set(iaxs
[x
], accountcode
, accountcode
);
1409 ast_string_field_set(iaxs
[x
], mohinterpret
, mohinterpret
);
1410 ast_string_field_set(iaxs
[x
], mohsuggest
, mohsuggest
);
1412 ast_log(LOG_WARNING
, "Out of resources\n");
1413 ast_mutex_unlock(&iaxsl
[x
]);
1417 ast_mutex_unlock(&iaxsl
[x
]);
1423 static int find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
) {
1425 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 0);
1428 static int find_callno_locked(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
) {
1430 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 1);
1433 static void iax2_frame_free(struct iax_frame
*fr
)
1435 AST_SCHED_DEL(sched
, fr
->retrans
);
1440 * \brief Queue a frame to a call's owning asterisk channel
1442 * \pre This function assumes that iaxsl[callno] is locked when called.
1444 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1445 * was valid before calling it, it may no longer be valid after calling it.
1446 * This function may unlock and lock the mutex associated with this callno,
1447 * meaning that another thread may grab it and destroy the call.
1449 static int iax2_queue_frame(int callno
, struct ast_frame
*f
)
1452 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1453 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1454 /* Avoid deadlock by pausing and trying again */
1455 ast_mutex_unlock(&iaxsl
[callno
]);
1457 ast_mutex_lock(&iaxsl
[callno
]);
1459 ast_queue_frame(iaxs
[callno
]->owner
, f
);
1460 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1470 * \brief Queue a hangup frame on the ast_channel owner
1472 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1473 * is active for the given call number.
1475 * \pre Assumes lock for callno is already held.
1477 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1478 * was valid before calling it, it may no longer be valid after calling it.
1479 * This function may unlock and lock the mutex associated with this callno,
1480 * meaning that another thread may grab it and destroy the call.
1482 static int iax2_queue_hangup(int callno
)
1485 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1486 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1487 /* Avoid deadlock by pausing and trying again */
1488 ast_mutex_unlock(&iaxsl
[callno
]);
1490 ast_mutex_lock(&iaxsl
[callno
]);
1492 ast_queue_hangup(iaxs
[callno
]->owner
);
1493 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1503 * \brief Queue a control frame on the ast_channel owner
1505 * This function queues a control frame on the owner of the IAX2 pvt struct that
1506 * is active for the given call number.
1508 * \pre Assumes lock for callno is already held.
1510 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1511 * was valid before calling it, it may no longer be valid after calling it.
1512 * This function may unlock and lock the mutex associated with this callno,
1513 * meaning that another thread may grab it and destroy the call.
1515 static int iax2_queue_control_data(int callno
,
1516 enum ast_control_frame_type control
, const void *data
, size_t datalen
)
1519 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1520 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1521 /* Avoid deadlock by pausing and trying again */
1522 ast_mutex_unlock(&iaxsl
[callno
]);
1524 ast_mutex_lock(&iaxsl
[callno
]);
1526 ast_queue_control_data(iaxs
[callno
]->owner
, control
, data
, datalen
);
1527 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1535 static void destroy_firmware(struct iax_firmware
*cur
)
1537 /* Close firmware */
1539 munmap((void*)cur
->fwh
, ntohl(cur
->fwh
->datalen
) + sizeof(*(cur
->fwh
)));
1545 static int try_firmware(char *s
)
1548 struct iax_firmware
*cur
;
1553 struct ast_iax2_firmware_header
*fwh
, fwh2
;
1554 struct MD5Context md5
;
1555 unsigned char sum
[16];
1556 unsigned char buf
[1024];
1560 s2
= alloca(strlen(s
) + 100);
1562 ast_log(LOG_WARNING
, "Alloca failed!\n");
1565 last
= strrchr(s
, '/');
1570 snprintf(s2
, strlen(s
) + 100, "/var/tmp/%s-%ld", last
, (unsigned long)ast_random());
1571 res
= stat(s
, &stbuf
);
1573 ast_log(LOG_WARNING
, "Failed to stat '%s': %s\n", s
, strerror(errno
));
1576 /* Make sure it's not a directory */
1577 if (S_ISDIR(stbuf
.st_mode
))
1579 ifd
= open(s
, O_RDONLY
);
1581 ast_log(LOG_WARNING
, "Cannot open '%s': %s\n", s
, strerror(errno
));
1584 fd
= open(s2
, O_RDWR
| O_CREAT
| O_EXCL
, 0600);
1586 ast_log(LOG_WARNING
, "Cannot open '%s' for writing: %s\n", s2
, strerror(errno
));
1590 /* Unlink our newly created file */
1593 /* Now copy the firmware into it */
1594 len
= stbuf
.st_size
;
1597 if (chunk
> sizeof(buf
))
1598 chunk
= sizeof(buf
);
1599 res
= read(ifd
, buf
, chunk
);
1601 ast_log(LOG_WARNING
, "Only read %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1606 res
= write(fd
, buf
, chunk
);
1608 ast_log(LOG_WARNING
, "Only write %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1616 /* Return to the beginning */
1617 lseek(fd
, 0, SEEK_SET
);
1618 if ((res
= read(fd
, &fwh2
, sizeof(fwh2
))) != sizeof(fwh2
)) {
1619 ast_log(LOG_WARNING
, "Unable to read firmware header in '%s'\n", s
);
1623 if (ntohl(fwh2
.magic
) != IAX_FIRMWARE_MAGIC
) {
1624 ast_log(LOG_WARNING
, "'%s' is not a valid firmware file\n", s
);
1628 if (ntohl(fwh2
.datalen
) != (stbuf
.st_size
- sizeof(fwh2
))) {
1629 ast_log(LOG_WARNING
, "Invalid data length in firmware '%s'\n", s
);
1633 if (fwh2
.devname
[sizeof(fwh2
.devname
) - 1] || ast_strlen_zero((char *)fwh2
.devname
)) {
1634 ast_log(LOG_WARNING
, "No or invalid device type specified for '%s'\n", s
);
1638 fwh
= (struct ast_iax2_firmware_header
*)mmap(NULL
, stbuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1639 if (fwh
== (void *) -1) {
1640 ast_log(LOG_WARNING
, "mmap failed: %s\n", strerror(errno
));
1645 MD5Update(&md5
, fwh
->data
, ntohl(fwh
->datalen
));
1646 MD5Final(sum
, &md5
);
1647 if (memcmp(sum
, fwh
->chksum
, sizeof(sum
))) {
1648 ast_log(LOG_WARNING
, "Firmware file '%s' fails checksum\n", s
);
1649 munmap((void*)fwh
, stbuf
.st_size
);
1655 if (!strcmp((char *)cur
->fwh
->devname
, (char *)fwh
->devname
)) {
1656 /* Found a candidate */
1657 if (cur
->dead
|| (ntohs(cur
->fwh
->version
) < ntohs(fwh
->version
)))
1658 /* The version we have on loaded is older, load this one instead */
1660 /* This version is no newer than what we have. Don't worry about it.
1661 We'll consider it a proper load anyhow though */
1662 munmap((void*)fwh
, stbuf
.st_size
);
1669 /* Allocate a new one and link it */
1670 if ((cur
= ast_calloc(1, sizeof(*cur
)))) {
1672 cur
->next
= waresl
.wares
;
1678 munmap((void*)cur
->fwh
, cur
->mmaplen
);
1684 cur
->mmaplen
= stbuf
.st_size
;
1690 static int iax_check_version(char *dev
)
1693 struct iax_firmware
*cur
;
1694 if (!ast_strlen_zero(dev
)) {
1695 ast_mutex_lock(&waresl
.lock
);
1698 if (!strcmp(dev
, (char *)cur
->fwh
->devname
)) {
1699 res
= ntohs(cur
->fwh
->version
);
1704 ast_mutex_unlock(&waresl
.lock
);
1709 static int iax_firmware_append(struct iax_ie_data
*ied
, const unsigned char *dev
, unsigned int desc
)
1712 unsigned int bs
= desc
& 0xff;
1713 unsigned int start
= (desc
>> 8) & 0xffffff;
1715 struct iax_firmware
*cur
;
1716 if (!ast_strlen_zero((char *)dev
) && bs
) {
1718 ast_mutex_lock(&waresl
.lock
);
1721 if (!strcmp((char *)dev
, (char *)cur
->fwh
->devname
)) {
1722 iax_ie_append_int(ied
, IAX_IE_FWBLOCKDESC
, desc
);
1723 if (start
< ntohl(cur
->fwh
->datalen
)) {
1724 bytes
= ntohl(cur
->fwh
->datalen
) - start
;
1727 iax_ie_append_raw(ied
, IAX_IE_FWBLOCKDATA
, cur
->fwh
->data
+ start
, bytes
);
1730 iax_ie_append(ied
, IAX_IE_FWBLOCKDATA
);
1740 ast_mutex_unlock(&waresl
.lock
);
1746 static void reload_firmware(int unload
)
1748 struct iax_firmware
*cur
, *curl
, *curp
;
1753 /* Mark all as dead */
1754 ast_mutex_lock(&waresl
.lock
);
1761 /* Now that we've freed them, load the new ones */
1763 snprintf(dir
, sizeof(dir
), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR
);
1766 while((de
= readdir(fwd
))) {
1767 if (de
->d_name
[0] != '.') {
1768 snprintf(fn
, sizeof(fn
), "%s/%s", dir
, de
->d_name
);
1769 if (!try_firmware(fn
)) {
1770 if (option_verbose
> 1)
1771 ast_verbose(VERBOSE_PREFIX_2
"Loaded firmware '%s'\n", de
->d_name
);
1777 ast_log(LOG_WARNING
, "Error opening firmware directory '%s': %s\n", dir
, strerror(errno
));
1780 /* Clean up leftovers */
1792 destroy_firmware(curl
);
1797 ast_mutex_unlock(&waresl
.lock
);
1801 * \note This function assumes that iaxsl[callno] is locked when called.
1803 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1804 * was valid before calling it, it may no longer be valid after calling it.
1805 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1806 * associated with this callno, meaning that another thread may grab it and destroy the call.
1808 static int __do_deliver(void *data
)
1810 /* Just deliver the packet by using queueing. This is called by
1811 the IAX thread with the iaxsl lock held. */
1812 struct iax_frame
*fr
= data
;
1814 ast_clear_flag(&fr
->af
, AST_FRFLAG_HAS_TIMING_INFO
);
1815 if (iaxs
[fr
->callno
] && !ast_test_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
))
1816 iax2_queue_frame(fr
->callno
, &fr
->af
);
1817 /* Free our iax frame */
1818 iax2_frame_free(fr
);
1819 /* And don't run again */
1823 static int handle_error(void)
1825 /* XXX Ideally we should figure out why an error occured and then abort those
1826 rather than continuing to try. Unfortunately, the published interface does
1827 not seem to work XXX */
1829 struct sockaddr_in
*sin
;
1832 struct sock_extended_err e
;
1837 m
.msg_controllen
= sizeof(e
);
1839 res
= recvmsg(netsocket
, &m
, MSG_ERRQUEUE
);
1841 ast_log(LOG_WARNING
, "Error detected, but unable to read error: %s\n", strerror(errno
));
1843 if (m
.msg_controllen
) {
1844 sin
= (struct sockaddr_in
*)SO_EE_OFFENDER(&e
);
1846 ast_log(LOG_WARNING
, "Receive error from %s\n", ast_inet_ntoa(sin
->sin_addr
));
1848 ast_log(LOG_WARNING
, "No address detected??\n");
1850 ast_log(LOG_WARNING
, "Local error: %s\n", strerror(e
.ee_errno
));
1857 static int transmit_trunk(struct iax_frame
*f
, struct sockaddr_in
*sin
, int sockfd
)
1860 res
= sendto(sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)sin
,
1864 ast_log(LOG_DEBUG
, "Received error: %s\n", strerror(errno
));
1871 static int send_packet(struct iax_frame
*f
)
1874 int callno
= f
->callno
;
1876 /* Don't send if there was an error, but return error instead */
1877 if (!callno
|| !iaxs
[callno
] || iaxs
[callno
]->error
)
1880 /* Called with iaxsl held */
1881 if (option_debug
> 2 && iaxdebug
)
1882 ast_log(LOG_DEBUG
, "Sending %d on %d/%d to %s:%d\n", f
->ts
, callno
, iaxs
[callno
]->peercallno
, ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
), ntohs(iaxs
[callno
]->addr
.sin_port
));
1885 iax_showframe(f
, NULL
, 0, &iaxs
[callno
]->transfer
, f
->datalen
- sizeof(struct ast_iax2_full_hdr
));
1886 res
= sendto(iaxs
[callno
]->sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)&iaxs
[callno
]->transfer
,
1887 sizeof(iaxs
[callno
]->transfer
));
1890 iax_showframe(f
, NULL
, 0, &iaxs
[callno
]->addr
, f
->datalen
- sizeof(struct ast_iax2_full_hdr
));
1891 res
= sendto(iaxs
[callno
]->sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)&iaxs
[callno
]->addr
,
1892 sizeof(iaxs
[callno
]->addr
));
1895 if (option_debug
&& iaxdebug
)
1896 ast_log(LOG_DEBUG
, "Received error: %s\n", strerror(errno
));
1903 static void iax2_destroy_helper(struct chan_iax2_pvt
*pvt
)
1905 /* Decrement AUTHREQ count if needed */
1906 if (ast_test_flag(pvt
, IAX_MAXAUTHREQ
)) {
1907 struct iax2_user
*user
;
1908 struct iax2_user tmp_user
= {
1909 .name
= pvt
->username
,
1912 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
1914 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
1918 ast_clear_flag(pvt
, IAX_MAXAUTHREQ
);
1920 /* No more pings or lagrq's */
1921 AST_SCHED_DEL(sched
, pvt
->pingid
);
1922 AST_SCHED_DEL(sched
, pvt
->lagid
);
1923 AST_SCHED_DEL(sched
, pvt
->autoid
);
1924 AST_SCHED_DEL(sched
, pvt
->authid
);
1925 AST_SCHED_DEL(sched
, pvt
->initid
);
1926 AST_SCHED_DEL(sched
, pvt
->jbid
);
1930 * \note Since this function calls iax2_queue_hangup(), the pvt struct
1931 * for the given call number may disappear during its execution.
1933 static int iax2_predestroy(int callno
)
1935 struct ast_channel
*c
;
1936 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
1940 if (!ast_test_flag(pvt
, IAX_ALREADYGONE
)) {
1941 iax2_destroy_helper(pvt
);
1942 ast_set_flag(pvt
, IAX_ALREADYGONE
);
1947 iax2_queue_hangup(callno
);
1949 ast_module_unref(ast_module_info
->self
);
1954 static void iax2_destroy(int callno
)
1956 struct chan_iax2_pvt
*pvt
;
1957 struct iax_frame
*cur
;
1958 struct ast_channel
*owner
;
1962 gettimeofday(&lastused
[callno
], NULL
);
1964 owner
= pvt
? pvt
->owner
: NULL
;
1967 if (ast_mutex_trylock(&owner
->lock
)) {
1968 ast_log(LOG_NOTICE
, "Avoiding IAX destroy deadlock\n");
1969 ast_mutex_unlock(&iaxsl
[callno
]);
1971 ast_mutex_lock(&iaxsl
[callno
]);
1976 iaxs
[callno
] = NULL
;
1980 iax2_destroy_helper(pvt
);
1983 ast_set_flag(pvt
, IAX_ALREADYGONE
);
1986 /* If there's an owner, prod it to give up */
1987 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
1988 * because we already hold the owner channel lock. */
1989 ast_queue_hangup(owner
);
1992 AST_LIST_LOCK(&iaxq
.queue
);
1993 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
1994 /* Cancel any pending transmissions */
1995 if (cur
->callno
== pvt
->callno
)
1998 AST_LIST_UNLOCK(&iaxq
.queue
);
2001 pvt
->reg
->callno
= 0;
2005 ast_variables_destroy(pvt
->vars
);
2009 while (jb_getall(pvt
->jb
, &frame
) == JB_OK
)
2010 iax2_frame_free(frame
.data
);
2011 jb_destroy(pvt
->jb
);
2012 /* gotta free up the stringfields */
2013 ast_string_field_free_memory(pvt
);
2018 ast_mutex_unlock(&owner
->lock
);
2020 if (callno
& 0x4000)
2024 static int update_packet(struct iax_frame
*f
)
2026 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2027 struct ast_iax2_full_hdr
*fh
= f
->data
;
2028 /* Mark this as a retransmission */
2029 fh
->dcallno
= ntohs(IAX_FLAG_RETRANS
| f
->dcallno
);
2031 f
->iseqno
= iaxs
[f
->callno
]->iseqno
;
2032 fh
->iseqno
= f
->iseqno
;
2036 static int attempt_transmit(const void *data
);
2037 static void __attempt_transmit(const void *data
)
2039 /* Attempt to transmit the frame to the remote peer...
2040 Called without iaxsl held. */
2041 struct iax_frame
*f
= (struct iax_frame
*)data
;
2043 int callno
= f
->callno
;
2044 /* Make sure this call is still active */
2046 ast_mutex_lock(&iaxsl
[callno
]);
2047 if (callno
&& iaxs
[callno
]) {
2048 if ((f
->retries
< 0) /* Already ACK'd */ ||
2049 (f
->retries
>= max_retries
) /* Too many attempts */) {
2050 /* Record an error if we've transmitted too many times */
2051 if (f
->retries
>= max_retries
) {
2053 /* Transfer timeout */
2054 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, NULL
, 0, -1);
2055 } else if (f
->final
) {
2057 iax2_destroy(callno
);
2059 if (iaxs
[callno
]->owner
)
2060 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
);
2061 iaxs
[callno
]->error
= ETIMEDOUT
;
2062 if (iaxs
[callno
]->owner
) {
2063 struct ast_frame fr
= { 0, };
2065 fr
.frametype
= AST_FRAME_CONTROL
;
2066 fr
.subclass
= AST_CONTROL_HANGUP
;
2067 iax2_queue_frame(callno
, &fr
); // XXX
2068 /* Remember, owner could disappear */
2069 if (iaxs
[callno
] && iaxs
[callno
]->owner
)
2070 iaxs
[callno
]->owner
->hangupcause
= AST_CAUSE_DESTINATION_OUT_OF_ORDER
;
2072 if (iaxs
[callno
]->reg
) {
2073 memset(&iaxs
[callno
]->reg
->us
, 0, sizeof(iaxs
[callno
]->reg
->us
));
2074 iaxs
[callno
]->reg
->regstate
= REG_STATE_TIMEOUT
;
2075 iaxs
[callno
]->reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
2077 iax2_destroy(callno
);
2084 /* Update it if it needs it */
2086 /* Attempt transmission */
2089 /* Try again later after 10 times as long */
2091 if (f
->retrytime
> MAX_RETRY_TIME
)
2092 f
->retrytime
= MAX_RETRY_TIME
;
2093 /* Transfer messages max out at one second */
2094 if (f
->transfer
&& (f
->retrytime
> 1000))
2095 f
->retrytime
= 1000;
2096 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
2099 /* Make sure it gets freed */
2104 ast_mutex_unlock(&iaxsl
[callno
]);
2105 /* Do not try again */
2107 /* Don't attempt delivery, just remove it from the queue */
2108 AST_LIST_LOCK(&iaxq
.queue
);
2109 AST_LIST_REMOVE(&iaxq
.queue
, f
, list
);
2111 AST_LIST_UNLOCK(&iaxq
.queue
);
2113 /* Free the IAX frame */
2118 static int attempt_transmit(const void *data
)
2120 #ifdef SCHED_MULTITHREADED
2121 if (schedule_action(__attempt_transmit
, data
))
2123 __attempt_transmit(data
);
2127 static int iax2_prune_realtime(int fd
, int argc
, char *argv
[])
2129 struct iax2_peer
*peer
;
2132 return RESULT_SHOWUSAGE
;
2133 if (!strcmp(argv
[3],"all")) {
2135 ast_cli(fd
, "OK cache is flushed.\n");
2136 } else if ((peer
= find_peer(argv
[3], 0))) {
2137 if(ast_test_flag(peer
, IAX_RTCACHEFRIENDS
)) {
2138 ast_set_flag(peer
, IAX_RTAUTOCLEAR
);
2139 expire_registry(peer_ref(peer
));
2140 ast_cli(fd
, "OK peer %s was removed from the cache.\n", argv
[3]);
2142 ast_cli(fd
, "SORRY peer %s is not eligible for this operation.\n", argv
[3]);
2146 ast_cli(fd
, "SORRY peer %s was not found in the cache.\n", argv
[3]);
2149 return RESULT_SUCCESS
;
2152 static int iax2_test_losspct(int fd
, int argc
, char *argv
[])
2155 return RESULT_SHOWUSAGE
;
2157 test_losspct
= atoi(argv
[3]);
2159 return RESULT_SUCCESS
;
2163 static int iax2_test_late(int fd
, int argc
, char *argv
[])
2166 return RESULT_SHOWUSAGE
;
2168 test_late
= atoi(argv
[3]);
2170 return RESULT_SUCCESS
;
2173 static int iax2_test_resync(int fd
, int argc
, char *argv
[])
2176 return RESULT_SHOWUSAGE
;
2178 test_resync
= atoi(argv
[3]);
2180 return RESULT_SUCCESS
;
2183 static int iax2_test_jitter(int fd
, int argc
, char *argv
[])
2185 if (argc
< 4 || argc
> 5)
2186 return RESULT_SHOWUSAGE
;
2188 test_jit
= atoi(argv
[3]);
2190 test_jitpct
= atoi(argv
[4]);
2192 return RESULT_SUCCESS
;
2194 #endif /* IAXTESTS */
2196 /*! \brief peer_status: Report Peer status in character string */
2197 /* returns 1 if peer is online, -1 if unmonitored */
2198 static int peer_status(struct iax2_peer
*peer
, char *status
, int statuslen
)
2202 if (peer
->lastms
< 0) {
2203 ast_copy_string(status
, "UNREACHABLE", statuslen
);
2204 } else if (peer
->lastms
> peer
->maxms
) {
2205 snprintf(status
, statuslen
, "LAGGED (%d ms)", peer
->lastms
);
2207 } else if (peer
->lastms
) {
2208 snprintf(status
, statuslen
, "OK (%d ms)", peer
->lastms
);
2211 ast_copy_string(status
, "UNKNOWN", statuslen
);
2214 ast_copy_string(status
, "Unmonitored", statuslen
);
2220 /*! \brief Show one peer in detail */
2221 static int iax2_show_peer(int fd
, int argc
, char *argv
[])
2225 struct iax2_peer
*peer
;
2226 char codec_buf
[512];
2227 int x
= 0, codec
= 0, load_realtime
= 0;
2230 return RESULT_SHOWUSAGE
;
2232 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? 1 : 0;
2234 peer
= find_peer(argv
[3], load_realtime
);
2237 ast_cli(fd
, " * Name : %s\n", peer
->name
);
2238 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(peer
->secret
)?"<Not set>":"<Set>");
2239 ast_cli(fd
, " Context : %s\n", peer
->context
);
2240 ast_cli(fd
, " Mailbox : %s\n", peer
->mailbox
);
2241 ast_cli(fd
, " Dynamic : %s\n", ast_test_flag(peer
, IAX_DYNAMIC
) ? "Yes":"No");
2242 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, "<unspecified>"));
2243 ast_cli(fd
, " Expire : %d\n", peer
->expire
);
2244 ast_cli(fd
, " ACL : %s\n", (peer
->ha
?"Yes":"No"));
2245 ast_cli(fd
, " Addr->IP : %s Port %d\n", peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)", ntohs(peer
->addr
.sin_port
));
2246 ast_cli(fd
, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
2247 ast_cli(fd
, " Username : %s\n", peer
->username
);
2248 ast_cli(fd
, " Codecs : ");
2249 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
2250 ast_cli(fd
, "%s\n", codec_buf
);
2252 ast_cli(fd
, " Codec Order : (");
2253 for(x
= 0; x
< 32 ; x
++) {
2254 codec
= ast_codec_pref_index(&peer
->prefs
,x
);
2257 ast_cli(fd
, "%s", ast_getformatname(codec
));
2258 if(x
< 31 && ast_codec_pref_index(&peer
->prefs
,x
+1))
2263 ast_cli(fd
, "none");
2266 ast_cli(fd
, " Status : ");
2267 peer_status(peer
, status
, sizeof(status
));
2268 ast_cli(fd
, "%s\n",status
);
2269 ast_cli(fd
, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer
->pokefreqok
, peer
->pokefreqnotok
, peer
->smoothing
? "On" : "Off");
2273 ast_cli(fd
,"Peer %s not found.\n", argv
[3]);
2277 return RESULT_SUCCESS
;
2280 static char *complete_iax2_show_peer(const char *line
, const char *word
, int pos
, int state
)
2283 struct iax2_peer
*peer
;
2285 int wordlen
= strlen(word
);
2286 struct ao2_iterator i
;
2288 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2292 i
= ao2_iterator_init(peers
, 0);
2293 while ((peer
= ao2_iterator_next(&i
))) {
2294 if (!strncasecmp(peer
->name
, word
, wordlen
) && ++which
> state
) {
2295 res
= ast_strdup(peer
->name
);
2305 static int iax2_show_stats(int fd
, int argc
, char *argv
[])
2307 struct iax_frame
*cur
;
2308 int cnt
= 0, dead
=0, final
=0;
2311 return RESULT_SHOWUSAGE
;
2313 AST_LIST_LOCK(&iaxq
.queue
);
2314 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
2315 if (cur
->retries
< 0)
2321 AST_LIST_UNLOCK(&iaxq
.queue
);
2323 ast_cli(fd
, " IAX Statistics\n");
2324 ast_cli(fd
, "---------------------\n");
2325 ast_cli(fd
, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2326 ast_cli(fd
, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead
, final
, cnt
);
2328 return RESULT_SUCCESS
;
2331 static int iax2_show_cache(int fd
, int argc
, char *argv
[])
2333 struct iax2_dpcache
*dp
;
2334 char tmp
[1024], *pc
;
2338 gettimeofday(&tv
, NULL
);
2339 ast_mutex_lock(&dpcache_lock
);
2341 ast_cli(fd
, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2343 s
= dp
->expiry
.tv_sec
- tv
.tv_sec
;
2345 if (dp
->flags
& CACHE_FLAG_EXISTS
)
2346 strncat(tmp
, "EXISTS|", sizeof(tmp
) - strlen(tmp
) - 1);
2347 if (dp
->flags
& CACHE_FLAG_NONEXISTENT
)
2348 strncat(tmp
, "NONEXISTENT|", sizeof(tmp
) - strlen(tmp
) - 1);
2349 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
2350 strncat(tmp
, "CANEXIST|", sizeof(tmp
) - strlen(tmp
) - 1);
2351 if (dp
->flags
& CACHE_FLAG_PENDING
)
2352 strncat(tmp
, "PENDING|", sizeof(tmp
) - strlen(tmp
) - 1);
2353 if (dp
->flags
& CACHE_FLAG_TIMEOUT
)
2354 strncat(tmp
, "TIMEOUT|", sizeof(tmp
) - strlen(tmp
) - 1);
2355 if (dp
->flags
& CACHE_FLAG_TRANSMITTED
)
2356 strncat(tmp
, "TRANSMITTED|", sizeof(tmp
) - strlen(tmp
) - 1);
2357 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
2358 strncat(tmp
, "MATCHMORE|", sizeof(tmp
) - strlen(tmp
) - 1);
2359 if (dp
->flags
& CACHE_FLAG_UNKNOWN
)
2360 strncat(tmp
, "UNKNOWN|", sizeof(tmp
) - strlen(tmp
) - 1);
2361 /* Trim trailing pipe */
2362 if (!ast_strlen_zero(tmp
))
2363 tmp
[strlen(tmp
) - 1] = '\0';
2365 ast_copy_string(tmp
, "(none)", sizeof(tmp
));
2367 pc
= strchr(dp
->peercontext
, '@');
2369 pc
= dp
->peercontext
;
2372 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
2373 if (dp
->waiters
[x
] > -1)
2376 ast_cli(fd
, "%-20.20s %-12.12s %-9d %-8d %s\n", pc
, dp
->exten
, s
, y
, tmp
);
2378 ast_cli(fd
, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc
, dp
->exten
, "(expired)", y
, tmp
);
2381 ast_mutex_unlock(&dpcache_lock
);
2382 return RESULT_SUCCESS
;
2385 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
);
2387 static void unwrap_timestamp(struct iax_frame
*fr
)
2391 if ( (fr
->ts
& 0xFFFF0000) == (iaxs
[fr
->callno
]->last
& 0xFFFF0000) ) {
2392 x
= fr
->ts
- iaxs
[fr
->callno
]->last
;
2394 /* Sudden big jump backwards in timestamp:
2395 What likely happened here is that miniframe timestamp has circled but we haven't
2396 gotten the update from the main packet. We'll just pretend that we did, and
2397 update the timestamp appropriately. */
2398 fr
->ts
= ( (iaxs
[fr
->callno
]->last
& 0xFFFF0000) + 0x10000) | (fr
->ts
& 0xFFFF);
2399 if (option_debug
&& iaxdebug
)
2400 ast_log(LOG_DEBUG
, "schedule_delivery: pushed forward timestamp\n");
2403 /* Sudden apparent big jump forwards in timestamp:
2404 What's likely happened is this is an old miniframe belonging to the previous
2405 top-16-bit timestamp that has turned up out of order.
2406 Adjust the timestamp appropriately. */
2407 fr
->ts
= ( (iaxs
[fr
->callno
]->last
& 0xFFFF0000) - 0x10000) | (fr
->ts
& 0xFFFF);
2408 if (option_debug
&& iaxdebug
)
2409 ast_log(LOG_DEBUG
, "schedule_delivery: pushed back timestamp\n");
2414 static int get_from_jb(const void *p
);
2416 static void update_jbsched(struct chan_iax2_pvt
*pvt
)
2420 when
= ast_tvdiff_ms(ast_tvnow(), pvt
->rxcore
);
2422 when
= jb_next(pvt
->jb
) - when
;
2424 AST_SCHED_DEL(sched
, pvt
->jbid
);
2427 /* XXX should really just empty until when > 0.. */
2431 pvt
->jbid
= iax2_sched_add(sched
, when
, get_from_jb
, CALLNO_TO_PTR(pvt
->callno
));
2434 static void __get_from_jb(const void *p
)
2436 int callno
= PTR_TO_CALLNO(p
);
2437 struct chan_iax2_pvt
*pvt
= NULL
;
2438 struct iax_frame
*fr
;
2445 /* Make sure we have a valid private structure before going on */
2446 ast_mutex_lock(&iaxsl
[callno
]);
2450 ast_mutex_unlock(&iaxsl
[callno
]);
2456 gettimeofday(&tv
,NULL
);
2457 /* round up a millisecond since ast_sched_runq does; */
2458 /* prevents us from spinning while waiting for our now */
2459 /* to catch up with runq's now */
2462 now
= ast_tvdiff_ms(tv
, pvt
->rxcore
);
2464 if(now
>= (next
= jb_next(pvt
->jb
))) {
2465 ret
= jb_get(pvt
->jb
,&frame
,now
,ast_codec_interp_len(pvt
->voiceformat
));
2470 /* __do_deliver() can cause the call to disappear */
2475 struct ast_frame af
= { 0, };
2477 /* create an interpolation frame */
2478 af
.frametype
= AST_FRAME_VOICE
;
2479 af
.subclass
= pvt
->voiceformat
;
2480 af
.samples
= frame
.ms
* 8;
2481 af
.src
= "IAX2 JB interpolation";
2482 af
.delivery
= ast_tvadd(pvt
->rxcore
, ast_samp2tv(next
, 1000));
2483 af
.offset
= AST_FRIENDLY_OFFSET
;
2485 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2486 * which we'd need to malloc, and then it would free it. That seems like a drag */
2487 if (!ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
)) {
2488 iax2_queue_frame(callno
, &af
);
2489 /* iax2_queue_frame() could cause the call to disappear */
2495 iax2_frame_free(frame
.data
);
2502 /* shouldn't happen */
2507 update_jbsched(pvt
);
2508 ast_mutex_unlock(&iaxsl
[callno
]);
2511 static int get_from_jb(const void *data
)
2513 #ifdef SCHED_MULTITHREADED
2514 if (schedule_action(__get_from_jb
, data
))
2516 __get_from_jb(data
);
2521 * \note This function assumes fr->callno is locked
2523 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2524 * was valid before calling it, it may no longer be valid after calling it.
2526 static int schedule_delivery(struct iax_frame
*fr
, int updatehistory
, int fromtrunk
, unsigned int *tsout
)
2531 struct ast_channel
*owner
= NULL
;
2532 struct ast_channel
*bridge
= NULL
;
2534 /* Attempt to recover wrapped timestamps */
2535 unwrap_timestamp(fr
);
2537 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2538 if ( !fromtrunk
&& !ast_tvzero(iaxs
[fr
->callno
]->rxcore
))
2539 fr
->af
.delivery
= ast_tvadd(iaxs
[fr
->callno
]->rxcore
, ast_samp2tv(fr
->ts
, 1000));
2543 ast_log(LOG_DEBUG
, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2545 fr
->af
.delivery
= ast_tv(0,0);
2548 type
= JB_TYPE_CONTROL
;
2551 if(fr
->af
.frametype
== AST_FRAME_VOICE
) {
2552 type
= JB_TYPE_VOICE
;
2553 len
= ast_codec_get_samples(&fr
->af
) / 8;
2554 } else if(fr
->af
.frametype
== AST_FRAME_CNG
) {
2555 type
= JB_TYPE_SILENCE
;
2558 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_USEJITTERBUF
)) ) {
2565 if ((owner
= iaxs
[fr
->callno
]->owner
))
2566 bridge
= ast_bridged_channel(owner
);
2568 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2569 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2570 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_FORCEJITTERBUF
)) && owner
&& bridge
&& (bridge
->tech
->properties
& AST_CHAN_TP_WANTSJITTER
) ) {
2573 /* deliver any frames in the jb */
2574 while (jb_getall(iaxs
[fr
->callno
]->jb
, &frame
) == JB_OK
) {
2575 __do_deliver(frame
.data
);
2576 /* __do_deliver() can make the call disappear */
2577 if (!iaxs
[fr
->callno
])
2581 jb_reset(iaxs
[fr
->callno
]->jb
);
2583 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->jbid
);
2585 /* deliver this frame now */
2592 /* insert into jitterbuffer */
2593 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2594 ret
= jb_put(iaxs
[fr
->callno
]->jb
, fr
, type
, len
, fr
->ts
,
2595 calc_rxstamp(iaxs
[fr
->callno
],fr
->ts
));
2596 if (ret
== JB_DROP
) {
2598 } else if (ret
== JB_SCHED
) {
2599 update_jbsched(iaxs
[fr
->callno
]);
2604 /* Free our iax frame */
2605 iax2_frame_free(fr
);
2611 static int iax2_transmit(struct iax_frame
*fr
)
2613 /* Lock the queue and place this packet at the end */
2614 /* By setting this to 0, the network thread will send it for us, and
2615 queue retransmission if necessary */
2617 AST_LIST_LOCK(&iaxq
.queue
);
2618 AST_LIST_INSERT_TAIL(&iaxq
.queue
, fr
, list
);
2620 AST_LIST_UNLOCK(&iaxq
.queue
);
2621 /* Wake up the network and scheduler thread */
2622 if (netthreadid
!= AST_PTHREADT_NULL
)
2623 pthread_kill(netthreadid
, SIGURG
);
2624 signal_condition(&sched_lock
, &sched_cond
);
2630 static int iax2_digit_begin(struct ast_channel
*c
, char digit
)
2632 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_BEGIN
, digit
, 0, NULL
, 0, -1);
2635 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
)
2637 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_END
, digit
, 0, NULL
, 0, -1);
2640 static int iax2_sendtext(struct ast_channel
*c
, const char *text
)
2643 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_TEXT
,
2644 0, 0, (unsigned char *)text
, strlen(text
) + 1, -1);
2647 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
)
2649 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_IMAGE
, img
->subclass
, 0, img
->data
, img
->datalen
, -1);
2652 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
)
2654 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_HTML
, subclass
, 0, (unsigned char *)data
, datalen
, -1);
2657 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
)
2659 unsigned short callno
= PTR_TO_CALLNO(newchan
->tech_pvt
);
2660 ast_mutex_lock(&iaxsl
[callno
]);
2662 iaxs
[callno
]->owner
= newchan
;
2664 ast_log(LOG_WARNING
, "Uh, this isn't a good sign...\n");
2665 ast_mutex_unlock(&iaxsl
[callno
]);
2670 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2671 * so do not call this with a pvt lock held.
2673 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
)
2675 struct ast_variable
*var
= NULL
;
2676 struct ast_variable
*tmp
;
2677 struct iax2_peer
*peer
=NULL
;
2678 time_t regseconds
= 0, nowtime
;
2682 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", "dynamic", NULL
);
2684 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", ast_inet_ntoa(sin
->sin_addr
), NULL
);
2687 sprintf(porta
, "%d", ntohs(sin
->sin_port
));
2688 var
= ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2690 /* We'll need the peer name in order to build the structure! */
2691 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2692 if (!strcasecmp(tmp
->name
, "name"))
2693 peername
= tmp
->value
;
2697 if (!var
&& peername
) { /* Last ditch effort */
2698 var
= ast_load_realtime("iaxpeers", "name", peername
, NULL
);
2700 * If this one loaded something, then we need to ensure that the host
2701 * field matched. The only reason why we can't have this as a criteria
2702 * is because we only have the IP address and the host field might be
2703 * set as a name (and the reverse PTR might not match).
2706 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2707 if (!strcasecmp(tmp
->name
, "host")) {
2708 struct ast_hostent ahp
;
2710 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
2712 ast_variables_destroy(var
);
2723 peer
= build_peer(peername
, var
, NULL
, ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
) ? 0 : 1);
2726 ast_variables_destroy(var
);
2730 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2731 /* Make sure it's not a user only... */
2732 if (!strcasecmp(tmp
->name
, "type")) {
2733 if (strcasecmp(tmp
->value
, "friend") &&
2734 strcasecmp(tmp
->value
, "peer")) {
2735 /* Whoops, we weren't supposed to exist! */
2736 peer
= peer_unref(peer
);
2739 } else if (!strcasecmp(tmp
->name
, "regseconds")) {
2740 ast_get_time_t(tmp
->value
, ®seconds
, 0, NULL
);
2741 } else if (!strcasecmp(tmp
->name
, "ipaddr")) {
2742 inet_aton(tmp
->value
, &(peer
->addr
.sin_addr
));
2743 } else if (!strcasecmp(tmp
->name
, "port")) {
2744 peer
->addr
.sin_port
= htons(atoi(tmp
->value
));
2745 } else if (!strcasecmp(tmp
->name
, "host")) {
2746 if (!strcasecmp(tmp
->value
, "dynamic"))
2751 ast_variables_destroy(var
);
2756 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
2757 ast_copy_flags(peer
, &globalflags
, IAX_RTAUTOCLEAR
|IAX_RTCACHEFRIENDS
);
2758 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
)) {
2759 if (peer
->expire
> -1) {
2760 if (!ast_sched_del(sched
, peer
->expire
)) {
2765 peer
->expire
= iax2_sched_add(sched
, (global_rtautoclear
) * 1000, expire_registry
, peer_ref(peer
));
2766 if (peer
->expire
== -1)
2769 ao2_link(peers
, peer
);
2770 if (ast_test_flag(peer
, IAX_DYNAMIC
))
2771 reg_source_db(peer
);
2773 ast_set_flag(peer
, IAX_TEMPONLY
);
2776 if (!ast_test_flag(&globalflags
, IAX_RTIGNOREREGEXPIRE
) && dynamic
) {
2778 if ((nowtime
- regseconds
) > IAX_DEFAULT_REG_EXPIRE
) {
2779 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
2780 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
2782 ast_log(LOG_DEBUG
, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2783 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
2787 ast_log(LOG_DEBUG
, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2788 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
2795 static struct iax2_user
*realtime_user(const char *username
, struct sockaddr_in
*sin
)
2797 struct ast_variable
*var
;
2798 struct ast_variable
*tmp
;
2799 struct iax2_user
*user
=NULL
;
2801 var
= ast_load_realtime("iaxusers", "name", username
, "host", "dynamic", NULL
);
2803 var
= ast_load_realtime("iaxusers", "name", username
, "host", ast_inet_ntoa(sin
->sin_addr
), NULL
);
2806 snprintf(porta
, sizeof(porta
), "%d", ntohs(sin
->sin_port
));
2807 var
= ast_load_realtime("iaxusers", "name", username
, "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2809 var
= ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2811 if (!var
) { /* Last ditch effort */
2812 var
= ast_load_realtime("iaxusers", "name", username
, NULL
);
2814 * If this one loaded something, then we need to ensure that the host
2815 * field matched. The only reason why we can't have this as a criteria
2816 * is because we only have the IP address and the host field might be
2817 * set as a name (and the reverse PTR might not match).
2820 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2821 if (!strcasecmp(tmp
->name
, "host")) {
2822 struct ast_hostent ahp
;
2824 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
2826 ast_variables_destroy(var
);
2839 /* Make sure it's not a peer only... */
2840 if (!strcasecmp(tmp
->name
, "type")) {
2841 if (strcasecmp(tmp
->value
, "friend") &&
2842 strcasecmp(tmp
->value
, "user")) {
2849 user
= build_user(username
, var
, NULL
, !ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
));
2851 ast_variables_destroy(var
);
2856 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
2857 ast_set_flag(user
, IAX_RTCACHEFRIENDS
);
2858 ao2_link(users
, user
);
2860 ast_set_flag(user
, IAX_TEMPONLY
);
2866 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
)
2869 char regseconds
[20];
2871 snprintf(regseconds
, sizeof(regseconds
), "%d", (int)regtime
);
2872 snprintf(port
, sizeof(port
), "%d", ntohs(sin
->sin_port
));
2873 ast_update_realtime("iaxpeers", "name", peername
,
2874 "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", port
,
2875 "regseconds", regseconds
, NULL
);
2878 struct create_addr_info
{
2891 char context
[AST_MAX_CONTEXT
];
2892 char peercontext
[AST_MAX_CONTEXT
];
2893 char mohinterpret
[MAX_MUSICCLASS
];
2894 char mohsuggest
[MAX_MUSICCLASS
];
2897 static int create_addr(const char *peername
, struct ast_channel
*c
, struct sockaddr_in
*sin
, struct create_addr_info
*cai
)
2899 struct ast_hostent ahp
;
2901 struct iax2_peer
*peer
;
2903 struct ast_codec_pref ourprefs
;
2905 ast_clear_flag(cai
, IAX_SENDANI
| IAX_TRUNK
);
2906 cai
->sockfd
= defaultsockfd
;
2908 sin
->sin_family
= AF_INET
;
2910 if (!(peer
= find_peer(peername
, 1))) {
2913 hp
= ast_gethostbyname(peername
, &ahp
);
2915 memcpy(&sin
->sin_addr
, hp
->h_addr
, sizeof(sin
->sin_addr
));
2916 sin
->sin_port
= htons(IAX_DEFAULT_PORTNO
);
2917 /* use global iax prefs for unknown peer/user */
2918 /* But move the calling channel's native codec to the top of the preference list */
2919 memcpy(&ourprefs
, &prefs
, sizeof(ourprefs
));
2921 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
2922 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
2925 ast_log(LOG_WARNING
, "No such host: %s\n", peername
);
2932 /* if the peer has no address (current or default), return failure */
2933 if (!(peer
->addr
.sin_addr
.s_addr
|| peer
->defaddr
.sin_addr
.s_addr
))
2936 /* if the peer is being monitored and is currently unreachable, return failure */
2937 if (peer
->maxms
&& ((peer
->lastms
> peer
->maxms
) || (peer
->lastms
< 0)))
2940 ast_copy_flags(cai
, peer
, IAX_SENDANI
| IAX_TRUNK
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
2941 cai
->maxtime
= peer
->maxms
;
2942 cai
->capability
= peer
->capability
;
2943 cai
->encmethods
= peer
->encmethods
;
2944 cai
->sockfd
= peer
->sockfd
;
2945 cai
->adsi
= peer
->adsi
;
2946 memcpy(&ourprefs
, &peer
->prefs
, sizeof(ourprefs
));
2947 /* Move the calling channel's native codec to the top of the preference list */
2949 ast_log(LOG_DEBUG
, "prepending %x to prefs\n", c
->nativeformats
);
2950 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
2952 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
2953 ast_copy_string(cai
->context
, peer
->context
, sizeof(cai
->context
));
2954 ast_copy_string(cai
->peercontext
, peer
->peercontext
, sizeof(cai
->peercontext
));
2955 ast_copy_string(cai
->username
, peer
->username
, sizeof(cai
->username
));
2956 ast_copy_string(cai
->timezone
, peer
->zonetag
, sizeof(cai
->timezone
));
2957 ast_copy_string(cai
->outkey
, peer
->outkey
, sizeof(cai
->outkey
));
2958 ast_copy_string(cai
->mohinterpret
, peer
->mohinterpret
, sizeof(cai
->mohinterpret
));
2959 ast_copy_string(cai
->mohsuggest
, peer
->mohsuggest
, sizeof(cai
->mohsuggest
));
2960 if (ast_strlen_zero(peer
->dbsecret
)) {
2961 ast_copy_string(cai
->secret
, peer
->secret
, sizeof(cai
->secret
));
2966 family
= ast_strdupa(peer
->dbsecret
);
2967 key
= strchr(family
, '/');
2970 if (!key
|| ast_db_get(family
, key
, cai
->secret
, sizeof(cai
->secret
))) {
2971 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", peer
->dbsecret
);
2976 if (peer
->addr
.sin_addr
.s_addr
) {
2977 sin
->sin_addr
= peer
->addr
.sin_addr
;
2978 sin
->sin_port
= peer
->addr
.sin_port
;
2980 sin
->sin_addr
= peer
->defaddr
.sin_addr
;
2981 sin
->sin_port
= peer
->defaddr
.sin_port
;
2992 static void __auto_congest(const void *nothing
)
2994 int callno
= PTR_TO_CALLNO(nothing
);
2995 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_CONGESTION
};
2996 ast_mutex_lock(&iaxsl
[callno
]);
2998 iaxs
[callno
]->initid
= -1;
2999 iax2_queue_frame(callno
, &f
);
3000 ast_log(LOG_NOTICE
, "Auto-congesting call due to slow response\n");
3002 ast_mutex_unlock(&iaxsl
[callno
]);
3005 static int auto_congest(const void *data
)
3007 #ifdef SCHED_MULTITHREADED
3008 if (schedule_action(__auto_congest
, data
))
3010 __auto_congest(data
);
3014 static unsigned int iax2_datetime(const char *tz
)
3020 if (!ast_strlen_zero(tz
))
3021 ast_localtime(&t
, &tm
, tz
);
3023 ast_localtime(&t
, &tm
, NULL
);
3024 tmp
= (tm
.tm_sec
>> 1) & 0x1f; /* 5 bits of seconds */
3025 tmp
|= (tm
.tm_min
& 0x3f) << 5; /* 6 bits of minutes */
3026 tmp
|= (tm
.tm_hour
& 0x1f) << 11; /* 5 bits of hours */
3027 tmp
|= (tm
.tm_mday
& 0x1f) << 16; /* 5 bits of day of month */
3028 tmp
|= ((tm
.tm_mon
+ 1) & 0xf) << 21; /* 4 bits of month */
3029 tmp
|= ((tm
.tm_year
- 100) & 0x7f) << 25; /* 7 bits of year */
3033 struct parsed_dial_string
{
3045 * \brief Parses an IAX dial string into its component parts.
3046 * \param data the string to be parsed
3047 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3050 * This function parses the string and fills the structure
3051 * with pointers to its component parts. The input string
3054 * \note This function supports both plaintext passwords and RSA
3055 * key names; if the password string is formatted as '[keyname]',
3056 * then the keyname will be placed into the key field, and the
3057 * password field will be set to NULL.
3059 * \note The dial string format is:
3060 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3062 static void parse_dial_string(char *data
, struct parsed_dial_string
*pds
)
3064 if (ast_strlen_zero(data
))
3067 pds
->peer
= strsep(&data
, "/");
3068 pds
->exten
= strsep(&data
, "/");
3069 pds
->options
= data
;
3073 pds
->exten
= strsep(&data
, "@");
3074 pds
->context
= data
;
3077 if (strchr(pds
->peer
, '@')) {
3079 pds
->username
= strsep(&data
, "@");
3083 if (pds
->username
) {
3084 data
= pds
->username
;
3085 pds
->username
= strsep(&data
, ":");
3086 pds
->password
= data
;
3090 pds
->peer
= strsep(&data
, ":");
3093 /* check for a key name wrapped in [] in the secret position, if found,
3094 move it to the key field instead
3096 if (pds
->password
&& (pds
->password
[0] == '[')) {
3097 pds
->key
= ast_strip_quoted(pds
->password
, "[", "]");
3098 pds
->password
= NULL
;
3102 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
)
3104 struct sockaddr_in sin
;
3105 char *l
=NULL
, *n
=NULL
, *tmpstr
;
3106 struct iax_ie_data ied
;
3107 char *defaultrdest
= "s";
3108 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3109 struct parsed_dial_string pds
;
3110 struct create_addr_info cai
;
3112 if ((c
->_state
!= AST_STATE_DOWN
) && (c
->_state
!= AST_STATE_RESERVED
)) {
3113 ast_log(LOG_WARNING
, "Channel is already in use (%s)?\n", c
->name
);
3117 memset(&cai
, 0, sizeof(cai
));
3118 cai
.encmethods
= iax2_encryption
;
3120 memset(&pds
, 0, sizeof(pds
));
3121 tmpstr
= ast_strdupa(dest
);
3122 parse_dial_string(tmpstr
, &pds
);
3124 if (ast_strlen_zero(pds
.peer
)) {
3125 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", dest
);
3130 if (!ast_strlen_zero(c
->exten
))
3131 pds
.exten
= c
->exten
;
3133 pds
.exten
= defaultrdest
;
3136 if (create_addr(pds
.peer
, c
, &sin
, &cai
)) {
3137 ast_log(LOG_WARNING
, "No address associated with '%s'\n", pds
.peer
);
3141 if (!pds
.username
&& !ast_strlen_zero(cai
.username
))
3142 pds
.username
= cai
.username
;
3143 if (!pds
.password
&& !ast_strlen_zero(cai
.secret
))
3144 pds
.password
= cai
.secret
;
3145 if (!pds
.key
&& !ast_strlen_zero(cai
.outkey
))
3146 pds
.key
= cai
.outkey
;
3147 if (!pds
.context
&& !ast_strlen_zero(cai
.peercontext
))
3148 pds
.context
= cai
.peercontext
;
3150 /* Keep track of the context for outgoing calls too */
3151 ast_copy_string(c
->context
, cai
.context
, sizeof(c
->context
));
3154 sin
.sin_port
= htons(atoi(pds
.port
));
3157 n
= c
->cid
.cid_name
;
3159 /* Now build request */
3160 memset(&ied
, 0, sizeof(ied
));
3162 /* On new call, first IE MUST be IAX version of caller */
3163 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
3164 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, pds
.exten
);
3165 if (pds
.options
&& strchr(pds
.options
, 'a')) {
3166 /* Request auto answer */
3167 iax_ie_append(&ied
, IAX_IE_AUTOANSWER
);
3170 iax_ie_append_str(&ied
, IAX_IE_CODEC_PREFS
, cai
.prefs
);
3173 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, l
);
3174 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3177 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3179 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, AST_PRES_NUMBER_NOT_AVAILABLE
);
3182 iax_ie_append_byte(&ied
, IAX_IE_CALLINGTON
, c
->cid
.cid_ton
);
3183 iax_ie_append_short(&ied
, IAX_IE_CALLINGTNS
, c
->cid
.cid_tns
);
3186 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, n
);
3187 if (ast_test_flag(iaxs
[callno
], IAX_SENDANI
) && c
->cid
.cid_ani
)
3188 iax_ie_append_str(&ied
, IAX_IE_CALLING_ANI
, c
->cid
.cid_ani
);
3190 if (!ast_strlen_zero(c
->language
))
3191 iax_ie_append_str(&ied
, IAX_IE_LANGUAGE
, c
->language
);
3192 if (!ast_strlen_zero(c
->cid
.cid_dnid
))
3193 iax_ie_append_str(&ied
, IAX_IE_DNID
, c
->cid
.cid_dnid
);
3194 if (!ast_strlen_zero(c
->cid
.cid_rdnis
))
3195 iax_ie_append_str(&ied
, IAX_IE_RDNIS
, c
->cid
.cid_rdnis
);
3198 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.context
);
3201 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
3204 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, cai
.encmethods
);
3206 ast_mutex_lock(&iaxsl
[callno
]);
3208 if (!ast_strlen_zero(c
->context
))
3209 ast_string_field_set(iaxs
[callno
], context
, c
->context
);
3212 ast_string_field_set(iaxs
[callno
], username
, pds
.username
);
3214 iaxs
[callno
]->encmethods
= cai
.encmethods
;
3216 iaxs
[callno
]->adsi
= cai
.adsi
;
3218 ast_string_field_set(iaxs
[callno
], mohinterpret
, cai
.mohinterpret
);
3219 ast_string_field_set(iaxs
[callno
], mohsuggest
, cai
.mohsuggest
);
3222 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
3224 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
3226 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, c
->nativeformats
);
3227 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, iaxs
[callno
]->capability
);
3228 iax_ie_append_short(&ied
, IAX_IE_ADSICPE
, c
->adsicpe
);
3229 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(cai
.timezone
));
3231 if (iaxs
[callno
]->maxtime
) {
3232 /* Initialize pingtime and auto-congest time */
3233 iaxs
[callno
]->pingtime
= iaxs
[callno
]->maxtime
/ 2;
3234 iaxs
[callno
]->initid
= iax2_sched_add(sched
, iaxs
[callno
]->maxtime
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3235 } else if (autokill
) {
3236 iaxs
[callno
]->pingtime
= autokill
/ 2;
3237 iaxs
[callno
]->initid
= iax2_sched_add(sched
, autokill
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3240 /* send the command using the appropriate socket for this peer */
3241 iaxs
[callno
]->sockfd
= cai
.sockfd
;
3243 /* Transmit the string in a "NEW" request */
3244 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
3246 ast_mutex_unlock(&iaxsl
[callno
]);
3247 ast_setstate(c
, AST_STATE_RINGING
);
3252 static int iax2_hangup(struct ast_channel
*c
)
3254 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3256 struct iax_ie_data ied
;
3257 memset(&ied
, 0, sizeof(ied
));
3258 ast_mutex_lock(&iaxsl
[callno
]);
3259 if (callno
&& iaxs
[callno
]) {
3261 ast_log(LOG_DEBUG
, "We're hanging up %s now...\n", c
->name
);
3262 alreadygone
= ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
);
3263 /* Send the hangup unless we have had a transmission error or are already gone */
3264 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, (unsigned char)c
->hangupcause
);
3265 if (!iaxs
[callno
]->error
&& !alreadygone
) {
3266 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
3267 if (!iaxs
[callno
]) {
3268 ast_mutex_unlock(&iaxsl
[callno
]);
3272 /* Explicitly predestroy it */
3273 iax2_predestroy(callno
);
3274 /* If we were already gone to begin with, destroy us now */
3275 if (alreadygone
&& iaxs
[callno
]) {
3277 ast_log(LOG_DEBUG
, "Really destroying %s now...\n", c
->name
);
3278 iax2_destroy(callno
);
3281 ast_mutex_unlock(&iaxsl
[callno
]);
3282 if (option_verbose
> 2)
3283 ast_verbose(VERBOSE_PREFIX_3
"Hungup '%s'\n", c
->name
);
3287 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
)
3289 struct ast_option_header
*h
;
3293 case AST_OPTION_TXGAIN
:
3294 case AST_OPTION_RXGAIN
:
3295 /* these two cannot be sent, because they require a result */
3299 if (!(h
= ast_malloc(datalen
+ sizeof(*h
))))
3302 h
->flag
= AST_OPTION_FLAG_REQUEST
;
3303 h
->option
= htons(option
);
3304 memcpy(h
->data
, data
, datalen
);
3305 res
= send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_CONTROL
,
3306 AST_CONTROL_OPTION
, 0, (unsigned char *) h
,
3307 datalen
+ sizeof(*h
), -1);
3313 static struct ast_frame
*iax2_read(struct ast_channel
*c
)
3315 ast_log(LOG_NOTICE
, "I should never be called!\n");
3316 return &ast_null_frame
;
3319 static int iax2_start_transfer(unsigned short callno0
, unsigned short callno1
, int mediaonly
)
3322 struct iax_ie_data ied0
;
3323 struct iax_ie_data ied1
;
3324 unsigned int transferid
= (unsigned int)ast_random();
3325 memset(&ied0
, 0, sizeof(ied0
));
3326 iax_ie_append_addr(&ied0
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno1
]->addr
);
3327 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[callno1
]->peercallno
);
3328 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, transferid
);
3330 memset(&ied1
, 0, sizeof(ied1
));
3331 iax_ie_append_addr(&ied1
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno0
]->addr
);
3332 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[callno0
]->peercallno
);
3333 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, transferid
);
3335 res
= send_command(iaxs
[callno0
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied0
.buf
, ied0
.pos
, -1);
3338 res
= send_command(iaxs
[callno1
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied1
.buf
, ied1
.pos
, -1);
3341 iaxs
[callno0
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3342 iaxs
[callno1
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3346 static void lock_both(unsigned short callno0
, unsigned short callno1
)
3348 ast_mutex_lock(&iaxsl
[callno0
]);
3349 while (ast_mutex_trylock(&iaxsl
[callno1
])) {
3350 ast_mutex_unlock(&iaxsl
[callno0
]);
3352 ast_mutex_lock(&iaxsl
[callno0
]);
3356 static void unlock_both(unsigned short callno0
, unsigned short callno1
)
3358 ast_mutex_unlock(&iaxsl
[callno1
]);
3359 ast_mutex_unlock(&iaxsl
[callno0
]);
3362 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
)
3364 struct ast_channel
*cs
[3];
3365 struct ast_channel
*who
, *other
;
3368 int transferstarted
=0;
3369 struct ast_frame
*f
;
3370 unsigned short callno0
= PTR_TO_CALLNO(c0
->tech_pvt
);
3371 unsigned short callno1
= PTR_TO_CALLNO(c1
->tech_pvt
);
3372 struct timeval waittimer
= {0, 0}, tv
;
3374 lock_both(callno0
, callno1
);
3375 if (!iaxs
[callno0
] || !iaxs
[callno1
]) {
3376 unlock_both(callno0
, callno1
);
3377 return AST_BRIDGE_FAILED
;
3379 /* Put them in native bridge mode */
3380 if (!flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) {
3381 iaxs
[callno0
]->bridgecallno
= callno1
;
3382 iaxs
[callno1
]->bridgecallno
= callno0
;
3384 unlock_both(callno0
, callno1
);
3386 /* If not, try to bridge until we can execute a transfer, if we can */
3389 for (/* ever */;;) {
3390 /* Check in case we got masqueraded into */
3391 if ((c0
->tech
!= &iax2_tech
) || (c1
->tech
!= &iax2_tech
)) {
3392 if (option_verbose
> 2)
3393 ast_verbose(VERBOSE_PREFIX_3
"Can't masquerade, we're different...\n");
3394 /* Remove from native mode */
3395 if (c0
->tech
== &iax2_tech
) {
3396 ast_mutex_lock(&iaxsl
[callno0
]);
3397 iaxs
[callno0
]->bridgecallno
= 0;
3398 ast_mutex_unlock(&iaxsl
[callno0
]);
3400 if (c1
->tech
== &iax2_tech
) {
3401 ast_mutex_lock(&iaxsl
[callno1
]);
3402 iaxs
[callno1
]->bridgecallno
= 0;
3403 ast_mutex_unlock(&iaxsl
[callno1
]);
3405 return AST_BRIDGE_FAILED_NOWARN
;
3407 if (c0
->nativeformats
!= c1
->nativeformats
) {
3408 if (option_verbose
> 2) {
3411 ast_getformatname_multiple(buf0
, sizeof(buf0
) -1, c0
->nativeformats
);
3412 ast_getformatname_multiple(buf1
, sizeof(buf1
) -1, c1
->nativeformats
);
3413 ast_verbose(VERBOSE_PREFIX_3
"Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0
->nativeformats
, buf0
, c1
->nativeformats
, buf1
);
3415 /* Remove from native mode */
3416 lock_both(callno0
, callno1
);
3418 iaxs
[callno0
]->bridgecallno
= 0;
3420 iaxs
[callno1
]->bridgecallno
= 0;
3421 unlock_both(callno0
, callno1
);
3422 return AST_BRIDGE_FAILED_NOWARN
;
3424 /* check if transfered and if we really want native bridging */
3425 if (!transferstarted
&& !ast_test_flag(iaxs
[callno0
], IAX_NOTRANSFER
) && !ast_test_flag(iaxs
[callno1
], IAX_NOTRANSFER
)) {
3426 /* Try the transfer */
3427 if (iax2_start_transfer(callno0
, callno1
, (flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) ||
3428 ast_test_flag(iaxs
[callno0
], IAX_TRANSFERMEDIA
) | ast_test_flag(iaxs
[callno1
], IAX_TRANSFERMEDIA
)))
3429 ast_log(LOG_WARNING
, "Unable to start the transfer\n");
3430 transferstarted
= 1;
3432 if ((iaxs
[callno0
]->transferring
== TRANSFER_RELEASED
) && (iaxs
[callno1
]->transferring
== TRANSFER_RELEASED
)) {
3433 /* Call has been transferred. We're no longer involved */
3434 gettimeofday(&tv
, NULL
);
3435 if (ast_tvzero(waittimer
)) {
3437 } else if (tv
.tv_sec
- waittimer
.tv_sec
> IAX_LINGER_TIMEOUT
) {
3438 c0
->_softhangup
|= AST_SOFTHANGUP_DEV
;
3439 c1
->_softhangup
|= AST_SOFTHANGUP_DEV
;
3442 res
= AST_BRIDGE_COMPLETE
;
3447 who
= ast_waitfor_n(cs
, 2, &to
);
3448 if (timeoutms
> -1) {
3449 timeoutms
-= (1000 - to
);
3455 res
= AST_BRIDGE_RETRY
;
3458 if (ast_check_hangup(c0
) || ast_check_hangup(c1
)) {
3459 res
= AST_BRIDGE_FAILED
;
3468 res
= AST_BRIDGE_COMPLETE
;
3471 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3474 res
= AST_BRIDGE_COMPLETE
;
3477 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
3478 if ((f
->frametype
== AST_FRAME_VOICE
) ||
3479 (f
->frametype
== AST_FRAME_TEXT
) ||
3480 (f
->frametype
== AST_FRAME_VIDEO
) ||
3481 (f
->frametype
== AST_FRAME_IMAGE
) ||
3482 (f
->frametype
== AST_FRAME_DTMF
)) {
3483 /* monitored dtmf take out of the bridge.
3484 * check if we monitor the specific source.
3486 int monitored_source
= (who
== c0
) ? AST_BRIDGE_DTMF_CHANNEL_0
: AST_BRIDGE_DTMF_CHANNEL_1
;
3487 if (f
->frametype
== AST_FRAME_DTMF
&& (flags
& monitored_source
)) {
3490 res
= AST_BRIDGE_COMPLETE
;
3491 /* Remove from native mode */
3494 /* everything else goes to the other side */
3495 ast_write(other
, f
);
3498 /* Swap who gets priority */
3503 lock_both(callno0
, callno1
);
3505 iaxs
[callno0
]->bridgecallno
= 0;
3507 iaxs
[callno1
]->bridgecallno
= 0;
3508 unlock_both(callno0
, callno1
);
3512 static int iax2_answer(struct ast_channel
*c
)
3514 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3516 ast_log(LOG_DEBUG
, "Answering IAX2 call\n");
3517 return send_command_locked(callno
, AST_FRAME_CONTROL
, AST_CONTROL_ANSWER
, 0, NULL
, 0, -1);
3520 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
)
3522 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3523 struct chan_iax2_pvt
*pvt
;
3526 if (option_debug
&& iaxdebug
)
3527 ast_log(LOG_DEBUG
, "Indicating condition %d\n", condition
);
3529 ast_mutex_lock(&iaxsl
[callno
]);
3532 switch (condition
) {
3533 case AST_CONTROL_HOLD
:
3534 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
3535 ast_moh_start(c
, data
, pvt
->mohinterpret
);
3539 case AST_CONTROL_UNHOLD
:
3540 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
3546 res
= send_command(pvt
, AST_FRAME_CONTROL
, condition
, 0, data
, datalen
, -1);
3549 ast_mutex_unlock(&iaxsl
[callno
]);
3554 static int iax2_transfer(struct ast_channel
*c
, const char *dest
)
3556 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3557 struct iax_ie_data ied
;
3558 char tmp
[256], *context
;
3559 ast_copy_string(tmp
, dest
, sizeof(tmp
));
3560 context
= strchr(tmp
, '@');
3565 memset(&ied
, 0, sizeof(ied
));
3566 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, tmp
);
3568 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, context
);
3570 ast_log(LOG_DEBUG
, "Transferring '%s' to '%s'\n", c
->name
, dest
);
3571 return send_command_locked(callno
, AST_FRAME_IAX
, IAX_COMMAND_TRANSFER
, 0, ied
.buf
, ied
.pos
, -1);
3574 static int iax2_getpeertrunk(struct sockaddr_in sin
)
3576 struct iax2_peer
*peer
;
3578 struct ao2_iterator i
;
3580 i
= ao2_iterator_init(peers
, 0);
3581 while ((peer
= ao2_iterator_next(&i
))) {
3582 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
3583 (peer
->addr
.sin_port
== sin
.sin_port
)) {
3584 res
= ast_test_flag(peer
, IAX_TRUNK
);
3594 /*! \brief Create new call, interface with the PBX core */
3595 static struct ast_channel
*ast_iax2_new(int callno
, int state
, int capability
)
3597 struct ast_channel
*tmp
;
3598 struct chan_iax2_pvt
*i
;
3599 struct ast_variable
*v
= NULL
;
3601 if (!(i
= iaxs
[callno
])) {
3602 ast_log(LOG_WARNING
, "No IAX2 pvt found for callno '%d' !\n", callno
);
3606 /* Don't hold call lock */
3607 ast_mutex_unlock(&iaxsl
[callno
]);
3608 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
);
3609 ast_mutex_lock(&iaxsl
[callno
]);
3610 if (!iaxs
[callno
]) {
3612 ast_channel_free(tmp
);
3614 ast_mutex_unlock(&iaxsl
[callno
]);
3620 tmp
->tech
= &iax2_tech
;
3621 /* We can support any format by default, until we get restricted */
3622 tmp
->nativeformats
= capability
;
3623 tmp
->readformat
= ast_best_codec(capability
);
3624 tmp
->writeformat
= ast_best_codec(capability
);
3625 tmp
->tech_pvt
= CALLNO_TO_PTR(i
->callno
);
3627 /* Don't use ast_set_callerid() here because it will
3628 * generate a NewCallerID event before the NewChannel event */
3629 if (!ast_strlen_zero(i
->ani
))
3630 tmp
->cid
.cid_ani
= ast_strdup(i
->ani
);
3632 tmp
->cid
.cid_ani
= ast_strdup(i
->cid_num
);
3633 tmp
->cid
.cid_dnid
= ast_strdup(i
->dnid
);
3634 tmp
->cid
.cid_rdnis
= ast_strdup(i
->rdnis
);
3635 tmp
->cid
.cid_pres
= i
->calling_pres
;
3636 tmp
->cid
.cid_ton
= i
->calling_ton
;
3637 tmp
->cid
.cid_tns
= i
->calling_tns
;
3638 if (!ast_strlen_zero(i
->language
))
3639 ast_string_field_set(tmp
, language
, i
->language
);
3640 if (!ast_strlen_zero(i
->accountcode
))
3641 ast_string_field_set(tmp
, accountcode
, i
->accountcode
);
3643 tmp
->amaflags
= i
->amaflags
;
3644 ast_copy_string(tmp
->context
, i
->context
, sizeof(tmp
->context
));
3645 ast_copy_string(tmp
->exten
, i
->exten
, sizeof(tmp
->exten
));
3647 tmp
->adsicpe
= i
->peeradsicpe
;
3649 tmp
->adsicpe
= AST_ADSI_UNAVAILABLE
;
3651 i
->capability
= capability
;
3653 for (v
= i
->vars
; v
; v
= v
->next
)
3654 pbx_builtin_setvar_helper(tmp
, v
->name
, v
->value
);
3656 if (state
!= AST_STATE_DOWN
) {
3657 if (ast_pbx_start(tmp
)) {
3658 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmp
->name
);
3665 ast_module_ref(ast_module_info
->self
);
3670 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer
*tpeer
, int sampms
, struct timeval
*tv
)
3672 unsigned long int mssincetx
; /* unsigned to handle overflows */
3675 tpeer
->trunkact
= *tv
;
3676 mssincetx
= ast_tvdiff_ms(*tv
, tpeer
->lasttxtime
);
3677 if (mssincetx
> 5000 || ast_tvzero(tpeer
->txtrunktime
)) {
3678 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3679 tpeer
->txtrunktime
= *tv
;
3680 tpeer
->lastsent
= 999999;
3682 /* Update last transmit time now */
3683 tpeer
->lasttxtime
= *tv
;
3685 /* Calculate ms offset */
3686 ms
= ast_tvdiff_ms(*tv
, tpeer
->txtrunktime
);
3687 /* Predict from last value */
3688 pred
= tpeer
->lastsent
+ sampms
;
3689 if (abs(ms
- pred
) < MAX_TIMESTAMP_SKEW
)
3692 /* We never send the same timestamp twice, so fudge a little if we must */
3693 if (ms
== tpeer
->lastsent
)
3694 ms
= tpeer
->lastsent
+ 1;
3695 tpeer
->lastsent
= ms
;
3699 static unsigned int fix_peerts(struct timeval
*tv
, int callno
, unsigned int ts
)
3701 long ms
; /* NOT unsigned */
3702 if (ast_tvzero(iaxs
[callno
]->rxcore
)) {
3703 /* Initialize rxcore time if appropriate */
3704 gettimeofday(&iaxs
[callno
]->rxcore
, NULL
);
3705 /* Round to nearest 20ms so traces look pretty */
3706 iaxs
[callno
]->rxcore
.tv_usec
-= iaxs
[callno
]->rxcore
.tv_usec
% 20000;
3708 /* Calculate difference between trunk and channel */
3709 ms
= ast_tvdiff_ms(*tv
, iaxs
[callno
]->rxcore
);
3710 /* Return as the sum of trunk time and the difference between trunk and real time */
3714 static unsigned int calc_timestamp(struct chan_iax2_pvt
*p
, unsigned int ts
, struct ast_frame
*f
)
3720 struct timeval
*delivery
= NULL
;
3723 /* What sort of frame do we have?: voice is self-explanatory
3724 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3725 non-genuine frames are CONTROL frames [ringing etc], DTMF
3726 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3727 the others need a timestamp slaved to the voice frames so that they go in sequence
3730 if (f
->frametype
== AST_FRAME_VOICE
) {
3732 delivery
= &f
->delivery
;
3733 } else if (f
->frametype
== AST_FRAME_IAX
) {
3735 } else if (f
->frametype
== AST_FRAME_CNG
) {
3739 if (ast_tvzero(p
->offset
)) {
3740 gettimeofday(&p
->offset
, NULL
);
3741 /* Round to nearest 20ms for nice looking traces */
3742 p
->offset
.tv_usec
-= p
->offset
.tv_usec
% 20000;
3744 /* If the timestamp is specified, just send it as is */
3747 /* If we have a time that the frame arrived, always use it to make our timestamp */
3748 if (delivery
&& !ast_tvzero(*delivery
)) {
3749 ms
= ast_tvdiff_ms(*delivery
, p
->offset
);
3750 if (option_debug
> 2 && iaxdebug
)
3751 ast_log(LOG_DEBUG
, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p
->callno
, iaxs
[p
->callno
]->peercallno
);
3753 ms
= ast_tvdiff_ms(ast_tvnow(), p
->offset
);
3757 /* On a voice frame, use predicted values if appropriate */
3758 if (p
->notsilenttx
&& abs(ms
- p
->nextpred
) <= MAX_TIMESTAMP_SKEW
) {
3759 /* Adjust our txcore, keeping voice and non-voice synchronized */
3761 When we send voice, we usually send "calculated" timestamps worked out
3762 on the basis of the number of samples sent. When we send other frames,
3763 we usually send timestamps worked out from the real clock.
3764 The problem is that they can tend to drift out of step because the
3765 source channel's clock and our clock may not be exactly at the same rate.
3766 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3767 for this call. Moving it adjusts timestamps for non-voice frames.
3768 We make the adjustment in the style of a moving average. Each time we
3769 adjust p->offset by 10% of the difference between our clock-derived
3770 timestamp and the predicted timestamp. That's why you see "10000"
3771 below even though IAX2 timestamps are in milliseconds.
3772 The use of a moving average avoids offset moving too radically.
3773 Generally, "adjust" roams back and forth around 0, with offset hardly
3774 changing at all. But if a consistent different starts to develop it
3775 will be eliminated over the course of 10 frames (200-300msecs)
3777 adjust
= (ms
- p
->nextpred
);
3779 p
->offset
= ast_tvsub(p
->offset
, ast_samp2tv(abs(adjust
), 10000));
3780 else if (adjust
> 0)
3781 p
->offset
= ast_tvadd(p
->offset
, ast_samp2tv(adjust
, 10000));
3784 p
->nextpred
= ms
; /*f->samples / 8;*/
3785 if (p
->nextpred
<= p
->lastsent
)
3786 p
->nextpred
= p
->lastsent
+ 3;
3790 /* in this case, just use the actual
3791 * time, since we're either way off
3792 * (shouldn't happen), or we're ending a
3793 * silent period -- and seed the next
3794 * predicted time. Also, round ms to the
3795 * next multiple of frame size (so our
3796 * silent periods are multiples of
3797 * frame size too) */
3799 if (option_debug
&& iaxdebug
&& abs(ms
- p
->nextpred
) > MAX_TIMESTAMP_SKEW
)
3800 ast_log(LOG_DEBUG
, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3801 abs(ms
- p
->nextpred
), MAX_TIMESTAMP_SKEW
);
3803 if (f
->samples
>= 8) /* check to make sure we dont core dump */
3805 int diff
= ms
% (f
->samples
/ 8);
3807 ms
+= f
->samples
/8 - diff
;
3813 } else if ( f
->frametype
== AST_FRAME_VIDEO
) {
3815 * IAX2 draft 03 says that timestamps MUST be in order.
3816 * It does not say anything about several frames having the same timestamp
3817 * When transporting video, we can have a frame that spans multiple iax packets
3818 * (so called slices), so it would make sense to use the same timestamp for all of
3820 * We do want to make sure that frames don't go backwards though
3822 if ( (unsigned int)ms
< p
->lastsent
)
3825 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3826 it's a genuine frame */
3828 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3829 if (ms
<= p
->lastsent
)
3830 ms
= p
->lastsent
+ 3;
3831 } else if (abs(ms
- p
->lastsent
) <= MAX_TIMESTAMP_SKEW
) {
3832 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3833 ms
= p
->lastsent
+ 3;
3839 p
->nextpred
= p
->nextpred
+ f
->samples
/ 8;
3843 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
)
3845 /* Returns where in "receive time" we are. That is, how many ms
3846 since we received (or would have received) the frame with timestamp 0 */
3850 #endif /* IAXTESTS */
3851 /* Setup rxcore if necessary */
3852 if (ast_tvzero(p
->rxcore
)) {
3853 p
->rxcore
= ast_tvnow();
3854 if (option_debug
&& iaxdebug
)
3855 ast_log(LOG_DEBUG
, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3856 p
->callno
, (int)(p
->rxcore
.tv_sec
), (int)(p
->rxcore
.tv_usec
), offset
);
3857 p
->rxcore
= ast_tvsub(p
->rxcore
, ast_samp2tv(offset
, 1000));
3859 if (option_debug
&& iaxdebug
)
3860 ast_log(LOG_DEBUG
, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3861 p
->callno
, (int)(p
->rxcore
.tv_sec
),(int)( p
->rxcore
.tv_usec
));
3865 ms
= ast_tvdiff_ms(ast_tvnow(), p
->rxcore
);
3868 if (!test_jitpct
|| ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_jitpct
)) {
3869 jit
= (int)((float)test_jit
* ast_random() / (RAND_MAX
+ 1.0));
3870 if ((int)(2.0 * ast_random() / (RAND_MAX
+ 1.0)))
3879 #endif /* IAXTESTS */
3883 static struct iax2_trunk_peer
*find_tpeer(struct sockaddr_in
*sin
, int fd
)
3885 struct iax2_trunk_peer
*tpeer
;
3887 /* Finds and locks trunk peer */
3888 ast_mutex_lock(&tpeerlock
);
3889 for (tpeer
= tpeers
; tpeer
; tpeer
= tpeer
->next
) {
3890 /* We don't lock here because tpeer->addr *never* changes */
3891 if (!inaddrcmp(&tpeer
->addr
, sin
)) {
3892 ast_mutex_lock(&tpeer
->lock
);
3897 if ((tpeer
= ast_calloc(1, sizeof(*tpeer
)))) {
3898 ast_mutex_init(&tpeer
->lock
);
3899 tpeer
->lastsent
= 9999;
3900 memcpy(&tpeer
->addr
, sin
, sizeof(tpeer
->addr
));
3901 tpeer
->trunkact
= ast_tvnow();
3902 ast_mutex_lock(&tpeer
->lock
);
3903 tpeer
->next
= tpeers
;
3907 setsockopt(tpeer
->sockfd
, SOL_SOCKET
, SO_NO_CHECK
, &nochecksums
, sizeof(nochecksums
));
3910 ast_log(LOG_DEBUG
, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
));
3913 ast_mutex_unlock(&tpeerlock
);
3917 static int iax2_trunk_queue(struct chan_iax2_pvt
*pvt
, struct iax_frame
*fr
)
3919 struct ast_frame
*f
;
3920 struct iax2_trunk_peer
*tpeer
;
3922 struct ast_iax2_meta_trunk_entry
*met
;
3923 struct ast_iax2_meta_trunk_mini
*mtm
;
3926 tpeer
= find_tpeer(&pvt
->addr
, pvt
->sockfd
);
3928 if (tpeer
->trunkdatalen
+ f
->datalen
+ 4 >= tpeer
->trunkdataalloc
) {
3929 /* Need to reallocate space */
3930 if (tpeer
->trunkdataalloc
< MAX_TRUNKDATA
) {
3931 if (!(tmp
= ast_realloc(tpeer
->trunkdata
, tpeer
->trunkdataalloc
+ DEFAULT_TRUNKDATA
+ IAX2_TRUNK_PREFACE
))) {
3932 ast_mutex_unlock(&tpeer
->lock
);
3936 tpeer
->trunkdataalloc
+= DEFAULT_TRUNKDATA
;
3937 tpeer
->trunkdata
= tmp
;
3939 ast_log(LOG_DEBUG
, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
), tpeer
->trunkdataalloc
);
3941 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
));
3942 ast_mutex_unlock(&tpeer
->lock
);
3947 /* Append to meta frame */
3948 ptr
= tpeer
->trunkdata
+ IAX2_TRUNK_PREFACE
+ tpeer
->trunkdatalen
;
3949 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
)) {
3950 mtm
= (struct ast_iax2_meta_trunk_mini
*)ptr
;
3951 mtm
->len
= htons(f
->datalen
);
3952 mtm
->mini
.callno
= htons(pvt
->callno
);
3953 mtm
->mini
.ts
= htons(0xffff & fr
->ts
);
3954 ptr
+= sizeof(struct ast_iax2_meta_trunk_mini
);
3955 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_mini
);
3957 met
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
3958 /* Store call number and length in meta header */
3959 met
->callno
= htons(pvt
->callno
);
3960 met
->len
= htons(f
->datalen
);
3961 /* Advance pointers/decrease length past trunk entry header */
3962 ptr
+= sizeof(struct ast_iax2_meta_trunk_entry
);
3963 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_entry
);
3965 /* Copy actual trunk data */
3966 memcpy(ptr
, f
->data
, f
->datalen
);
3967 tpeer
->trunkdatalen
+= f
->datalen
;
3970 ast_mutex_unlock(&tpeer
->lock
);
3975 static void build_enc_keys(const unsigned char *digest
, aes_encrypt_ctx
*ecx
, aes_decrypt_ctx
*dcx
)
3977 aes_encrypt_key128(digest
, ecx
);
3978 aes_decrypt_key128(digest
, dcx
);
3981 static void memcpy_decrypt(unsigned char *dst
, const unsigned char *src
, int len
, aes_decrypt_ctx
*dcx
)
3984 /* Debug with "fake encryption" */
3987 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
3989 dst
[x
] = src
[x
] ^ 0xff;
3991 unsigned char lastblock
[16] = { 0 };
3994 aes_decrypt(src
, dst
, dcx
);
3996 dst
[x
] ^= lastblock
[x
];
3997 memcpy(lastblock
, src
, sizeof(lastblock
));
4005 static void memcpy_encrypt(unsigned char *dst
, const unsigned char *src
, int len
, aes_encrypt_ctx
*ecx
)
4008 /* Debug with "fake encryption" */
4011 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
4013 dst
[x
] = src
[x
] ^ 0xff;
4015 unsigned char curblock
[16] = { 0 };
4019 curblock
[x
] ^= src
[x
];
4020 aes_encrypt(curblock
, dst
, ecx
);
4021 memcpy(curblock
, dst
, sizeof(curblock
));
4029 static int decode_frame(aes_decrypt_ctx
*dcx
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4032 unsigned char *workspace
;
4034 workspace
= alloca(*datalen
);
4035 memset(f
, 0, sizeof(*f
));
4036 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4037 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4038 if (*datalen
< 16 + sizeof(struct ast_iax2_full_hdr
))
4041 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), dcx
);
4043 padding
= 16 + (workspace
[15] & 0xf);
4044 if (option_debug
&& iaxdebug
)
4045 ast_log(LOG_DEBUG
, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen
, padding
, workspace
[15]);
4046 if (*datalen
< padding
+ sizeof(struct ast_iax2_full_hdr
))
4049 *datalen
-= padding
;
4050 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4051 f
->frametype
= fh
->type
;
4052 if (f
->frametype
== AST_FRAME_VIDEO
) {
4053 f
->subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
4055 f
->subclass
= uncompress_subclass(fh
->csub
);
4058 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4059 if (option_debug
&& iaxdebug
)
4060 ast_log(LOG_DEBUG
, "Decoding mini with length %d\n", *datalen
);
4061 if (*datalen
< 16 + sizeof(struct ast_iax2_mini_hdr
))
4064 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), dcx
);
4065 padding
= 16 + (workspace
[15] & 0x0f);
4066 if (*datalen
< padding
+ sizeof(struct ast_iax2_mini_hdr
))
4068 *datalen
-= padding
;
4069 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4074 static int encrypt_frame(aes_encrypt_ctx
*ecx
, struct ast_iax2_full_hdr
*fh
, unsigned char *poo
, int *datalen
)
4077 unsigned char *workspace
;
4078 workspace
= alloca(*datalen
+ 32);
4081 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4082 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4083 if (option_debug
&& iaxdebug
)
4084 ast_log(LOG_DEBUG
, "Encoding full frame %d/%d with length %d\n", fh
->type
, fh
->csub
, *datalen
);
4085 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_full_enc_hdr
)) % 16);
4086 padding
= 16 + (padding
& 0xf);
4087 memcpy(workspace
, poo
, padding
);
4088 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4089 workspace
[15] &= 0xf0;
4090 workspace
[15] |= (padding
& 0xf);
4091 if (option_debug
&& iaxdebug
)
4092 ast_log(LOG_DEBUG
, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh
->type
, fh
->csub
, *datalen
, padding
, workspace
[15]);
4093 *datalen
+= padding
;
4094 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), ecx
);
4095 if (*datalen
>= 32 + sizeof(struct ast_iax2_full_enc_hdr
))
4096 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4098 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4099 if (option_debug
&& iaxdebug
)
4100 ast_log(LOG_DEBUG
, "Encoding mini frame with length %d\n", *datalen
);
4101 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_mini_enc_hdr
)) % 16);
4102 padding
= 16 + (padding
& 0xf);
4103 memcpy(workspace
, poo
, padding
);
4104 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4105 workspace
[15] &= 0xf0;
4106 workspace
[15] |= (padding
& 0x0f);
4107 *datalen
+= padding
;
4108 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), ecx
);
4109 if (*datalen
>= 32 + sizeof(struct ast_iax2_mini_enc_hdr
))
4110 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4115 static int decrypt_frame(int callno
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4118 if (!ast_test_flag(iaxs
[callno
], IAX_KEYPOPULATED
)) {
4119 /* Search for possible keys, given secrets */
4120 struct MD5Context md5
;
4121 unsigned char digest
[16];
4122 char *tmppw
, *stringp
;
4124 tmppw
= ast_strdupa(iaxs
[callno
]->secret
);
4126 while ((tmppw
= strsep(&stringp
, ";"))) {
4128 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
4129 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
4130 MD5Final(digest
, &md5
);
4131 build_enc_keys(digest
, &iaxs
[callno
]->ecx
, &iaxs
[callno
]->dcx
);
4132 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4134 ast_set_flag(iaxs
[callno
], IAX_KEYPOPULATED
);
4139 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4143 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
)
4145 /* Queue a packet for delivery on a given private structure. Use "ts" for
4146 timestamp, or calculate if ts is 0. Send immediately without retransmission
4147 or delayed, with retransmission */
4148 struct ast_iax2_full_hdr
*fh
;
4149 struct ast_iax2_mini_hdr
*mh
;
4150 struct ast_iax2_video_hdr
*vh
;
4152 struct iax_frame fr2
;
4153 unsigned char buffer
[4096];
4155 struct iax_frame
*fr
;
4158 unsigned int lastsent
;
4161 frb
.fr2
.afdatalen
= sizeof(frb
.buffer
);
4164 ast_log(LOG_WARNING
, "No private structure for packet?\n");
4168 lastsent
= pvt
->lastsent
;
4170 /* Calculate actual timestamp */
4171 fts
= calc_timestamp(pvt
, ts
, f
);
4173 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4174 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4175 * increment the "predicted timestamps" for voice, if we're predecting */
4176 if(f
->frametype
== AST_FRAME_VOICE
&& f
->datalen
== 0)
4180 if ((ast_test_flag(pvt
, IAX_TRUNK
) ||
4181 (((fts
& 0xFFFF0000L
) == (lastsent
& 0xFFFF0000L
)) ||
4182 ((fts
& 0xFFFF0000L
) == ((lastsent
+ 0x10000) & 0xFFFF0000L
))))
4183 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4184 (f
->frametype
== AST_FRAME_VOICE
)
4185 /* is a voice frame */ &&
4186 (f
->subclass
== pvt
->svoiceformat
)
4187 /* is the same type */ ) {
4188 /* Force immediate rather than delayed transmission */
4190 /* Mark that mini-style frame is appropriate */
4193 if ( f
->frametype
== AST_FRAME_VIDEO
) {
4195 * If the lower 15 bits of the timestamp roll over, or if
4196 * the video format changed then send a full frame.
4197 * Otherwise send a mini video frame
4199 if (((fts
& 0xFFFF8000L
) == (pvt
->lastvsent
& 0xFFFF8000L
)) &&
4200 ((f
->subclass
& ~0x1) == pvt
->svideoformat
)
4208 pvt
->lastvsent
= fts
;
4210 /* Allocate an iax_frame */
4214 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
));
4216 ast_log(LOG_WARNING
, "Out of memory\n");
4219 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4220 iax_frame_wrap(fr
, f
);
4223 fr
->callno
= pvt
->callno
;
4224 fr
->transfer
= transfer
;
4227 /* We need a full frame */
4231 fr
->oseqno
= pvt
->oseqno
++;
4232 fr
->iseqno
= pvt
->iseqno
;
4233 fh
= (struct ast_iax2_full_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_full_hdr
));
4234 fh
->scallno
= htons(fr
->callno
| IAX_FLAG_FULL
);
4235 fh
->ts
= htonl(fr
->ts
);
4236 fh
->oseqno
= fr
->oseqno
;
4240 fh
->iseqno
= fr
->iseqno
;
4241 /* Keep track of the last thing we've acknowledged */
4243 pvt
->aseqno
= fr
->iseqno
;
4244 fh
->type
= fr
->af
.frametype
& 0xFF;
4245 if (fr
->af
.frametype
== AST_FRAME_VIDEO
)
4246 fh
->csub
= compress_subclass(fr
->af
.subclass
& ~0x1) | ((fr
->af
.subclass
& 0x1) << 6);
4248 fh
->csub
= compress_subclass(fr
->af
.subclass
);
4250 fr
->dcallno
= pvt
->transfercallno
;
4252 fr
->dcallno
= pvt
->peercallno
;
4253 fh
->dcallno
= htons(fr
->dcallno
);
4254 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_full_hdr
);
4257 /* Retry after 2x the ping time has passed */
4258 fr
->retrytime
= pvt
->pingtime
* 2;
4259 if (fr
->retrytime
< MIN_RETRY_TIME
)
4260 fr
->retrytime
= MIN_RETRY_TIME
;
4261 if (fr
->retrytime
> MAX_RETRY_TIME
)
4262 fr
->retrytime
= MAX_RETRY_TIME
;
4263 /* Acks' don't get retried */
4264 if ((f
->frametype
== AST_FRAME_IAX
) && (f
->subclass
== IAX_COMMAND_ACK
))
4266 else if (f
->frametype
== AST_FRAME_VOICE
)
4267 pvt
->svoiceformat
= f
->subclass
;
4268 else if (f
->frametype
== AST_FRAME_VIDEO
)
4269 pvt
->svideoformat
= f
->subclass
& ~0x1;
4270 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4271 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4274 iax_showframe(fr
, NULL
, 2, &pvt
->transfer
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4276 iax_showframe(fr
, NULL
, 2, &pvt
->addr
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4278 encrypt_frame(&pvt
->ecx
, fh
, pvt
->semirand
, &fr
->datalen
);
4280 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4284 res
= send_packet(fr
);
4286 res
= iax2_transmit(fr
);
4288 if (ast_test_flag(pvt
, IAX_TRUNK
)) {
4289 iax2_trunk_queue(pvt
, fr
);
4291 } else if (fr
->af
.frametype
== AST_FRAME_VIDEO
) {
4292 /* Video frame have no sequence number */
4295 vh
= (struct ast_iax2_video_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_video_hdr
));
4297 vh
->callno
= htons(0x8000 | fr
->callno
);
4298 vh
->ts
= htons((fr
->ts
& 0x7FFF) | (fr
->af
.subclass
& 0x1 ? 0x8000 : 0));
4299 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_video_hdr
);
4302 res
= send_packet(fr
);
4304 /* Mini-frames have no sequence number */
4307 /* Mini frame will do */
4308 mh
= (struct ast_iax2_mini_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_mini_hdr
));
4309 mh
->callno
= htons(fr
->callno
);
4310 mh
->ts
= htons(fr
->ts
& 0xFFFF);
4311 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_mini_hdr
);
4314 if (pvt
->transferring
== TRANSFER_MEDIAPASS
)
4316 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4317 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4318 encrypt_frame(&pvt
->ecx
, (struct ast_iax2_full_hdr
*)mh
, pvt
->semirand
, &fr
->datalen
);
4320 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4322 res
= send_packet(fr
);
4328 static int iax2_show_users(int fd
, int argc
, char *argv
[])
4331 int havepattern
= 0;
4333 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4334 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4336 struct iax2_user
*user
= NULL
;
4339 struct ao2_iterator i
;
4343 if (!strcasecmp(argv
[3], "like")) {
4344 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
4345 return RESULT_SHOWUSAGE
;
4348 return RESULT_SHOWUSAGE
;
4352 return RESULT_SHOWUSAGE
;
4355 ast_cli(fd
, FORMAT
, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4356 i
= ao2_iterator_init(users
, 0);
4357 for (user
= ao2_iterator_next(&i
); user
;
4358 user_unref(user
), user
= ao2_iterator_next(&i
)) {
4359 if (havepattern
&& regexec(®exbuf
, user
->name
, 0, NULL
, 0))
4362 if (!ast_strlen_zero(user
->secret
)) {
4363 ast_copy_string(auth
,user
->secret
,sizeof(auth
));
4364 } else if (!ast_strlen_zero(user
->inkeys
)) {
4365 snprintf(auth
, sizeof(auth
), "Key: %-15.15s ", user
->inkeys
);
4367 ast_copy_string(auth
, "-no secret-", sizeof(auth
));
4369 if(ast_test_flag(user
,IAX_CODEC_NOCAP
))
4371 else if(ast_test_flag(user
,IAX_CODEC_NOPREFS
))
4374 pstr
= ast_test_flag(user
,IAX_CODEC_USER_FIRST
) ? "Caller" : "Host";
4376 ast_cli(fd
, FORMAT2
, user
->name
, auth
, user
->authmethods
,
4377 user
->contexts
? user
->contexts
->context
: context
,
4378 user
->ha
? "Yes" : "No", pstr
);
4384 return RESULT_SUCCESS
;
4389 static int __iax2_show_peers(int manager
, int fd
, struct mansession
*s
, int argc
, char *argv
[])
4392 int havepattern
= 0;
4393 int total_peers
= 0;
4394 int online_peers
= 0;
4395 int offline_peers
= 0;
4396 int unmonitored_peers
= 0;
4397 struct ao2_iterator i
;
4399 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4400 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4402 struct iax2_peer
*peer
= NULL
;
4404 int registeredonly
=0;
4405 char *term
= manager
? "\r\n" : "\n";
4409 if (!strcasecmp(argv
[3], "registered"))
4412 return RESULT_SHOWUSAGE
;
4413 if (!strcasecmp(argv
[4], "like")) {
4414 if (regcomp(®exbuf
, argv
[5], REG_EXTENDED
| REG_NOSUB
))
4415 return RESULT_SHOWUSAGE
;
4418 return RESULT_SHOWUSAGE
;
4421 if (!strcasecmp(argv
[3], "like")) {
4422 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
4423 return RESULT_SHOWUSAGE
;
4426 return RESULT_SHOWUSAGE
;
4429 if (!strcasecmp(argv
[3], "registered"))
4432 return RESULT_SHOWUSAGE
;
4437 return RESULT_SHOWUSAGE
;
4442 astman_append(s
, FORMAT2
, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term
);
4444 ast_cli(fd
, FORMAT2
, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term
);
4446 i
= ao2_iterator_init(peers
, 0);
4447 for (peer
= ao2_iterator_next(&i
); peer
;
4448 peer_unref(peer
), peer
= ao2_iterator_next(&i
)) {
4454 if (registeredonly
&& !peer
->addr
.sin_addr
.s_addr
)
4456 if (havepattern
&& regexec(®exbuf
, peer
->name
, 0, NULL
, 0))
4459 if (!ast_strlen_zero(peer
->username
))
4460 snprintf(name
, sizeof(name
), "%s/%s", peer
->name
, peer
->username
);
4462 ast_copy_string(name
, peer
->name
, sizeof(name
));
4464 retstatus
= peer_status(peer
, status
, sizeof(status
));
4467 else if (!retstatus
)
4470 unmonitored_peers
++;
4472 ast_copy_string(nm
, ast_inet_ntoa(peer
->mask
), sizeof(nm
));
4474 snprintf(srch
, sizeof(srch
), FORMAT
, name
,
4475 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
4476 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4478 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4479 peer
->encmethods
? "(E)" : " ", status
, term
);
4482 astman_append(s
, FORMAT
, name
,
4483 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa( peer
->addr
.sin_addr
) : "(Unspecified)",
4484 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4486 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4487 peer
->encmethods
? "(E)" : " ", status
, term
);
4489 ast_cli(fd
, FORMAT
, name
,
4490 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
4491 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4493 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4494 peer
->encmethods
? "(E)" : " ", status
, term
);
4499 astman_append(s
,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers
, online_peers
, offline_peers
, unmonitored_peers
, term
);
4501 ast_cli(fd
,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers
, online_peers
, offline_peers
, unmonitored_peers
, term
);
4506 return RESULT_SUCCESS
;
4511 static int iax2_show_threads(int fd
, int argc
, char *argv
[])
4513 struct iax2_thread
*thread
= NULL
;
4515 int threadcount
= 0, dynamiccount
= 0;
4519 return RESULT_SHOWUSAGE
;
4521 ast_cli(fd
, "IAX2 Thread Information\n");
4523 ast_cli(fd
, "Idle Threads:\n");
4524 AST_LIST_LOCK(&idle_list
);
4525 AST_LIST_TRAVERSE(&idle_list
, thread
, list
) {
4526 #ifdef DEBUG_SCHED_MULTITHREAD
4527 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4528 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4530 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
4531 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4535 AST_LIST_UNLOCK(&idle_list
);
4536 ast_cli(fd
, "Active Threads:\n");
4537 AST_LIST_LOCK(&active_list
);
4538 AST_LIST_TRAVERSE(&active_list
, thread
, list
) {
4539 if (thread
->type
== IAX_TYPE_DYNAMIC
)
4543 #ifdef DEBUG_SCHED_MULTITHREAD
4544 ast_cli(fd
, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4545 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4547 ast_cli(fd
, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4548 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4552 AST_LIST_UNLOCK(&active_list
);
4553 ast_cli(fd
, "Dynamic Threads:\n");
4554 AST_LIST_LOCK(&dynamic_list
);
4555 AST_LIST_TRAVERSE(&dynamic_list
, thread
, list
) {
4556 #ifdef DEBUG_SCHED_MULTITHREAD
4557 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4558 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4560 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
4561 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4565 AST_LIST_UNLOCK(&dynamic_list
);
4566 ast_cli(fd
, "%d of %d threads accounted for with %d dynamic threads\n", threadcount
, iaxthreadcount
, dynamiccount
);
4567 return RESULT_SUCCESS
;
4570 static int iax2_show_peers(int fd
, int argc
, char *argv
[])
4572 return __iax2_show_peers(0, fd
, NULL
, argc
, argv
);
4574 static int manager_iax2_show_netstats(struct mansession
*s
, const struct message
*m
)
4576 ast_cli_netstats(s
, -1, 0);
4577 astman_append(s
, "\r\n");
4578 return RESULT_SUCCESS
;
4581 static int iax2_show_firmware(int fd
, int argc
, char *argv
[])
4583 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4584 #if !defined(__FreeBSD__)
4585 #define FORMAT "%-15.15s %-15d %-15d\n"
4586 #else /* __FreeBSD__ */
4587 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4588 #endif /* __FreeBSD__ */
4589 struct iax_firmware
*cur
;
4590 if ((argc
!= 3) && (argc
!= 4))
4591 return RESULT_SHOWUSAGE
;
4592 ast_mutex_lock(&waresl
.lock
);
4594 ast_cli(fd
, FORMAT2
, "Device", "Version", "Size");
4595 for (cur
= waresl
.wares
;cur
;cur
= cur
->next
) {
4596 if ((argc
== 3) || (!strcasecmp(argv
[3], (char *)cur
->fwh
->devname
)))
4597 ast_cli(fd
, FORMAT
, cur
->fwh
->devname
, ntohs(cur
->fwh
->version
),
4598 (int)ntohl(cur
->fwh
->datalen
));
4600 ast_mutex_unlock(&waresl
.lock
);
4601 return RESULT_SUCCESS
;
4606 /* JDG: callback to display iax peers in manager */
4607 static int manager_iax2_show_peers(struct mansession
*s
, const struct message
*m
)
4609 char *a
[] = { "iax2", "show", "users" };
4611 const char *id
= astman_get_header(m
,"ActionID");
4613 if (!ast_strlen_zero(id
))
4614 astman_append(s
, "ActionID: %s\r\n",id
);
4615 ret
= __iax2_show_peers(1, -1, s
, 3, a
);
4616 astman_append(s
, "\r\n\r\n" );
4620 static char *regstate2str(int regstate
)
4623 case REG_STATE_UNREGISTERED
:
4624 return "Unregistered";
4625 case REG_STATE_REGSENT
:
4626 return "Request Sent";
4627 case REG_STATE_AUTHSENT
:
4628 return "Auth. Sent";
4629 case REG_STATE_REGISTERED
:
4630 return "Registered";
4631 case REG_STATE_REJECTED
:
4633 case REG_STATE_TIMEOUT
:
4635 case REG_STATE_NOAUTH
:
4636 return "No Authentication";
4642 static int iax2_show_registry(int fd
, int argc
, char *argv
[])
4644 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4645 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4646 struct iax2_registry
*reg
= NULL
;
4651 return RESULT_SHOWUSAGE
;
4652 ast_cli(fd
, FORMAT2
, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4653 AST_LIST_LOCK(®istrations
);
4654 AST_LIST_TRAVERSE(®istrations
, reg
, entry
) {
4655 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(reg
->addr
.sin_addr
), ntohs(reg
->addr
.sin_port
));
4656 if (reg
->us
.sin_addr
.s_addr
)
4657 snprintf(perceived
, sizeof(perceived
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
4659 ast_copy_string(perceived
, "<Unregistered>", sizeof(perceived
));
4660 ast_cli(fd
, FORMAT
, host
,
4661 (reg
->dnsmgr
) ? "Y" : "N",
4662 reg
->username
, perceived
, reg
->refresh
, regstate2str(reg
->regstate
));
4664 AST_LIST_UNLOCK(®istrations
);
4665 return RESULT_SUCCESS
;
4670 static int iax2_show_channels(int fd
, int argc
, char *argv
[])
4672 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4673 #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"
4674 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4679 return RESULT_SHOWUSAGE
;
4680 ast_cli(fd
, FORMAT2
, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4681 for (x
=0;x
<IAX_MAX_CALLS
;x
++) {
4682 ast_mutex_lock(&iaxsl
[x
]);
4684 int lag
, jitter
, localdelay
;
4687 if(ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
4688 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
4689 jitter
= jbinfo
.jitter
;
4690 localdelay
= jbinfo
.current
- jbinfo
.min
;
4695 lag
= iaxs
[x
]->remote_rr
.delay
;
4697 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4698 ast_inet_ntoa(iaxs
[x
]->addr
.sin_addr
),
4699 S_OR(iaxs
[x
]->username
, "(None)"),
4700 iaxs
[x
]->callno
, iaxs
[x
]->peercallno
,
4701 iaxs
[x
]->oseqno
, iaxs
[x
]->iseqno
,
4705 ast_getformatname(iaxs
[x
]->voiceformat
) );
4708 ast_mutex_unlock(&iaxsl
[x
]);
4710 ast_cli(fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
4711 return RESULT_SUCCESS
;
4717 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
)
4721 for (x
=0;x
<IAX_MAX_CALLS
;x
++) {
4722 ast_mutex_lock(&iaxsl
[x
]);
4724 int localjitter
, localdelay
, locallost
, locallosspct
, localdropped
, localooo
;
4728 if(ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
4729 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
4730 localjitter
= jbinfo
.jitter
;
4731 localdelay
= jbinfo
.current
- jbinfo
.min
;
4732 locallost
= jbinfo
.frames_lost
;
4733 locallosspct
= jbinfo
.losspct
/1000;
4734 localdropped
= jbinfo
.frames_dropped
;
4735 localooo
= jbinfo
.frames_ooo
;
4745 fmt
= "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4747 fmt
= "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4750 astman_append(s
, fmt
,
4751 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4759 iaxs
[x
]->frames_received
/1000,
4760 iaxs
[x
]->remote_rr
.jitter
,
4761 iaxs
[x
]->remote_rr
.delay
,
4762 iaxs
[x
]->remote_rr
.losscnt
,
4763 iaxs
[x
]->remote_rr
.losspct
,
4764 iaxs
[x
]->remote_rr
.dropped
,
4765 iaxs
[x
]->remote_rr
.ooo
,
4766 iaxs
[x
]->remote_rr
.packets
/1000);
4769 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4777 iaxs
[x
]->frames_received
/1000,
4778 iaxs
[x
]->remote_rr
.jitter
,
4779 iaxs
[x
]->remote_rr
.delay
,
4780 iaxs
[x
]->remote_rr
.losscnt
,
4781 iaxs
[x
]->remote_rr
.losspct
,
4782 iaxs
[x
]->remote_rr
.dropped
,
4783 iaxs
[x
]->remote_rr
.ooo
,
4784 iaxs
[x
]->remote_rr
.packets
/1000
4788 ast_mutex_unlock(&iaxsl
[x
]);
4793 static int iax2_show_netstats(int fd
, int argc
, char *argv
[])
4797 return RESULT_SHOWUSAGE
;
4798 ast_cli(fd
, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4799 ast_cli(fd
, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4800 numchans
= ast_cli_netstats(NULL
, fd
, 1);
4801 ast_cli(fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
4802 return RESULT_SUCCESS
;
4805 static int iax2_do_debug(int fd
, int argc
, char *argv
[])
4807 if (argc
< 2 || argc
> 3)
4808 return RESULT_SHOWUSAGE
;
4810 ast_cli(fd
, "IAX2 Debugging Enabled\n");
4811 return RESULT_SUCCESS
;
4814 static int iax2_do_trunk_debug(int fd
, int argc
, char *argv
[])
4816 if (argc
< 3 || argc
> 4)
4817 return RESULT_SHOWUSAGE
;
4819 ast_cli(fd
, "IAX2 Trunk Debug Requested\n");
4820 return RESULT_SUCCESS
;
4823 static int iax2_do_jb_debug(int fd
, int argc
, char *argv
[])
4825 if (argc
< 3 || argc
> 4)
4826 return RESULT_SHOWUSAGE
;
4827 jb_setoutput(jb_error_output
, jb_warning_output
, jb_debug_output
);
4828 ast_cli(fd
, "IAX2 Jitterbuffer Debugging Enabled\n");
4829 return RESULT_SUCCESS
;
4832 static int iax2_no_debug(int fd
, int argc
, char *argv
[])
4834 if (argc
< 3 || argc
> 4)
4835 return RESULT_SHOWUSAGE
;
4837 ast_cli(fd
, "IAX2 Debugging Disabled\n");
4838 return RESULT_SUCCESS
;
4841 static int iax2_no_trunk_debug(int fd
, int argc
, char *argv
[])
4843 if (argc
< 4 || argc
> 5)
4844 return RESULT_SHOWUSAGE
;
4846 ast_cli(fd
, "IAX2 Trunk Debugging Disabled\n");
4847 return RESULT_SUCCESS
;
4850 static int iax2_no_jb_debug(int fd
, int argc
, char *argv
[])
4852 if (argc
< 4 || argc
> 5)
4853 return RESULT_SHOWUSAGE
;
4854 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
4855 jb_debug_output("\n");
4856 ast_cli(fd
, "IAX2 Jitterbuffer Debugging Disabled\n");
4857 return RESULT_SUCCESS
;
4860 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
)
4862 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
4864 ast_mutex_lock(&iaxsl
[callno
]);
4866 /* If there's an outstanding error, return failure now */
4867 if (!iaxs
[callno
]->error
) {
4868 if (ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
))
4870 /* Don't waste bandwidth sending null frames */
4871 else if (f
->frametype
== AST_FRAME_NULL
)
4873 else if ((f
->frametype
== AST_FRAME_VOICE
) && ast_test_flag(iaxs
[callno
], IAX_QUELCH
))
4875 else if (!ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
4878 /* Simple, just queue for transmission */
4879 res
= iax2_send(iaxs
[callno
], f
, 0, -1, 0, 0, 0);
4882 ast_log(LOG_DEBUG
, "Write error: %s\n", strerror(errno
));
4885 /* If it's already gone, just return */
4886 ast_mutex_unlock(&iaxsl
[callno
]);
4890 static int __send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
,
4891 int now
, int transfer
, int final
)
4893 struct ast_frame f
= { 0, };
4896 f
.subclass
= command
;
4897 f
.datalen
= datalen
;
4898 f
.src
= __FUNCTION__
;
4899 f
.data
= (void *) data
;
4901 return iax2_send(i
, &f
, ts
, seqno
, now
, transfer
, final
);
4904 static int send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
4906 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 0);
4909 static int send_command_locked(unsigned short callno
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
4912 ast_mutex_lock(&iaxsl
[callno
]);
4913 res
= send_command(iaxs
[callno
], type
, command
, ts
, data
, datalen
, seqno
);
4914 ast_mutex_unlock(&iaxsl
[callno
]);
4919 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
4920 * the pvt struct for the given call number may disappear during its
4923 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
)
4925 int call_num
= i
->callno
;
4926 /* It is assumed that the callno has already been locked */
4927 iax2_predestroy(i
->callno
);
4928 if (!iaxs
[call_num
])
4930 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 1);
4933 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
)
4935 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 1, 0, 0);
4938 static int send_command_transfer(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
)
4940 return __send_command(i
, type
, command
, ts
, data
, datalen
, 0, 0, 1, 0);
4943 static int apply_context(struct iax2_context
*con
, const char *context
)
4946 if (!strcmp(con
->context
, context
) || !strcmp(con
->context
, "*"))
4954 static int check_access(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
4956 /* Start pessimistic */
4959 struct iax2_user
*user
= NULL
, *best
= NULL
;
4961 int gotcapability
= 0;
4962 struct ast_variable
*v
= NULL
, *tmpvar
= NULL
;
4963 struct ao2_iterator i
;
4967 if (ies
->called_number
)
4968 ast_string_field_set(iaxs
[callno
], exten
, ies
->called_number
);
4969 if (ies
->calling_number
) {
4970 ast_shrink_phone_number(ies
->calling_number
);
4971 ast_string_field_set(iaxs
[callno
], cid_num
, ies
->calling_number
);
4973 if (ies
->calling_name
)
4974 ast_string_field_set(iaxs
[callno
], cid_name
, ies
->calling_name
);
4975 if (ies
->calling_ani
)
4976 ast_string_field_set(iaxs
[callno
], ani
, ies
->calling_ani
);
4978 ast_string_field_set(iaxs
[callno
], dnid
, ies
->dnid
);
4980 ast_string_field_set(iaxs
[callno
], rdnis
, ies
->rdnis
);
4981 if (ies
->called_context
)
4982 ast_string_field_set(iaxs
[callno
], context
, ies
->called_context
);
4984 ast_string_field_set(iaxs
[callno
], language
, ies
->language
);
4986 ast_string_field_set(iaxs
[callno
], username
, ies
->username
);
4987 if (ies
->calling_ton
> -1)
4988 iaxs
[callno
]->calling_ton
= ies
->calling_ton
;
4989 if (ies
->calling_tns
> -1)
4990 iaxs
[callno
]->calling_tns
= ies
->calling_tns
;
4991 if (ies
->calling_pres
> -1)
4992 iaxs
[callno
]->calling_pres
= ies
->calling_pres
;
4994 iaxs
[callno
]->peerformat
= ies
->format
;
4996 iaxs
[callno
]->peeradsicpe
= ies
->adsicpe
;
4997 if (ies
->capability
) {
4999 iaxs
[callno
]->peercapability
= ies
->capability
;
5002 version
= ies
->version
;
5004 /* Use provided preferences until told otherwise for actual preferences */
5005 if(ies
->codec_prefs
) {
5006 ast_codec_pref_convert(&iaxs
[callno
]->rprefs
, ies
->codec_prefs
, 32, 0);
5007 ast_codec_pref_convert(&iaxs
[callno
]->prefs
, ies
->codec_prefs
, 32, 0);
5011 iaxs
[callno
]->peercapability
= iaxs
[callno
]->peerformat
;
5012 if (version
> IAX_PROTO_VERSION
) {
5013 ast_log(LOG_WARNING
, "Peer '%s' has too new a protocol version (%d) for me\n",
5014 ast_inet_ntoa(sin
->sin_addr
), version
);
5017 /* Search the userlist for a compatible entry, and fill in the rest */
5018 i
= ao2_iterator_init(users
, 0);
5019 while ((user
= ao2_iterator_next(&i
))) {
5020 if ((ast_strlen_zero(iaxs
[callno
]->username
) || /* No username specified */
5021 !strcmp(iaxs
[callno
]->username
, user
->name
)) /* Or this username specified */
5022 && ast_apply_ha(user
->ha
, sin
) /* Access is permitted from this IP */
5023 && (ast_strlen_zero(iaxs
[callno
]->context
) || /* No context specified */
5024 apply_context(user
->contexts
, iaxs
[callno
]->context
))) { /* Context is permitted */
5025 if (!ast_strlen_zero(iaxs
[callno
]->username
)) {
5026 /* Exact match, stop right now. */
5031 } else if (ast_strlen_zero(user
->secret
) && ast_strlen_zero(user
->dbsecret
) && ast_strlen_zero(user
->inkeys
)) {
5032 /* No required authentication */
5034 /* There was host authentication and we passed, bonus! */
5035 if (bestscore
< 4) {
5043 /* No host access, but no secret, either, not bad */
5044 if (bestscore
< 3) {
5054 /* Authentication, but host access too, eh, it's something.. */
5055 if (bestscore
< 2) {
5063 /* Authentication and no host access... This is our baseline */
5064 if (bestscore
< 1) {
5077 if (!user
&& !ast_strlen_zero(iaxs
[callno
]->username
)) {
5078 user
= realtime_user(iaxs
[callno
]->username
, sin
);
5079 if (user
&& !ast_strlen_zero(iaxs
[callno
]->context
) && /* No context specified */
5080 !apply_context(user
->contexts
, iaxs
[callno
]->context
)) { /* Context is permitted */
5081 user
= user_unref(user
);
5085 /* We found our match (use the first) */
5087 for (v
= user
->vars
; v
; v
= v
->next
) {
5088 if((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
5089 tmpvar
->next
= iaxs
[callno
]->vars
;
5090 iaxs
[callno
]->vars
= tmpvar
;
5093 /* If a max AUTHREQ restriction is in place, activate it */
5094 if (user
->maxauthreq
> 0)
5095 ast_set_flag(iaxs
[callno
], IAX_MAXAUTHREQ
);
5096 iaxs
[callno
]->prefs
= user
->prefs
;
5097 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_USER_FIRST
);
5098 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOPREFS
);
5099 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOCAP
);
5100 iaxs
[callno
]->encmethods
= user
->encmethods
;
5101 /* Store the requested username if not specified */
5102 if (ast_strlen_zero(iaxs
[callno
]->username
))
5103 ast_string_field_set(iaxs
[callno
], username
, user
->name
);
5104 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5105 ast_copy_flags(iaxs
[callno
], user
, IAX_TRUNK
);
5106 iaxs
[callno
]->capability
= user
->capability
;
5107 /* And use the default context */
5108 if (ast_strlen_zero(iaxs
[callno
]->context
)) {
5110 ast_string_field_set(iaxs
[callno
], context
, user
->contexts
->context
);
5112 ast_string_field_set(iaxs
[callno
], context
, context
);
5114 /* And any input keys */
5115 ast_string_field_set(iaxs
[callno
], inkeys
, user
->inkeys
);
5116 /* And the permitted authentication methods */
5117 iaxs
[callno
]->authmethods
= user
->authmethods
;
5118 iaxs
[callno
]->adsi
= user
->adsi
;
5119 /* If they have callerid, override the given caller id. Always store the ANI */
5120 if (!ast_strlen_zero(iaxs
[callno
]->cid_num
) || !ast_strlen_zero(iaxs
[callno
]->cid_name
)) {
5121 if (ast_test_flag(user
, IAX_HASCALLERID
)) {
5122 iaxs
[callno
]->calling_tns
= 0;
5123 iaxs
[callno
]->calling_ton
= 0;
5124 ast_string_field_set(iaxs
[callno
], cid_num
, user
->cid_num
);
5125 ast_string_field_set(iaxs
[callno
], cid_name
, user
->cid_name
);
5126 iaxs
[callno
]->calling_pres
= AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
;
5128 if (ast_strlen_zero(iaxs
[callno
]->ani
))
5129 ast_string_field_set(iaxs
[callno
], ani
, user
->cid_num
);
5131 iaxs
[callno
]->calling_pres
= AST_PRES_NUMBER_NOT_AVAILABLE
;
5133 if (!ast_strlen_zero(user
->accountcode
))
5134 ast_string_field_set(iaxs
[callno
], accountcode
, user
->accountcode
);
5135 if (!ast_strlen_zero(user
->mohinterpret
))
5136 ast_string_field_set(iaxs
[callno
], mohinterpret
, user
->mohinterpret
);
5137 if (!ast_strlen_zero(user
->mohsuggest
))
5138 ast_string_field_set(iaxs
[callno
], mohsuggest
, user
->mohsuggest
);
5140 iaxs
[callno
]->amaflags
= user
->amaflags
;
5141 if (!ast_strlen_zero(user
->language
))
5142 ast_string_field_set(iaxs
[callno
], language
, user
->language
);
5143 ast_copy_flags(iaxs
[callno
], user
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
5144 /* Keep this check last */
5145 if (!ast_strlen_zero(user
->dbsecret
)) {
5146 char *family
, *key
=NULL
;
5148 family
= ast_strdupa(user
->dbsecret
);
5149 key
= strchr(family
, '/');
5154 if (!key
|| ast_db_get(family
, key
, buf
, sizeof(buf
)))
5155 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", user
->dbsecret
);
5157 ast_string_field_set(iaxs
[callno
], secret
, buf
);
5159 ast_string_field_set(iaxs
[callno
], secret
, user
->secret
);
5161 user
= user_unref(user
);
5163 ast_set2_flag(iaxs
[callno
], iax2_getpeertrunk(*sin
), IAX_TRUNK
);
5167 static int raw_hangup(struct sockaddr_in
*sin
, unsigned short src
, unsigned short dst
, int sockfd
)
5169 struct ast_iax2_full_hdr fh
;
5170 fh
.scallno
= htons(src
| IAX_FLAG_FULL
);
5171 fh
.dcallno
= htons(dst
);
5175 fh
.type
= AST_FRAME_IAX
;
5176 fh
.csub
= compress_subclass(IAX_COMMAND_INVAL
);
5178 iax_showframe(NULL
, &fh
, 0, sin
, 0);
5180 ast_log(LOG_DEBUG
, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5181 ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), src
, dst
);
5182 return sendto(sockfd
, &fh
, sizeof(fh
), 0, (struct sockaddr
*)sin
, sizeof(*sin
));
5185 static void merge_encryption(struct chan_iax2_pvt
*p
, unsigned int enc
)
5187 /* Select exactly one common encryption if there are any */
5188 p
->encmethods
&= enc
;
5189 if (p
->encmethods
) {
5190 if (p
->encmethods
& IAX_ENCRYPT_AES128
)
5191 p
->encmethods
= IAX_ENCRYPT_AES128
;
5198 * \pre iaxsl[call_num] is locked
5200 * \note Since this function calls send_command_final(), the pvt struct for the given
5201 * call number may disappear while executing this function.
5203 static int authenticate_request(int call_num
)
5205 struct iax_ie_data ied
;
5206 int res
= -1, authreq_restrict
= 0;
5208 struct chan_iax2_pvt
*p
= iaxs
[call_num
];
5210 memset(&ied
, 0, sizeof(ied
));
5212 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5213 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
5214 struct iax2_user
*user
, tmp_user
= {
5215 .name
= p
->username
,
5218 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
5220 if (user
->curauthreq
== user
->maxauthreq
)
5221 authreq_restrict
= 1;
5224 user
= user_unref(user
);
5228 /* If the AUTHREQ limit test failed, send back an error */
5229 if (authreq_restrict
) {
5230 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Unauthenticated call limit reached");
5231 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_CALL_REJECTED
);
5232 send_command_final(p
, AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied
.buf
, ied
.pos
, -1);
5236 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
5237 if (p
->authmethods
& (IAX_AUTH_MD5
| IAX_AUTH_RSA
)) {
5238 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
5239 ast_string_field_set(p
, challenge
, challenge
);
5240 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5241 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, p
->challenge
);
5244 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, p
->encmethods
);
5246 iax_ie_append_str(&ied
,IAX_IE_USERNAME
, p
->username
);
5248 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREQ
, 0, ied
.buf
, ied
.pos
, -1);
5251 ast_set_flag(p
, IAX_ENCRYPTED
);
5256 static int authenticate_verify(struct chan_iax2_pvt
*p
, struct iax_ies
*ies
)
5258 char requeststr
[256];
5259 char md5secret
[256] = "";
5260 char secret
[256] = "";
5261 char rsasecret
[256] = "";
5264 struct iax2_user
*user
, tmp_user
= {
5265 .name
= p
->username
,
5268 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
5270 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
5271 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
5272 ast_clear_flag(p
, IAX_MAXAUTHREQ
);
5274 ast_string_field_set(p
, host
, user
->name
);
5275 user
= user_unref(user
);
5278 if (!ast_test_flag(&p
->state
, IAX_STATE_AUTHENTICATED
))
5281 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
5282 if (ies
->md5_result
)
5283 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
5284 if (ies
->rsa_result
)
5285 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
5286 if ((p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(rsasecret
) && !ast_strlen_zero(p
->inkeys
)) {
5287 struct ast_key
*key
;
5291 ast_copy_string(tmpkey
, p
->inkeys
, sizeof(tmpkey
));
5293 keyn
= strsep(&stringp
, ":");
5295 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
5296 if (key
&& !ast_check_signature(key
, p
->challenge
, rsasecret
)) {
5300 ast_log(LOG_WARNING
, "requested inkey '%s' for RSA authentication does not exist\n", keyn
);
5301 keyn
= strsep(&stringp
, ":");
5303 } else if (p
->authmethods
& IAX_AUTH_MD5
) {
5304 struct MD5Context md5
;
5305 unsigned char digest
[16];
5306 char *tmppw
, *stringp
;
5308 tmppw
= ast_strdupa(p
->secret
);
5310 while((tmppw
= strsep(&stringp
, ";"))) {
5312 MD5Update(&md5
, (unsigned char *)p
->challenge
, strlen(p
->challenge
));
5313 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
5314 MD5Final(digest
, &md5
);
5315 /* If they support md5, authenticate with it. */
5317 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5318 if (!strcasecmp(requeststr
, md5secret
)) {
5323 } else if (p
->authmethods
& IAX_AUTH_PLAINTEXT
) {
5324 if (!strcmp(secret
, p
->secret
))
5330 /*! \brief Verify inbound registration */
5331 static int register_verify(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
5333 char requeststr
[256] = "";
5334 char peer
[256] = "";
5335 char md5secret
[256] = "";
5336 char rsasecret
[256] = "";
5337 char secret
[256] = "";
5338 struct iax2_peer
*p
= NULL
;
5339 struct ast_key
*key
;
5345 ast_clear_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
);
5346 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5348 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
5350 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
5351 if (ies
->md5_result
)
5352 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
5353 if (ies
->rsa_result
)
5354 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
5356 expire
= ies
->refresh
;
5358 if (ast_strlen_zero(peer
)) {
5359 ast_log(LOG_NOTICE
, "Empty registration from %s\n", ast_inet_ntoa(sin
->sin_addr
));
5363 /* SLD: first call to lookup peer during registration */
5364 ast_mutex_unlock(&iaxsl
[callno
]);
5365 p
= find_peer(peer
, 1);
5366 ast_mutex_lock(&iaxsl
[callno
]);
5367 if (!p
|| !iaxs
[callno
]) {
5368 if (authdebug
&& !p
)
5369 ast_log(LOG_NOTICE
, "No registration for peer '%s' (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
5373 if (!ast_test_flag(p
, IAX_DYNAMIC
)) {
5375 ast_log(LOG_NOTICE
, "Peer '%s' is not dynamic (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
5379 if (!ast_apply_ha(p
->ha
, sin
)) {
5381 ast_log(LOG_NOTICE
, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
5384 if (!inaddrcmp(&p
->addr
, sin
))
5385 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_UNCHANGED
);
5386 ast_string_field_set(iaxs
[callno
], secret
, p
->secret
);
5387 ast_string_field_set(iaxs
[callno
], inkeys
, p
->inkeys
);
5388 /* Check secret against what we have on file */
5389 if (!ast_strlen_zero(rsasecret
) && (p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
5390 if (!ast_strlen_zero(p
->inkeys
)) {
5393 ast_copy_string(tmpkeys
, p
->inkeys
, sizeof(tmpkeys
));
5395 keyn
= strsep(&stringp
, ":");
5397 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
5398 if (key
&& !ast_check_signature(key
, iaxs
[callno
]->challenge
, rsasecret
)) {
5399 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5402 ast_log(LOG_WARNING
, "requested inkey '%s' does not exist\n", keyn
);
5403 keyn
= strsep(&stringp
, ":");
5407 ast_log(LOG_NOTICE
, "Host %s failed RSA authentication with inkeys '%s'\n", peer
, p
->inkeys
);
5412 ast_log(LOG_NOTICE
, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer
);
5415 } else if (!ast_strlen_zero(md5secret
) && (p
->authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
5416 struct MD5Context md5
;
5417 unsigned char digest
[16];
5418 char *tmppw
, *stringp
;
5420 tmppw
= ast_strdupa(p
->secret
);
5422 while((tmppw
= strsep(&stringp
, ";"))) {
5424 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
5425 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
5426 MD5Final(digest
, &md5
);
5428 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5429 if (!strcasecmp(requeststr
, md5secret
))
5433 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5436 ast_log(LOG_NOTICE
, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
, requeststr
, md5secret
);
5439 } else if (!ast_strlen_zero(secret
) && (p
->authmethods
& IAX_AUTH_PLAINTEXT
)) {
5440 /* They've provided a plain text password and we support that */
5441 if (strcmp(secret
, p
->secret
)) {
5443 ast_log(LOG_NOTICE
, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
5446 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5447 } else if (!ast_strlen_zero(md5secret
) || !ast_strlen_zero(secret
)) {
5449 ast_log(LOG_NOTICE
, "Inappropriate authentication received\n");
5452 ast_string_field_set(iaxs
[callno
], peer
, peer
);
5453 /* Choose lowest expiry number */
5454 if (expire
&& (expire
< iaxs
[callno
]->expiry
))
5455 iaxs
[callno
]->expiry
= expire
;
5457 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
5468 static int authenticate(const char *challenge
, const char *secret
, const char *keyn
, int authmethods
, struct iax_ie_data
*ied
, struct sockaddr_in
*sin
, aes_encrypt_ctx
*ecx
, aes_decrypt_ctx
*dcx
)
5472 if (!ast_strlen_zero(keyn
)) {
5473 if (!(authmethods
& IAX_AUTH_RSA
)) {
5474 if (ast_strlen_zero(secret
))
5475 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
));
5476 } else if (ast_strlen_zero(challenge
)) {
5477 ast_log(LOG_NOTICE
, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin
->sin_addr
));
5480 struct ast_key
*key
;
5481 key
= ast_key_get(keyn
, AST_KEY_PRIVATE
);
5483 ast_log(LOG_NOTICE
, "Unable to find private key '%s'\n", keyn
);
5485 if (ast_sign(key
, (char*)challenge
, sig
)) {
5486 ast_log(LOG_NOTICE
, "Unable to sign challenge with key\n");
5489 iax_ie_append_str(ied
, IAX_IE_RSA_RESULT
, sig
);
5496 if (res
&& !ast_strlen_zero(secret
)) {
5497 if ((authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(challenge
)) {
5498 struct MD5Context md5
;
5499 unsigned char digest
[16];
5502 MD5Update(&md5
, (unsigned char *)challenge
, strlen(challenge
));
5503 MD5Update(&md5
, (unsigned char *)secret
, strlen(secret
));
5504 MD5Final(digest
, &md5
);
5505 /* If they support md5, authenticate with it. */
5507 sprintf(digres
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5509 build_enc_keys(digest
, ecx
, dcx
);
5510 iax_ie_append_str(ied
, IAX_IE_MD5_RESULT
, digres
);
5512 } else if (authmethods
& IAX_AUTH_PLAINTEXT
) {
5513 iax_ie_append_str(ied
, IAX_IE_PASSWORD
, secret
);
5516 ast_log(LOG_NOTICE
, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin
->sin_addr
), authmethods
);
5522 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5523 * so do not call this function with a pvt lock held.
5525 static int authenticate_reply(struct chan_iax2_pvt
*p
, struct sockaddr_in
*sin
, struct iax_ies
*ies
, const char *override
, const char *okey
)
5527 struct iax2_peer
*peer
= NULL
;
5528 /* Start pessimistic */
5530 int authmethods
= 0;
5531 struct iax_ie_data ied
;
5532 uint16_t callno
= p
->callno
;
5534 memset(&ied
, 0, sizeof(ied
));
5537 ast_string_field_set(p
, username
, ies
->username
);
5539 ast_string_field_set(p
, challenge
, ies
->challenge
);
5540 if (ies
->authmethods
)
5541 authmethods
= ies
->authmethods
;
5542 if (authmethods
& IAX_AUTH_MD5
)
5543 merge_encryption(p
, ies
->encmethods
);
5547 /* Check for override RSA authentication first */
5548 if (!ast_strlen_zero(override
) || !ast_strlen_zero(okey
)) {
5549 /* Normal password authentication */
5550 res
= authenticate(p
->challenge
, override
, okey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5552 struct ao2_iterator i
= ao2_iterator_init(peers
, 0);
5553 while ((peer
= ao2_iterator_next(&i
))) {
5554 if ((ast_strlen_zero(p
->peer
) || !strcmp(p
->peer
, peer
->name
))
5555 /* No peer specified at our end, or this is the peer */
5556 && (ast_strlen_zero(peer
->username
) || (!strcmp(peer
->username
, p
->username
)))
5557 /* No username specified in peer rule, or this is the right username */
5558 && (!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
)))
5559 /* No specified host, or this is our host */
5561 res
= authenticate(p
->challenge
, peer
->secret
, peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5570 /* We checked our list and didn't find one. It's unlikely, but possible,
5571 that we're trying to authenticate *to* a realtime peer */
5572 const char *peer_name
= ast_strdupa(p
->peer
);
5573 ast_mutex_unlock(&iaxsl
[callno
]);
5574 if ((peer
= realtime_peer(peer_name
, NULL
))) {
5575 ast_mutex_lock(&iaxsl
[callno
]);
5576 if (!(p
= iaxs
[callno
])) {
5580 res
= authenticate(p
->challenge
, peer
->secret
,peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5584 ast_mutex_lock(&iaxsl
[callno
]);
5585 if (!(p
= iaxs
[callno
]))
5590 if (ies
->encmethods
)
5591 ast_set_flag(p
, IAX_ENCRYPTED
| IAX_KEYPOPULATED
);
5593 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREP
, 0, ied
.buf
, ied
.pos
, -1);
5597 static int iax2_do_register(struct iax2_registry
*reg
);
5599 static void __iax2_do_register_s(const void *data
)
5601 struct iax2_registry
*reg
= (struct iax2_registry
*)data
;
5603 iax2_do_register(reg
);
5606 static int iax2_do_register_s(const void *data
)
5608 #ifdef SCHED_MULTITHREADED
5609 if (schedule_action(__iax2_do_register_s
, data
))
5611 __iax2_do_register_s(data
);
5615 static int try_transfer(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
5619 struct iax_ie_data ied
;
5620 struct sockaddr_in
new;
5623 memset(&ied
, 0, sizeof(ied
));
5624 if (ies
->apparent_addr
)
5625 bcopy(ies
->apparent_addr
, &new, sizeof(new));
5627 newcall
= ies
->callno
;
5628 if (!newcall
|| !new.sin_addr
.s_addr
|| !new.sin_port
) {
5629 ast_log(LOG_WARNING
, "Invalid transfer request\n");
5632 pvt
->transfercallno
= newcall
;
5633 memcpy(&pvt
->transfer
, &new, sizeof(pvt
->transfer
));
5634 inet_aton(newip
, &pvt
->transfer
.sin_addr
);
5635 pvt
->transfer
.sin_family
= AF_INET
;
5636 pvt
->transferring
= TRANSFER_BEGIN
;
5637 pvt
->transferid
= ies
->transferid
;
5638 if (ies
->transferid
)
5639 iax_ie_append_int(&ied
, IAX_IE_TRANSFERID
, ies
->transferid
);
5640 send_command_transfer(pvt
, AST_FRAME_IAX
, IAX_COMMAND_TXCNT
, 0, ied
.buf
, ied
.pos
);
5644 static int complete_dpreply(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
5646 char exten
[256] = "";
5647 int status
= CACHE_FLAG_UNKNOWN
;
5648 int expiry
= iaxdefaultdpcache
;
5651 struct iax2_dpcache
*dp
, *prev
;
5653 if (ies
->called_number
)
5654 ast_copy_string(exten
, ies
->called_number
, sizeof(exten
));
5656 if (ies
->dpstatus
& IAX_DPSTATUS_EXISTS
)
5657 status
= CACHE_FLAG_EXISTS
;
5658 else if (ies
->dpstatus
& IAX_DPSTATUS_CANEXIST
)
5659 status
= CACHE_FLAG_CANEXIST
;
5660 else if (ies
->dpstatus
& IAX_DPSTATUS_NONEXISTENT
)
5661 status
= CACHE_FLAG_NONEXISTENT
;
5663 if (ies
->dpstatus
& IAX_DPSTATUS_IGNOREPAT
) {
5664 /* Don't really do anything with this */
5667 expiry
= ies
->refresh
;
5668 if (ies
->dpstatus
& IAX_DPSTATUS_MATCHMORE
)
5669 matchmore
= CACHE_FLAG_MATCHMORE
;
5670 ast_mutex_lock(&dpcache_lock
);
5672 dp
= pvt
->dpentries
;
5674 if (!strcmp(dp
->exten
, exten
)) {
5677 prev
->peer
= dp
->peer
;
5679 pvt
->dpentries
= dp
->peer
;
5682 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ expiry
;
5683 if (dp
->flags
& CACHE_FLAG_PENDING
) {
5684 dp
->flags
&= ~CACHE_FLAG_PENDING
;
5685 dp
->flags
|= status
;
5686 dp
->flags
|= matchmore
;
5688 /* Wake up waiters */
5689 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
5690 if (dp
->waiters
[x
] > -1)
5691 write(dp
->waiters
[x
], "asdf", 4);
5696 ast_mutex_unlock(&dpcache_lock
);
5700 static int complete_transfer(int callno
, struct iax_ies
*ies
)
5703 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
5704 struct iax_frame
*cur
;
5708 peercallno
= ies
->callno
;
5710 if (peercallno
< 1) {
5711 ast_log(LOG_WARNING
, "Invalid transfer request\n");
5714 memcpy(&pvt
->addr
, &pvt
->transfer
, sizeof(pvt
->addr
));
5715 memset(&pvt
->transfer
, 0, sizeof(pvt
->transfer
));
5716 /* Reset sequence numbers */
5721 pvt
->peercallno
= peercallno
;
5722 pvt
->transferring
= TRANSFER_NONE
;
5723 pvt
->svoiceformat
= -1;
5724 pvt
->voiceformat
= 0;
5725 pvt
->svideoformat
= -1;
5726 pvt
->videoformat
= 0;
5727 pvt
->transfercallno
= -1;
5728 memset(&pvt
->rxcore
, 0, sizeof(pvt
->rxcore
));
5729 memset(&pvt
->offset
, 0, sizeof(pvt
->offset
));
5730 /* reset jitterbuffer */
5731 while(jb_getall(pvt
->jb
,&frame
) == JB_OK
)
5732 iax2_frame_free(frame
.data
);
5738 pvt
->pingtime
= DEFAULT_RETRY_TIME
;
5739 AST_LIST_LOCK(&iaxq
.queue
);
5740 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
5741 /* We must cancel any packets that would have been transmitted
5742 because now we're talking to someone new. It's okay, they
5743 were transmitted to someone that didn't care anyway. */
5744 if (callno
== cur
->callno
)
5747 AST_LIST_UNLOCK(&iaxq
.queue
);
5751 /*! \brief Acknowledgment received for OUR registration */
5752 static int iax2_ack_registry(struct iax_ies
*ies
, struct sockaddr_in
*sin
, int callno
)
5754 struct iax2_registry
*reg
;
5755 /* Start pessimistic */
5756 char peer
[256] = "";
5759 char ourip
[256] = "<Unspecified>";
5760 struct sockaddr_in oldus
;
5761 struct sockaddr_in us
;
5764 memset(&us
, 0, sizeof(us
));
5765 if (ies
->apparent_addr
)
5766 bcopy(ies
->apparent_addr
, &us
, sizeof(us
));
5768 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
5770 refresh
= ies
->refresh
;
5771 if (ies
->calling_number
) {
5772 /* We don't do anything with it really, but maybe we should */
5774 reg
= iaxs
[callno
]->reg
;
5776 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registry '%s'\n", peer
);
5779 memcpy(&oldus
, ®
->us
, sizeof(oldus
));
5780 oldmsgs
= reg
->messages
;
5781 if (inaddrcmp(®
->addr
, sin
)) {
5782 ast_log(LOG_WARNING
, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
5785 memcpy(®
->us
, &us
, sizeof(reg
->us
));
5786 if (ies
->msgcount
>= 0)
5787 reg
->messages
= ies
->msgcount
& 0xffff; /* only low 16 bits are used in the transmission of the IE */
5788 /* always refresh the registration at the interval requested by the server
5789 we are registering to
5791 reg
->refresh
= refresh
;
5792 AST_SCHED_DEL(sched
, reg
->expire
);
5793 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
5794 if (inaddrcmp(&oldus
, ®
->us
) || (reg
->messages
!= oldmsgs
)) {
5795 if (option_verbose
> 2) {
5796 if (reg
->messages
> 255)
5797 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new and %d old messages waiting", reg
->messages
& 0xff, reg
->messages
>> 8);
5798 else if (reg
->messages
> 1)
5799 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new messages waiting\n", reg
->messages
);
5800 else if (reg
->messages
> 0)
5801 snprintf(msgstatus
, sizeof(msgstatus
), " with 1 new message waiting\n");
5803 snprintf(msgstatus
, sizeof(msgstatus
), " with no messages waiting\n");
5804 snprintf(ourip
, sizeof(ourip
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
5805 ast_verbose(VERBOSE_PREFIX_3
"Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin
->sin_addr
), ourip
, msgstatus
);
5807 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin
->sin_addr
));
5809 reg
->regstate
= REG_STATE_REGISTERED
;
5813 static int iax2_register(char *value
, int lineno
)
5815 struct iax2_registry
*reg
;
5817 char *username
, *hostname
, *secret
;
5823 ast_copy_string(copy
, value
, sizeof(copy
));
5825 username
= strsep(&stringp
, "@");
5826 hostname
= strsep(&stringp
, "@");
5828 ast_log(LOG_WARNING
, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno
);
5832 username
= strsep(&stringp
, ":");
5833 secret
= strsep(&stringp
, ":");
5835 hostname
= strsep(&stringp
, ":");
5836 porta
= strsep(&stringp
, ":");
5838 if (porta
&& !atoi(porta
)) {
5839 ast_log(LOG_WARNING
, "%s is not a valid port number at line %d\n", porta
, lineno
);
5842 if (!(reg
= ast_calloc(1, sizeof(*reg
))))
5844 if (ast_dnsmgr_lookup(hostname
, ®
->addr
.sin_addr
, ®
->dnsmgr
) < 0) {
5848 ast_copy_string(reg
->username
, username
, sizeof(reg
->username
));
5850 ast_copy_string(reg
->secret
, secret
, sizeof(reg
->secret
));
5852 reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
5853 reg
->addr
.sin_family
= AF_INET
;
5854 reg
->addr
.sin_port
= porta
? htons(atoi(porta
)) : htons(IAX_DEFAULT_PORTNO
);
5855 AST_LIST_LOCK(®istrations
);
5856 AST_LIST_INSERT_HEAD(®istrations
, reg
, entry
);
5857 AST_LIST_UNLOCK(®istrations
);
5862 static void register_peer_exten(struct iax2_peer
*peer
, int onoff
)
5865 char *stringp
, *ext
;
5866 if (!ast_strlen_zero(regcontext
)) {
5867 ast_copy_string(multi
, S_OR(peer
->regexten
, peer
->name
), sizeof(multi
));
5869 while((ext
= strsep(&stringp
, "&"))) {
5871 if (!ast_exists_extension(NULL
, regcontext
, ext
, 1, NULL
))
5872 ast_add_extension(regcontext
, 1, ext
, 1, NULL
, NULL
,
5873 "Noop", ast_strdup(peer
->name
), ast_free
, "IAX2");
5875 ast_context_remove_extension(regcontext
, ext
, 1, NULL
);
5879 static void prune_peers(void);
5881 static void unlink_peer(struct iax2_peer
*peer
)
5883 if (peer
->expire
> -1) {
5884 if (!ast_sched_del(sched
, peer
->expire
)) {
5890 if (peer
->pokeexpire
> -1) {
5891 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
5892 peer
->pokeexpire
= -1;
5897 ao2_unlink(peers
, peer
);
5900 static void __expire_registry(const void *data
)
5902 struct iax2_peer
*peer
= (struct iax2_peer
*) data
;
5910 ast_log(LOG_DEBUG
, "Expiring registration for peer '%s'\n", peer
->name
);
5911 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(peer
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
)))
5912 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
5913 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer
->name
);
5914 /* Reset the address */
5915 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
5916 /* Reset expiry value */
5917 peer
->expiry
= min_reg_expire
;
5918 if (!ast_test_flag(peer
, IAX_TEMPONLY
))
5919 ast_db_del("IAX/Registry", peer
->name
);
5920 register_peer_exten(peer
, 0);
5921 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
5923 iax2_regfunk(peer
->name
, 0);
5925 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
))
5931 static int expire_registry(const void *data
)
5933 #ifdef SCHED_MULTITHREADED
5934 if (schedule_action(__expire_registry
, data
))
5936 __expire_registry(data
);
5940 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
5942 static void reg_source_db(struct iax2_peer
*p
)
5947 if (!ast_test_flag(p
, IAX_TEMPONLY
) && (!ast_db_get("IAX/Registry", p
->name
, data
, sizeof(data
)))) {
5948 c
= strchr(data
, ':');
5952 if (inet_aton(data
, &in
)) {
5957 if (option_verbose
> 2)
5958 ast_verbose(VERBOSE_PREFIX_3
"Seeding '%s' at %s:%d for %d\n", p
->name
,
5959 ast_inet_ntoa(in
), atoi(c
), atoi(d
));
5960 iax2_poke_peer(p
, 0);
5961 p
->expiry
= atoi(d
);
5962 memset(&p
->addr
, 0, sizeof(p
->addr
));
5963 p
->addr
.sin_family
= AF_INET
;
5964 p
->addr
.sin_addr
= in
;
5965 p
->addr
.sin_port
= htons(atoi(c
));
5966 if (p
->expire
> -1) {
5967 if (!ast_sched_del(sched
, p
->expire
)) {
5972 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
5973 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
5974 if (p
->expire
== -1)
5977 iax2_regfunk(p
->name
, 1);
5978 register_peer_exten(p
, 1);
5987 * \pre iaxsl[callno] is locked
5989 * \note Since this function calls send_command_final(), the pvt struct for
5990 * the given call number may disappear while executing this function.
5992 static int update_registry(struct sockaddr_in
*sin
, int callno
, char *devtype
, int fd
, unsigned short refresh
)
5994 /* Called from IAX thread only, with proper iaxsl lock */
5995 struct iax_ie_data ied
;
5996 struct iax2_peer
*p
;
6000 const char *peer_name
;
6003 memset(&ied
, 0, sizeof(ied
));
6005 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
6007 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6008 ast_mutex_unlock(&iaxsl
[callno
]);
6009 if (!(p
= find_peer(peer_name
, 1))) {
6010 ast_mutex_lock(&iaxsl
[callno
]);
6011 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
6014 ast_mutex_lock(&iaxsl
[callno
]);
6018 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(p
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
))) {
6019 if (sin
->sin_addr
.s_addr
) {
6022 realtime_update_peer(peer_name
, sin
, nowtime
);
6024 realtime_update_peer(peer_name
, sin
, 0);
6027 if (inaddrcmp(&p
->addr
, sin
)) {
6029 iax2_regfunk(p
->name
, 1);
6030 /* Stash the IP address from which they registered */
6031 memcpy(&p
->addr
, sin
, sizeof(p
->addr
));
6032 snprintf(data
, sizeof(data
), "%s:%d:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), p
->expiry
);
6033 if (!ast_test_flag(p
, IAX_TEMPONLY
) && sin
->sin_addr
.s_addr
) {
6034 ast_db_put("IAX/Registry", p
->name
, data
);
6035 if (option_verbose
> 2)
6036 ast_verbose(VERBOSE_PREFIX_3
"Registered IAX2 '%s' (%s) at %s:%d\n", p
->name
,
6037 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
6038 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p
->name
);
6039 register_peer_exten(p
, 1);
6040 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
6041 } else if (!ast_test_flag(p
, IAX_TEMPONLY
)) {
6042 if (option_verbose
> 2)
6043 ast_verbose(VERBOSE_PREFIX_3
"Unregistered IAX2 '%s' (%s)\n", p
->name
,
6044 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6045 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p
->name
);
6046 register_peer_exten(p
, 0);
6047 ast_db_del("IAX/Registry", p
->name
);
6048 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
6050 /* Update the host */
6051 /* Verify that the host is really there */
6052 iax2_poke_peer(p
, callno
);
6055 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6056 if (!iaxs
[callno
]) {
6061 /* Store socket fd */
6063 /* Setup the expiry */
6064 if (p
->expire
> -1) {
6065 if (!ast_sched_del(sched
, p
->expire
)) {
6070 /* treat an unspecified refresh interval as the minimum */
6072 refresh
= min_reg_expire
;
6073 if (refresh
> max_reg_expire
) {
6074 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6075 p
->name
, max_reg_expire
, refresh
);
6076 p
->expiry
= max_reg_expire
;
6077 } else if (refresh
< min_reg_expire
) {
6078 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6079 p
->name
, min_reg_expire
, refresh
);
6080 p
->expiry
= min_reg_expire
;
6082 p
->expiry
= refresh
;
6084 if (p
->expiry
&& sin
->sin_addr
.s_addr
) {
6085 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
6086 if (p
->expire
== -1)
6089 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, p
->name
);
6090 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(p
->zonetag
));
6091 if (sin
->sin_addr
.s_addr
) {
6092 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, p
->expiry
);
6093 iax_ie_append_addr(&ied
, IAX_IE_APPARENT_ADDR
, &p
->addr
);
6094 if (!ast_strlen_zero(p
->mailbox
)) {
6096 ast_app_inboxcount(p
->mailbox
, &new, &old
);
6101 msgcount
= (old
<< 8) | new;
6102 iax_ie_append_short(&ied
, IAX_IE_MSGCOUNT
, msgcount
);
6104 if (ast_test_flag(p
, IAX_HASCALLERID
)) {
6105 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, p
->cid_num
);
6106 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, p
->cid_name
);
6109 version
= iax_check_version(devtype
);
6111 iax_ie_append_short(&ied
, IAX_IE_FIRMWAREVER
, version
);
6118 return res
? res
: send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGACK
, 0, ied
.buf
, ied
.pos
, -1);
6121 static int registry_authrequest(int callno
)
6123 struct iax_ie_data ied
;
6124 struct iax2_peer
*p
;
6126 const char *peer_name
;
6129 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
6131 /* SLD: third call to find_peer in registration */
6132 ast_mutex_unlock(&iaxsl
[callno
]);
6133 p
= find_peer(peer_name
, 1);
6134 ast_mutex_lock(&iaxsl
[callno
]);
6138 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
6142 memset(&ied
, 0, sizeof(ied
));
6143 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
6144 if (p
->authmethods
& (IAX_AUTH_RSA
| IAX_AUTH_MD5
)) {
6145 /* Build the challenge */
6146 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
6147 ast_string_field_set(iaxs
[callno
], challenge
, challenge
);
6148 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, iaxs
[callno
]->challenge
);
6150 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, peer_name
);
6157 return res
? res
: send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGAUTH
, 0, ied
.buf
, ied
.pos
, -1);;
6160 static int registry_rerequest(struct iax_ies
*ies
, int callno
, struct sockaddr_in
*sin
)
6162 struct iax2_registry
*reg
;
6163 /* Start pessimistic */
6164 struct iax_ie_data ied
;
6165 char peer
[256] = "";
6166 char challenge
[256] = "";
6168 int authmethods
= 0;
6169 if (ies
->authmethods
)
6170 authmethods
= ies
->authmethods
;
6172 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
6174 ast_copy_string(challenge
, ies
->challenge
, sizeof(challenge
));
6175 memset(&ied
, 0, sizeof(ied
));
6176 reg
= iaxs
[callno
]->reg
;
6178 if (inaddrcmp(®
->addr
, sin
)) {
6179 ast_log(LOG_WARNING
, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
6182 if (ast_strlen_zero(reg
->secret
)) {
6183 ast_log(LOG_NOTICE
, "No secret associated with peer '%s'\n", reg
->username
);
6184 reg
->regstate
= REG_STATE_NOAUTH
;
6187 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
6188 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
6189 if (reg
->secret
[0] == '[') {
6191 ast_copy_string(tmpkey
, reg
->secret
+ 1, sizeof(tmpkey
));
6192 tmpkey
[strlen(tmpkey
) - 1] = '\0';
6193 res
= authenticate(challenge
, NULL
, tmpkey
, authmethods
, &ied
, sin
, NULL
, NULL
);
6195 res
= authenticate(challenge
, reg
->secret
, NULL
, authmethods
, &ied
, sin
, NULL
, NULL
);
6197 reg
->regstate
= REG_STATE_AUTHSENT
;
6198 return send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
6201 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registery '%s'\n", peer
);
6203 ast_log(LOG_NOTICE
, "Can't reregister without a reg\n");
6207 static void stop_stuff(int callno
)
6209 iax2_destroy_helper(iaxs
[callno
]);
6212 static void __auth_reject(const void *nothing
)
6214 /* Called from IAX thread only, without iaxs lock */
6215 int callno
= (int)(long)(nothing
);
6216 struct iax_ie_data ied
;
6217 ast_mutex_lock(&iaxsl
[callno
]);
6219 memset(&ied
, 0, sizeof(ied
));
6220 if (iaxs
[callno
]->authfail
== IAX_COMMAND_REGREJ
) {
6221 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Registration Refused");
6222 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_REJECTED
);
6223 } else if (iaxs
[callno
]->authfail
== IAX_COMMAND_REJECT
) {
6224 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "No authority found");
6225 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
6227 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, iaxs
[callno
]->authfail
, 0, ied
.buf
, ied
.pos
, -1);
6229 ast_mutex_unlock(&iaxsl
[callno
]);
6232 static int auth_reject(const void *data
)
6234 int callno
= (int)(long)(data
);
6235 ast_mutex_lock(&iaxsl
[callno
]);
6237 iaxs
[callno
]->authid
= -1;
6238 ast_mutex_unlock(&iaxsl
[callno
]);
6239 #ifdef SCHED_MULTITHREADED
6240 if (schedule_action(__auth_reject
, data
))
6242 __auth_reject(data
);
6246 static int auth_fail(int callno
, int failcode
)
6248 /* Schedule sending the authentication failure in one second, to prevent
6251 iaxs
[callno
]->authfail
= failcode
;
6253 AST_SCHED_DEL(sched
, iaxs
[callno
]->authid
);
6254 iaxs
[callno
]->authid
= iax2_sched_add(sched
, 1000, auth_reject
, (void *)(long)callno
);
6256 auth_reject((void *)(long)callno
);
6261 static void __auto_hangup(const void *nothing
)
6263 /* Called from IAX thread only, without iaxs lock */
6264 int callno
= (int)(long)(nothing
);
6265 struct iax_ie_data ied
;
6266 ast_mutex_lock(&iaxsl
[callno
]);
6268 memset(&ied
, 0, sizeof(ied
));
6269 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Timeout");
6270 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_USER_RESPONSE
);
6271 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
6273 ast_mutex_unlock(&iaxsl
[callno
]);
6276 static int auto_hangup(const void *data
)
6278 int callno
= (int)(long)(data
);
6279 ast_mutex_lock(&iaxsl
[callno
]);
6281 iaxs
[callno
]->autoid
= -1;
6283 ast_mutex_unlock(&iaxsl
[callno
]);
6284 #ifdef SCHED_MULTITHREADED
6285 if (schedule_action(__auto_hangup
, data
))
6287 __auto_hangup(data
);
6291 static void iax2_dprequest(struct iax2_dpcache
*dp
, int callno
)
6293 struct iax_ie_data ied
;
6294 /* Auto-hangup with 30 seconds of inactivity */
6295 AST_SCHED_DEL(sched
, iaxs
[callno
]->autoid
);
6296 iaxs
[callno
]->autoid
= iax2_sched_add(sched
, 30000, auto_hangup
, (void *)(long)callno
);
6297 memset(&ied
, 0, sizeof(ied
));
6298 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, dp
->exten
);
6299 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREQ
, 0, ied
.buf
, ied
.pos
, -1);
6300 dp
->flags
|= CACHE_FLAG_TRANSMITTED
;
6303 static int iax2_vnak(int callno
)
6305 return send_command_immediate(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_VNAK
, 0, NULL
, 0, iaxs
[callno
]->iseqno
);
6308 static void vnak_retransmit(int callno
, int last
)
6310 struct iax_frame
*f
;
6312 AST_LIST_LOCK(&iaxq
.queue
);
6313 AST_LIST_TRAVERSE(&iaxq
.queue
, f
, list
) {
6314 /* Send a copy immediately */
6315 if ((f
->callno
== callno
) && iaxs
[f
->callno
] &&
6316 ((unsigned char ) (f
->oseqno
- last
) < 128) &&
6317 (f
->retries
>= 0)) {
6321 AST_LIST_UNLOCK(&iaxq
.queue
);
6324 static void __iax2_poke_peer_s(const void *data
)
6326 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
6327 iax2_poke_peer(peer
, 0);
6331 static int iax2_poke_peer_s(const void *data
)
6333 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
6334 peer
->pokeexpire
= -1;
6335 #ifdef SCHED_MULTITHREADED
6336 if (schedule_action(__iax2_poke_peer_s
, data
))
6338 __iax2_poke_peer_s(data
);
6342 static int send_trunk(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
6345 struct iax_frame
*fr
;
6346 struct ast_iax2_meta_hdr
*meta
;
6347 struct ast_iax2_meta_trunk_hdr
*mth
;
6350 /* Point to frame */
6351 fr
= (struct iax_frame
*)tpeer
->trunkdata
;
6352 /* Point to meta data */
6353 meta
= (struct ast_iax2_meta_hdr
*)fr
->afdata
;
6354 mth
= (struct ast_iax2_meta_trunk_hdr
*)meta
->data
;
6355 if (tpeer
->trunkdatalen
) {
6356 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6358 meta
->metacmd
= IAX_META_TRUNK
;
6359 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
))
6360 meta
->cmddata
= IAX_META_TRUNK_MINI
;
6362 meta
->cmddata
= IAX_META_TRUNK_SUPERMINI
;
6363 mth
->ts
= htonl(calc_txpeerstamp(tpeer
, trunkfreq
, now
));
6364 /* And the rest of the ast_iax2 header */
6365 fr
->direction
= DIRECTION_OUTGRESS
;
6368 /* Any appropriate call will do */
6369 fr
->data
= fr
->afdata
;
6370 fr
->datalen
= tpeer
->trunkdatalen
+ sizeof(struct ast_iax2_meta_hdr
) + sizeof(struct ast_iax2_meta_trunk_hdr
);
6371 res
= transmit_trunk(fr
, &tpeer
->addr
, tpeer
->sockfd
);
6372 calls
= tpeer
->calls
;
6375 ast_log(LOG_DEBUG
, "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
));
6377 /* Reset transmit trunk side data */
6378 tpeer
->trunkdatalen
= 0;
6386 static inline int iax2_trunk_expired(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
6388 /* Drop when trunk is about 5 seconds idle */
6389 if (now
->tv_sec
> tpeer
->trunkact
.tv_sec
+ 5)
6394 static int timing_read(int *id
, int fd
, short events
, void *cbdata
)
6398 struct iax2_trunk_peer
*tpeer
, *prev
= NULL
, *drop
=NULL
;
6406 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA
);
6407 gettimeofday(&now
, NULL
);
6408 if (events
& AST_IO_PRI
) {
6410 /* Great, this is a timing interface, just call the ioctl */
6411 if (ioctl(fd
, ZT_TIMERACK
, &x
)) {
6412 ast_log(LOG_WARNING
, "Unable to acknowledge zap timer. IAX trunking will fail!\n");
6418 /* Read and ignore from the pseudo channel for timing */
6419 res
= read(fd
, buf
, sizeof(buf
));
6421 ast_log(LOG_WARNING
, "Unable to read from timing fd\n");
6425 /* For each peer that supports trunking... */
6426 ast_mutex_lock(&tpeerlock
);
6431 ast_mutex_lock(&tpeer
->lock
);
6432 /* We can drop a single tpeer per pass. That makes all this logic
6433 substantially easier */
6434 if (!drop
&& iax2_trunk_expired(tpeer
, &now
)) {
6435 /* Take it out of the list, but don't free it yet, because it
6438 prev
->next
= tpeer
->next
;
6440 tpeers
= tpeer
->next
;
6443 res
= send_trunk(tpeer
, &now
);
6445 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
);
6449 ast_mutex_unlock(&tpeer
->lock
);
6451 tpeer
= tpeer
->next
;
6453 ast_mutex_unlock(&tpeerlock
);
6455 ast_mutex_lock(&drop
->lock
);
6456 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6457 because by the time they could get tpeerlock, we've already grabbed it */
6459 ast_log(LOG_DEBUG
, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop
->addr
.sin_addr
), ntohs(drop
->addr
.sin_port
));
6460 if (drop
->trunkdata
) {
6461 free(drop
->trunkdata
);
6462 drop
->trunkdata
= NULL
;
6464 ast_mutex_unlock(&drop
->lock
);
6465 ast_mutex_destroy(&drop
->lock
);
6470 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed
, totalcalls
);
6477 char context
[AST_MAX_EXTENSION
];
6478 char callednum
[AST_MAX_EXTENSION
];
6482 static void dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
, int skiplock
)
6484 unsigned short dpstatus
= 0;
6485 struct iax_ie_data ied1
;
6488 memset(&ied1
, 0, sizeof(ied1
));
6489 mm
= ast_matchmore_extension(NULL
, context
, callednum
, 1, callerid
);
6490 /* Must be started */
6491 if (!strcmp(callednum
, ast_parking_ext()) || ast_exists_extension(NULL
, context
, callednum
, 1, callerid
)) {
6492 dpstatus
= IAX_DPSTATUS_EXISTS
;
6493 } else if (ast_canmatch_extension(NULL
, context
, callednum
, 1, callerid
)) {
6494 dpstatus
= IAX_DPSTATUS_CANEXIST
;
6496 dpstatus
= IAX_DPSTATUS_NONEXISTENT
;
6498 if (ast_ignore_pattern(context
, callednum
))
6499 dpstatus
|= IAX_DPSTATUS_IGNOREPAT
;
6501 dpstatus
|= IAX_DPSTATUS_MATCHMORE
;
6503 ast_mutex_lock(&iaxsl
[callno
]);
6505 iax_ie_append_str(&ied1
, IAX_IE_CALLED_NUMBER
, callednum
);
6506 iax_ie_append_short(&ied1
, IAX_IE_DPSTATUS
, dpstatus
);
6507 iax_ie_append_short(&ied1
, IAX_IE_REFRESH
, iaxdefaultdpcache
);
6508 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREP
, 0, ied1
.buf
, ied1
.pos
, -1);
6511 ast_mutex_unlock(&iaxsl
[callno
]);
6514 static void *dp_lookup_thread(void *data
)
6516 /* Look up for dpreq */
6517 struct dpreq_data
*dpr
= data
;
6518 dp_lookup(dpr
->callno
, dpr
->context
, dpr
->callednum
, dpr
->callerid
, 0);
6520 free(dpr
->callerid
);
6525 static void spawn_dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
)
6527 pthread_t newthread
;
6528 struct dpreq_data
*dpr
;
6529 pthread_attr_t attr
;
6531 if (!(dpr
= ast_calloc(1, sizeof(*dpr
))))
6534 pthread_attr_init(&attr
);
6535 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
6537 dpr
->callno
= callno
;
6538 ast_copy_string(dpr
->context
, context
, sizeof(dpr
->context
));
6539 ast_copy_string(dpr
->callednum
, callednum
, sizeof(dpr
->callednum
));
6541 dpr
->callerid
= ast_strdup(callerid
);
6542 if (ast_pthread_create(&newthread
, &attr
, dp_lookup_thread
, dpr
)) {
6543 ast_log(LOG_WARNING
, "Unable to start lookup thread!\n");
6546 pthread_attr_destroy(&attr
);
6550 struct ast_channel
*chan1
;
6551 struct ast_channel
*chan2
;
6554 static void *iax_park_thread(void *stuff
)
6556 struct ast_channel
*chan1
, *chan2
;
6558 struct ast_frame
*f
;
6565 f
= ast_read(chan1
);
6568 res
= ast_park_call(chan1
, chan2
, 0, &ext
);
6570 ast_log(LOG_NOTICE
, "Parked on extension '%d'\n", ext
);
6574 static int iax_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
)
6577 struct ast_channel
*chan1m
, *chan2m
;
6579 chan1m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan1
->exten
, chan1
->context
, chan1
->amaflags
, "Parking/%s", chan1
->name
);
6580 chan2m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan2
->exten
, chan2
->context
, chan2
->amaflags
, "IAXPeer/%s",chan2
->name
);
6581 if (chan2m
&& chan1m
) {
6582 /* Make formats okay */
6583 chan1m
->readformat
= chan1
->readformat
;
6584 chan1m
->writeformat
= chan1
->writeformat
;
6585 ast_channel_masquerade(chan1m
, chan1
);
6586 /* Setup the extensions and such */
6587 ast_copy_string(chan1m
->context
, chan1
->context
, sizeof(chan1m
->context
));
6588 ast_copy_string(chan1m
->exten
, chan1
->exten
, sizeof(chan1m
->exten
));
6589 chan1m
->priority
= chan1
->priority
;
6591 /* We make a clone of the peer channel too, so we can play
6592 back the announcement */
6593 /* Make formats okay */
6594 chan2m
->readformat
= chan2
->readformat
;
6595 chan2m
->writeformat
= chan2
->writeformat
;
6596 ast_channel_masquerade(chan2m
, chan2
);
6597 /* Setup the extensions and such */
6598 ast_copy_string(chan2m
->context
, chan2
->context
, sizeof(chan2m
->context
));
6599 ast_copy_string(chan2m
->exten
, chan2
->exten
, sizeof(chan2m
->exten
));
6600 chan2m
->priority
= chan2
->priority
;
6601 if (ast_do_masquerade(chan2m
)) {
6602 ast_log(LOG_WARNING
, "Masquerade failed :(\n");
6613 if ((d
= ast_calloc(1, sizeof(*d
)))) {
6614 pthread_attr_t attr
;
6616 pthread_attr_init(&attr
);
6617 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
6621 if (!ast_pthread_create_background(&th
, &attr
, iax_park_thread
, d
)) {
6622 pthread_attr_destroy(&attr
);
6625 pthread_attr_destroy(&attr
);
6632 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
6634 static int check_provisioning(struct sockaddr_in
*sin
, int sockfd
, char *si
, unsigned int ver
)
6636 unsigned int ourver
;
6638 snprintf(rsi
, sizeof(rsi
), "si-%s", si
);
6639 if (iax_provision_version(&ourver
, rsi
, 1))
6642 ast_log(LOG_DEBUG
, "Service identifier '%s', we think '%08x', they think '%08x'\n", si
, ourver
, ver
);
6644 iax2_provision(sin
, sockfd
, NULL
, rsi
, 1);
6648 static void construct_rr(struct chan_iax2_pvt
*pvt
, struct iax_ie_data
*iep
)
6651 jb_getinfo(pvt
->jb
, &stats
);
6653 memset(iep
, 0, sizeof(*iep
));
6655 iax_ie_append_int(iep
,IAX_IE_RR_JITTER
, stats
.jitter
);
6656 if(stats
.frames_in
== 0) stats
.frames_in
= 1;
6657 iax_ie_append_int(iep
,IAX_IE_RR_LOSS
, ((0xff & (stats
.losspct
/1000)) << 24 | (stats
.frames_lost
& 0x00ffffff)));
6658 iax_ie_append_int(iep
,IAX_IE_RR_PKTS
, stats
.frames_in
);
6659 iax_ie_append_short(iep
,IAX_IE_RR_DELAY
, stats
.current
- stats
.min
);
6660 iax_ie_append_int(iep
,IAX_IE_RR_DROPPED
, stats
.frames_dropped
);
6661 iax_ie_append_int(iep
,IAX_IE_RR_OOO
, stats
.frames_ooo
);
6664 static void save_rr(struct iax_frame
*fr
, struct iax_ies
*ies
)
6666 iaxs
[fr
->callno
]->remote_rr
.jitter
= ies
->rr_jitter
;
6667 iaxs
[fr
->callno
]->remote_rr
.losspct
= ies
->rr_loss
>> 24;
6668 iaxs
[fr
->callno
]->remote_rr
.losscnt
= ies
->rr_loss
& 0xffffff;
6669 iaxs
[fr
->callno
]->remote_rr
.packets
= ies
->rr_pkts
;
6670 iaxs
[fr
->callno
]->remote_rr
.delay
= ies
->rr_delay
;
6671 iaxs
[fr
->callno
]->remote_rr
.dropped
= ies
->rr_dropped
;
6672 iaxs
[fr
->callno
]->remote_rr
.ooo
= ies
->rr_ooo
;
6675 static int socket_process(struct iax2_thread
*thread
);
6678 * \brief Handle any deferred full frames for this thread
6680 static void handle_deferred_full_frames(struct iax2_thread
*thread
)
6682 struct iax2_pkt_buf
*pkt_buf
;
6684 ast_mutex_lock(&thread
->lock
);
6686 while ((pkt_buf
= AST_LIST_REMOVE_HEAD(&thread
->full_frames
, entry
))) {
6687 ast_mutex_unlock(&thread
->lock
);
6689 thread
->buf
= pkt_buf
->buf
;
6690 thread
->buf_len
= pkt_buf
->len
;
6691 thread
->buf_size
= pkt_buf
->len
+ 1;
6693 socket_process(thread
);
6698 ast_mutex_lock(&thread
->lock
);
6701 ast_mutex_unlock(&thread
->lock
);
6705 * \brief Queue the last read full frame for processing by a certain thread
6707 * If there are already any full frames queued, they are sorted
6708 * by sequence number.
6710 static void defer_full_frame(struct iax2_thread
*from_here
, struct iax2_thread
*to_here
)
6712 struct iax2_pkt_buf
*pkt_buf
, *cur_pkt_buf
;
6713 struct ast_iax2_full_hdr
*fh
, *cur_fh
;
6715 if (!(pkt_buf
= ast_calloc(1, sizeof(*pkt_buf
) + from_here
->buf_len
)))
6718 pkt_buf
->len
= from_here
->buf_len
;
6719 memcpy(pkt_buf
->buf
, from_here
->buf
, pkt_buf
->len
);
6721 fh
= (struct ast_iax2_full_hdr
*) pkt_buf
->buf
;
6722 ast_mutex_lock(&to_here
->lock
);
6723 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here
->full_frames
, cur_pkt_buf
, entry
) {
6724 cur_fh
= (struct ast_iax2_full_hdr
*) cur_pkt_buf
->buf
;
6725 if (fh
->oseqno
< cur_fh
->oseqno
) {
6726 AST_LIST_INSERT_BEFORE_CURRENT(&to_here
->full_frames
, pkt_buf
, entry
);
6730 AST_LIST_TRAVERSE_SAFE_END
6733 AST_LIST_INSERT_TAIL(&to_here
->full_frames
, pkt_buf
, entry
);
6735 ast_mutex_unlock(&to_here
->lock
);
6738 static int socket_read(int *id
, int fd
, short events
, void *cbdata
)
6740 struct iax2_thread
*thread
;
6743 static time_t last_errtime
= 0;
6744 struct ast_iax2_full_hdr
*fh
;
6746 if (!(thread
= find_idle_thread())) {
6748 if (t
!= last_errtime
&& option_debug
)
6749 ast_log(LOG_DEBUG
, "Out of idle IAX2 threads for I/O, pausing!\n");
6755 len
= sizeof(thread
->iosin
);
6757 thread
->buf_len
= recvfrom(fd
, thread
->readbuf
, sizeof(thread
->readbuf
), 0, (struct sockaddr
*) &thread
->iosin
, &len
);
6758 thread
->buf_size
= sizeof(thread
->readbuf
);
6759 thread
->buf
= thread
->readbuf
;
6760 if (thread
->buf_len
< 0) {
6761 if (errno
!= ECONNREFUSED
&& errno
!= EAGAIN
)
6762 ast_log(LOG_WARNING
, "Error: %s\n", strerror(errno
));
6764 thread
->iostate
= IAX_IOSTATE_IDLE
;
6765 signal_condition(&thread
->lock
, &thread
->cond
);
6768 if (test_losspct
&& ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_losspct
)) { /* simulate random loss condition */
6769 thread
->iostate
= IAX_IOSTATE_IDLE
;
6770 signal_condition(&thread
->lock
, &thread
->cond
);
6774 /* Determine if this frame is a full frame; if so, and any thread is currently
6775 processing a full frame for the same callno from this peer, then drop this
6776 frame (and the peer will retransmit it) */
6777 fh
= (struct ast_iax2_full_hdr
*) thread
->buf
;
6778 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
6779 struct iax2_thread
*cur
= NULL
;
6780 uint16_t callno
= ntohs(fh
->scallno
) & ~IAX_FLAG_FULL
;
6782 AST_LIST_LOCK(&active_list
);
6783 AST_LIST_TRAVERSE(&active_list
, cur
, list
) {
6784 if ((cur
->ffinfo
.callno
== callno
) &&
6785 !inaddrcmp(&cur
->ffinfo
.sin
, &thread
->iosin
))
6789 /* we found another thread processing a full frame for this call,
6790 so queue it up for processing later. */
6791 defer_full_frame(thread
, cur
);
6792 AST_LIST_UNLOCK(&active_list
);
6793 thread
->iostate
= IAX_IOSTATE_IDLE
;
6794 signal_condition(&thread
->lock
, &thread
->cond
);
6797 /* this thread is going to process this frame, so mark it */
6798 thread
->ffinfo
.callno
= callno
;
6799 memcpy(&thread
->ffinfo
.sin
, &thread
->iosin
, sizeof(thread
->ffinfo
.sin
));
6800 thread
->ffinfo
.type
= fh
->type
;
6801 thread
->ffinfo
.csub
= fh
->csub
;
6803 AST_LIST_UNLOCK(&active_list
);
6806 /* Mark as ready and send on its way */
6807 thread
->iostate
= IAX_IOSTATE_READY
;
6808 #ifdef DEBUG_SCHED_MULTITHREAD
6809 ast_copy_string(thread
->curfunc
, "socket_process", sizeof(thread
->curfunc
));
6811 signal_condition(&thread
->lock
, &thread
->cond
);
6816 static int socket_process(struct iax2_thread
*thread
)
6818 struct sockaddr_in sin
;
6820 int updatehistory
=1;
6821 int new = NEW_PREVENT
;
6824 struct ast_iax2_full_hdr
*fh
= (struct ast_iax2_full_hdr
*)thread
->buf
;
6825 struct ast_iax2_mini_hdr
*mh
= (struct ast_iax2_mini_hdr
*)thread
->buf
;
6826 struct ast_iax2_meta_hdr
*meta
= (struct ast_iax2_meta_hdr
*)thread
->buf
;
6827 struct ast_iax2_video_hdr
*vh
= (struct ast_iax2_video_hdr
*)thread
->buf
;
6828 struct ast_iax2_meta_trunk_hdr
*mth
;
6829 struct ast_iax2_meta_trunk_entry
*mte
;
6830 struct ast_iax2_meta_trunk_mini
*mtm
;
6831 struct iax_frame
*fr
;
6832 struct iax_frame
*cur
;
6833 struct ast_frame f
= { 0, };
6834 struct ast_channel
*c
;
6835 struct iax2_dpcache
*dp
;
6836 struct iax2_peer
*peer
;
6837 struct iax2_trunk_peer
*tpeer
;
6838 struct timeval rxtrunktime
;
6840 struct iax_ie_data ied0
, ied1
;
6846 char empty
[32]=""; /* Safety measure */
6847 struct iax_frame
*duped_fr
;
6848 char host_pref_buf
[128];
6849 char caller_pref_buf
[128];
6850 struct ast_codec_pref pref
;
6851 char *using_prefs
= "mine";
6853 /* allocate an iax_frame with 4096 bytes of data buffer */
6854 fr
= alloca(sizeof(*fr
) + 4096);
6856 fr
->afdatalen
= 4096; /* From alloca() above */
6858 /* Copy frequently used parameters to the stack */
6859 res
= thread
->buf_len
;
6861 memcpy(&sin
, &thread
->iosin
, sizeof(sin
));
6863 if (res
< sizeof(*mh
)) {
6864 ast_log(LOG_WARNING
, "midget packet received (%d of %zd min)\n", res
, sizeof(*mh
));
6867 if ((vh
->zeros
== 0) && (ntohs(vh
->callno
) & 0x8000)) {
6868 if (res
< sizeof(*vh
)) {
6869 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
));
6873 /* This is a video frame, get call number */
6874 fr
->callno
= find_callno(ntohs(vh
->callno
) & ~0x8000, dcallno
, &sin
, new, fd
);
6876 } else if ((meta
->zeros
== 0) && !(ntohs(meta
->metacmd
) & 0x8000)) {
6877 unsigned char metatype
;
6879 if (res
< sizeof(*meta
)) {
6880 ast_log(LOG_WARNING
, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
6884 /* This is a meta header */
6885 switch(meta
->metacmd
) {
6886 case IAX_META_TRUNK
:
6887 if (res
< (sizeof(*meta
) + sizeof(*mth
))) {
6888 ast_log(LOG_WARNING
, "midget meta trunk packet received (%d of %zd min)\n", res
,
6889 sizeof(*meta
) + sizeof(*mth
));
6892 mth
= (struct ast_iax2_meta_trunk_hdr
*)(meta
->data
);
6893 ts
= ntohl(mth
->ts
);
6894 metatype
= meta
->cmddata
;
6895 res
-= (sizeof(*meta
) + sizeof(*mth
));
6897 tpeer
= find_tpeer(&sin
, fd
);
6899 ast_log(LOG_WARNING
, "Unable to accept trunked packet from '%s:%d': No matching peer\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
6902 tpeer
->trunkact
= ast_tvnow();
6903 if (!ts
|| ast_tvzero(tpeer
->rxtrunktime
))
6904 tpeer
->rxtrunktime
= tpeer
->trunkact
;
6905 rxtrunktime
= tpeer
->rxtrunktime
;
6906 ast_mutex_unlock(&tpeer
->lock
);
6907 while(res
>= sizeof(*mte
)) {
6908 /* Process channels */
6909 unsigned short callno
, trunked_ts
, len
;
6911 if (metatype
== IAX_META_TRUNK_MINI
) {
6912 mtm
= (struct ast_iax2_meta_trunk_mini
*)ptr
;
6913 ptr
+= sizeof(*mtm
);
6914 res
-= sizeof(*mtm
);
6915 len
= ntohs(mtm
->len
);
6916 callno
= ntohs(mtm
->mini
.callno
);
6917 trunked_ts
= ntohs(mtm
->mini
.ts
);
6918 } else if (metatype
== IAX_META_TRUNK_SUPERMINI
) {
6919 mte
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
6920 ptr
+= sizeof(*mte
);
6921 res
-= sizeof(*mte
);
6922 len
= ntohs(mte
->len
);
6923 callno
= ntohs(mte
->callno
);
6926 ast_log(LOG_WARNING
, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
6929 /* Stop if we don't have enough data */
6932 fr
->callno
= find_callno_locked(callno
& ~IAX_FLAG_FULL
, 0, &sin
, NEW_PREVENT
, fd
);
6934 /* If it's a valid call, deliver the contents. If not, we
6935 drop it, since we don't have a scallno to use for an INVAL */
6936 /* Process as a mini frame */
6937 memset(&f
, 0, sizeof(f
));
6938 f
.frametype
= AST_FRAME_VOICE
;
6939 if (iaxs
[fr
->callno
]) {
6940 if (iaxs
[fr
->callno
]->voiceformat
> 0) {
6941 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
6943 if (f
.datalen
>= 0) {
6947 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | (trunked_ts
& 0xffff);
6949 fr
->ts
= fix_peerts(&rxtrunktime
, fr
->callno
, ts
);
6950 /* Don't pass any packets until we're started */
6951 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
6954 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
))
6955 f
.samples
= ast_codec_get_samples(&f
);
6956 iax_frame_wrap(fr
, &f
);
6957 duped_fr
= iaxfrdup2(fr
);
6959 schedule_delivery(duped_fr
, updatehistory
, 1, &fr
->ts
);
6961 /* It is possible for the pvt structure to go away after we call schedule_delivery */
6962 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
6963 iaxs
[fr
->callno
]->last
= fr
->ts
;
6965 if (option_debug
&& iaxdebug
)
6966 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
6971 ast_log(LOG_WARNING
, "Datalen < 0?\n");
6974 ast_log(LOG_WARNING
, "Received trunked frame before first full voice frame\n ");
6975 iax2_vnak(fr
->callno
);
6978 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
6988 #ifdef DEBUG_SUPPORT
6989 if (iaxdebug
&& (res
>= sizeof(*fh
)))
6990 iax_showframe(NULL
, fh
, 1, &sin
, res
- sizeof(*fh
));
6992 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
6993 if (res
< sizeof(*fh
)) {
6994 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
));
6998 /* Get the destination call number */
6999 dcallno
= ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
;
7000 /* Retrieve the type and subclass */
7001 f
.frametype
= fh
->type
;
7002 if (f
.frametype
== AST_FRAME_VIDEO
) {
7003 f
.subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
7005 f
.subclass
= uncompress_subclass(fh
->csub
);
7007 if ((f
.frametype
== AST_FRAME_IAX
) && ((f
.subclass
== IAX_COMMAND_NEW
) || (f
.subclass
== IAX_COMMAND_REGREQ
) ||
7008 (f
.subclass
== IAX_COMMAND_POKE
) || (f
.subclass
== IAX_COMMAND_FWDOWNL
) ||
7009 (f
.subclass
== IAX_COMMAND_REGREL
)))
7012 /* Don't know anything about it yet */
7013 f
.frametype
= AST_FRAME_NULL
;
7018 fr
->callno
= find_callno(ntohs(mh
->callno
) & ~IAX_FLAG_FULL
, dcallno
, &sin
, new, fd
);
7021 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7023 if (!fr
->callno
|| !iaxs
[fr
->callno
]) {
7024 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7025 frame, reply with an inval */
7026 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7027 /* We can only raw hangup control frames */
7028 if (((f
.subclass
!= IAX_COMMAND_INVAL
) &&
7029 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7030 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7031 (f
.subclass
!= IAX_COMMAND_FWDOWNL
))||
7032 (f
.frametype
!= AST_FRAME_IAX
))
7033 raw_hangup(&sin
, ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
, ntohs(mh
->callno
) & ~IAX_FLAG_FULL
,
7037 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7040 if (ast_test_flag(iaxs
[fr
->callno
], IAX_ENCRYPTED
)) {
7041 if (decrypt_frame(fr
->callno
, fh
, &f
, &res
)) {
7042 ast_log(LOG_NOTICE
, "Packet Decrypt Failed!\n");
7043 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7046 #ifdef DEBUG_SUPPORT
7048 iax_showframe(NULL
, fh
, 3, &sin
, res
- sizeof(*fh
));
7052 /* count this frame */
7053 iaxs
[fr
->callno
]->frames_received
++;
7055 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) && !minivid
&&
7056 f
.subclass
!= IAX_COMMAND_TXCNT
&& /* for attended transfer */
7057 f
.subclass
!= IAX_COMMAND_TXACC
) /* for attended transfer */
7058 iaxs
[fr
->callno
]->peercallno
= (unsigned short)(ntohs(mh
->callno
) & ~IAX_FLAG_FULL
);
7059 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7060 if (option_debug
&& iaxdebug
)
7061 ast_log(LOG_DEBUG
, "Received packet %d, (%d, %d)\n", fh
->oseqno
, f
.frametype
, f
.subclass
);
7062 /* Check if it's out of order (and not an ACK or INVAL) */
7063 fr
->oseqno
= fh
->oseqno
;
7064 fr
->iseqno
= fh
->iseqno
;
7065 fr
->ts
= ntohl(fh
->ts
);
7069 ast_log(LOG_DEBUG
, "Simulating frame ts resync, was %u now %u\n", fr
->ts
, fr
->ts
+ test_resync
);
7070 fr
->ts
+= test_resync
;
7072 #endif /* IAXTESTS */
7074 if ( (ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) ||
7075 ( (f
.frametype
!= AST_FRAME_VOICE
) && ! (f
.frametype
== AST_FRAME_IAX
&&
7076 (f
.subclass
== IAX_COMMAND_NEW
||
7077 f
.subclass
== IAX_COMMAND_AUTHREQ
||
7078 f
.subclass
== IAX_COMMAND_ACCEPT
||
7079 f
.subclass
== IAX_COMMAND_REJECT
)) ) )
7081 if ((ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) || (f
.frametype
!= AST_FRAME_VOICE
))
7083 if ((iaxs
[fr
->callno
]->iseqno
!= fr
->oseqno
) &&
7084 (iaxs
[fr
->callno
]->iseqno
||
7085 ((f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7086 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
7087 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
7088 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
7089 (f
.subclass
!= IAX_COMMAND_TXACC
)) ||
7090 (f
.frametype
!= AST_FRAME_IAX
))) {
7092 ((f
.subclass
!= IAX_COMMAND_ACK
) &&
7093 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
7094 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7095 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
7096 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
7097 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
7098 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7099 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
7100 (f
.frametype
!= AST_FRAME_IAX
)) {
7101 /* If it's not an ACK packet, it's out of order. */
7103 ast_log(LOG_DEBUG
, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7104 iaxs
[fr
->callno
]->iseqno
, fr
->oseqno
, f
.frametype
, f
.subclass
);
7105 /* Check to see if we need to request retransmission,
7106 * and take sequence number wraparound into account */
7107 if ((unsigned char) (iaxs
[fr
->callno
]->iseqno
- fr
->oseqno
) < 128) {
7108 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7109 if ((f
.frametype
!= AST_FRAME_IAX
) ||
7110 ((f
.subclass
!= IAX_COMMAND_ACK
) && (f
.subclass
!= IAX_COMMAND_INVAL
))) {
7112 ast_log(LOG_DEBUG
, "Acking anyway\n");
7113 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7114 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7115 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7118 /* Send a VNAK requesting retransmission */
7119 iax2_vnak(fr
->callno
);
7121 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7125 /* Increment unless it's an ACK or VNAK */
7126 if (((f
.subclass
!= IAX_COMMAND_ACK
) &&
7127 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
7128 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7129 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7130 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
7131 (f
.frametype
!= AST_FRAME_IAX
))
7132 iaxs
[fr
->callno
]->iseqno
++;
7135 if (res
< sizeof(*fh
)) {
7136 ast_log(LOG_WARNING
, "midget packet received (%d of %zd min)\n", res
, sizeof(*fh
));
7137 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7140 /* Ensure text frames are NULL-terminated */
7141 if (f
.frametype
== AST_FRAME_TEXT
&& thread
->buf
[res
- 1] != '\0') {
7142 if (res
< thread
->buf_size
)
7143 thread
->buf
[res
++] = '\0';
7144 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7145 thread
->buf
[res
- 1] = '\0';
7147 f
.datalen
= res
- sizeof(*fh
);
7149 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7150 from the real peer, not the transfer peer */
7151 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) &&
7152 ((f
.subclass
!= IAX_COMMAND_INVAL
) ||
7153 (f
.frametype
!= AST_FRAME_IAX
))) {
7155 int call_to_destroy
;
7156 /* XXX This code is not very efficient. Surely there is a better way which still
7157 properly handles boundary conditions? XXX */
7158 /* First we have to qualify that the ACKed value is within our window */
7159 for (x
=iaxs
[fr
->callno
]->rseqno
; x
!= iaxs
[fr
->callno
]->oseqno
; x
++)
7160 if (fr
->iseqno
== x
)
7162 if ((x
!= iaxs
[fr
->callno
]->oseqno
) || (iaxs
[fr
->callno
]->oseqno
== fr
->iseqno
)) {
7163 /* The acknowledgement is within our window. Time to acknowledge everything
7165 for (x
=iaxs
[fr
->callno
]->rseqno
; x
!= fr
->iseqno
; x
++) {
7166 /* Ack the packet with the given timestamp */
7167 if (option_debug
&& iaxdebug
)
7168 ast_log(LOG_DEBUG
, "Cancelling transmission of packet %d\n", x
);
7169 call_to_destroy
= 0;
7170 AST_LIST_LOCK(&iaxq
.queue
);
7171 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
7172 /* If it's our call, and our timestamp, mark -1 retries */
7173 if ((fr
->callno
== cur
->callno
) && (x
== cur
->oseqno
)) {
7175 /* Destroy call if this is the end */
7177 call_to_destroy
= fr
->callno
;
7180 AST_LIST_UNLOCK(&iaxq
.queue
);
7181 if (call_to_destroy
) {
7182 if (iaxdebug
&& option_debug
)
7183 ast_log(LOG_DEBUG
, "Really destroying %d, having been acked on final message\n", call_to_destroy
);
7184 ast_mutex_lock(&iaxsl
[call_to_destroy
]);
7185 iax2_destroy(call_to_destroy
);
7186 ast_mutex_unlock(&iaxsl
[call_to_destroy
]);
7189 /* Note how much we've received acknowledgement for */
7190 if (iaxs
[fr
->callno
])
7191 iaxs
[fr
->callno
]->rseqno
= fr
->iseqno
;
7193 /* Stop processing now */
7194 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7197 } else if (option_debug
)
7198 ast_log(LOG_DEBUG
, "Received iseqno %d not within window %d->%d\n", fr
->iseqno
, iaxs
[fr
->callno
]->rseqno
, iaxs
[fr
->callno
]->oseqno
);
7200 if (inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) &&
7201 ((f
.frametype
!= AST_FRAME_IAX
) ||
7202 ((f
.subclass
!= IAX_COMMAND_TXACC
) &&
7203 (f
.subclass
!= IAX_COMMAND_TXCNT
)))) {
7204 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7205 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7210 if (f
.frametype
== AST_FRAME_IAX
) {
7211 if (iax_parse_ies(&ies
, thread
->buf
+ sizeof(*fh
), f
.datalen
)) {
7212 ast_log(LOG_WARNING
, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin
.sin_addr
));
7213 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7219 f
.data
= thread
->buf
+ sizeof(*fh
);
7221 if (f
.frametype
== AST_FRAME_IAX
)
7225 memset(&ies
, 0, sizeof(ies
));
7228 /* when we receive the first full frame for a new incoming channel,
7229 it is safe to start the PBX on the channel because we have now
7230 completed a 3-way handshake with the peer */
7231 if ((f
.frametype
== AST_FRAME_VOICE
) ||
7232 (f
.frametype
== AST_FRAME_VIDEO
) ||
7233 (f
.frametype
== AST_FRAME_IAX
)) {
7234 if (ast_test_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
)) {
7235 ast_clear_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
7236 if (!ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->chosenformat
)) {
7237 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7243 if (f
.frametype
== AST_FRAME_VOICE
) {
7244 if (f
.subclass
!= iaxs
[fr
->callno
]->voiceformat
) {
7245 iaxs
[fr
->callno
]->voiceformat
= f
.subclass
;
7247 ast_log(LOG_DEBUG
, "Ooh, voice format changed to %d\n", f
.subclass
);
7248 if (iaxs
[fr
->callno
]->owner
) {
7251 if (ast_mutex_trylock(&iaxs
[fr
->callno
]->owner
->lock
)) {
7252 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7254 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7255 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner
;
7257 if (iaxs
[fr
->callno
]) {
7258 if (iaxs
[fr
->callno
]->owner
) {
7259 orignative
= iaxs
[fr
->callno
]->owner
->nativeformats
;
7260 iaxs
[fr
->callno
]->owner
->nativeformats
= f
.subclass
;
7261 if (iaxs
[fr
->callno
]->owner
->readformat
)
7262 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
7263 iaxs
[fr
->callno
]->owner
->nativeformats
= orignative
;
7264 ast_mutex_unlock(&iaxs
[fr
->callno
]->owner
->lock
);
7268 ast_log(LOG_DEBUG
, "Neat, somebody took away the channel at a magical time but i found it!\n");
7269 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7275 if (f
.frametype
== AST_FRAME_VIDEO
) {
7276 if (f
.subclass
!= iaxs
[fr
->callno
]->videoformat
) {
7278 ast_log(LOG_DEBUG
, "Ooh, video format changed to %d\n", f
.subclass
& ~0x1);
7279 iaxs
[fr
->callno
]->videoformat
= f
.subclass
& ~0x1;
7282 if (f
.frametype
== AST_FRAME_IAX
) {
7283 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->initid
);
7284 /* Handle the IAX pseudo frame itself */
7285 if (option_debug
&& iaxdebug
)
7286 ast_log(LOG_DEBUG
, "IAX subclass %d received\n", f
.subclass
);
7288 /* Update last ts unless the frame's timestamp originated with us. */
7289 if (iaxs
[fr
->callno
]->last
< fr
->ts
&&
7290 f
.subclass
!= IAX_COMMAND_ACK
&&
7291 f
.subclass
!= IAX_COMMAND_PONG
&&
7292 f
.subclass
!= IAX_COMMAND_LAGRP
) {
7293 iaxs
[fr
->callno
]->last
= fr
->ts
;
7294 if (option_debug
&& iaxdebug
)
7295 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
7298 switch(f
.subclass
) {
7299 case IAX_COMMAND_ACK
:
7302 case IAX_COMMAND_QUELCH
:
7303 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7304 /* Generate Manager Hold event, if necessary*/
7305 if (iaxs
[fr
->callno
]->owner
) {
7306 manager_event(EVENT_FLAG_CALL
, "Hold",
7309 iaxs
[fr
->callno
]->owner
->name
,
7310 iaxs
[fr
->callno
]->owner
->uniqueid
);
7313 ast_set_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
7314 if (ies
.musiconhold
) {
7315 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
7316 const char *mohsuggest
= iaxs
[fr
->callno
]->mohsuggest
;
7317 iax2_queue_control_data(fr
->callno
, AST_CONTROL_HOLD
,
7318 S_OR(mohsuggest
, NULL
),
7319 !ast_strlen_zero(mohsuggest
) ? strlen(mohsuggest
) + 1 : 0);
7320 if (!iaxs
[fr
->callno
]) {
7321 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7328 case IAX_COMMAND_UNQUELCH
:
7329 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7330 /* Generate Manager Unhold event, if necessary*/
7331 if (iaxs
[fr
->callno
]->owner
&& ast_test_flag(iaxs
[fr
->callno
], IAX_QUELCH
)) {
7332 manager_event(EVENT_FLAG_CALL
, "Unhold",
7335 iaxs
[fr
->callno
]->owner
->name
,
7336 iaxs
[fr
->callno
]->owner
->uniqueid
);
7339 ast_clear_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
7340 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
7341 iax2_queue_control_data(fr
->callno
, AST_CONTROL_UNHOLD
, NULL
, 0);
7342 if (!iaxs
[fr
->callno
]) {
7343 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7349 case IAX_COMMAND_TXACC
:
7350 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) {
7351 /* Ack the packet with the given timestamp */
7352 AST_LIST_LOCK(&iaxq
.queue
);
7353 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
7354 /* Cancel any outstanding txcnt's */
7355 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
))
7358 AST_LIST_UNLOCK(&iaxq
.queue
);
7359 memset(&ied1
, 0, sizeof(ied1
));
7360 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->callno
);
7361 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREADY
, 0, ied1
.buf
, ied1
.pos
, -1);
7362 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
7365 case IAX_COMMAND_NEW
:
7366 /* Ignore if it's already up */
7367 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
))
7369 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
7370 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7371 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
7372 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7373 if (!iaxs
[fr
->callno
]) {
7374 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7378 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7379 if (ast_test_flag(iaxs
[fr
->callno
], IAX_TRUNK
)) {
7381 if ((new_callno
= make_trunk(fr
->callno
, 1)) != -1)
7382 fr
->callno
= new_callno
;
7384 /* For security, always ack immediately */
7386 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7387 if (check_access(fr
->callno
, &sin
, &ies
)) {
7388 /* They're not allowed on */
7389 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
7391 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
);
7394 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7395 const char *context
, *exten
, *cid_num
;
7397 context
= ast_strdupa(iaxs
[fr
->callno
]->context
);
7398 exten
= ast_strdupa(iaxs
[fr
->callno
]->exten
);
7399 cid_num
= ast_strdupa(iaxs
[fr
->callno
]->cid_num
);
7401 /* This might re-enter the IAX code and need the lock */
7402 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7403 exists
= ast_exists_extension(NULL
, context
, exten
, 1, cid_num
);
7404 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7406 if (!iaxs
[fr
->callno
]) {
7407 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7412 if (ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) {
7413 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
7414 memset(&ied0
, 0, sizeof(ied0
));
7415 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
7416 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
7417 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7418 if (!iaxs
[fr
->callno
]) {
7419 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7423 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
);
7425 /* Select an appropriate format */
7427 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7428 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7429 using_prefs
= "reqonly";
7431 using_prefs
= "disabled";
7433 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
7434 memset(&pref
, 0, sizeof(pref
));
7435 strcpy(caller_pref_buf
, "disabled");
7436 strcpy(host_pref_buf
, "disabled");
7438 using_prefs
= "mine";
7439 /* If the information elements are in here... use them */
7440 if (ies
.codec_prefs
)
7441 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
7442 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7443 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7444 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7445 pref
= iaxs
[fr
->callno
]->rprefs
;
7446 using_prefs
= "caller";
7448 pref
= iaxs
[fr
->callno
]->prefs
;
7451 pref
= iaxs
[fr
->callno
]->prefs
;
7453 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
7454 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
7455 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
7458 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7459 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
7461 memset(&ied0
, 0, sizeof(ied0
));
7462 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7463 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7464 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7465 if (!iaxs
[fr
->callno
]) {
7466 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7470 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7471 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
);
7473 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
);
7477 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7478 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
7481 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7482 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
7483 memset(&pref
, 0, sizeof(pref
));
7484 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7485 strcpy(caller_pref_buf
,"disabled");
7486 strcpy(host_pref_buf
,"disabled");
7488 using_prefs
= "mine";
7489 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7490 /* Do the opposite of what we tried above. */
7491 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7492 pref
= iaxs
[fr
->callno
]->prefs
;
7494 pref
= iaxs
[fr
->callno
]->rprefs
;
7495 using_prefs
= "caller";
7497 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
7499 } else /* if no codec_prefs IE do it the old way */
7500 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7505 memset(&ied0
, 0, sizeof(ied0
));
7506 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7507 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7508 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7509 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7510 if (!iaxs
[fr
->callno
]) {
7511 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7515 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
);
7516 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
7522 /* No authentication required, let them in */
7523 memset(&ied1
, 0, sizeof(ied1
));
7524 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
7525 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
7526 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7527 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7528 if (option_verbose
> 2)
7529 ast_verbose(VERBOSE_PREFIX_3
"Accepting UNAUTHENTICATED call from %s:\n"
7530 "%srequested format = %s,\n"
7531 "%srequested prefs = %s,\n"
7532 "%sactual format = %s,\n"
7533 "%shost prefs = %s,\n"
7534 "%spriority = %s\n",
7535 ast_inet_ntoa(sin
.sin_addr
),
7537 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
7541 ast_getformatname(format
),
7547 iaxs
[fr
->callno
]->chosenformat
= format
;
7548 ast_set_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
7550 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
7551 /* If this is a TBD call, we're ready but now what... */
7552 if (option_verbose
> 2)
7553 ast_verbose(VERBOSE_PREFIX_3
"Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
7559 if (iaxs
[fr
->callno
]->authmethods
& IAX_AUTH_MD5
)
7560 merge_encryption(iaxs
[fr
->callno
],ies
.encmethods
);
7562 iaxs
[fr
->callno
]->encmethods
= 0;
7563 if (!authenticate_request(fr
->callno
) && iaxs
[fr
->callno
])
7564 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
);
7565 if (!iaxs
[fr
->callno
]) {
7566 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7570 case IAX_COMMAND_DPREQ
:
7571 /* Request status in the dialplan */
7572 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
) &&
7573 !ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
) && ies
.called_number
) {
7575 /* Spawn a thread for the lookup */
7576 spawn_dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
);
7578 /* Just look it up */
7579 dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
, 1);
7583 case IAX_COMMAND_HANGUP
:
7584 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
7586 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received hangup\n", fr
->callno
);
7587 /* Set hangup cause according to remote */
7588 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
7589 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
7590 /* Send ack immediately, before we destroy */
7591 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7592 iax2_destroy(fr
->callno
);
7594 case IAX_COMMAND_REJECT
:
7595 /* Set hangup cause according to remote */
7596 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
7597 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
7599 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
7600 if (iaxs
[fr
->callno
]->owner
&& authdebug
)
7601 ast_log(LOG_WARNING
, "Call rejected by %s: %s\n",
7602 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
),
7603 ies
.cause
? ies
.cause
: "<Unknown>");
7605 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received reject\n",
7608 /* Send ack immediately, before we destroy */
7609 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
,
7610 fr
->ts
, NULL
, 0, fr
->iseqno
);
7611 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
))
7612 iaxs
[fr
->callno
]->error
= EPERM
;
7613 iax2_destroy(fr
->callno
);
7615 case IAX_COMMAND_TRANSFER
:
7617 struct ast_channel
*bridged_chan
;
7619 if (iaxs
[fr
->callno
]->owner
&& (bridged_chan
= ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) && ies
.called_number
) {
7620 /* Set BLINDTRANSFER channel variables */
7622 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7623 pbx_builtin_setvar_helper(iaxs
[fr
->callno
]->owner
, "BLINDTRANSFER", bridged_chan
->name
);
7624 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7625 if (!iaxs
[fr
->callno
]) {
7626 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7630 pbx_builtin_setvar_helper(bridged_chan
, "BLINDTRANSFER", iaxs
[fr
->callno
]->owner
->name
);
7631 if (!strcmp(ies
.called_number
, ast_parking_ext())) {
7632 if (iax_park(bridged_chan
, iaxs
[fr
->callno
]->owner
)) {
7633 ast_log(LOG_WARNING
, "Failed to park call on '%s'\n", bridged_chan
->name
);
7635 ast_log(LOG_DEBUG
, "Parked call on '%s'\n", bridged_chan
->name
);
7638 if (ast_async_goto(bridged_chan
, iaxs
[fr
->callno
]->context
, ies
.called_number
, 1))
7639 ast_log(LOG_WARNING
, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan
->name
,
7640 ies
.called_number
, iaxs
[fr
->callno
]->context
);
7642 ast_log(LOG_DEBUG
, "Async goto of '%s' to '%s@%s' started\n", bridged_chan
->name
,
7643 ies
.called_number
, iaxs
[fr
->callno
]->context
);
7646 ast_log(LOG_DEBUG
, "Async goto not applicable on call %d\n", fr
->callno
);
7650 case IAX_COMMAND_ACCEPT
:
7651 /* Ignore if call is already up or needs authentication or is a TBD */
7652 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
| IAX_STATE_AUTHENTICATED
))
7654 if (ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
7655 /* Send ack immediately, before we destroy */
7656 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7657 iax2_destroy(fr
->callno
);
7661 iaxs
[fr
->callno
]->peerformat
= ies
.format
;
7663 if (iaxs
[fr
->callno
]->owner
)
7664 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->owner
->nativeformats
;
7666 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->capability
;
7668 if (option_verbose
> 2)
7669 ast_verbose(VERBOSE_PREFIX_3
"Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), ast_getformatname(iaxs
[fr
->callno
]->peerformat
));
7670 if (!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
)) {
7671 memset(&ied0
, 0, sizeof(ied0
));
7672 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7673 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7674 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7675 if (!iaxs
[fr
->callno
]) {
7676 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7680 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
);
7682 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7683 if (iaxs
[fr
->callno
]->owner
) {
7684 /* Switch us to use a compatible format */
7685 iaxs
[fr
->callno
]->owner
->nativeformats
= iaxs
[fr
->callno
]->peerformat
;
7686 if (option_verbose
> 2)
7687 ast_verbose(VERBOSE_PREFIX_3
"Format for call is %s\n", ast_getformatname(iaxs
[fr
->callno
]->owner
->nativeformats
));
7689 if (ast_mutex_trylock(&iaxs
[fr
->callno
]->owner
->lock
)) {
7690 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7692 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7693 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner2
;
7696 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) {
7697 /* Setup read/write formats properly. */
7698 if (iaxs
[fr
->callno
]->owner
->writeformat
)
7699 ast_set_write_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->writeformat
);
7700 if (iaxs
[fr
->callno
]->owner
->readformat
)
7701 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
7702 ast_mutex_unlock(&iaxs
[fr
->callno
]->owner
->lock
);
7706 if (iaxs
[fr
->callno
]) {
7707 ast_mutex_lock(&dpcache_lock
);
7708 dp
= iaxs
[fr
->callno
]->dpentries
;
7710 if (!(dp
->flags
& CACHE_FLAG_TRANSMITTED
)) {
7711 iax2_dprequest(dp
, fr
->callno
);
7715 ast_mutex_unlock(&dpcache_lock
);
7718 case IAX_COMMAND_POKE
:
7719 /* Send back a pong packet with the original timestamp */
7720 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, NULL
, 0, -1);
7721 if (!iaxs
[fr
->callno
]) {
7722 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7726 case IAX_COMMAND_PING
:
7728 struct iax_ie_data pingied
;
7729 construct_rr(iaxs
[fr
->callno
], &pingied
);
7730 /* Send back a pong packet with the original timestamp */
7731 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, pingied
.buf
, pingied
.pos
, -1);
7734 case IAX_COMMAND_PONG
:
7735 /* Calculate ping time */
7736 iaxs
[fr
->callno
]->pingtime
= calc_timestamp(iaxs
[fr
->callno
], 0, &f
) - fr
->ts
;
7740 if (iaxs
[fr
->callno
]->peerpoke
) {
7741 peer
= iaxs
[fr
->callno
]->peerpoke
;
7742 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
)) {
7743 if (iaxs
[fr
->callno
]->pingtime
<= peer
->maxms
) {
7744 ast_log(LOG_NOTICE
, "Peer '%s' is now REACHABLE! Time: %d\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7745 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7746 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
7748 } else if ((peer
->historicms
> 0) && (peer
->historicms
<= peer
->maxms
)) {
7749 if (iaxs
[fr
->callno
]->pingtime
> peer
->maxms
) {
7750 ast_log(LOG_NOTICE
, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7751 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7752 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
7755 peer
->lastms
= iaxs
[fr
->callno
]->pingtime
;
7756 if (peer
->smoothing
&& (peer
->lastms
> -1))
7757 peer
->historicms
= (iaxs
[fr
->callno
]->pingtime
+ peer
->historicms
) / 2;
7758 else if (peer
->smoothing
&& peer
->lastms
< 0)
7759 peer
->historicms
= (0 + peer
->historicms
) / 2;
7761 peer
->historicms
= iaxs
[fr
->callno
]->pingtime
;
7763 /* Remove scheduled iax2_poke_noanswer */
7764 if (peer
->pokeexpire
> -1) {
7765 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
7767 peer
->pokeexpire
= -1;
7770 /* Schedule the next cycle */
7771 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
))
7772 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
7774 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqok
, iax2_poke_peer_s
, peer_ref(peer
));
7775 if (peer
->pokeexpire
== -1)
7777 /* and finally send the ack */
7778 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7779 /* And wrap up the qualify call */
7780 iax2_destroy(fr
->callno
);
7783 ast_log(LOG_DEBUG
, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer
->name
, peer
->lastms
, peer
->historicms
, peer
->maxms
);
7786 case IAX_COMMAND_LAGRQ
:
7787 case IAX_COMMAND_LAGRP
:
7792 iax_frame_wrap(fr
, &f
);
7793 if(f
.subclass
== IAX_COMMAND_LAGRQ
) {
7794 /* Received a LAGRQ - echo back a LAGRP */
7795 fr
->af
.subclass
= IAX_COMMAND_LAGRP
;
7796 iax2_send(iaxs
[fr
->callno
], &fr
->af
, fr
->ts
, -1, 0, 0, 0);
7798 /* Received LAGRP in response to our LAGRQ */
7800 /* This is a reply we've been given, actually measure the difference */
7801 ts
= calc_timestamp(iaxs
[fr
->callno
], 0, &fr
->af
);
7802 iaxs
[fr
->callno
]->lag
= ts
- fr
->ts
;
7803 if (option_debug
&& iaxdebug
)
7804 ast_log(LOG_DEBUG
, "Peer %s lag measured as %dms\n",
7805 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), iaxs
[fr
->callno
]->lag
);
7808 case IAX_COMMAND_AUTHREQ
:
7809 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
7810 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>");
7813 if (authenticate_reply(iaxs
[fr
->callno
], &iaxs
[fr
->callno
]->addr
, &ies
, iaxs
[fr
->callno
]->secret
, iaxs
[fr
->callno
]->outkey
)) {
7814 struct ast_frame hangup_fr
= { .frametype
= AST_FRAME_CONTROL
,
7815 .subclass
= AST_CONTROL_HANGUP
,
7817 ast_log(LOG_WARNING
,
7818 "I don't know how to authenticate %s to %s\n",
7819 ies
.username
? ies
.username
: "<unknown>", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
));
7820 iax2_queue_frame(fr
->callno
, &hangup_fr
);
7822 if (!iaxs
[fr
->callno
]) {
7823 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7827 case IAX_COMMAND_AUTHREP
:
7828 /* For security, always ack immediately */
7830 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7831 /* Ignore once we've started */
7832 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
7833 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>");
7836 if (authenticate_verify(iaxs
[fr
->callno
], &ies
)) {
7838 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
);
7839 memset(&ied0
, 0, sizeof(ied0
));
7840 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
7843 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7844 /* This might re-enter the IAX code and need the lock */
7845 exists
= ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
);
7848 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
7850 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
);
7851 memset(&ied0
, 0, sizeof(ied0
));
7852 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
7853 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
7854 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7855 if (!iaxs
[fr
->callno
]) {
7856 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7860 /* Select an appropriate format */
7861 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7862 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7863 using_prefs
= "reqonly";
7865 using_prefs
= "disabled";
7867 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
7868 memset(&pref
, 0, sizeof(pref
));
7869 strcpy(caller_pref_buf
, "disabled");
7870 strcpy(host_pref_buf
, "disabled");
7872 using_prefs
= "mine";
7873 if (ies
.codec_prefs
)
7874 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
7875 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7876 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7877 pref
= iaxs
[fr
->callno
]->rprefs
;
7878 using_prefs
= "caller";
7880 pref
= iaxs
[fr
->callno
]->prefs
;
7882 } else /* if no codec_prefs IE do it the old way */
7883 pref
= iaxs
[fr
->callno
]->prefs
;
7885 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
7886 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
7887 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
7890 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7892 ast_log(LOG_DEBUG
, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs
[fr
->callno
]->peerformat
), iaxs
[fr
->callno
]->peercapability
);
7893 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
7897 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7898 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
);
7900 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
);
7902 memset(&ied0
, 0, sizeof(ied0
));
7903 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7904 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7905 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7906 if (!iaxs
[fr
->callno
]) {
7907 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7912 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7913 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
7916 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7917 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
7918 memset(&pref
, 0, sizeof(pref
));
7919 format
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ?
7920 iaxs
[fr
->callno
]->peerformat
: ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7921 strcpy(caller_pref_buf
,"disabled");
7922 strcpy(host_pref_buf
,"disabled");
7924 using_prefs
= "mine";
7925 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7926 /* Do the opposite of what we tried above. */
7927 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7928 pref
= iaxs
[fr
->callno
]->prefs
;
7930 pref
= iaxs
[fr
->callno
]->rprefs
;
7931 using_prefs
= "caller";
7933 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
7934 } else /* if no codec_prefs IE do it the old way */
7935 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7939 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7941 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7942 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
);
7944 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
);
7946 memset(&ied0
, 0, sizeof(ied0
));
7947 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7948 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7949 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7950 if (!iaxs
[fr
->callno
]) {
7951 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7958 /* Authentication received */
7959 memset(&ied1
, 0, sizeof(ied1
));
7960 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
7961 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
7962 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7963 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7964 if (option_verbose
> 2)
7965 ast_verbose(VERBOSE_PREFIX_3
"Accepting AUTHENTICATED call from %s:\n"
7966 "%srequested format = %s,\n"
7967 "%srequested prefs = %s,\n"
7968 "%sactual format = %s,\n"
7969 "%shost prefs = %s,\n"
7970 "%spriority = %s\n",
7971 ast_inet_ntoa(sin
.sin_addr
),
7973 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
7977 ast_getformatname(format
),
7983 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7984 if(!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, format
)))
7985 iax2_destroy(fr
->callno
);
7987 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
7988 /* If this is a TBD call, we're ready but now what... */
7989 if (option_verbose
> 2)
7990 ast_verbose(VERBOSE_PREFIX_3
"Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
7995 case IAX_COMMAND_DIAL
:
7996 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
)) {
7997 ast_clear_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
7998 ast_string_field_set(iaxs
[fr
->callno
], exten
, ies
.called_number
? ies
.called_number
: "s");
7999 if (!ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
)) {
8001 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
);
8002 memset(&ied0
, 0, sizeof(ied0
));
8003 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
8004 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
8005 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8006 if (!iaxs
[fr
->callno
]) {
8007 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8011 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8012 if (option_verbose
> 2)
8013 ast_verbose(VERBOSE_PREFIX_3
"Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
);
8014 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8015 send_command(iaxs
[fr
->callno
], AST_FRAME_CONTROL
, AST_CONTROL_PROGRESS
, 0, NULL
, 0, -1);
8016 if(!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->peerformat
)))
8017 iax2_destroy(fr
->callno
);
8021 case IAX_COMMAND_INVAL
:
8022 iaxs
[fr
->callno
]->error
= ENOTCONN
;
8024 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received INVAL\n", fr
->callno
);
8025 iax2_destroy(fr
->callno
);
8027 ast_log(LOG_DEBUG
, "Destroying call %d\n", fr
->callno
);
8029 case IAX_COMMAND_VNAK
:
8031 ast_log(LOG_DEBUG
, "Received VNAK: resending outstanding frames\n");
8032 /* Force retransmission */
8033 vnak_retransmit(fr
->callno
, fr
->iseqno
);
8035 case IAX_COMMAND_REGREQ
:
8036 case IAX_COMMAND_REGREL
:
8037 /* For security, always ack immediately */
8039 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8040 if (register_verify(fr
->callno
, &sin
, &ies
)) {
8041 if (!iaxs
[fr
->callno
]) {
8042 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8045 /* Send delayed failure */
8046 auth_fail(fr
->callno
, IAX_COMMAND_REGREJ
);
8049 if (!iaxs
[fr
->callno
]) {
8050 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8053 if ((ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) ||
8054 ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
)) {
8055 if (f
.subclass
== IAX_COMMAND_REGREL
)
8056 memset(&sin
, 0, sizeof(sin
));
8057 if (update_registry(&sin
, fr
->callno
, ies
.devicetype
, fd
, ies
.refresh
))
8058 ast_log(LOG_WARNING
, "Registry error\n");
8059 if (!iaxs
[fr
->callno
]) {
8060 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8063 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
8064 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8065 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
8066 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8067 if (!iaxs
[fr
->callno
]) {
8068 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8074 registry_authrequest(fr
->callno
);
8075 if (!iaxs
[fr
->callno
]) {
8076 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8080 case IAX_COMMAND_REGACK
:
8081 if (iax2_ack_registry(&ies
, &sin
, fr
->callno
))
8082 ast_log(LOG_WARNING
, "Registration failure\n");
8083 /* Send ack immediately, before we destroy */
8084 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8085 iax2_destroy(fr
->callno
);
8087 case IAX_COMMAND_REGREJ
:
8088 if (iaxs
[fr
->callno
]->reg
) {
8090 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
));
8091 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs
[fr
->callno
]->reg
->username
, ies
.cause
? ies
.cause
: "<unknown>");
8093 iaxs
[fr
->callno
]->reg
->regstate
= REG_STATE_REJECTED
;
8095 /* Send ack immediately, before we destroy */
8096 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8097 iax2_destroy(fr
->callno
);
8099 case IAX_COMMAND_REGAUTH
:
8100 /* Authentication request */
8101 if (registry_rerequest(&ies
, fr
->callno
, &sin
)) {
8102 memset(&ied0
, 0, sizeof(ied0
));
8103 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No authority found");
8104 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
8105 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8106 if (!iaxs
[fr
->callno
]) {
8107 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8112 case IAX_COMMAND_TXREJ
:
8113 iaxs
[fr
->callno
]->transferring
= 0;
8114 if (option_verbose
> 2)
8115 ast_verbose(VERBOSE_PREFIX_3
"Channel '%s' unable to transfer\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8116 memset(&iaxs
[fr
->callno
]->transfer
, 0, sizeof(iaxs
[fr
->callno
]->transfer
));
8117 if (iaxs
[fr
->callno
]->bridgecallno
) {
8118 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
) {
8119 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= 0;
8120 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, NULL
, 0, -1);
8124 case IAX_COMMAND_TXREADY
:
8125 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) ||
8126 (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)) {
8127 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)
8128 iaxs
[fr
->callno
]->transferring
= TRANSFER_MREADY
;
8130 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
8131 if (option_verbose
> 2)
8132 ast_verbose(VERBOSE_PREFIX_3
"Channel '%s' ready to transfer\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8133 if (iaxs
[fr
->callno
]->bridgecallno
) {
8134 if ((iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_READY
) ||
8135 (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_MREADY
)) {
8136 /* They're both ready, now release them. */
8137 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_MREADY
) {
8138 if (option_verbose
> 2)
8139 ast_verbose(VERBOSE_PREFIX_3
"Attempting media bridge of %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
8140 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
8142 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_MEDIA
;
8143 iaxs
[fr
->callno
]->transferring
= TRANSFER_MEDIA
;
8145 memset(&ied0
, 0, sizeof(ied0
));
8146 memset(&ied1
, 0, sizeof(ied1
));
8147 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
8148 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
8149 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied0
.buf
, ied0
.pos
, -1);
8150 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied1
.buf
, ied1
.pos
, -1);
8152 if (option_verbose
> 2)
8153 ast_verbose(VERBOSE_PREFIX_3
"Releasing %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
8154 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
8156 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_RELEASED
;
8157 iaxs
[fr
->callno
]->transferring
= TRANSFER_RELEASED
;
8158 ast_set_flag(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], IAX_ALREADYGONE
);
8159 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
8161 /* Stop doing lag & ping requests */
8162 stop_stuff(fr
->callno
);
8163 stop_stuff(iaxs
[fr
->callno
]->bridgecallno
);
8165 memset(&ied0
, 0, sizeof(ied0
));
8166 memset(&ied1
, 0, sizeof(ied1
));
8167 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
8168 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
8169 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied0
.buf
, ied0
.pos
, -1);
8170 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied1
.buf
, ied1
.pos
, -1);
8177 case IAX_COMMAND_TXREQ
:
8178 try_transfer(iaxs
[fr
->callno
], &ies
);
8180 case IAX_COMMAND_TXCNT
:
8181 if (iaxs
[fr
->callno
]->transferring
)
8182 send_command_transfer(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXACC
, 0, NULL
, 0);
8184 case IAX_COMMAND_TXREL
:
8185 /* Send ack immediately, rather than waiting until we've changed addresses */
8186 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8187 complete_transfer(fr
->callno
, &ies
);
8188 stop_stuff(fr
->callno
); /* for attended transfer to work with libiax */
8190 case IAX_COMMAND_TXMEDIA
:
8191 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_READY
) {
8192 AST_LIST_LOCK(&iaxq
.queue
);
8193 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
8194 /* Cancel any outstanding frames and start anew */
8195 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
)) {
8199 AST_LIST_UNLOCK(&iaxq
.queue
);
8200 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8201 iaxs
[fr
->callno
]->transferring
= TRANSFER_MEDIAPASS
;
8204 case IAX_COMMAND_DPREP
:
8205 complete_dpreply(iaxs
[fr
->callno
], &ies
);
8207 case IAX_COMMAND_UNSUPPORT
:
8208 ast_log(LOG_NOTICE
, "Peer did not understand our iax command '%d'\n", ies
.iax_unknown
);
8210 case IAX_COMMAND_FWDOWNL
:
8211 /* Firmware download */
8212 memset(&ied0
, 0, sizeof(ied0
));
8213 res
= iax_firmware_append(&ied0
, (unsigned char *)ies
.devicetype
, ies
.fwdesc
);
8215 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8217 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
8219 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
8220 if (!iaxs
[fr
->callno
]) {
8221 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8227 ast_log(LOG_DEBUG
, "Unknown IAX command %d on %d/%d\n", f
.subclass
, fr
->callno
, iaxs
[fr
->callno
]->peercallno
);
8228 memset(&ied0
, 0, sizeof(ied0
));
8229 iax_ie_append_byte(&ied0
, IAX_IE_IAX_UNKNOWN
, f
.subclass
);
8230 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_UNSUPPORT
, 0, ied0
.buf
, ied0
.pos
, -1);
8232 /* Don't actually pass these frames along */
8233 if ((f
.subclass
!= IAX_COMMAND_ACK
) &&
8234 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8235 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
8236 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
8237 (f
.subclass
!= IAX_COMMAND_VNAK
)) {
8238 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
8239 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8241 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8244 /* Unless this is an ACK or INVAL frame, ack it */
8245 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
8246 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8247 } else if (minivid
) {
8248 f
.frametype
= AST_FRAME_VIDEO
;
8249 if (iaxs
[fr
->callno
]->videoformat
> 0)
8250 f
.subclass
= iaxs
[fr
->callno
]->videoformat
| (ntohs(vh
->ts
) & 0x8000 ? 1 : 0);
8252 ast_log(LOG_WARNING
, "Received mini frame before first full video frame\n ");
8253 iax2_vnak(fr
->callno
);
8254 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8257 f
.datalen
= res
- sizeof(*vh
);
8259 f
.data
= thread
->buf
+ sizeof(*vh
);
8264 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | ((ntohs(vh
->ts
) + test_resync
) & 0x7fff);
8266 #endif /* IAXTESTS */
8267 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | (ntohs(vh
->ts
) & 0x7fff);
8270 f
.frametype
= AST_FRAME_VOICE
;
8271 if (iaxs
[fr
->callno
]->voiceformat
> 0)
8272 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
8275 ast_log(LOG_DEBUG
, "Received mini frame before first full voice frame\n");
8276 iax2_vnak(fr
->callno
);
8277 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8280 f
.datalen
= res
- sizeof(struct ast_iax2_mini_hdr
);
8281 if (f
.datalen
< 0) {
8282 ast_log(LOG_WARNING
, "Datalen < 0?\n");
8283 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8287 f
.data
= thread
->buf
+ sizeof(*mh
);
8292 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ((ntohs(mh
->ts
) + test_resync
) & 0xffff);
8294 #endif /* IAXTESTS */
8295 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ntohs(mh
->ts
);
8296 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8298 /* Don't pass any packets until we're started */
8299 if (!ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
8300 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8308 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
)) {
8309 f
.samples
= ast_codec_get_samples(&f
);
8310 /* We need to byteswap incoming slinear samples from network byte order */
8311 if (f
.subclass
== AST_FORMAT_SLINEAR
)
8312 ast_frame_byteswap_be(&f
);
8315 iax_frame_wrap(fr
, &f
);
8317 /* If this is our most recent packet, use it as our basis for timestamping */
8318 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
8319 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8322 if (option_debug
&& iaxdebug
&& iaxs
[fr
->callno
])
8323 ast_log(LOG_DEBUG
, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f
.frametype
, f
.subclass
, fr
->ts
, iaxs
[fr
->callno
]->last
);
8324 fr
->outoforder
= -1;
8326 fr
->cacheable
= ((f
.frametype
== AST_FRAME_VOICE
) || (f
.frametype
== AST_FRAME_VIDEO
));
8327 duped_fr
= iaxfrdup2(fr
);
8329 schedule_delivery(duped_fr
, updatehistory
, 0, &fr
->ts
);
8331 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
8332 iaxs
[fr
->callno
]->last
= fr
->ts
;
8334 if (option_debug
&& iaxdebug
)
8335 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
8339 /* Always run again */
8340 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8344 /* Function to clean up process thread if it is cancelled */
8345 static void iax2_process_thread_cleanup(void *data
)
8347 struct iax2_thread
*thread
= data
;
8348 ast_mutex_destroy(&thread
->lock
);
8349 ast_cond_destroy(&thread
->cond
);
8351 ast_atomic_dec_and_test(&iaxactivethreadcount
);
8354 static void *iax2_process_thread(void *data
)
8356 struct iax2_thread
*thread
= data
;
8359 int put_into_idle
= 0;
8361 ast_atomic_fetchadd_int(&iaxactivethreadcount
,1);
8362 pthread_cleanup_push(iax2_process_thread_cleanup
, data
);
8364 /* Wait for something to signal us to be awake */
8365 ast_mutex_lock(&thread
->lock
);
8367 /* Flag that we're ready to accept signals */
8368 thread
->ready_for_signal
= 1;
8370 /* Put into idle list if applicable */
8372 insert_idle_thread(thread
);
8374 if (thread
->type
== IAX_TYPE_DYNAMIC
) {
8375 struct iax2_thread
*t
= NULL
;
8376 /* Wait to be signalled or time out */
8377 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8378 ts
.tv_sec
= tv
.tv_sec
;
8379 ts
.tv_nsec
= tv
.tv_usec
* 1000;
8380 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
) {
8381 /* This thread was never put back into the available dynamic
8382 * thread list, so just go away. */
8383 if (!put_into_idle
) {
8384 ast_mutex_unlock(&thread
->lock
);
8387 AST_LIST_LOCK(&dynamic_list
);
8388 /* Account for the case where this thread is acquired *right* after a timeout */
8389 if ((t
= AST_LIST_REMOVE(&dynamic_list
, thread
, list
)))
8390 iaxdynamicthreadcount
--;
8391 AST_LIST_UNLOCK(&dynamic_list
);
8393 /* This dynamic thread timed out waiting for a task and was
8394 * not acquired immediately after the timeout,
8395 * so it's time to go away. */
8396 ast_mutex_unlock(&thread
->lock
);
8399 /* Someone grabbed our thread *right* after we timed out.
8400 * Wait for them to set us up with something to do and signal
8401 * us to continue. */
8402 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8403 ts
.tv_sec
= tv
.tv_sec
;
8404 ts
.tv_nsec
= tv
.tv_usec
* 1000;
8405 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
)
8407 ast_mutex_unlock(&thread
->lock
);
8412 ast_cond_wait(&thread
->cond
, &thread
->lock
);
8415 /* Go back into our respective list */
8418 ast_mutex_unlock(&thread
->lock
);
8420 if (thread
->iostate
== IAX_IOSTATE_IDLE
)
8423 /* Add ourselves to the active list now */
8424 AST_LIST_LOCK(&active_list
);
8425 AST_LIST_INSERT_HEAD(&active_list
, thread
, list
);
8426 AST_LIST_UNLOCK(&active_list
);
8428 /* See what we need to do */
8429 switch(thread
->iostate
) {
8430 case IAX_IOSTATE_READY
:
8432 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
8433 socket_process(thread
);
8434 handle_deferred_full_frames(thread
);
8436 case IAX_IOSTATE_SCHEDREADY
:
8438 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
8439 #ifdef SCHED_MULTITHREADED
8440 thread
->schedfunc(thread
->scheddata
);
8444 time(&thread
->checktime
);
8445 thread
->iostate
= IAX_IOSTATE_IDLE
;
8446 #ifdef DEBUG_SCHED_MULTITHREAD
8447 thread
->curfunc
[0]='\0';
8450 /* Now... remove ourselves from the active list, and return to the idle list */
8451 AST_LIST_LOCK(&active_list
);
8452 AST_LIST_REMOVE(&active_list
, thread
, list
);
8453 AST_LIST_UNLOCK(&active_list
);
8455 /* Make sure another frame didn't sneak in there after we thought we were done. */
8456 handle_deferred_full_frames(thread
);
8459 /*!\note For some reason, idle threads are exiting without being removed
8460 * from an idle list, which is causing memory corruption. Forcibly remove
8461 * it from the list, if it's there.
8463 AST_LIST_LOCK(&idle_list
);
8464 AST_LIST_REMOVE(&idle_list
, thread
, list
);
8465 AST_LIST_UNLOCK(&idle_list
);
8467 AST_LIST_LOCK(&dynamic_list
);
8468 AST_LIST_REMOVE(&dynamic_list
, thread
, list
);
8469 AST_LIST_UNLOCK(&dynamic_list
);
8471 /* I am exiting here on my own volition, I need to clean up my own data structures
8472 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8474 pthread_cleanup_pop(1);
8479 static int iax2_do_register(struct iax2_registry
*reg
)
8481 struct iax_ie_data ied
;
8482 if (option_debug
&& iaxdebug
)
8483 ast_log(LOG_DEBUG
, "Sending registration request for '%s'\n", reg
->username
);
8486 ((reg
->regstate
== REG_STATE_TIMEOUT
) || !reg
->addr
.sin_addr
.s_addr
)) {
8487 /* Maybe the IP has changed, force DNS refresh */
8488 ast_dnsmgr_refresh(reg
->dnsmgr
);
8492 * if IP has Changed, free allocated call to create a new one with new IP
8493 * call has the pointer to IP and must be updated to the new one
8495 if (reg
->dnsmgr
&& ast_dnsmgr_changed(reg
->dnsmgr
) && (reg
->callno
> 0)) {
8496 ast_mutex_lock(&iaxsl
[reg
->callno
]);
8497 iax2_destroy(reg
->callno
);
8498 ast_mutex_unlock(&iaxsl
[reg
->callno
]);
8501 if (!reg
->addr
.sin_addr
.s_addr
) {
8502 if (option_debug
&& iaxdebug
)
8503 ast_log(LOG_DEBUG
, "Unable to send registration request for '%s' without IP address\n", reg
->username
);
8504 /* Setup the next registration attempt */
8505 AST_SCHED_DEL(sched
, reg
->expire
);
8506 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
8512 ast_log(LOG_DEBUG
, "Allocate call number\n");
8513 reg
->callno
= find_callno_locked(0, 0, ®
->addr
, NEW_FORCE
, defaultsockfd
);
8514 if (reg
->callno
< 1) {
8515 ast_log(LOG_WARNING
, "Unable to create call for registration\n");
8517 } else if (option_debug
)
8518 ast_log(LOG_DEBUG
, "Registration created on call %d\n", reg
->callno
);
8519 iaxs
[reg
->callno
]->reg
= reg
;
8520 ast_mutex_unlock(&iaxsl
[reg
->callno
]);
8522 /* Schedule the next registration attempt */
8523 AST_SCHED_DEL(sched
, reg
->expire
);
8524 /* Setup the next registration a little early */
8525 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
8526 /* Send the request */
8527 memset(&ied
, 0, sizeof(ied
));
8528 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
8529 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
8530 send_command(iaxs
[reg
->callno
],AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
8531 reg
->regstate
= REG_STATE_REGSENT
;
8535 static char *iax2_prov_complete_template_3rd(const char *line
, const char *word
, int pos
, int state
)
8539 return iax_prov_complete_template(line
, word
, pos
, state
);
8542 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
)
8544 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8545 is found for template */
8546 struct iax_ie_data provdata
;
8547 struct iax_ie_data ied
;
8549 struct sockaddr_in sin
;
8551 struct create_addr_info cai
;
8553 memset(&cai
, 0, sizeof(cai
));
8556 ast_log(LOG_DEBUG
, "Provisioning '%s' from template '%s'\n", dest
, template);
8558 if (iax_provision_build(&provdata
, &sig
, template, force
)) {
8560 ast_log(LOG_DEBUG
, "No provisioning found for template '%s'\n", template);
8565 memcpy(&sin
, end
, sizeof(sin
));
8566 cai
.sockfd
= sockfd
;
8567 } else if (create_addr(dest
, NULL
, &sin
, &cai
))
8570 /* Build the rest of the message */
8571 memset(&ied
, 0, sizeof(ied
));
8572 iax_ie_append_raw(&ied
, IAX_IE_PROVISIONING
, provdata
.buf
, provdata
.pos
);
8574 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
);
8579 /* Schedule autodestruct in case they don't ever give us anything back */
8580 AST_SCHED_DEL(sched
, iaxs
[callno
]->autoid
);
8581 iaxs
[callno
]->autoid
= iax2_sched_add(sched
, 15000, auto_hangup
, (void *)(long)callno
);
8582 ast_set_flag(iaxs
[callno
], IAX_PROVISION
);
8583 /* Got a call number now, so go ahead and send the provisioning information */
8584 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PROVISION
, 0, ied
.buf
, ied
.pos
, -1);
8586 ast_mutex_unlock(&iaxsl
[callno
]);
8591 static char *papp
= "IAX2Provision";
8592 static char *psyn
= "Provision a calling IAXy with a given template";
8593 static char *pdescrip
=
8594 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8595 "the calling entity is in fact an IAXy) with the given template or\n"
8596 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8599 \ingroup applications
8601 static int iax2_prov_app(struct ast_channel
*chan
, void *data
)
8607 unsigned short callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
8608 if (ast_strlen_zero(data
))
8610 sdata
= ast_strdupa(data
);
8611 opts
= strchr(sdata
, '|');
8615 if (chan
->tech
!= &iax2_tech
) {
8616 ast_log(LOG_NOTICE
, "Can't provision a non-IAX device!\n");
8619 if (!callno
|| !iaxs
[callno
] || !iaxs
[callno
]->addr
.sin_addr
.s_addr
) {
8620 ast_log(LOG_NOTICE
, "Can't provision something with no IP?\n");
8623 res
= iax2_provision(&iaxs
[callno
]->addr
, iaxs
[callno
]->sockfd
, NULL
, sdata
, force
);
8624 if (option_verbose
> 2)
8625 ast_verbose(VERBOSE_PREFIX_3
"Provisioned IAXY at '%s' with '%s'= %d\n",
8626 ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
),
8632 static int iax2_prov_cmd(int fd
, int argc
, char *argv
[])
8637 return RESULT_SHOWUSAGE
;
8639 if (!strcasecmp(argv
[4], "forced"))
8642 return RESULT_SHOWUSAGE
;
8644 res
= iax2_provision(NULL
, -1, argv
[2], argv
[3], force
);
8646 ast_cli(fd
, "Unable to find peer/address '%s'\n", argv
[2]);
8648 ast_cli(fd
, "No template (including wildcard) matching '%s'\n", argv
[3]);
8650 ast_cli(fd
, "Provisioning '%s' with template '%s'%s\n", argv
[2], argv
[3], force
? ", forced" : "");
8651 return RESULT_SUCCESS
;
8654 static void __iax2_poke_noanswer(const void *data
)
8656 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
8657 if (peer
->lastms
> -1) {
8658 ast_log(LOG_NOTICE
, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer
->name
, peer
->lastms
);
8659 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer
->name
, peer
->lastms
);
8660 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
8662 if (peer
->callno
> 0) {
8663 ast_mutex_lock(&iaxsl
[peer
->callno
]);
8664 iax2_destroy(peer
->callno
);
8665 ast_mutex_unlock(&iaxsl
[peer
->callno
]);
8669 /* Try again quickly */
8670 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
8671 if (peer
->pokeexpire
== -1)
8675 static int iax2_poke_noanswer(const void *data
)
8677 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
8678 peer
->pokeexpire
= -1;
8679 #ifdef SCHED_MULTITHREADED
8680 if (schedule_action(__iax2_poke_noanswer
, data
))
8682 __iax2_poke_noanswer(data
);
8687 static int iax2_poke_peer_cb(void *obj
, void *arg
, int flags
)
8689 struct iax2_peer
*peer
= obj
;
8691 iax2_poke_peer(peer
, 0);
8696 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
)
8698 if (!peer
->maxms
|| (!peer
->addr
.sin_addr
.s_addr
&& !peer
->dnsmgr
)) {
8699 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8700 immediately after clearing things out */
8702 peer
->historicms
= 0;
8703 peer
->pokeexpire
= -1;
8707 if (peer
->callno
> 0) {
8708 ast_log(LOG_NOTICE
, "Still have a callno...\n");
8709 ast_mutex_lock(&iaxsl
[peer
->callno
]);
8710 iax2_destroy(peer
->callno
);
8711 ast_mutex_unlock(&iaxsl
[peer
->callno
]);
8714 ast_mutex_unlock(&iaxsl
[heldcall
]);
8715 peer
->callno
= find_callno(0, 0, &peer
->addr
, NEW_FORCE
, peer
->sockfd
);
8717 ast_mutex_lock(&iaxsl
[heldcall
]);
8718 if (peer
->callno
< 1) {
8719 ast_log(LOG_WARNING
, "Unable to allocate call for poking peer '%s'\n", peer
->name
);
8723 /* Speed up retransmission times for this qualify call */
8724 iaxs
[peer
->callno
]->pingtime
= peer
->maxms
/ 4 + 1;
8725 iaxs
[peer
->callno
]->peerpoke
= peer
;
8727 /* Remove any pending pokeexpire task */
8728 if (peer
->pokeexpire
> -1) {
8729 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
8730 peer
->pokeexpire
= -1;
8735 /* Queue up a new task to handle no reply */
8736 /* If the host is already unreachable then use the unreachable interval instead */
8737 if (peer
->lastms
< 0) {
8738 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_noanswer
, peer_ref(peer
));
8740 peer
->pokeexpire
= iax2_sched_add(sched
, DEFAULT_MAXMS
* 2, iax2_poke_noanswer
, peer_ref(peer
));
8742 if (peer
->pokeexpire
== -1)
8745 /* And send the poke */
8746 send_command(iaxs
[peer
->callno
], AST_FRAME_IAX
, IAX_COMMAND_POKE
, 0, NULL
, 0, -1);
8751 static void free_context(struct iax2_context
*con
)
8753 struct iax2_context
*conl
;
8761 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
)
8766 struct sockaddr_in sin
;
8767 struct ast_channel
*c
;
8768 struct parsed_dial_string pds
;
8769 struct create_addr_info cai
;
8772 memset(&pds
, 0, sizeof(pds
));
8773 tmpstr
= ast_strdupa(data
);
8774 parse_dial_string(tmpstr
, &pds
);
8776 if (ast_strlen_zero(pds
.peer
)) {
8777 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
8781 memset(&cai
, 0, sizeof(cai
));
8782 cai
.capability
= iax2_capability
;
8784 ast_copy_flags(&cai
, &globalflags
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
8786 /* Populate our address from the given */
8787 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
)) {
8788 *cause
= AST_CAUSE_UNREGISTERED
;
8793 sin
.sin_port
= htons(atoi(pds
.port
));
8795 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
);
8797 ast_log(LOG_WARNING
, "Unable to create call\n");
8798 *cause
= AST_CAUSE_CONGESTION
;
8802 /* If this is a trunk, update it now */
8803 ast_copy_flags(iaxs
[callno
], &cai
, IAX_TRUNK
| IAX_SENDANI
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
8804 if (ast_test_flag(&cai
, IAX_TRUNK
)) {
8806 if ((new_callno
= make_trunk(callno
, 1)) != -1)
8807 callno
= new_callno
;
8809 iaxs
[callno
]->maxtime
= cai
.maxtime
;
8811 ast_string_field_set(iaxs
[callno
], host
, pds
.peer
);
8813 c
= ast_iax2_new(callno
, AST_STATE_DOWN
, cai
.capability
);
8815 ast_mutex_unlock(&iaxsl
[callno
]);
8818 /* Choose a format we can live with */
8819 if (c
->nativeformats
& format
)
8820 c
->nativeformats
&= format
;
8822 native
= c
->nativeformats
;
8824 res
= ast_translator_best_choice(&fmt
, &native
);
8826 ast_log(LOG_WARNING
, "Unable to create translator path for %s to %s on %s\n",
8827 ast_getformatname(c
->nativeformats
), ast_getformatname(fmt
), c
->name
);
8831 c
->nativeformats
= native
;
8833 c
->readformat
= ast_best_codec(c
->nativeformats
);
8834 c
->writeformat
= c
->readformat
;
8840 static void *sched_thread(void *ignore
)
8848 res
= ast_sched_wait(sched
);
8849 if ((res
> 1000) || (res
< 0))
8851 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(res
, 1000));
8852 ts
.tv_sec
= tv
.tv_sec
;
8853 ts
.tv_nsec
= tv
.tv_usec
* 1000;
8855 pthread_testcancel();
8856 ast_mutex_lock(&sched_lock
);
8857 ast_cond_timedwait(&sched_cond
, &sched_lock
, &ts
);
8858 ast_mutex_unlock(&sched_lock
);
8859 pthread_testcancel();
8861 count
= ast_sched_runq(sched
);
8862 if (option_debug
&& count
>= 20)
8863 ast_log(LOG_DEBUG
, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count
);
8868 static void *network_thread(void *ignore
)
8870 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
8871 from the network, and queue them for delivery to the channels */
8872 int res
, count
, wakeup
;
8873 struct iax_frame
*f
;
8876 ast_io_add(io
, timingfd
, timing_read
, AST_IO_IN
| AST_IO_PRI
, NULL
);
8879 pthread_testcancel();
8881 /* Go through the queue, sending messages which have not yet been
8882 sent, and scheduling retransmissions if appropriate */
8883 AST_LIST_LOCK(&iaxq
.queue
);
8886 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq
.queue
, f
, list
) {
8890 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
8891 if (ast_mutex_trylock(&iaxsl
[f
->callno
])) {
8898 if (iaxs
[f
->callno
]) {
8903 ast_mutex_unlock(&iaxsl
[f
->callno
]);
8905 if (f
->retries
< 0) {
8906 /* This is not supposed to be retransmitted */
8907 AST_LIST_REMOVE_CURRENT(&iaxq
.queue
, list
);
8909 /* Free the iax frame */
8912 /* We need reliable delivery. Schedule a retransmission */
8914 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
8917 AST_LIST_TRAVERSE_SAFE_END
8918 AST_LIST_UNLOCK(&iaxq
.queue
);
8920 pthread_testcancel();
8922 if (option_debug
&& count
>= 20)
8923 ast_log(LOG_DEBUG
, "chan_iax2: Sent %d queued outbound frames all at once\n", count
);
8925 /* Now do the IO, and run scheduled tasks */
8926 res
= ast_io_wait(io
, wakeup
);
8928 if (option_debug
&& res
>= 20)
8929 ast_log(LOG_DEBUG
, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res
);
8935 static int start_network_thread(void)
8937 pthread_attr_t attr
;
8938 int threadcount
= 0;
8940 for (x
= 0; x
< iaxthreadcount
; x
++) {
8941 struct iax2_thread
*thread
= ast_calloc(1, sizeof(struct iax2_thread
));
8943 thread
->type
= IAX_TYPE_POOL
;
8944 thread
->threadnum
= ++threadcount
;
8945 ast_mutex_init(&thread
->lock
);
8946 ast_cond_init(&thread
->cond
, NULL
);
8947 pthread_attr_init(&attr
);
8948 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
8949 if (ast_pthread_create(&thread
->threadid
, &attr
, iax2_process_thread
, thread
)) {
8950 ast_log(LOG_WARNING
, "Failed to create new thread!\n");
8954 AST_LIST_LOCK(&idle_list
);
8955 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
8956 AST_LIST_UNLOCK(&idle_list
);
8959 ast_pthread_create_background(&schedthreadid
, NULL
, sched_thread
, NULL
);
8960 ast_pthread_create_background(&netthreadid
, NULL
, network_thread
, NULL
);
8961 if (option_verbose
> 1)
8962 ast_verbose(VERBOSE_PREFIX_2
"%d helper threaads started\n", threadcount
);
8966 static struct iax2_context
*build_context(char *context
)
8968 struct iax2_context
*con
;
8970 if ((con
= ast_calloc(1, sizeof(*con
))))
8971 ast_copy_string(con
->context
, context
, sizeof(con
->context
));
8976 static int get_auth_methods(char *value
)
8979 if (strstr(value
, "rsa"))
8980 methods
|= IAX_AUTH_RSA
;
8981 if (strstr(value
, "md5"))
8982 methods
|= IAX_AUTH_MD5
;
8983 if (strstr(value
, "plaintext"))
8984 methods
|= IAX_AUTH_PLAINTEXT
;
8989 /*! \brief Check if address can be used as packet source.
8990 \return 0 address available, 1 address unavailable, -1 error
8992 static int check_srcaddr(struct sockaddr
*sa
, socklen_t salen
)
8997 sd
= socket(AF_INET
, SOCK_DGRAM
, 0);
8999 ast_log(LOG_ERROR
, "Socket: %s\n", strerror(errno
));
9003 res
= bind(sd
, sa
, salen
);
9006 ast_log(LOG_DEBUG
, "Can't bind: %s\n", strerror(errno
));
9015 /*! \brief Parse the "sourceaddress" value,
9016 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9018 static int peer_set_srcaddr(struct iax2_peer
*peer
, const char *srcaddr
)
9020 struct sockaddr_in sin
;
9022 int port
= IAX_DEFAULT_PORTNO
;
9023 int sockfd
= defaultsockfd
;
9028 if (!(tmp
= ast_strdupa(srcaddr
)))
9031 addr
= strsep(&tmp
, ":");
9035 port
= atoi(portstr
);
9037 port
= IAX_DEFAULT_PORTNO
;
9040 if (!ast_get_ip(&sin
, addr
)) {
9041 struct ast_netsock
*sock
;
9045 sin
.sin_family
= AF_INET
;
9046 res
= check_srcaddr((struct sockaddr
*) &sin
, sizeof(sin
));
9048 /* ip address valid. */
9049 sin
.sin_port
= htons(port
);
9050 if (!(sock
= ast_netsock_find(netsock
, &sin
)))
9051 sock
= ast_netsock_find(outsock
, &sin
);
9053 sockfd
= ast_netsock_sockfd(sock
);
9056 unsigned int orig_saddr
= sin
.sin_addr
.s_addr
;
9057 /* INADDR_ANY matches anyway! */
9058 sin
.sin_addr
.s_addr
= INADDR_ANY
;
9059 if (ast_netsock_find(netsock
, &sin
)) {
9060 sin
.sin_addr
.s_addr
= orig_saddr
;
9061 sock
= ast_netsock_bind(outsock
, io
, srcaddr
, port
, tos
, socket_read
, NULL
);
9063 sockfd
= ast_netsock_sockfd(sock
);
9064 ast_netsock_unref(sock
);
9074 peer
->sockfd
= sockfd
;
9076 if (nonlocal
== 1) {
9077 ast_log(LOG_WARNING
, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9078 srcaddr
, peer
->name
);
9080 } else if (nonlocal
== 2) {
9081 ast_log(LOG_WARNING
, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9082 srcaddr
, peer
->name
);
9086 ast_log(LOG_DEBUG
, "Using sourceaddress %s for '%s'\n", srcaddr
, peer
->name
);
9091 static void peer_destructor(void *obj
)
9093 struct iax2_peer
*peer
= obj
;
9095 ast_free_ha(peer
->ha
);
9097 if (peer
->callno
> 0) {
9098 ast_mutex_lock(&iaxsl
[peer
->callno
]);
9099 iax2_destroy(peer
->callno
);
9100 ast_mutex_unlock(&iaxsl
[peer
->callno
]);
9103 register_peer_exten(peer
, 0);
9106 ast_dnsmgr_release(peer
->dnsmgr
);
9108 ast_string_field_free_memory(peer
);
9111 /*! \brief Create peer structure based on configuration */
9112 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
9114 struct iax2_peer
*peer
= NULL
;
9115 struct ast_ha
*oldha
= NULL
;
9119 struct iax2_peer tmp_peer
= {
9124 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
9125 if (peer
&& !ast_test_flag(peer
, IAX_DELME
))
9136 } else if ((peer
= ao2_alloc(sizeof(*peer
), peer_destructor
))) {
9138 peer
->pokeexpire
= -1;
9139 peer
->sockfd
= defaultsockfd
;
9140 if (ast_string_field_init(peer
, 32))
9141 peer
= peer_unref(peer
);
9146 ast_copy_flags(peer
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
9147 peer
->encmethods
= iax2_encryption
;
9149 ast_string_field_set(peer
,secret
,"");
9151 ast_string_field_set(peer
, name
, name
);
9152 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
9153 peer
->expiry
= min_reg_expire
;
9155 peer
->prefs
= prefs
;
9156 peer
->capability
= iax2_capability
;
9157 peer
->smoothing
= 0;
9158 peer
->pokefreqok
= DEFAULT_FREQ_OK
;
9159 peer
->pokefreqnotok
= DEFAULT_FREQ_NOTOK
;
9160 ast_string_field_set(peer
,context
,"");
9161 ast_string_field_set(peer
,peercontext
,"");
9162 ast_clear_flag(peer
, IAX_HASCALLERID
);
9163 ast_string_field_set(peer
, cid_name
, "");
9164 ast_string_field_set(peer
, cid_num
, "");
9172 if (!strcasecmp(v
->name
, "secret")) {
9173 ast_string_field_set(peer
, secret
, v
->value
);
9174 } else if (!strcasecmp(v
->name
, "mailbox")) {
9175 ast_string_field_set(peer
, mailbox
, v
->value
);
9176 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
9177 ast_string_field_set(peer
, mohinterpret
, v
->value
);
9178 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
9179 ast_string_field_set(peer
, mohsuggest
, v
->value
);
9180 } else if (!strcasecmp(v
->name
, "dbsecret")) {
9181 ast_string_field_set(peer
, dbsecret
, v
->value
);
9182 } else if (!strcasecmp(v
->name
, "trunk")) {
9183 ast_set2_flag(peer
, ast_true(v
->value
), IAX_TRUNK
);
9184 if (ast_test_flag(peer
, IAX_TRUNK
) && (timingfd
< 0)) {
9185 ast_log(LOG_WARNING
, "Unable to support trunking on peer '%s' without zaptel timing\n", peer
->name
);
9186 ast_clear_flag(peer
, IAX_TRUNK
);
9188 } else if (!strcasecmp(v
->name
, "auth")) {
9189 peer
->authmethods
= get_auth_methods(v
->value
);
9190 } else if (!strcasecmp(v
->name
, "encryption")) {
9191 peer
->encmethods
= get_encrypt_methods(v
->value
);
9192 } else if (!strcasecmp(v
->name
, "notransfer")) {
9193 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9194 ast_clear_flag(peer
, IAX_TRANSFERMEDIA
);
9195 ast_set2_flag(peer
, ast_true(v
->value
), IAX_NOTRANSFER
);
9196 } else if (!strcasecmp(v
->name
, "transfer")) {
9197 if (!strcasecmp(v
->value
, "mediaonly")) {
9198 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
9199 } else if (ast_true(v
->value
)) {
9200 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
9202 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
9203 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
9204 ast_set2_flag(peer
, ast_true(v
->value
), IAX_USEJITTERBUF
);
9205 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
9206 ast_set2_flag(peer
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
9207 } else if (!strcasecmp(v
->name
, "host")) {
9208 if (!strcasecmp(v
->value
, "dynamic")) {
9209 /* They'll register with us */
9210 ast_set_flag(peer
, IAX_DYNAMIC
);
9212 /* Initialize stuff iff we're not found, otherwise
9213 we keep going with what we had */
9214 memset(&peer
->addr
.sin_addr
, 0, 4);
9215 if (peer
->addr
.sin_port
) {
9216 /* If we've already got a port, make it the default rather than absolute */
9217 peer
->defaddr
.sin_port
= peer
->addr
.sin_port
;
9218 peer
->addr
.sin_port
= 0;
9222 /* Non-dynamic. Make sure we become that way if we're not */
9223 AST_SCHED_DEL(sched
, peer
->expire
);
9224 ast_clear_flag(peer
, IAX_DYNAMIC
);
9225 if (ast_dnsmgr_lookup(v
->value
, &peer
->addr
.sin_addr
, &peer
->dnsmgr
))
9226 return peer_unref(peer
);
9227 if (!peer
->addr
.sin_port
)
9228 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
9231 inet_aton("255.255.255.255", &peer
->mask
);
9232 } else if (!strcasecmp(v
->name
, "defaultip")) {
9233 if (ast_get_ip(&peer
->defaddr
, v
->value
))
9234 return peer_unref(peer
);
9235 } else if (!strcasecmp(v
->name
, "sourceaddress")) {
9236 peer_set_srcaddr(peer
, v
->value
);
9237 } else if (!strcasecmp(v
->name
, "permit") ||
9238 !strcasecmp(v
->name
, "deny")) {
9239 peer
->ha
= ast_append_ha(v
->name
, v
->value
, peer
->ha
);
9240 } else if (!strcasecmp(v
->name
, "mask")) {
9242 inet_aton(v
->value
, &peer
->mask
);
9243 } else if (!strcasecmp(v
->name
, "context")) {
9244 ast_string_field_set(peer
, context
, v
->value
);
9245 } else if (!strcasecmp(v
->name
, "regexten")) {
9246 ast_string_field_set(peer
, regexten
, v
->value
);
9247 } else if (!strcasecmp(v
->name
, "peercontext")) {
9248 ast_string_field_set(peer
, peercontext
, v
->value
);
9249 } else if (!strcasecmp(v
->name
, "port")) {
9250 if (ast_test_flag(peer
, IAX_DYNAMIC
))
9251 peer
->defaddr
.sin_port
= htons(atoi(v
->value
));
9253 peer
->addr
.sin_port
= htons(atoi(v
->value
));
9254 } else if (!strcasecmp(v
->name
, "username")) {
9255 ast_string_field_set(peer
, username
, v
->value
);
9256 } else if (!strcasecmp(v
->name
, "allow")) {
9257 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 1);
9258 } else if (!strcasecmp(v
->name
, "disallow")) {
9259 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 0);
9260 } else if (!strcasecmp(v
->name
, "callerid")) {
9261 if (!ast_strlen_zero(v
->value
)) {
9264 ast_callerid_split(v
->value
, name2
, 80, num2
, 80);
9265 ast_string_field_set(peer
, cid_name
, name2
);
9266 ast_string_field_set(peer
, cid_num
, num2
);
9267 ast_set_flag(peer
, IAX_HASCALLERID
);
9269 ast_clear_flag(peer
, IAX_HASCALLERID
);
9270 ast_string_field_set(peer
, cid_name
, "");
9271 ast_string_field_set(peer
, cid_num
, "");
9273 } else if (!strcasecmp(v
->name
, "fullname")) {
9274 if (!ast_strlen_zero(v
->value
)) {
9275 ast_string_field_set(peer
, cid_name
, v
->value
);
9276 ast_set_flag(peer
, IAX_HASCALLERID
);
9278 ast_string_field_set(peer
, cid_name
, "");
9279 if (ast_strlen_zero(peer
->cid_num
))
9280 ast_clear_flag(peer
, IAX_HASCALLERID
);
9282 } else if (!strcasecmp(v
->name
, "cid_number")) {
9283 if (!ast_strlen_zero(v
->value
)) {
9284 ast_string_field_set(peer
, cid_num
, v
->value
);
9285 ast_set_flag(peer
, IAX_HASCALLERID
);
9287 ast_string_field_set(peer
, cid_num
, "");
9288 if (ast_strlen_zero(peer
->cid_name
))
9289 ast_clear_flag(peer
, IAX_HASCALLERID
);
9291 } else if (!strcasecmp(v
->name
, "sendani")) {
9292 ast_set2_flag(peer
, ast_true(v
->value
), IAX_SENDANI
);
9293 } else if (!strcasecmp(v
->name
, "inkeys")) {
9294 ast_string_field_set(peer
, inkeys
, v
->value
);
9295 } else if (!strcasecmp(v
->name
, "outkey")) {
9296 ast_string_field_set(peer
, outkey
, v
->value
);
9297 } else if (!strcasecmp(v
->name
, "qualify")) {
9298 if (!strcasecmp(v
->value
, "no")) {
9300 } else if (!strcasecmp(v
->value
, "yes")) {
9301 peer
->maxms
= DEFAULT_MAXMS
;
9302 } else if (sscanf(v
->value
, "%d", &peer
->maxms
) != 1) {
9303 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
);
9306 } else if (!strcasecmp(v
->name
, "qualifysmoothing")) {
9307 peer
->smoothing
= ast_true(v
->value
);
9308 } else if (!strcasecmp(v
->name
, "qualifyfreqok")) {
9309 if (sscanf(v
->value
, "%d", &peer
->pokefreqok
) != 1) {
9310 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
);
9312 } else if (!strcasecmp(v
->name
, "qualifyfreqnotok")) {
9313 if (sscanf(v
->value
, "%d", &peer
->pokefreqnotok
) != 1) {
9314 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
);
9315 } else ast_log(LOG_WARNING
, "Set peer->pokefreqnotok to %d\n", peer
->pokefreqnotok
);
9316 } else if (!strcasecmp(v
->name
, "timezone")) {
9317 ast_string_field_set(peer
, zonetag
, v
->value
);
9318 } else if (!strcasecmp(v
->name
, "adsi")) {
9319 peer
->adsi
= ast_true(v
->value
);
9320 }/* else if (strcasecmp(v->name,"type")) */
9321 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9328 if (!peer
->authmethods
)
9329 peer
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9330 ast_clear_flag(peer
, IAX_DELME
);
9331 /* Make sure these are IPv4 addresses */
9332 peer
->addr
.sin_family
= AF_INET
;
9339 static void user_destructor(void *obj
)
9341 struct iax2_user
*user
= obj
;
9343 ast_free_ha(user
->ha
);
9344 free_context(user
->contexts
);
9346 ast_variables_destroy(user
->vars
);
9349 ast_string_field_free_memory(user
);
9352 /*! \brief Create in-memory user structure from configuration */
9353 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
9355 struct iax2_user
*user
= NULL
;
9356 struct iax2_context
*con
, *conl
= NULL
;
9357 struct ast_ha
*oldha
= NULL
;
9358 struct iax2_context
*oldcon
= NULL
;
9361 int oldcurauthreq
= 0;
9362 char *varname
= NULL
, *varval
= NULL
;
9363 struct ast_variable
*tmpvar
= NULL
;
9364 struct iax2_user tmp_user
= {
9369 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
9370 if (user
&& !ast_test_flag(user
, IAX_DELME
))
9376 oldcurauthreq
= user
->curauthreq
;
9378 oldcon
= user
->contexts
;
9380 user
->contexts
= NULL
;
9382 /* Already in the list, remove it and it will be added back (or FREE'd) */
9383 ao2_unlink(users
, user
);
9385 user
= ao2_alloc(sizeof(*user
), user_destructor
);
9390 ast_string_field_free_memory(user
);
9391 memset(user
, 0, sizeof(struct iax2_user
));
9392 if (ast_string_field_init(user
, 32)) {
9393 user
= user_unref(user
);
9396 user
->maxauthreq
= maxauthreq
;
9397 user
->curauthreq
= oldcurauthreq
;
9398 user
->prefs
= prefs
;
9399 user
->capability
= iax2_capability
;
9400 user
->encmethods
= iax2_encryption
;
9402 ast_string_field_set(user
, name
, name
);
9403 ast_string_field_set(user
, language
, language
);
9404 ast_copy_flags(user
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_CODEC_USER_FIRST
| IAX_CODEC_NOPREFS
| IAX_CODEC_NOCAP
);
9405 ast_clear_flag(user
, IAX_HASCALLERID
);
9406 ast_string_field_set(user
, cid_name
, "");
9407 ast_string_field_set(user
, cid_num
, "");
9414 if (!strcasecmp(v
->name
, "context")) {
9415 con
= build_context(v
->value
);
9420 user
->contexts
= con
;
9423 } else if (!strcasecmp(v
->name
, "permit") ||
9424 !strcasecmp(v
->name
, "deny")) {
9425 user
->ha
= ast_append_ha(v
->name
, v
->value
, user
->ha
);
9426 } else if (!strcasecmp(v
->name
, "setvar")) {
9427 varname
= ast_strdupa(v
->value
);
9428 if (varname
&& (varval
= strchr(varname
,'='))) {
9431 if((tmpvar
= ast_variable_new(varname
, varval
))) {
9432 tmpvar
->next
= user
->vars
;
9433 user
->vars
= tmpvar
;
9436 } else if (!strcasecmp(v
->name
, "allow")) {
9437 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 1);
9438 } else if (!strcasecmp(v
->name
, "disallow")) {
9439 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
,v
->value
, 0);
9440 } else if (!strcasecmp(v
->name
, "trunk")) {
9441 ast_set2_flag(user
, ast_true(v
->value
), IAX_TRUNK
);
9442 if (ast_test_flag(user
, IAX_TRUNK
) && (timingfd
< 0)) {
9443 ast_log(LOG_WARNING
, "Unable to support trunking on user '%s' without zaptel timing\n", user
->name
);
9444 ast_clear_flag(user
, IAX_TRUNK
);
9446 } else if (!strcasecmp(v
->name
, "auth")) {
9447 user
->authmethods
= get_auth_methods(v
->value
);
9448 } else if (!strcasecmp(v
->name
, "encryption")) {
9449 user
->encmethods
= get_encrypt_methods(v
->value
);
9450 } else if (!strcasecmp(v
->name
, "notransfer")) {
9451 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9452 ast_clear_flag(user
, IAX_TRANSFERMEDIA
);
9453 ast_set2_flag(user
, ast_true(v
->value
), IAX_NOTRANSFER
);
9454 } else if (!strcasecmp(v
->name
, "transfer")) {
9455 if (!strcasecmp(v
->value
, "mediaonly")) {
9456 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
9457 } else if (ast_true(v
->value
)) {
9458 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
9460 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
9461 } else if (!strcasecmp(v
->name
, "codecpriority")) {
9462 if(!strcasecmp(v
->value
, "caller"))
9463 ast_set_flag(user
, IAX_CODEC_USER_FIRST
);
9464 else if(!strcasecmp(v
->value
, "disabled"))
9465 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
9466 else if(!strcasecmp(v
->value
, "reqonly")) {
9467 ast_set_flag(user
, IAX_CODEC_NOCAP
);
9468 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
9470 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
9471 ast_set2_flag(user
, ast_true(v
->value
), IAX_USEJITTERBUF
);
9472 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
9473 ast_set2_flag(user
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
9474 } else if (!strcasecmp(v
->name
, "dbsecret")) {
9475 ast_string_field_set(user
, dbsecret
, v
->value
);
9476 } else if (!strcasecmp(v
->name
, "secret")) {
9477 if (!ast_strlen_zero(user
->secret
)) {
9478 char *old
= ast_strdupa(user
->secret
);
9480 ast_string_field_build(user
, secret
, "%s;%s", old
, v
->value
);
9482 ast_string_field_set(user
, secret
, v
->value
);
9483 } else if (!strcasecmp(v
->name
, "callerid")) {
9484 if (!ast_strlen_zero(v
->value
) && strcasecmp(v
->value
, "asreceived")) {
9487 ast_callerid_split(v
->value
, name2
, sizeof(name2
), num2
, sizeof(num2
));
9488 ast_string_field_set(user
, cid_name
, name2
);
9489 ast_string_field_set(user
, cid_num
, num2
);
9490 ast_set_flag(user
, IAX_HASCALLERID
);
9492 ast_clear_flag(user
, IAX_HASCALLERID
);
9493 ast_string_field_set(user
, cid_name
, "");
9494 ast_string_field_set(user
, cid_num
, "");
9496 } else if (!strcasecmp(v
->name
, "fullname")) {
9497 if (!ast_strlen_zero(v
->value
)) {
9498 ast_string_field_set(user
, cid_name
, v
->value
);
9499 ast_set_flag(user
, IAX_HASCALLERID
);
9501 ast_string_field_set(user
, cid_name
, "");
9502 if (ast_strlen_zero(user
->cid_num
))
9503 ast_clear_flag(user
, IAX_HASCALLERID
);
9505 } else if (!strcasecmp(v
->name
, "cid_number")) {
9506 if (!ast_strlen_zero(v
->value
)) {
9507 ast_string_field_set(user
, cid_num
, v
->value
);
9508 ast_set_flag(user
, IAX_HASCALLERID
);
9510 ast_string_field_set(user
, cid_num
, "");
9511 if (ast_strlen_zero(user
->cid_name
))
9512 ast_clear_flag(user
, IAX_HASCALLERID
);
9514 } else if (!strcasecmp(v
->name
, "accountcode")) {
9515 ast_string_field_set(user
, accountcode
, v
->value
);
9516 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
9517 ast_string_field_set(user
, mohinterpret
, v
->value
);
9518 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
9519 ast_string_field_set(user
, mohsuggest
, v
->value
);
9520 } else if (!strcasecmp(v
->name
, "language")) {
9521 ast_string_field_set(user
, language
, v
->value
);
9522 } else if (!strcasecmp(v
->name
, "amaflags")) {
9523 format
= ast_cdr_amaflags2int(v
->value
);
9525 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
9527 user
->amaflags
= format
;
9529 } else if (!strcasecmp(v
->name
, "inkeys")) {
9530 ast_string_field_set(user
, inkeys
, v
->value
);
9531 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
9532 user
->maxauthreq
= atoi(v
->value
);
9533 if (user
->maxauthreq
< 0)
9534 user
->maxauthreq
= 0;
9535 } else if (!strcasecmp(v
->name
, "adsi")) {
9536 user
->adsi
= ast_true(v
->value
);
9537 }/* else if (strcasecmp(v->name,"type")) */
9538 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9545 if (!user
->authmethods
) {
9546 if (!ast_strlen_zero(user
->secret
)) {
9547 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9548 if (!ast_strlen_zero(user
->inkeys
))
9549 user
->authmethods
|= IAX_AUTH_RSA
;
9550 } else if (!ast_strlen_zero(user
->inkeys
)) {
9551 user
->authmethods
= IAX_AUTH_RSA
;
9553 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9556 ast_clear_flag(user
, IAX_DELME
);
9562 free_context(oldcon
);
9566 static int peer_delme_cb(void *obj
, void *arg
, int flags
)
9568 struct iax2_peer
*peer
= obj
;
9570 ast_set_flag(peer
, IAX_DELME
);
9575 static int user_delme_cb(void *obj
, void *arg
, int flags
)
9577 struct iax2_user
*user
= obj
;
9579 ast_set_flag(user
, IAX_DELME
);
9584 static void delete_users(void)
9586 struct iax2_registry
*reg
;
9588 ao2_callback(users
, 0, user_delme_cb
, NULL
);
9590 AST_LIST_LOCK(®istrations
);
9591 while ((reg
= AST_LIST_REMOVE_HEAD(®istrations
, entry
))) {
9592 ast_sched_del(sched
, reg
->expire
);
9594 ast_mutex_lock(&iaxsl
[reg
->callno
]);
9595 if (iaxs
[reg
->callno
]) {
9596 iaxs
[reg
->callno
]->reg
= NULL
;
9597 iax2_destroy(reg
->callno
);
9599 ast_mutex_unlock(&iaxsl
[reg
->callno
]);
9602 ast_dnsmgr_release(reg
->dnsmgr
);
9605 AST_LIST_UNLOCK(®istrations
);
9607 ao2_callback(peers
, 0, peer_delme_cb
, NULL
);
9610 static void prune_users(void)
9612 struct iax2_user
*user
;
9613 struct ao2_iterator i
;
9615 i
= ao2_iterator_init(users
, 0);
9616 while ((user
= ao2_iterator_next(&i
))) {
9617 if (ast_test_flag(user
, IAX_DELME
))
9618 ao2_unlink(users
, user
);
9623 /* Prune peers who still are supposed to be deleted */
9624 static void prune_peers(void)
9626 struct iax2_peer
*peer
;
9627 struct ao2_iterator i
;
9629 i
= ao2_iterator_init(peers
, 0);
9630 while ((peer
= ao2_iterator_next(&i
))) {
9631 if (ast_test_flag(peer
, IAX_DELME
))
9637 static void set_timing(void)
9640 int bs
= trunkfreq
* 8;
9641 if (timingfd
> -1) {
9644 ioctl(timingfd
, ZT_TIMERCONFIG
, &bs
) &&
9646 ioctl(timingfd
, ZT_SET_BLOCKSIZE
, &bs
))
9647 ast_log(LOG_WARNING
, "Unable to set blocksize on timing source\n");
9652 static void set_config_destroy(void)
9654 strcpy(accountcode
, "");
9655 strcpy(language
, "");
9656 strcpy(mohinterpret
, "default");
9657 strcpy(mohsuggest
, "");
9660 ast_clear_flag((&globalflags
), IAX_NOTRANSFER
);
9661 ast_clear_flag((&globalflags
), IAX_TRANSFERMEDIA
);
9662 ast_clear_flag((&globalflags
), IAX_USEJITTERBUF
);
9663 ast_clear_flag((&globalflags
), IAX_FORCEJITTERBUF
);
9667 /*! \brief Load configuration */
9668 static int set_config(char *config_file
, int reload
)
9670 struct ast_config
*cfg
, *ucfg
;
9671 int capability
=iax2_capability
;
9672 struct ast_variable
*v
;
9677 int portno
= IAX_DEFAULT_PORTNO
;
9679 struct iax2_user
*user
;
9680 struct iax2_peer
*peer
;
9681 struct ast_netsock
*ns
;
9683 static unsigned short int last_port
=0;
9686 cfg
= ast_config_load(config_file
);
9689 ast_log(LOG_ERROR
, "Unable to load config %s\n", config_file
);
9694 set_config_destroy();
9697 /* Reset global codec prefs */
9698 memset(&prefs
, 0 , sizeof(struct ast_codec_pref
));
9700 /* Reset Global Flags */
9701 memset(&globalflags
, 0, sizeof(globalflags
));
9702 ast_set_flag(&globalflags
, IAX_RTUPDATE
);
9708 min_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
9709 max_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
9713 v
= ast_variable_browse(cfg
, "general");
9715 /* Seed initial tos value */
9716 tosval
= ast_variable_retrieve(cfg
, "general", "tos");
9718 if (ast_str2tos(tosval
, &tos
))
9719 ast_log(LOG_WARNING
, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9722 if (!strcasecmp(v
->name
, "bindport")){
9724 ast_log(LOG_NOTICE
, "Ignoring bindport on reload\n");
9726 portno
= atoi(v
->value
);
9727 } else if (!strcasecmp(v
->name
, "pingtime"))
9728 ping_time
= atoi(v
->value
);
9729 else if (!strcasecmp(v
->name
, "iaxthreadcount")) {
9731 if (atoi(v
->value
) != iaxthreadcount
)
9732 ast_log(LOG_NOTICE
, "Ignoring any changes to iaxthreadcount during reload\n");
9734 iaxthreadcount
= atoi(v
->value
);
9735 if (iaxthreadcount
< 1) {
9736 ast_log(LOG_NOTICE
, "iaxthreadcount must be at least 1.\n");
9738 } else if (iaxthreadcount
> 256) {
9739 ast_log(LOG_NOTICE
, "limiting iaxthreadcount to 256\n");
9740 iaxthreadcount
= 256;
9743 } else if (!strcasecmp(v
->name
, "iaxmaxthreadcount")) {
9745 AST_LIST_LOCK(&dynamic_list
);
9746 iaxmaxthreadcount
= atoi(v
->value
);
9747 AST_LIST_UNLOCK(&dynamic_list
);
9749 iaxmaxthreadcount
= atoi(v
->value
);
9750 if (iaxmaxthreadcount
< 0) {
9751 ast_log(LOG_NOTICE
, "iaxmaxthreadcount must be at least 0.\n");
9752 iaxmaxthreadcount
= 0;
9753 } else if (iaxmaxthreadcount
> 256) {
9754 ast_log(LOG_NOTICE
, "Limiting iaxmaxthreadcount to 256\n");
9755 iaxmaxthreadcount
= 256;
9758 } else if (!strcasecmp(v
->name
, "nochecksums")) {
9760 if (ast_true(v
->value
))
9765 if (ast_true(v
->value
))
9766 ast_log(LOG_WARNING
, "Disabling RTP checksums is not supported on this operating system!\n");
9769 else if (!strcasecmp(v
->name
, "maxjitterbuffer"))
9770 maxjitterbuffer
= atoi(v
->value
);
9771 else if (!strcasecmp(v
->name
, "resyncthreshold"))
9772 resyncthreshold
= atoi(v
->value
);
9773 else if (!strcasecmp(v
->name
, "maxjitterinterps"))
9774 maxjitterinterps
= atoi(v
->value
);
9775 else if (!strcasecmp(v
->name
, "lagrqtime"))
9776 lagrq_time
= atoi(v
->value
);
9777 else if (!strcasecmp(v
->name
, "maxregexpire"))
9778 max_reg_expire
= atoi(v
->value
);
9779 else if (!strcasecmp(v
->name
, "minregexpire"))
9780 min_reg_expire
= atoi(v
->value
);
9781 else if (!strcasecmp(v
->name
, "bindaddr")) {
9783 ast_log(LOG_NOTICE
, "Ignoring bindaddr on reload\n");
9785 if (!(ns
= ast_netsock_bind(netsock
, io
, v
->value
, portno
, tos
, socket_read
, NULL
))) {
9786 ast_log(LOG_WARNING
, "Unable apply binding to '%s' at line %d\n", v
->value
, v
->lineno
);
9788 if (option_verbose
> 1) {
9789 if (strchr(v
->value
, ':'))
9790 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to '%s'\n", v
->value
);
9792 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to '%s:%d'\n", v
->value
, portno
);
9794 if (defaultsockfd
< 0)
9795 defaultsockfd
= ast_netsock_sockfd(ns
);
9796 ast_netsock_unref(ns
);
9799 } else if (!strcasecmp(v
->name
, "authdebug"))
9800 authdebug
= ast_true(v
->value
);
9801 else if (!strcasecmp(v
->name
, "encryption"))
9802 iax2_encryption
= get_encrypt_methods(v
->value
);
9803 else if (!strcasecmp(v
->name
, "notransfer")) {
9804 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9805 ast_clear_flag((&globalflags
), IAX_TRANSFERMEDIA
);
9806 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_NOTRANSFER
);
9807 } else if (!strcasecmp(v
->name
, "transfer")) {
9808 if (!strcasecmp(v
->value
, "mediaonly")) {
9809 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
9810 } else if (ast_true(v
->value
)) {
9811 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
9813 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
9814 } else if (!strcasecmp(v
->name
, "codecpriority")) {
9815 if(!strcasecmp(v
->value
, "caller"))
9816 ast_set_flag((&globalflags
), IAX_CODEC_USER_FIRST
);
9817 else if(!strcasecmp(v
->value
, "disabled"))
9818 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
9819 else if(!strcasecmp(v
->value
, "reqonly")) {
9820 ast_set_flag((&globalflags
), IAX_CODEC_NOCAP
);
9821 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
9823 } else if (!strcasecmp(v
->name
, "jitterbuffer"))
9824 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_USEJITTERBUF
);
9825 else if (!strcasecmp(v
->name
, "forcejitterbuffer"))
9826 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_FORCEJITTERBUF
);
9827 else if (!strcasecmp(v
->name
, "delayreject"))
9828 delayreject
= ast_true(v
->value
);
9829 else if (!strcasecmp(v
->name
, "rtcachefriends"))
9830 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTCACHEFRIENDS
);
9831 else if (!strcasecmp(v
->name
, "rtignoreregexpire"))
9832 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTIGNOREREGEXPIRE
);
9833 else if (!strcasecmp(v
->name
, "rtupdate"))
9834 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTUPDATE
);
9835 else if (!strcasecmp(v
->name
, "trunktimestamps"))
9836 ast_set2_flag(&globalflags
, ast_true(v
->value
), IAX_TRUNKTIMESTAMPS
);
9837 else if (!strcasecmp(v
->name
, "rtautoclear")) {
9838 int i
= atoi(v
->value
);
9840 global_rtautoclear
= i
;
9843 ast_set2_flag((&globalflags
), i
|| ast_true(v
->value
), IAX_RTAUTOCLEAR
);
9844 } else if (!strcasecmp(v
->name
, "trunkfreq")) {
9845 trunkfreq
= atoi(v
->value
);
9848 } else if (!strcasecmp(v
->name
, "autokill")) {
9849 if (sscanf(v
->value
, "%d", &x
) == 1) {
9853 ast_log(LOG_NOTICE
, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v
->lineno
);
9854 } else if (ast_true(v
->value
)) {
9855 autokill
= DEFAULT_MAXMS
;
9859 } else if (!strcasecmp(v
->name
, "bandwidth")) {
9860 if (!strcasecmp(v
->value
, "low")) {
9861 capability
= IAX_CAPABILITY_LOWBANDWIDTH
;
9862 } else if (!strcasecmp(v
->value
, "medium")) {
9863 capability
= IAX_CAPABILITY_MEDBANDWIDTH
;
9864 } else if (!strcasecmp(v
->value
, "high")) {
9865 capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
9867 ast_log(LOG_WARNING
, "bandwidth must be either low, medium, or high\n");
9868 } else if (!strcasecmp(v
->name
, "allow")) {
9869 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 1);
9870 } else if (!strcasecmp(v
->name
, "disallow")) {
9871 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 0);
9872 } else if (!strcasecmp(v
->name
, "register")) {
9873 iax2_register(v
->value
, v
->lineno
);
9874 } else if (!strcasecmp(v
->name
, "iaxcompat")) {
9875 iaxcompat
= ast_true(v
->value
);
9876 } else if (!strcasecmp(v
->name
, "regcontext")) {
9877 ast_copy_string(regcontext
, v
->value
, sizeof(regcontext
));
9878 /* Create context if it doesn't exist already */
9879 if (!ast_context_find(regcontext
))
9880 ast_context_create(NULL
, regcontext
, "IAX2");
9881 } else if (!strcasecmp(v
->name
, "tos")) {
9882 if (ast_str2tos(v
->value
, &tos
))
9883 ast_log(LOG_WARNING
, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v
->lineno
);
9884 } else if (!strcasecmp(v
->name
, "accountcode")) {
9885 ast_copy_string(accountcode
, v
->value
, sizeof(accountcode
));
9886 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
9887 ast_copy_string(mohinterpret
, v
->value
, sizeof(user
->mohinterpret
));
9888 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
9889 ast_copy_string(mohsuggest
, v
->value
, sizeof(user
->mohsuggest
));
9890 } else if (!strcasecmp(v
->name
, "amaflags")) {
9891 format
= ast_cdr_amaflags2int(v
->value
);
9893 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
9897 } else if (!strcasecmp(v
->name
, "language")) {
9898 ast_copy_string(language
, v
->value
, sizeof(language
));
9899 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
9900 maxauthreq
= atoi(v
->value
);
9903 } else if (!strcasecmp(v
->name
, "adsi")) {
9904 adsi
= ast_true(v
->value
);
9905 } /*else if (strcasecmp(v->name,"type")) */
9906 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9910 if (defaultsockfd
< 0) {
9911 if (!(ns
= ast_netsock_bind(netsock
, io
, "0.0.0.0", portno
, tos
, socket_read
, NULL
))) {
9912 ast_log(LOG_ERROR
, "Unable to create network socket: %s\n", strerror(errno
));
9914 if (option_verbose
> 1)
9915 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to default address 0.0.0.0:%d\n", portno
);
9916 defaultsockfd
= ast_netsock_sockfd(ns
);
9917 ast_netsock_unref(ns
);
9921 ast_netsock_release(outsock
);
9922 outsock
= ast_netsock_list_alloc();
9924 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
9927 ast_netsock_init(outsock
);
9930 if (min_reg_expire
> max_reg_expire
) {
9931 ast_log(LOG_WARNING
, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
9932 min_reg_expire
, max_reg_expire
, max_reg_expire
);
9933 min_reg_expire
= max_reg_expire
;
9935 iax2_capability
= capability
;
9937 ucfg
= ast_config_load("users.conf");
9939 struct ast_variable
*gen
;
9942 const char *hasiax
, *registeriax
;
9944 genhasiax
= ast_true(ast_variable_retrieve(ucfg
, "general", "hasiax"));
9945 genregisteriax
= ast_true(ast_variable_retrieve(ucfg
, "general", "registeriax"));
9946 gen
= ast_variable_browse(ucfg
, "general");
9947 cat
= ast_category_browse(ucfg
, NULL
);
9949 if (strcasecmp(cat
, "general")) {
9950 hasiax
= ast_variable_retrieve(ucfg
, cat
, "hasiax");
9951 registeriax
= ast_variable_retrieve(ucfg
, cat
, "registeriax");
9952 if (ast_true(hasiax
) || (!hasiax
&& genhasiax
)) {
9953 /* Start with general parameters, then specific parameters, user and peer */
9954 user
= build_user(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
9956 __ao2_link(users
, user
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
9957 user
= user_unref(user
);
9959 peer
= build_peer(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
9961 if (ast_test_flag(peer
, IAX_DYNAMIC
))
9962 reg_source_db(peer
);
9963 __ao2_link(peers
, peer
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
9964 peer
= peer_unref(peer
);
9967 if (ast_true(registeriax
) || (!registeriax
&& genregisteriax
)) {
9969 const char *host
= ast_variable_retrieve(ucfg
, cat
, "host");
9970 const char *username
= ast_variable_retrieve(ucfg
, cat
, "username");
9971 const char *secret
= ast_variable_retrieve(ucfg
, cat
, "secret");
9973 host
= ast_variable_retrieve(ucfg
, "general", "host");
9975 username
= ast_variable_retrieve(ucfg
, "general", "username");
9977 secret
= ast_variable_retrieve(ucfg
, "general", "secret");
9978 if (!ast_strlen_zero(username
) && !ast_strlen_zero(host
)) {
9979 if (!ast_strlen_zero(secret
))
9980 snprintf(tmp
, sizeof(tmp
), "%s:%s@%s", username
, secret
, host
);
9982 snprintf(tmp
, sizeof(tmp
), "%s@%s", username
, host
);
9983 iax2_register(tmp
, 0);
9987 cat
= ast_category_browse(ucfg
, cat
);
9989 ast_config_destroy(ucfg
);
9992 cat
= ast_category_browse(cfg
, NULL
);
9994 if (strcasecmp(cat
, "general")) {
9995 utype
= ast_variable_retrieve(cfg
, cat
, "type");
9997 if (!strcasecmp(utype
, "user") || !strcasecmp(utype
, "friend")) {
9998 user
= build_user(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
10000 __ao2_link(users
, user
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10001 user
= user_unref(user
);
10004 if (!strcasecmp(utype
, "peer") || !strcasecmp(utype
, "friend")) {
10005 peer
= build_peer(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
10007 if (ast_test_flag(peer
, IAX_DYNAMIC
))
10008 reg_source_db(peer
);
10009 __ao2_link(peers
, peer
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10010 peer
= peer_unref(peer
);
10012 } else if (strcasecmp(utype
, "user")) {
10013 ast_log(LOG_WARNING
, "Unknown type '%s' for '%s' in %s\n", utype
, cat
, config_file
);
10016 ast_log(LOG_WARNING
, "Section '%s' lacks type\n", cat
);
10018 cat
= ast_category_browse(cfg
, cat
);
10020 ast_config_destroy(cfg
);
10025 static void poke_all_peers(void)
10027 struct ao2_iterator i
;
10028 struct iax2_peer
*peer
;
10030 i
= ao2_iterator_init(peers
, 0);
10031 while ((peer
= ao2_iterator_next(&i
))) {
10032 iax2_poke_peer(peer
, 0);
10036 static int reload_config(void)
10038 char *config
= "iax.conf";
10039 struct iax2_registry
*reg
;
10041 if (set_config(config
, 1) > 0) {
10044 AST_LIST_LOCK(®istrations
);
10045 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
10046 iax2_do_register(reg
);
10047 AST_LIST_UNLOCK(®istrations
);
10048 /* Qualify hosts, too */
10051 reload_firmware(0);
10052 iax_provision_reload();
10057 static int iax2_reload(int fd
, int argc
, char *argv
[])
10059 return reload_config();
10062 static int reload(void)
10064 return reload_config();
10067 static int cache_get_callno_locked(const char *data
)
10069 struct sockaddr_in sin
;
10072 struct iax_ie_data ied
;
10073 struct create_addr_info cai
;
10074 struct parsed_dial_string pds
;
10077 for (x
=0; x
<IAX_MAX_CALLS
; x
++) {
10078 /* Look for an *exact match* call. Once a call is negotiated, it can only
10079 look up entries for a single context */
10080 if (!ast_mutex_trylock(&iaxsl
[x
])) {
10081 if (iaxs
[x
] && !strcasecmp(data
, iaxs
[x
]->dproot
))
10083 ast_mutex_unlock(&iaxsl
[x
]);
10087 /* No match found, we need to create a new one */
10089 memset(&cai
, 0, sizeof(cai
));
10090 memset(&ied
, 0, sizeof(ied
));
10091 memset(&pds
, 0, sizeof(pds
));
10093 tmpstr
= ast_strdupa(data
);
10094 parse_dial_string(tmpstr
, &pds
);
10096 if (ast_strlen_zero(pds
.peer
)) {
10097 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", data
);
10101 /* Populate our address from the given */
10102 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
))
10106 ast_log(LOG_DEBUG
, "peer: %s, username: %s, password: %s, context: %s\n",
10107 pds
.peer
, pds
.username
, pds
.password
, pds
.context
);
10109 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
);
10111 ast_log(LOG_WARNING
, "Unable to create call\n");
10115 ast_string_field_set(iaxs
[callno
], dproot
, data
);
10116 iaxs
[callno
]->capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
10118 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
10119 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, "TBD");
10120 /* the string format is slightly different from a standard dial string,
10121 because the context appears in the 'exten' position
10124 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.exten
);
10126 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
10127 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, IAX_CAPABILITY_FULLBANDWIDTH
);
10128 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, IAX_CAPABILITY_FULLBANDWIDTH
);
10129 /* Keep password handy */
10131 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
10133 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
10134 /* Start the call going */
10135 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
10140 static struct iax2_dpcache
*find_cache(struct ast_channel
*chan
, const char *data
, const char *context
, const char *exten
, int priority
)
10142 struct iax2_dpcache
*dp
, *prev
= NULL
, *next
;
10151 struct ast_channel
*c
;
10152 struct ast_frame
*f
;
10153 gettimeofday(&tv
, NULL
);
10157 /* Expire old caches */
10158 if (ast_tvcmp(tv
, dp
->expiry
) > 0) {
10159 /* It's expired, let it disappear */
10161 prev
->next
= dp
->next
;
10163 dpcache
= dp
->next
;
10164 if (!dp
->peer
&& !(dp
->flags
& CACHE_FLAG_PENDING
) && !dp
->callno
) {
10165 /* Free memory and go again */
10168 ast_log(LOG_WARNING
, "DP still has peer field or pending or callno (flags = %d, peer = %p callno = %d)\n", dp
->flags
, dp
->peer
, dp
->callno
);
10173 /* We found an entry that matches us! */
10174 if (!strcmp(dp
->peercontext
, data
) && !strcmp(dp
->exten
, exten
))
10180 /* No matching entry. Create a new one. */
10181 /* First, can we make a callno? */
10182 callno
= cache_get_callno_locked(data
);
10184 ast_log(LOG_WARNING
, "Unable to generate call for '%s'\n", data
);
10187 if (!(dp
= ast_calloc(1, sizeof(*dp
)))) {
10188 ast_mutex_unlock(&iaxsl
[callno
]);
10191 ast_copy_string(dp
->peercontext
, data
, sizeof(dp
->peercontext
));
10192 ast_copy_string(dp
->exten
, exten
, sizeof(dp
->exten
));
10193 gettimeofday(&dp
->expiry
, NULL
);
10194 dp
->orig
= dp
->expiry
;
10195 /* Expires in 30 mins by default */
10196 dp
->expiry
.tv_sec
+= iaxdefaultdpcache
;
10197 dp
->next
= dpcache
;
10198 dp
->flags
= CACHE_FLAG_PENDING
;
10199 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
10200 dp
->waiters
[x
] = -1;
10202 dp
->peer
= iaxs
[callno
]->dpentries
;
10203 iaxs
[callno
]->dpentries
= dp
;
10204 /* Send the request if we're already up */
10205 if (ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
10206 iax2_dprequest(dp
, callno
);
10207 ast_mutex_unlock(&iaxsl
[callno
]);
10209 /* By here we must have a dp */
10210 if (dp
->flags
& CACHE_FLAG_PENDING
) {
10211 /* Okay, here it starts to get nasty. We need a pipe now to wait
10212 for a reply to come back so long as it's pending */
10213 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++) {
10214 /* Find an empty slot */
10215 if (dp
->waiters
[x
] < 0)
10218 if (x
>= sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0])) {
10219 ast_log(LOG_WARNING
, "No more waiter positions available\n");
10223 ast_log(LOG_WARNING
, "Unable to create pipe for comm\n");
10226 dp
->waiters
[x
] = com
[1];
10227 /* Okay, now we wait */
10228 timeout
= iaxdefaulttimeout
* 1000;
10229 /* Temporarily unlock */
10230 ast_mutex_unlock(&dpcache_lock
);
10231 /* Defer any dtmf */
10233 old
= ast_channel_defer_dtmf(chan
);
10236 c
= ast_waitfor_nandfds(&chan
, chan
? 1 : 0, &com
[0], 1, NULL
, &outfd
, &timeout
);
10245 /* Got hung up on, abort! */
10252 ast_log(LOG_WARNING
, "Timeout waiting for %s exten %s\n", data
, exten
);
10254 ast_mutex_lock(&dpcache_lock
);
10255 dp
->waiters
[x
] = -1;
10259 /* Don't interpret anything, just abort. Not sure what th epoint
10260 of undeferring dtmf on a hung up channel is but hey whatever */
10262 ast_channel_undefer_dtmf(chan
);
10265 if (!(dp
->flags
& CACHE_FLAG_TIMEOUT
)) {
10266 /* Now to do non-independent analysis the results of our wait */
10267 if (dp
->flags
& CACHE_FLAG_PENDING
) {
10268 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10269 pending. Don't let it take as long to timeout. */
10270 dp
->flags
&= ~CACHE_FLAG_PENDING
;
10271 dp
->flags
|= CACHE_FLAG_TIMEOUT
;
10272 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10273 systems without leaving it unavailable once the server comes back online */
10274 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ 60;
10275 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
10276 if (dp
->waiters
[x
] > -1)
10277 write(dp
->waiters
[x
], "asdf", 4);
10280 /* Our caller will obtain the rest */
10282 ast_channel_undefer_dtmf(chan
);
10287 /*! \brief Part of the IAX2 switch interface */
10288 static int iax2_exists(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10290 struct iax2_dpcache
*dp
;
10293 ast_log(LOG_NOTICE
, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10295 if ((priority
!= 1) && (priority
!= 2))
10297 ast_mutex_lock(&dpcache_lock
);
10298 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10300 if (dp
->flags
& CACHE_FLAG_EXISTS
)
10303 ast_mutex_unlock(&dpcache_lock
);
10305 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10310 /*! \brief part of the IAX2 dial plan switch interface */
10311 static int iax2_canmatch(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10314 struct iax2_dpcache
*dp
;
10316 ast_log(LOG_NOTICE
, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10318 if ((priority
!= 1) && (priority
!= 2))
10320 ast_mutex_lock(&dpcache_lock
);
10321 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10323 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
10326 ast_mutex_unlock(&dpcache_lock
);
10328 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10333 /*! \brief Part of the IAX2 Switch interface */
10334 static int iax2_matchmore(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10337 struct iax2_dpcache
*dp
;
10339 ast_log(LOG_NOTICE
, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10341 if ((priority
!= 1) && (priority
!= 2))
10343 ast_mutex_lock(&dpcache_lock
);
10344 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10346 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
10349 ast_mutex_unlock(&dpcache_lock
);
10351 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10356 /*! \brief Execute IAX2 dialplan switch */
10357 static int iax2_exec(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10362 struct iax2_dpcache
*dp
;
10363 struct ast_app
*dial
;
10365 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
);
10367 if (priority
== 2) {
10368 /* Indicate status, can be overridden in dialplan */
10369 const char *dialstatus
= pbx_builtin_getvar_helper(chan
, "DIALSTATUS");
10371 dial
= pbx_findapp(dialstatus
);
10373 pbx_exec(chan
, dial
, "");
10376 } else if (priority
!= 1)
10378 ast_mutex_lock(&dpcache_lock
);
10379 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10381 if (dp
->flags
& CACHE_FLAG_EXISTS
) {
10382 ast_copy_string(odata
, data
, sizeof(odata
));
10383 ncontext
= strchr(odata
, '/');
10387 snprintf(req
, sizeof(req
), "IAX2/%s/%s@%s", odata
, exten
, ncontext
);
10389 snprintf(req
, sizeof(req
), "IAX2/%s/%s", odata
, exten
);
10391 if (option_verbose
> 2)
10392 ast_verbose(VERBOSE_PREFIX_3
"Executing Dial('%s')\n", req
);
10394 ast_mutex_unlock(&dpcache_lock
);
10395 ast_log(LOG_WARNING
, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten
, context
, data
);
10399 ast_mutex_unlock(&dpcache_lock
);
10400 dial
= pbx_findapp("Dial");
10402 return pbx_exec(chan
, dial
, req
);
10404 ast_log(LOG_WARNING
, "No dial application registered\n");
10409 static int function_iaxpeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
10411 struct iax2_peer
*peer
;
10412 char *peername
, *colname
;
10414 peername
= ast_strdupa(data
);
10416 /* if our channel, return the IP address of the endpoint of current channel */
10417 if (!strcmp(peername
,"CURRENTCHANNEL")) {
10418 unsigned short callno
;
10419 if (chan
->tech
!= &iax2_tech
)
10421 callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
10422 ast_copy_string(buf
, iaxs
[callno
]->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
) : "", len
);
10426 if ((colname
= strchr(peername
, ':'))) /*! \todo : will be removed after the 1.4 relese */
10428 else if ((colname
= strchr(peername
, '|')))
10433 if (!(peer
= find_peer(peername
, 1)))
10436 if (!strcasecmp(colname
, "ip")) {
10437 ast_copy_string(buf
, peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", len
);
10438 } else if (!strcasecmp(colname
, "status")) {
10439 peer_status(peer
, buf
, len
);
10440 } else if (!strcasecmp(colname
, "mailbox")) {
10441 ast_copy_string(buf
, peer
->mailbox
, len
);
10442 } else if (!strcasecmp(colname
, "context")) {
10443 ast_copy_string(buf
, peer
->context
, len
);
10444 } else if (!strcasecmp(colname
, "expire")) {
10445 snprintf(buf
, len
, "%d", peer
->expire
);
10446 } else if (!strcasecmp(colname
, "dynamic")) {
10447 ast_copy_string(buf
, (ast_test_flag(peer
, IAX_DYNAMIC
) ? "yes" : "no"), len
);
10448 } else if (!strcasecmp(colname
, "callerid_name")) {
10449 ast_copy_string(buf
, peer
->cid_name
, len
);
10450 } else if (!strcasecmp(colname
, "callerid_num")) {
10451 ast_copy_string(buf
, peer
->cid_num
, len
);
10452 } else if (!strcasecmp(colname
, "codecs")) {
10453 ast_getformatname_multiple(buf
, len
-1, peer
->capability
);
10454 } else if (!strncasecmp(colname
, "codec[", 6)) {
10455 char *codecnum
, *ptr
;
10456 int index
= 0, codec
= 0;
10458 codecnum
= strchr(colname
, '[');
10461 if ((ptr
= strchr(codecnum
, ']'))) {
10464 index
= atoi(codecnum
);
10465 if((codec
= ast_codec_pref_index(&peer
->prefs
, index
))) {
10466 ast_copy_string(buf
, ast_getformatname(codec
), len
);
10475 struct ast_custom_function iaxpeer_function
= {
10477 .synopsis
= "Gets IAX peer information",
10478 .syntax
= "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10479 .read
= function_iaxpeer
,
10480 .desc
= "If peername specified, valid items are:\n"
10481 "- ip (default) The IP address.\n"
10482 "- status The peer's status (if qualify=yes)\n"
10483 "- mailbox The configured mailbox.\n"
10484 "- context The configured context.\n"
10485 "- expire The epoch time of the next expire.\n"
10486 "- dynamic Is it dynamic? (yes/no).\n"
10487 "- callerid_name The configured Caller ID name.\n"
10488 "- callerid_num The configured Caller ID number.\n"
10489 "- codecs The configured codecs.\n"
10490 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10492 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10497 /*! \brief Part of the device state notification system ---*/
10498 static int iax2_devicestate(void *data
)
10500 struct parsed_dial_string pds
;
10501 char *tmp
= ast_strdupa(data
);
10502 struct iax2_peer
*p
;
10503 int res
= AST_DEVICE_INVALID
;
10505 memset(&pds
, 0, sizeof(pds
));
10506 parse_dial_string(tmp
, &pds
);
10508 if (ast_strlen_zero(pds
.peer
)) {
10509 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
10513 if (option_debug
> 2)
10514 ast_log(LOG_DEBUG
, "Checking device state for device %s\n", pds
.peer
);
10516 /* SLD: FIXME: second call to find_peer during registration */
10517 if (!(p
= find_peer(pds
.peer
, 1)))
10520 res
= AST_DEVICE_UNAVAILABLE
;
10521 if (option_debug
> 2)
10522 ast_log(LOG_DEBUG
, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10523 pds
.peer
, p
->addr
.sin_addr
.s_addr
, p
->defaddr
.sin_addr
.s_addr
, p
->maxms
, p
->lastms
);
10525 if ((p
->addr
.sin_addr
.s_addr
|| p
->defaddr
.sin_addr
.s_addr
) &&
10526 (!p
->maxms
|| ((p
->lastms
> -1) && (p
->historicms
<= p
->maxms
)))) {
10527 /* Peer is registered, or have default IP address
10528 and a valid registration */
10529 if (p
->historicms
== 0 || p
->historicms
<= p
->maxms
)
10530 /* let the core figure out whether it is in use or not */
10531 res
= AST_DEVICE_UNKNOWN
;
10539 static struct ast_switch iax2_switch
=
10542 description
: "IAX Remote Dialplan Switch",
10543 exists
: iax2_exists
,
10544 canmatch
: iax2_canmatch
,
10546 matchmore
: iax2_matchmore
,
10549 static char show_stats_usage
[] =
10550 "Usage: iax2 show stats\n"
10551 " Display statistics on IAX channel driver.\n";
10553 static char show_cache_usage
[] =
10554 "Usage: iax2 show cache\n"
10555 " Display currently cached IAX Dialplan results.\n";
10557 static char show_peer_usage
[] =
10558 "Usage: iax2 show peer <name>\n"
10559 " Display details on specific IAX peer\n";
10561 static char prune_realtime_usage
[] =
10562 "Usage: iax2 prune realtime [<peername>|all]\n"
10563 " Prunes object(s) from the cache\n";
10565 static char iax2_reload_usage
[] =
10566 "Usage: iax2 reload\n"
10567 " Reloads IAX configuration from iax.conf\n";
10569 static char show_prov_usage
[] =
10570 "Usage: iax2 provision <host> <template> [forced]\n"
10571 " Provisions the given peer or IP address using a template\n"
10572 " matching either 'template' or '*' if the template is not\n"
10573 " found. If 'forced' is specified, even empty provisioning\n"
10574 " fields will be provisioned as empty fields.\n";
10576 static char show_users_usage
[] =
10577 "Usage: iax2 show users [like <pattern>]\n"
10578 " Lists all known IAX2 users.\n"
10579 " Optional regular expression pattern is used to filter the user list.\n";
10581 static char show_channels_usage
[] =
10582 "Usage: iax2 show channels\n"
10583 " Lists all currently active IAX channels.\n";
10585 static char show_netstats_usage
[] =
10586 "Usage: iax2 show netstats\n"
10587 " Lists network status for all currently active IAX channels.\n";
10589 static char show_threads_usage
[] =
10590 "Usage: iax2 show threads\n"
10591 " Lists status of IAX helper threads\n";
10593 static char show_peers_usage
[] =
10594 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10595 " Lists all known IAX2 peers.\n"
10596 " Optional 'registered' argument lists only peers with known addresses.\n"
10597 " Optional regular expression pattern is used to filter the peer list.\n";
10599 static char show_firmware_usage
[] =
10600 "Usage: iax2 show firmware\n"
10601 " Lists all known IAX firmware images.\n";
10603 static char show_reg_usage
[] =
10604 "Usage: iax2 show registry\n"
10605 " Lists all registration requests and status.\n";
10607 static char debug_usage
[] =
10608 "Usage: iax2 set debug\n"
10609 " Enables dumping of IAX packets for debugging purposes\n";
10611 static char no_debug_usage
[] =
10612 "Usage: iax2 set debug off\n"
10613 " Disables dumping of IAX packets for debugging purposes\n";
10615 static char debug_trunk_usage
[] =
10616 "Usage: iax2 set debug trunk\n"
10617 " Requests current status of IAX trunking\n";
10619 static char no_debug_trunk_usage
[] =
10620 "Usage: iax2 set debug trunk off\n"
10621 " Requests current status of IAX trunking\n";
10623 static char debug_jb_usage
[] =
10624 "Usage: iax2 set debug jb\n"
10625 " Enables jitterbuffer debugging information\n";
10627 static char no_debug_jb_usage
[] =
10628 "Usage: iax2 set debug jb off\n"
10629 " Disables jitterbuffer debugging information\n";
10631 static char iax2_test_losspct_usage
[] =
10632 "Usage: iax2 test losspct <percentage>\n"
10633 " For testing, throws away <percentage> percent of incoming packets\n";
10636 static char iax2_test_late_usage
[] =
10637 "Usage: iax2 test late <ms>\n"
10638 " For testing, count the next frame as <ms> ms late\n";
10640 static char iax2_test_resync_usage
[] =
10641 "Usage: iax2 test resync <ms>\n"
10642 " For testing, adjust all future frames by <ms> ms\n";
10644 static char iax2_test_jitter_usage
[] =
10645 "Usage: iax2 test jitter <ms> <pct>\n"
10646 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10647 #endif /* IAXTESTS */
10649 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated
= {
10650 { "iax2", "trunk", "debug", NULL
},
10651 iax2_do_trunk_debug
, NULL
,
10654 static struct ast_cli_entry cli_iax2_jb_debug_deprecated
= {
10655 { "iax2", "jb", "debug", NULL
},
10656 iax2_do_jb_debug
, NULL
,
10659 static struct ast_cli_entry cli_iax2_no_debug_deprecated
= {
10660 { "iax2", "no", "debug", NULL
},
10661 iax2_no_debug
, NULL
,
10664 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated
= {
10665 { "iax2", "no", "trunk", "debug", NULL
},
10666 iax2_no_trunk_debug
, NULL
,
10669 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated
= {
10670 { "iax2", "no", "jb", "debug", NULL
},
10671 iax2_no_jb_debug
, NULL
,
10674 static struct ast_cli_entry cli_iax2
[] = {
10675 { { "iax2", "show", "cache", NULL
},
10676 iax2_show_cache
, "Display IAX cached dialplan",
10677 show_cache_usage
, NULL
, },
10679 { { "iax2", "show", "channels", NULL
},
10680 iax2_show_channels
, "List active IAX channels",
10681 show_channels_usage
, NULL
, },
10683 { { "iax2", "show", "firmware", NULL
},
10684 iax2_show_firmware
, "List available IAX firmwares",
10685 show_firmware_usage
, NULL
, },
10687 { { "iax2", "show", "netstats", NULL
},
10688 iax2_show_netstats
, "List active IAX channel netstats",
10689 show_netstats_usage
, NULL
, },
10691 { { "iax2", "show", "peers", NULL
},
10692 iax2_show_peers
, "List defined IAX peers",
10693 show_peers_usage
, NULL
, },
10695 { { "iax2", "show", "registry", NULL
},
10696 iax2_show_registry
, "Display IAX registration status",
10697 show_reg_usage
, NULL
, },
10699 { { "iax2", "show", "stats", NULL
},
10700 iax2_show_stats
, "Display IAX statistics",
10701 show_stats_usage
, NULL
, },
10703 { { "iax2", "show", "threads", NULL
},
10704 iax2_show_threads
, "Display IAX helper thread info",
10705 show_threads_usage
, NULL
, },
10707 { { "iax2", "show", "users", NULL
},
10708 iax2_show_users
, "List defined IAX users",
10709 show_users_usage
, NULL
, },
10711 { { "iax2", "prune", "realtime", NULL
},
10712 iax2_prune_realtime
, "Prune a cached realtime lookup",
10713 prune_realtime_usage
, complete_iax2_show_peer
},
10715 { { "iax2", "reload", NULL
},
10716 iax2_reload
, "Reload IAX configuration",
10717 iax2_reload_usage
},
10719 { { "iax2", "show", "peer", NULL
},
10720 iax2_show_peer
, "Show details on specific IAX peer",
10721 show_peer_usage
, complete_iax2_show_peer
},
10723 { { "iax2", "set", "debug", NULL
},
10724 iax2_do_debug
, "Enable IAX debugging",
10727 { { "iax2", "set", "debug", "trunk", NULL
},
10728 iax2_do_trunk_debug
, "Enable IAX trunk debugging",
10729 debug_trunk_usage
, NULL
, &cli_iax2_trunk_debug_deprecated
},
10731 { { "iax2", "set", "debug", "jb", NULL
},
10732 iax2_do_jb_debug
, "Enable IAX jitterbuffer debugging",
10733 debug_jb_usage
, NULL
, &cli_iax2_jb_debug_deprecated
},
10735 { { "iax2", "set", "debug", "off", NULL
},
10736 iax2_no_debug
, "Disable IAX debugging",
10737 no_debug_usage
, NULL
, &cli_iax2_no_debug_deprecated
},
10739 { { "iax2", "set", "debug", "trunk", "off", NULL
},
10740 iax2_no_trunk_debug
, "Disable IAX trunk debugging",
10741 no_debug_trunk_usage
, NULL
, &cli_iax2_no_trunk_debug_deprecated
},
10743 { { "iax2", "set", "debug", "jb", "off", NULL
},
10744 iax2_no_jb_debug
, "Disable IAX jitterbuffer debugging",
10745 no_debug_jb_usage
, NULL
, &cli_iax2_no_jb_debug_deprecated
},
10747 { { "iax2", "test", "losspct", NULL
},
10748 iax2_test_losspct
, "Set IAX2 incoming frame loss percentage",
10749 iax2_test_losspct_usage
},
10751 { { "iax2", "provision", NULL
},
10752 iax2_prov_cmd
, "Provision an IAX device",
10753 show_prov_usage
, iax2_prov_complete_template_3rd
},
10756 { { "iax2", "test", "late", NULL
},
10757 iax2_test_late
, "Test the receipt of a late frame",
10758 iax2_test_late_usage
},
10760 { { "iax2", "test", "resync", NULL
},
10761 iax2_test_resync
, "Test a resync in received timestamps",
10762 iax2_test_resync_usage
},
10764 { { "iax2", "test", "jitter", NULL
},
10765 iax2_test_jitter
, "Simulates jitter for testing",
10766 iax2_test_jitter_usage
},
10767 #endif /* IAXTESTS */
10770 static int __unload_module(void)
10772 struct iax2_thread
*thread
= NULL
;
10775 /* Make sure threads do not hold shared resources when they are canceled */
10777 /* Grab the sched lock resource to keep it away from threads about to die */
10778 /* Cancel the network thread, close the net socket */
10779 if (netthreadid
!= AST_PTHREADT_NULL
) {
10780 AST_LIST_LOCK(&iaxq
.queue
);
10781 ast_mutex_lock(&sched_lock
);
10782 pthread_cancel(netthreadid
);
10783 ast_cond_signal(&sched_cond
);
10784 ast_mutex_unlock(&sched_lock
); /* Release the schedule lock resource */
10785 AST_LIST_UNLOCK(&iaxq
.queue
);
10786 pthread_join(netthreadid
, NULL
);
10788 if (schedthreadid
!= AST_PTHREADT_NULL
) {
10789 ast_mutex_lock(&sched_lock
);
10790 pthread_cancel(schedthreadid
);
10791 ast_cond_signal(&sched_cond
);
10792 ast_mutex_unlock(&sched_lock
);
10793 pthread_join(schedthreadid
, NULL
);
10796 /* Call for all threads to halt */
10797 AST_LIST_LOCK(&idle_list
);
10798 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list
, thread
, list
) {
10799 AST_LIST_REMOVE_CURRENT(&idle_list
, list
);
10800 pthread_cancel(thread
->threadid
);
10802 AST_LIST_TRAVERSE_SAFE_END
10803 AST_LIST_UNLOCK(&idle_list
);
10805 AST_LIST_LOCK(&active_list
);
10806 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list
, thread
, list
) {
10807 AST_LIST_REMOVE_CURRENT(&active_list
, list
);
10808 pthread_cancel(thread
->threadid
);
10810 AST_LIST_TRAVERSE_SAFE_END
10811 AST_LIST_UNLOCK(&active_list
);
10813 AST_LIST_LOCK(&dynamic_list
);
10814 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list
, thread
, list
) {
10815 AST_LIST_REMOVE_CURRENT(&dynamic_list
, list
);
10816 pthread_cancel(thread
->threadid
);
10818 AST_LIST_TRAVERSE_SAFE_END
10819 AST_LIST_UNLOCK(&dynamic_list
);
10821 AST_LIST_HEAD_DESTROY(&iaxq
.queue
);
10823 /* Wait for threads to exit */
10824 while(0 < iaxactivethreadcount
)
10827 ast_netsock_release(netsock
);
10828 ast_netsock_release(outsock
);
10829 for (x
=0;x
<IAX_MAX_CALLS
;x
++)
10832 ast_manager_unregister( "IAXpeers" );
10833 ast_manager_unregister( "IAXnetstats" );
10834 ast_unregister_application(papp
);
10835 ast_cli_unregister_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
10836 ast_unregister_switch(&iax2_switch
);
10837 ast_channel_unregister(&iax2_tech
);
10839 iax_provision_unload();
10840 sched_context_destroy(sched
);
10841 reload_firmware(1);
10843 ast_mutex_destroy(&waresl
.lock
);
10845 for (x
= 0; x
< IAX_MAX_CALLS
; x
++)
10846 ast_mutex_destroy(&iaxsl
[x
]);
10848 ao2_ref(peers
, -1);
10849 ao2_ref(users
, -1);
10854 static int unload_module(void)
10856 ast_custom_function_unregister(&iaxpeer_function
);
10857 return __unload_module();
10860 static int peer_set_sock_cb(void *obj
, void *arg
, int flags
)
10862 struct iax2_peer
*peer
= obj
;
10864 if (peer
->sockfd
< 0)
10865 peer
->sockfd
= defaultsockfd
;
10870 /*! \brief Load IAX2 module, load configuraiton ---*/
10871 static int load_module(void)
10873 char *config
= "iax.conf";
10876 struct iax2_registry
*reg
= NULL
;
10878 peers
= ao2_container_alloc(MAX_PEER_BUCKETS
, peer_hash_cb
, peer_cmp_cb
);
10880 return AST_MODULE_LOAD_FAILURE
;
10881 users
= ao2_container_alloc(MAX_USER_BUCKETS
, user_hash_cb
, user_cmp_cb
);
10883 ao2_ref(peers
, -1);
10884 return AST_MODULE_LOAD_FAILURE
;
10887 ast_custom_function_register(&iaxpeer_function
);
10889 iax_set_output(iax_debug_output
);
10890 iax_set_error(iax_error_output
);
10891 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
10895 timingfd
= open("/dev/zap/timer", O_RDWR
);
10898 timingfd
= open("/dev/zap/pseudo", O_RDWR
);
10900 ast_log(LOG_WARNING
, "Unable to open IAX timing interface: %s\n", strerror(errno
));
10903 memset(iaxs
, 0, sizeof(iaxs
));
10905 for (x
=0;x
<IAX_MAX_CALLS
;x
++)
10906 ast_mutex_init(&iaxsl
[x
]);
10908 ast_cond_init(&sched_cond
, NULL
);
10910 io
= io_context_create();
10911 sched
= sched_context_create();
10913 if (!io
|| !sched
) {
10914 ast_log(LOG_ERROR
, "Out of memory\n");
10918 netsock
= ast_netsock_list_alloc();
10920 ast_log(LOG_ERROR
, "Could not allocate netsock list.\n");
10923 ast_netsock_init(netsock
);
10925 outsock
= ast_netsock_list_alloc();
10927 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
10930 ast_netsock_init(outsock
);
10932 ast_mutex_init(&waresl
.lock
);
10934 AST_LIST_HEAD_INIT(&iaxq
.queue
);
10936 ast_cli_register_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
10938 ast_register_application(papp
, iax2_prov_app
, psyn
, pdescrip
);
10940 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers
, "List IAX Peers" );
10941 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats
, "Show IAX Netstats" );
10943 if(set_config(config
, 0) == -1)
10944 return AST_MODULE_LOAD_DECLINE
;
10946 if (ast_channel_register(&iax2_tech
)) {
10947 ast_log(LOG_ERROR
, "Unable to register channel class %s\n", "IAX2");
10952 if (ast_register_switch(&iax2_switch
))
10953 ast_log(LOG_ERROR
, "Unable to register IAX switch\n");
10955 res
= start_network_thread();
10957 if (option_verbose
> 1)
10958 ast_verbose(VERBOSE_PREFIX_2
"IAX Ready and Listening\n");
10960 ast_log(LOG_ERROR
, "Unable to start network thread\n");
10961 ast_netsock_release(netsock
);
10962 ast_netsock_release(outsock
);
10965 AST_LIST_LOCK(®istrations
);
10966 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
10967 iax2_do_register(reg
);
10968 AST_LIST_UNLOCK(®istrations
);
10970 ao2_callback(peers
, 0, peer_set_sock_cb
, NULL
);
10971 ao2_callback(peers
, 0, iax2_poke_peer_cb
, NULL
);
10973 reload_firmware(0);
10974 iax_provision_reload();
10978 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Inter Asterisk eXchange (Ver 2)",
10979 .load
= load_module
,
10980 .unload
= unload_module
,