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>
62 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
63 #include <sys/ioctl.h>
64 #include "asterisk/dahdi_compat.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
131 #define DEBUG_SUPPORT
133 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
135 /* Sample over last 100 units to determine historic jitter */
138 static struct ast_codec_pref prefs
;
140 static const char tdesc
[] = "Inter Asterisk eXchange Driver (Ver 2)";
142 static char context
[80] = "default";
144 static char language
[MAX_LANGUAGE
] = "";
145 static char regcontext
[AST_MAX_CONTEXT
] = "";
147 static int maxauthreq
= 3;
148 static int max_retries
= 4;
149 static int ping_time
= 21;
150 static int lagrq_time
= 10;
151 static int maxjitterbuffer
=1000;
152 static int resyncthreshold
=1000;
153 static int maxjitterinterps
=10;
154 static int trunkfreq
= 20;
155 static int authdebug
= 1;
156 static int autokill
= 0;
157 static int iaxcompat
= 0;
159 static int iaxdefaultdpcache
=10 * 60; /* Cache dialplan entries for 10 minutes by default */
161 static int iaxdefaulttimeout
= 5; /* Default to wait no more than 5 seconds for a reply to come back */
163 static unsigned int tos
= 0;
165 static int min_reg_expire
;
166 static int max_reg_expire
;
168 static int timingfd
= -1; /* Timing file descriptor */
170 static struct ast_netsock_list
*netsock
;
171 static struct ast_netsock_list
*outsock
; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
172 static int defaultsockfd
= -1;
174 int (*iax2_regfunk
)(const char *username
, int onoff
) = NULL
;
177 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
179 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
180 ~AST_FORMAT_SLINEAR & \
185 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
187 ~AST_FORMAT_G726_AAL2 & \
190 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
194 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
195 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
196 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
198 static struct io_context
*io
;
199 static struct sched_context
*sched
;
201 static int iax2_capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
203 static int iaxdebug
= 0;
205 static int iaxtrunkdebug
= 0;
207 static int test_losspct
= 0;
209 static int test_late
= 0;
210 static int test_resync
= 0;
211 static int test_jit
= 0;
212 static int test_jitpct
= 0;
213 #endif /* IAXTESTS */
215 static char accountcode
[AST_MAX_ACCOUNT_CODE
];
216 static char mohinterpret
[MAX_MUSICCLASS
];
217 static char mohsuggest
[MAX_MUSICCLASS
];
218 static int amaflags
= 0;
220 static int delayreject
= 0;
221 static int iax2_encryption
= 0;
223 static struct ast_flags globalflags
= { 0 };
225 static pthread_t netthreadid
= AST_PTHREADT_NULL
;
226 static pthread_t schedthreadid
= AST_PTHREADT_NULL
;
227 AST_MUTEX_DEFINE_STATIC(sched_lock
);
228 static ast_cond_t sched_cond
;
231 IAX_STATE_STARTED
= (1 << 0),
232 IAX_STATE_AUTHENTICATED
= (1 << 1),
233 IAX_STATE_TBD
= (1 << 2),
234 IAX_STATE_UNCHANGED
= (1 << 3),
237 struct iax2_context
{
238 char context
[AST_MAX_CONTEXT
];
239 struct iax2_context
*next
;
243 IAX_HASCALLERID
= (1 << 0), /*!< CallerID has been specified */
244 IAX_DELME
= (1 << 1), /*!< Needs to be deleted */
245 IAX_TEMPONLY
= (1 << 2), /*!< Temporary (realtime) */
246 IAX_TRUNK
= (1 << 3), /*!< Treat as a trunk */
247 IAX_NOTRANSFER
= (1 << 4), /*!< Don't native bridge */
248 IAX_USEJITTERBUF
= (1 << 5), /*!< Use jitter buffer */
249 IAX_DYNAMIC
= (1 << 6), /*!< dynamic peer */
250 IAX_SENDANI
= (1 << 7), /*!< Send ANI along with CallerID */
251 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
252 IAX_ALREADYGONE
= (1 << 9), /*!< Already disconnected */
253 IAX_PROVISION
= (1 << 10), /*!< This is a provisioning request */
254 IAX_QUELCH
= (1 << 11), /*!< Whether or not we quelch audio */
255 IAX_ENCRYPTED
= (1 << 12), /*!< Whether we should assume encrypted tx/rx */
256 IAX_KEYPOPULATED
= (1 << 13), /*!< Whether we have a key populated */
257 IAX_CODEC_USER_FIRST
= (1 << 14), /*!< are we willing to let the other guy choose the codec? */
258 IAX_CODEC_NOPREFS
= (1 << 15), /*!< Force old behaviour by turning off prefs */
259 IAX_CODEC_NOCAP
= (1 << 16), /*!< only consider requested format and ignore capabilities*/
260 IAX_RTCACHEFRIENDS
= (1 << 17), /*!< let realtime stay till your reload */
261 IAX_RTUPDATE
= (1 << 18), /*!< Send a realtime update */
262 IAX_RTAUTOCLEAR
= (1 << 19), /*!< erase me on expire */
263 IAX_FORCEJITTERBUF
= (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
264 IAX_RTIGNOREREGEXPIRE
= (1 << 21), /*!< When using realtime, ignore registration expiration */
265 IAX_TRUNKTIMESTAMPS
= (1 << 22), /*!< Send trunk timestamps */
266 IAX_TRANSFERMEDIA
= (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
267 IAX_MAXAUTHREQ
= (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
268 IAX_DELAYPBXSTART
= (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
269 response, so that we've achieved a three-way handshake with
270 them before sending voice or anything else*/
271 IAX_ALLOWFWDOWNLOAD
= (1 << 26), /*!< Allow the FWDOWNL command? */
274 static int global_rtautoclear
= 120;
276 static int reload_config(void);
277 static int iax2_reload(int fd
, int argc
, char *argv
[]);
281 AST_DECLARE_STRING_FIELDS(
282 AST_STRING_FIELD(name
);
283 AST_STRING_FIELD(secret
);
284 AST_STRING_FIELD(dbsecret
);
285 AST_STRING_FIELD(accountcode
);
286 AST_STRING_FIELD(mohinterpret
);
287 AST_STRING_FIELD(mohsuggest
);
288 AST_STRING_FIELD(inkeys
); /*!< Key(s) this user can use to authenticate to us */
289 AST_STRING_FIELD(language
);
290 AST_STRING_FIELD(cid_num
);
291 AST_STRING_FIELD(cid_name
);
300 int maxauthreq
; /*!< Maximum allowed outstanding AUTHREQs */
301 int curauthreq
; /*!< Current number of outstanding AUTHREQs */
302 struct ast_codec_pref prefs
;
304 struct iax2_context
*contexts
;
305 struct ast_variable
*vars
;
309 AST_DECLARE_STRING_FIELDS(
310 AST_STRING_FIELD(name
);
311 AST_STRING_FIELD(username
);
312 AST_STRING_FIELD(secret
);
313 AST_STRING_FIELD(dbsecret
);
314 AST_STRING_FIELD(outkey
); /*!< What key we use to talk to this peer */
316 AST_STRING_FIELD(regexten
); /*!< Extension to register (if regcontext is used) */
317 AST_STRING_FIELD(context
); /*!< For transfers only */
318 AST_STRING_FIELD(peercontext
); /*!< Context to pass to peer */
319 AST_STRING_FIELD(mailbox
); /*!< Mailbox */
320 AST_STRING_FIELD(mohinterpret
);
321 AST_STRING_FIELD(mohsuggest
);
322 AST_STRING_FIELD(inkeys
); /*!< Key(s) this peer can use to authenticate to us */
323 /* Suggested caller id if registering */
324 AST_STRING_FIELD(cid_num
); /*!< Default context (for transfer really) */
325 AST_STRING_FIELD(cid_name
); /*!< Default context (for transfer really) */
326 AST_STRING_FIELD(zonetag
); /*!< Time Zone */
328 struct ast_codec_pref prefs
;
329 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
330 struct sockaddr_in addr
;
332 int sockfd
; /*!< Socket to use for transmission */
337 /* Dynamic Registration fields */
338 struct sockaddr_in defaddr
; /*!< Default address if there is one */
339 int authmethods
; /*!< Authentication methods (IAX_AUTH_*) */
340 int encmethods
; /*!< Encryption methods (IAX_ENCRYPT_*) */
342 int expire
; /*!< Schedule entry for expiry */
343 int expiry
; /*!< How soon to expire */
344 int capability
; /*!< Capability */
347 int callno
; /*!< Call number of POKE request */
348 int pokeexpire
; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
349 int lastms
; /*!< How long last response took (in ms), or -1 for no response */
350 int maxms
; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
352 int pokefreqok
; /*!< How often to check if the host is up */
353 int pokefreqnotok
; /*!< How often to check when the host has been determined to be down */
354 int historicms
; /*!< How long recent average responses took */
355 int smoothing
; /*!< Sample over how many units to determine historic ms */
360 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
362 static struct iax2_trunk_peer
{
365 struct sockaddr_in addr
;
366 struct timeval txtrunktime
; /*!< Transmit trunktime */
367 struct timeval rxtrunktime
; /*!< Receive trunktime */
368 struct timeval lasttxtime
; /*!< Last transmitted trunktime */
369 struct timeval trunkact
; /*!< Last trunk activity */
370 unsigned int lastsent
; /*!< Last sent time */
371 /* Trunk data and length */
372 unsigned char *trunkdata
;
373 unsigned int trunkdatalen
;
374 unsigned int trunkdataalloc
;
375 struct iax2_trunk_peer
*next
;
380 AST_MUTEX_DEFINE_STATIC(tpeerlock
);
382 struct iax_firmware
{
383 struct iax_firmware
*next
;
387 struct ast_iax2_firmware_header
*fwh
;
392 REG_STATE_UNREGISTERED
= 0,
395 REG_STATE_REGISTERED
,
401 enum iax_transfer_state
{
406 TRANSFER_PASSTHROUGH
,
410 TRANSFER_MPASSTHROUGH
,
415 struct iax2_registry
{
416 struct sockaddr_in addr
; /*!< Who we connect to for registration purposes */
418 char secret
[80]; /*!< Password or key name in []'s */
420 int expire
; /*!< Sched ID of expiration */
421 int refresh
; /*!< How often to refresh */
422 enum iax_reg_state regstate
;
423 int messages
; /*!< Message count, low 8 bits = new, high 8 bits = old */
424 int callno
; /*!< Associated call number if applicable */
425 struct sockaddr_in us
; /*!< Who the server thinks we are */
426 struct ast_dnsmgr_entry
*dnsmgr
; /*!< DNS refresh manager */
427 AST_LIST_ENTRY(iax2_registry
) entry
;
430 static AST_LIST_HEAD_STATIC(registrations
, iax2_registry
);
432 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
433 #define MIN_RETRY_TIME 100
434 #define MAX_RETRY_TIME 10000
436 #define MAX_JITTER_BUFFER 50
437 #define MIN_JITTER_BUFFER 10
439 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
440 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
442 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
444 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
445 #define TS_GAP_FOR_JB_RESYNC 5000
447 static int iaxthreadcount
= DEFAULT_THREAD_COUNT
;
448 static int iaxmaxthreadcount
= DEFAULT_MAX_THREAD_COUNT
;
449 static int iaxdynamicthreadcount
= 0;
450 static int iaxdynamicthreadnum
= 0;
451 static int iaxactivethreadcount
= 0;
463 struct chan_iax2_pvt
{
464 /*! Socket to send/receive on for this call */
466 /*! Last received voice format */
468 /*! Last received video format */
470 /*! Last sent voice format */
472 /*! Last sent video format */
474 /*! What we are capable of sending */
476 /*! Last received timestamp */
478 /*! Last sent timestamp - never send the same timestamp twice in a single call */
479 unsigned int lastsent
;
480 /*! Timestamp of the last video frame sent */
481 unsigned int lastvsent
;
482 /*! Next outgoing timestamp if everything is good */
483 unsigned int nextpred
;
484 /*! True if the last voice we transmitted was not silence/CNG */
487 unsigned int pingtime
;
488 /*! Max time for initial response */
491 struct sockaddr_in addr
;
492 /*! Actual used codec preferences */
493 struct ast_codec_pref prefs
;
494 /*! Requested codec preferences */
495 struct ast_codec_pref rprefs
;
496 /*! Our call number */
497 unsigned short callno
;
499 unsigned short peercallno
;
500 /*! Negotiated format, this is only used to remember what format was
501 chosen for an unauthenticated call so that the channel can get
502 created later using the right format */
504 /*! Peer selected format */
506 /*! Peer capability */
508 /*! timeval that we base our transmission on */
509 struct timeval offset
;
510 /*! timeval that we base our delivery on */
511 struct timeval rxcore
;
512 /*! The jitterbuffer */
514 /*! active jb read scheduler id */
518 /*! Error, as discovered by the manager */
520 /*! Owner if we have one */
521 struct ast_channel
*owner
;
522 /*! What's our state? */
523 struct ast_flags state
;
524 /*! Expiry (optional) */
526 /*! Next outgoing sequence number */
527 unsigned char oseqno
;
528 /*! Next sequence number they have not yet acknowledged */
529 unsigned char rseqno
;
530 /*! Next incoming sequence number */
531 unsigned char iseqno
;
532 /*! Last incoming sequence number we have acknowledged */
533 unsigned char aseqno
;
535 AST_DECLARE_STRING_FIELDS(
537 AST_STRING_FIELD(peer
);
538 /*! Default Context */
539 AST_STRING_FIELD(context
);
540 /*! Caller ID if available */
541 AST_STRING_FIELD(cid_num
);
542 AST_STRING_FIELD(cid_name
);
543 /*! Hidden Caller ID (i.e. ANI) if appropriate */
544 AST_STRING_FIELD(ani
);
546 AST_STRING_FIELD(dnid
);
548 AST_STRING_FIELD(rdnis
);
549 /*! Requested Extension */
550 AST_STRING_FIELD(exten
);
551 /*! Expected Username */
552 AST_STRING_FIELD(username
);
553 /*! Expected Secret */
554 AST_STRING_FIELD(secret
);
556 AST_STRING_FIELD(challenge
);
557 /*! Public keys permitted keys for incoming authentication */
558 AST_STRING_FIELD(inkeys
);
559 /*! Private key for outgoing authentication */
560 AST_STRING_FIELD(outkey
);
561 /*! Preferred language */
562 AST_STRING_FIELD(language
);
563 /*! Hostname/peername for naming purposes */
564 AST_STRING_FIELD(host
);
566 AST_STRING_FIELD(dproot
);
567 AST_STRING_FIELD(accountcode
);
568 AST_STRING_FIELD(mohinterpret
);
569 AST_STRING_FIELD(mohsuggest
);
572 /*! permitted authentication methods */
574 /*! permitted encryption methods */
576 /*! Encryption AES-128 Key */
578 /*! Decryption AES-128 Key */
580 /*! 32 bytes of semi-random data */
581 unsigned char semirand
[32];
582 /*! Associated registry */
583 struct iax2_registry
*reg
;
584 /*! Associated peer for poking */
585 struct iax2_peer
*peerpoke
;
590 /*! Transferring status */
591 enum iax_transfer_state transferring
;
592 /*! Transfer identifier */
594 /*! Who we are IAX transfering to */
595 struct sockaddr_in transfer
;
596 /*! What's the new call number for the transfer */
597 unsigned short transfercallno
;
598 /*! Transfer decrypt AES-128 Key */
599 aes_encrypt_ctx tdcx
;
601 /*! Status of knowledge of peer ADSI capability */
604 /*! Who we are bridged to */
605 unsigned short bridgecallno
;
607 int pingid
; /*!< Transmit PING request */
608 int lagid
; /*!< Retransmit lag request */
609 int autoid
; /*!< Auto hangup for Dialplan requestor */
610 int authid
; /*!< Authentication rejection ID */
611 int authfail
; /*!< Reason to report failure */
612 int initid
; /*!< Initial peer auto-congest ID (based on qualified peers) */
617 struct iax2_dpcache
*dpentries
;
618 struct ast_variable
*vars
;
619 /*! last received remote rr */
620 struct iax_rr remote_rr
;
621 /*! Current base time: (just for stats) */
623 /*! Dropped frame count: (just for stats) */
625 /*! received frame count: (just for stats) */
629 static struct ast_iax2_queue
{
630 AST_LIST_HEAD(, iax_frame
) queue
;
635 * This module will get much higher performance when doing a lot of
636 * user and peer lookups if the number of buckets is increased from 1.
637 * However, to maintain old behavior for Asterisk 1.4, these are set to
638 * 1 by default. When using multiple buckets, search order through these
639 * containers is considered random, so you will not be able to depend on
640 * the order the entires are specified in iax.conf for matching order. */
642 #define MAX_PEER_BUCKETS 1
643 /* #define MAX_PEER_BUCKETS 17 */
645 #define MAX_PEER_BUCKETS 1
646 /* #define MAX_PEER_BUCKETS 563 */
648 static struct ao2_container
*peers
;
650 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
651 static struct ao2_container
*users
;
653 static struct ast_firmware_list
{
654 struct iax_firmware
*wares
;
658 /*! Extension exists */
659 #define CACHE_FLAG_EXISTS (1 << 0)
660 /*! Extension is nonexistent */
661 #define CACHE_FLAG_NONEXISTENT (1 << 1)
662 /*! Extension can exist */
663 #define CACHE_FLAG_CANEXIST (1 << 2)
664 /*! Waiting to hear back response */
665 #define CACHE_FLAG_PENDING (1 << 3)
667 #define CACHE_FLAG_TIMEOUT (1 << 4)
668 /*! Request transmitted */
669 #define CACHE_FLAG_TRANSMITTED (1 << 5)
671 #define CACHE_FLAG_UNKNOWN (1 << 6)
673 #define CACHE_FLAG_MATCHMORE (1 << 7)
675 static struct iax2_dpcache
{
676 char peercontext
[AST_MAX_CONTEXT
];
677 char exten
[AST_MAX_EXTENSION
];
679 struct timeval expiry
;
681 unsigned short callno
;
683 struct iax2_dpcache
*next
;
684 struct iax2_dpcache
*peer
; /*!< For linking in peers */
687 AST_MUTEX_DEFINE_STATIC(dpcache_lock
);
689 static void reg_source_db(struct iax2_peer
*p
);
690 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
);
692 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
);
694 #define IAX_IOSTATE_IDLE 0
695 #define IAX_IOSTATE_READY 1
696 #define IAX_IOSTATE_PROCESSING 2
697 #define IAX_IOSTATE_SCHEDREADY 3
699 #define IAX_TYPE_POOL 1
700 #define IAX_TYPE_DYNAMIC 2
702 struct iax2_pkt_buf
{
703 AST_LIST_ENTRY(iax2_pkt_buf
) entry
;
705 unsigned char buf
[1];
709 AST_LIST_ENTRY(iax2_thread
) list
;
712 #ifdef SCHED_MULTITHREADED
713 void (*schedfunc
)(const void *);
714 const void *scheddata
;
716 #ifdef DEBUG_SCHED_MULTITHREAD
722 struct sockaddr_in iosin
;
723 unsigned char readbuf
[4096];
731 unsigned int ready_for_signal
:1;
732 /*! if this thread is processing a full frame,
733 some information about that frame will be stored
734 here, so we can avoid dispatching any more full
735 frames for that callno to other threads */
737 unsigned short callno
;
738 struct sockaddr_in sin
;
742 /*! Queued up full frames for processing. If more full frames arrive for
743 * a call which this thread is already processing a full frame for, they
744 * are queued up here. */
745 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf
) full_frames
;
749 static AST_LIST_HEAD_STATIC(idle_list
, iax2_thread
);
750 static AST_LIST_HEAD_STATIC(active_list
, iax2_thread
);
751 static AST_LIST_HEAD_STATIC(dynamic_list
, iax2_thread
);
753 static void *iax2_process_thread(void *data
);
755 static void signal_condition(ast_mutex_t
*lock
, ast_cond_t
*cond
)
757 ast_mutex_lock(lock
);
758 ast_cond_signal(cond
);
759 ast_mutex_unlock(lock
);
762 static void iax_debug_output(const char *data
)
765 ast_verbose("%s", data
);
768 static void iax_error_output(const char *data
)
770 ast_log(LOG_WARNING
, "%s", data
);
773 static void jb_error_output(const char *fmt
, ...)
779 vsnprintf(buf
, 1024, fmt
, args
);
782 ast_log(LOG_ERROR
, buf
);
785 static void jb_warning_output(const char *fmt
, ...)
791 vsnprintf(buf
, 1024, fmt
, args
);
794 ast_log(LOG_WARNING
, buf
);
797 static void jb_debug_output(const char *fmt
, ...)
803 vsnprintf(buf
, 1024, fmt
, args
);
809 /* XXX We probably should use a mutex when working with this XXX */
810 static struct chan_iax2_pvt
*iaxs
[IAX_MAX_CALLS
];
811 static ast_mutex_t iaxsl
[ARRAY_LEN(iaxs
)];
812 static struct timeval lastused
[ARRAY_LEN(iaxs
)];
815 * \brief Another container of iax2_pvt structures
817 * Active IAX2 pvt structs are also stored in this container, if they are a part
818 * of an active call where we know the remote side's call number. The reason
819 * for this is that incoming media frames do not contain our call number. So,
820 * instead of having to iterate the entire iaxs array, we use this container to
821 * look up calls where the remote side is using a given call number.
823 static struct ao2_container
*iax_peercallno_pvts
;
825 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
826 but keeps the division between trunked and non-trunked better. */
827 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
829 static int maxtrunkcall
= TRUNK_CALL_START
;
830 static int maxnontrunkcall
= 1;
832 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
);
833 static int expire_registry(const void *data
);
834 static int iax2_answer(struct ast_channel
*c
);
835 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
);
836 static int iax2_devicestate(void *data
);
837 static int iax2_digit_begin(struct ast_channel
*c
, char digit
);
838 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
);
839 static int iax2_do_register(struct iax2_registry
*reg
);
840 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
);
841 static int iax2_hangup(struct ast_channel
*c
);
842 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
);
843 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
844 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
845 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
);
846 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
);
847 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
);
848 static int iax2_sendtext(struct ast_channel
*c
, const char *text
);
849 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
);
850 static int iax2_transfer(struct ast_channel
*c
, const char *dest
);
851 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
);
852 static int send_command(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
853 static int send_command_final(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
854 static int send_command_immediate(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int, int);
855 static int send_command_locked(unsigned short callno
, char, int, unsigned int, const unsigned char *, int, int);
856 static int send_command_transfer(struct chan_iax2_pvt
*, char, int, unsigned int, const unsigned char *, int);
857 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
);
858 static struct ast_frame
*iax2_read(struct ast_channel
*c
);
859 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
860 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
);
861 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
);
862 static void prune_peers(void);
864 static const struct ast_channel_tech iax2_tech
= {
866 .description
= tdesc
,
867 .capabilities
= IAX_CAPABILITY_FULLBANDWIDTH
,
868 .properties
= AST_CHAN_TP_WANTSJITTER
,
869 .requester
= iax2_request
,
870 .devicestate
= iax2_devicestate
,
871 .send_digit_begin
= iax2_digit_begin
,
872 .send_digit_end
= iax2_digit_end
,
873 .send_text
= iax2_sendtext
,
874 .send_image
= iax2_sendimage
,
875 .send_html
= iax2_sendhtml
,
877 .hangup
= iax2_hangup
,
878 .answer
= iax2_answer
,
881 .write_video
= iax2_write
,
882 .indicate
= iax2_indicate
,
883 .setoption
= iax2_setoption
,
884 .bridge
= iax2_bridge
,
885 .transfer
= iax2_transfer
,
889 /* WARNING: insert_idle_thread should only ever be called within the
890 * context of an iax2_process_thread() thread.
892 static void insert_idle_thread(struct iax2_thread
*thread
)
894 if (thread
->type
== IAX_TYPE_DYNAMIC
) {
895 AST_LIST_LOCK(&dynamic_list
);
896 AST_LIST_INSERT_TAIL(&dynamic_list
, thread
, list
);
897 AST_LIST_UNLOCK(&dynamic_list
);
899 AST_LIST_LOCK(&idle_list
);
900 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
901 AST_LIST_UNLOCK(&idle_list
);
907 static struct iax2_thread
*find_idle_thread(void)
910 struct iax2_thread
*thread
= NULL
;
912 /* Pop the head of the list off */
913 AST_LIST_LOCK(&idle_list
);
914 thread
= AST_LIST_REMOVE_HEAD(&idle_list
, list
);
915 AST_LIST_UNLOCK(&idle_list
);
917 /* If no idle thread is available from the regular list, try dynamic */
918 if (thread
== NULL
) {
919 AST_LIST_LOCK(&dynamic_list
);
920 thread
= AST_LIST_REMOVE_HEAD(&dynamic_list
, list
);
921 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
922 if (thread
== NULL
&& iaxmaxthreadcount
> iaxdynamicthreadcount
) {
923 /* We need to MAKE a thread! */
924 if ((thread
= ast_calloc(1, sizeof(*thread
)))) {
925 thread
->threadnum
= iaxdynamicthreadnum
++;
926 thread
->type
= IAX_TYPE_DYNAMIC
;
927 ast_mutex_init(&thread
->lock
);
928 ast_cond_init(&thread
->cond
, NULL
);
929 pthread_attr_init(&attr
);
930 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
931 if (ast_pthread_create(&thread
->threadid
, &attr
, iax2_process_thread
, thread
)) {
935 /* All went well and the thread is up, so increment our count */
936 iaxdynamicthreadcount
++;
938 /* Wait for the thread to be ready before returning it to the caller */
939 while (!thread
->ready_for_signal
)
944 AST_LIST_UNLOCK(&dynamic_list
);
947 /* this thread is not processing a full frame (since it is idle),
948 so ensure that the field for the full frame call number is empty */
950 memset(&thread
->ffinfo
, 0, sizeof(thread
->ffinfo
));
955 #ifdef SCHED_MULTITHREADED
956 static int __schedule_action(void (*func
)(const void *data
), const void *data
, const char *funcname
)
958 struct iax2_thread
*thread
= NULL
;
959 static time_t lasterror
;
962 thread
= find_idle_thread();
964 if (thread
!= NULL
) {
965 thread
->schedfunc
= func
;
966 thread
->scheddata
= data
;
967 thread
->iostate
= IAX_IOSTATE_SCHEDREADY
;
968 #ifdef DEBUG_SCHED_MULTITHREAD
969 ast_copy_string(thread
->curfunc
, funcname
, sizeof(thread
->curfunc
));
971 signal_condition(&thread
->lock
, &thread
->cond
);
975 if (t
!= lasterror
&& option_debug
)
976 ast_log(LOG_DEBUG
, "Out of idle IAX2 threads for scheduling!\n");
981 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
984 static int iax2_sched_add(struct sched_context
*con
, int when
, ast_sched_cb callback
, const void *data
)
988 res
= ast_sched_add(con
, when
, callback
, data
);
989 signal_condition(&sched_lock
, &sched_cond
);
994 static int send_ping(const void *data
);
996 static void __send_ping(const void *data
)
998 int callno
= (long) data
;
1000 ast_mutex_lock(&iaxsl
[callno
]);
1003 if (iaxs
[callno
]->peercallno
) {
1004 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PING
, 0, NULL
, 0, -1);
1005 iaxs
[callno
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, data
);
1007 /* I am the schedule, so I'm allowed to do this */
1008 iaxs
[callno
]->pingid
= -1;
1010 } else if (option_debug
> 0) {
1011 ast_log(LOG_DEBUG
, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno
);
1014 ast_mutex_unlock(&iaxsl
[callno
]);
1017 static int send_ping(const void *data
)
1019 #ifdef SCHED_MULTITHREADED
1020 if (schedule_action(__send_ping
, data
))
1027 static int get_encrypt_methods(const char *s
)
1030 if (!strcasecmp(s
, "aes128"))
1031 e
= IAX_ENCRYPT_AES128
;
1032 else if (ast_true(s
))
1033 e
= IAX_ENCRYPT_AES128
;
1039 static int send_lagrq(const void *data
);
1041 static void __send_lagrq(const void *data
)
1043 int callno
= (long) data
;
1045 ast_mutex_lock(&iaxsl
[callno
]);
1048 if (iaxs
[callno
]->peercallno
) {
1049 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_LAGRQ
, 0, NULL
, 0, -1);
1050 iaxs
[callno
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, data
);
1052 /* I am the schedule, so I'm allowed to do this */
1053 iaxs
[callno
]->lagid
= -1;
1056 ast_log(LOG_WARNING
, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno
);
1059 ast_mutex_unlock(&iaxsl
[callno
]);
1062 static int send_lagrq(const void *data
)
1064 #ifdef SCHED_MULTITHREADED
1065 if (schedule_action(__send_lagrq
, data
))
1072 static unsigned char compress_subclass(int subclass
)
1076 /* If it's 128 or smaller, just return it */
1077 if (subclass
< IAX_FLAG_SC_LOG
)
1079 /* Otherwise find its power */
1080 for (x
= 0; x
< IAX_MAX_SHIFT
; x
++) {
1081 if (subclass
& (1 << x
)) {
1083 ast_log(LOG_WARNING
, "Can't compress subclass %d\n", subclass
);
1089 return power
| IAX_FLAG_SC_LOG
;
1092 static int uncompress_subclass(unsigned char csub
)
1094 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1095 if (csub
& IAX_FLAG_SC_LOG
) {
1096 /* special case for 'compressed' -1 */
1100 return 1 << (csub
& ~IAX_FLAG_SC_LOG
& IAX_MAX_SHIFT
);
1107 * \note The only member of the peer passed here guaranteed to be set is the name field
1109 static int peer_hash_cb(const void *obj
, const int flags
)
1111 const struct iax2_peer
*peer
= obj
;
1113 return ast_str_hash(peer
->name
);
1117 * \note The only member of the peer passed here guaranteed to be set is the name field
1119 static int peer_cmp_cb(void *obj
, void *arg
, int flags
)
1121 struct iax2_peer
*peer
= obj
, *peer2
= arg
;
1123 return !strcmp(peer
->name
, peer2
->name
) ? CMP_MATCH
| CMP_STOP
: 0;
1127 * \note The only member of the user passed here guaranteed to be set is the name field
1129 static int user_hash_cb(const void *obj
, const int flags
)
1131 const struct iax2_user
*user
= obj
;
1133 return ast_str_hash(user
->name
);
1137 * \note The only member of the user passed here guaranteed to be set is the name field
1139 static int user_cmp_cb(void *obj
, void *arg
, int flags
)
1141 struct iax2_user
*user
= obj
, *user2
= arg
;
1143 return !strcmp(user
->name
, user2
->name
) ? CMP_MATCH
| CMP_STOP
: 0;
1147 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1148 * so do not call it with a pvt lock held.
1150 static struct iax2_peer
*find_peer(const char *name
, int realtime
)
1152 struct iax2_peer
*peer
= NULL
;
1153 struct iax2_peer tmp_peer
= {
1157 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
1159 /* Now go for realtime if applicable */
1160 if(!peer
&& realtime
)
1161 peer
= realtime_peer(name
, NULL
);
1166 static struct iax2_peer
*peer_ref(struct iax2_peer
*peer
)
1172 static inline struct iax2_peer
*peer_unref(struct iax2_peer
*peer
)
1178 static inline struct iax2_user
*user_ref(struct iax2_user
*user
)
1184 static inline struct iax2_user
*user_unref(struct iax2_user
*user
)
1190 static int iax2_getpeername(struct sockaddr_in sin
, char *host
, int len
)
1192 struct iax2_peer
*peer
= NULL
;
1194 struct ao2_iterator i
;
1196 i
= ao2_iterator_init(peers
, 0);
1197 while ((peer
= ao2_iterator_next(&i
))) {
1198 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
1199 (peer
->addr
.sin_port
== sin
.sin_port
)) {
1200 ast_copy_string(host
, peer
->name
, len
);
1209 peer
= realtime_peer(NULL
, &sin
);
1211 ast_copy_string(host
, peer
->name
, len
);
1220 static void iax2_destroy_helper(struct chan_iax2_pvt
*pvt
)
1222 /* Decrement AUTHREQ count if needed */
1223 if (ast_test_flag(pvt
, IAX_MAXAUTHREQ
)) {
1224 struct iax2_user
*user
;
1225 struct iax2_user tmp_user
= {
1226 .name
= pvt
->username
,
1229 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
1231 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
1232 user
= user_unref(user
);
1235 ast_clear_flag(pvt
, IAX_MAXAUTHREQ
);
1238 /* No more pings or lagrq's */
1239 AST_SCHED_DEL(sched
, pvt
->pingid
);
1240 AST_SCHED_DEL(sched
, pvt
->lagid
);
1241 AST_SCHED_DEL(sched
, pvt
->autoid
);
1242 AST_SCHED_DEL(sched
, pvt
->authid
);
1243 AST_SCHED_DEL(sched
, pvt
->initid
);
1244 AST_SCHED_DEL(sched
, pvt
->jbid
);
1247 static void store_by_peercallno(struct chan_iax2_pvt
*pvt
)
1249 if (!pvt
->peercallno
) {
1250 ast_log(LOG_ERROR
, "This should not be called without a peer call number.\n");
1254 ao2_link(iax_peercallno_pvts
, pvt
);
1257 static void remove_by_peercallno(struct chan_iax2_pvt
*pvt
)
1259 if (!pvt
->peercallno
) {
1260 ast_log(LOG_ERROR
, "This should not be called without a peer call number.\n");
1264 ao2_unlink(iax_peercallno_pvts
, pvt
);
1267 static void update_max_trunk(void)
1269 int max
= TRUNK_CALL_START
;
1272 /* XXX Prolly don't need locks here XXX */
1273 for (x
= TRUNK_CALL_START
; x
< ARRAY_LEN(iaxs
) - 1; x
++) {
1280 if (option_debug
&& iaxdebug
)
1281 ast_log(LOG_DEBUG
, "New max trunk callno is %d\n", max
);
1284 static void iax2_frame_free(struct iax_frame
*fr
)
1286 AST_SCHED_DEL(sched
, fr
->retrans
);
1290 static void iax2_destroy(int callno
)
1292 struct chan_iax2_pvt
*pvt
;
1293 struct ast_channel
*owner
;
1297 gettimeofday(&lastused
[callno
], NULL
);
1299 owner
= pvt
? pvt
->owner
: NULL
;
1302 if (ast_mutex_trylock(&owner
->lock
)) {
1303 if (option_debug
> 2)
1304 ast_log(LOG_DEBUG
, "Avoiding IAX destroy deadlock\n");
1305 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1309 if (!owner
&& iaxs
[callno
]) {
1310 AST_SCHED_DEL_SPINLOCK(sched
, iaxs
[callno
]->lagid
, &iaxsl
[callno
]);
1311 AST_SCHED_DEL_SPINLOCK(sched
, iaxs
[callno
]->pingid
, &iaxsl
[callno
]);
1312 iaxs
[callno
] = NULL
;
1319 /* If there's an owner, prod it to give up */
1320 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
1321 * because we already hold the owner channel lock. */
1322 ast_queue_hangup(owner
);
1325 if (pvt
->peercallno
) {
1326 remove_by_peercallno(pvt
);
1336 ast_mutex_unlock(&owner
->lock
);
1339 if (callno
& 0x4000) {
1344 static void pvt_destructor(void *obj
)
1346 struct chan_iax2_pvt
*pvt
= obj
;
1347 struct iax_frame
*cur
= NULL
;
1349 iax2_destroy_helper(pvt
);
1352 ast_set_flag(pvt
, IAX_ALREADYGONE
);
1354 AST_LIST_LOCK(&iaxq
.queue
);
1355 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
1356 /* Cancel any pending transmissions */
1357 if (cur
->callno
== pvt
->callno
) {
1361 AST_LIST_UNLOCK(&iaxq
.queue
);
1364 pvt
->reg
->callno
= 0;
1370 ast_variables_destroy(pvt
->vars
);
1374 while (jb_getall(pvt
->jb
, &frame
) == JB_OK
) {
1375 iax2_frame_free(frame
.data
);
1378 jb_destroy(pvt
->jb
);
1379 ast_string_field_free_memory(pvt
);
1383 static struct chan_iax2_pvt
*new_iax(struct sockaddr_in
*sin
, const char *host
)
1385 struct chan_iax2_pvt
*tmp
;
1388 if (!(tmp
= ao2_alloc(sizeof(*tmp
), pvt_destructor
))) {
1392 if (ast_string_field_init(tmp
, 32)) {
1400 tmp
->peercallno
= 0;
1401 tmp
->transfercallno
= 0;
1402 tmp
->bridgecallno
= 0;
1409 ast_string_field_set(tmp
,exten
, "s");
1410 ast_string_field_set(tmp
,host
, host
);
1414 jbconf
.max_jitterbuf
= maxjitterbuffer
;
1415 jbconf
.resync_threshold
= resyncthreshold
;
1416 jbconf
.max_contig_interp
= maxjitterinterps
;
1417 jb_setconf(tmp
->jb
,&jbconf
);
1422 static struct iax_frame
*iaxfrdup2(struct iax_frame
*fr
)
1424 struct iax_frame
*new = iax_frame_new(DIRECTION_INGRESS
, fr
->af
.datalen
, fr
->cacheable
);
1426 size_t afdatalen
= new->afdatalen
;
1427 memcpy(new, fr
, sizeof(*new));
1428 iax_frame_wrap(new, &fr
->af
);
1429 new->afdatalen
= afdatalen
;
1432 new->direction
= DIRECTION_INGRESS
;
1438 #define NEW_PREVENT 0
1442 static int match(struct sockaddr_in
*sin
, unsigned short callno
, unsigned short dcallno
, struct chan_iax2_pvt
*cur
, int check_dcallno
)
1444 if ((cur
->addr
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1445 (cur
->addr
.sin_port
== sin
->sin_port
)) {
1446 /* This is the main host */
1447 if ( (cur
->peercallno
== 0 || cur
->peercallno
== callno
) &&
1448 (check_dcallno
? dcallno
== cur
->callno
: 1) ) {
1449 /* That's us. Be sure we keep track of the peer call number */
1453 if ((cur
->transfer
.sin_addr
.s_addr
== sin
->sin_addr
.s_addr
) &&
1454 (cur
->transfer
.sin_port
== sin
->sin_port
) && (cur
->transferring
)) {
1455 /* We're transferring */
1456 if ((dcallno
== cur
->callno
) || (cur
->transferring
== TRANSFER_MEDIAPASS
&& cur
->transfercallno
== callno
))
1462 static void update_max_nontrunk(void)
1466 /* XXX Prolly don't need locks here XXX */
1467 for (x
=1;x
<TRUNK_CALL_START
- 1; x
++) {
1471 maxnontrunkcall
= max
;
1472 if (option_debug
&& iaxdebug
)
1473 ast_log(LOG_DEBUG
, "New max nontrunk callno is %d\n", max
);
1476 static int make_trunk(unsigned short callno
, int locked
)
1481 if (iaxs
[callno
]->oseqno
) {
1482 ast_log(LOG_WARNING
, "Can't make trunk once a call has started!\n");
1485 if (callno
& TRUNK_CALL_START
) {
1486 ast_log(LOG_WARNING
, "Call %d is already a trunk\n", callno
);
1489 gettimeofday(&now
, NULL
);
1490 for (x
= TRUNK_CALL_START
; x
< ARRAY_LEN(iaxs
) - 1; x
++) {
1491 ast_mutex_lock(&iaxsl
[x
]);
1492 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) {
1493 /* Update the two timers that should have been started */
1495 * \note We delete these before switching the slot, because if
1496 * they fire in the meantime, they will generate a warning.
1498 AST_SCHED_DEL(sched
, iaxs
[callno
]->pingid
);
1499 AST_SCHED_DEL(sched
, iaxs
[callno
]->lagid
);
1500 iaxs
[x
] = iaxs
[callno
];
1501 iaxs
[x
]->callno
= x
;
1502 iaxs
[callno
] = NULL
;
1503 iaxs
[x
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, (void *)(long)x
);
1504 iaxs
[x
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1506 ast_mutex_unlock(&iaxsl
[callno
]);
1509 ast_mutex_unlock(&iaxsl
[x
]);
1512 ast_mutex_unlock(&iaxsl
[x
]);
1514 if (x
>= ARRAY_LEN(iaxs
) - 1) {
1515 ast_log(LOG_WARNING
, "Unable to trunk call: Insufficient space\n");
1519 ast_log(LOG_DEBUG
, "Made call %d into trunk call %d\n", callno
, x
);
1520 /* We move this call from a non-trunked to a trunked call */
1522 update_max_nontrunk();
1527 * \note Calling this function while holding another pvt lock can cause a deadlock.
1529 static int __find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int return_locked
, int check_dcallno
)
1536 if (new <= NEW_ALLOW
) {
1538 struct chan_iax2_pvt
*pvt
;
1539 struct chan_iax2_pvt tmp_pvt
= {
1541 .peercallno
= callno
,
1543 .frames_received
= check_dcallno
,
1546 memcpy(&tmp_pvt
.addr
, sin
, sizeof(tmp_pvt
.addr
));
1548 if ((pvt
= ao2_find(iax_peercallno_pvts
, &tmp_pvt
, OBJ_POINTER
))) {
1549 if (return_locked
) {
1550 ast_mutex_lock(&iaxsl
[pvt
->callno
]);
1559 /* This will occur on the first response to a message that we initiated,
1560 * such as a PING. */
1561 if (callno
&& dcallno
&& iaxs
[dcallno
] && !iaxs
[dcallno
]->peercallno
&& match(sin
, callno
, dcallno
, iaxs
[dcallno
], check_dcallno
)) {
1562 iaxs
[dcallno
]->peercallno
= callno
;
1564 store_by_peercallno(iaxs
[dcallno
]);
1569 /* If we get here, we SHOULD NOT find a call structure for this
1570 callno; if we do, it means that there is a call structure that
1571 has a peer callno but did NOT get entered into the hash table,
1574 If we find a call structure using this old, slow method, output a log
1575 message so we'll know about it. After a few months of leaving this in
1576 place, if we don't hear about people seeing these messages, we can
1577 remove this code for good.
1580 for (x
= 1; !res
&& x
< maxnontrunkcall
; x
++) {
1581 ast_mutex_lock(&iaxsl
[x
]);
1583 /* Look for an exact match */
1584 if (match(sin
, callno
, dcallno
, iaxs
[x
], check_dcallno
)) {
1588 if (!res
|| !return_locked
)
1589 ast_mutex_unlock(&iaxsl
[x
]);
1592 for (x
= TRUNK_CALL_START
; !res
&& x
< maxtrunkcall
; x
++) {
1593 ast_mutex_lock(&iaxsl
[x
]);
1595 /* Look for an exact match */
1596 if (match(sin
, callno
, dcallno
, iaxs
[x
], check_dcallno
)) {
1600 if (!res
|| !return_locked
)
1601 ast_mutex_unlock(&iaxsl
[x
]);
1605 ast_log(LOG_WARNING
, "Old call search code found call number %d that was not in hash table!\n", res
);
1609 if (!res
&& (new >= NEW_ALLOW
)) {
1610 int start
, found
= 0;
1612 /* It may seem odd that we look through the peer list for a name for
1613 * this *incoming* call. Well, it is weird. However, users don't
1614 * have an IP address/port number that we can match against. So,
1615 * this is just checking for a peer that has that IP/port and
1616 * assuming that we have a user of the same name. This isn't always
1617 * correct, but it will be changed if needed after authentication. */
1618 if (!iax2_getpeername(*sin
, host
, sizeof(host
)))
1619 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
1622 start
= 2 + (ast_random() % (TRUNK_CALL_START
- 1));
1623 for (x
= start
; 1; x
++) {
1624 if (x
== TRUNK_CALL_START
) {
1629 /* Find first unused call number that hasn't been used in a while */
1630 ast_mutex_lock(&iaxsl
[x
]);
1631 if (!iaxs
[x
] && ((now
.tv_sec
- lastused
[x
].tv_sec
) > MIN_REUSE_TIME
)) {
1635 ast_mutex_unlock(&iaxsl
[x
]);
1637 if (x
== start
- 1) {
1641 /* We've still got lock held if we found a spot */
1642 if (x
== start
- 1 && !found
) {
1643 ast_log(LOG_WARNING
, "No more space\n");
1646 iaxs
[x
] = new_iax(sin
, host
);
1647 update_max_nontrunk();
1649 if (option_debug
&& iaxdebug
)
1650 ast_log(LOG_DEBUG
, "Creating new call structure %d\n", x
);
1651 iaxs
[x
]->sockfd
= sockfd
;
1652 iaxs
[x
]->addr
.sin_port
= sin
->sin_port
;
1653 iaxs
[x
]->addr
.sin_family
= sin
->sin_family
;
1654 iaxs
[x
]->addr
.sin_addr
.s_addr
= sin
->sin_addr
.s_addr
;
1655 iaxs
[x
]->peercallno
= callno
;
1656 iaxs
[x
]->callno
= x
;
1657 iaxs
[x
]->pingtime
= DEFAULT_RETRY_TIME
;
1658 iaxs
[x
]->expiry
= min_reg_expire
;
1659 iaxs
[x
]->pingid
= iax2_sched_add(sched
, ping_time
* 1000, send_ping
, (void *)(long)x
);
1660 iaxs
[x
]->lagid
= iax2_sched_add(sched
, lagrq_time
* 1000, send_lagrq
, (void *)(long)x
);
1661 iaxs
[x
]->amaflags
= amaflags
;
1662 ast_copy_flags(iaxs
[x
], (&globalflags
), IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
1664 ast_string_field_set(iaxs
[x
], accountcode
, accountcode
);
1665 ast_string_field_set(iaxs
[x
], mohinterpret
, mohinterpret
);
1666 ast_string_field_set(iaxs
[x
], mohsuggest
, mohsuggest
);
1668 if (iaxs
[x
]->peercallno
) {
1669 store_by_peercallno(iaxs
[x
]);
1672 ast_log(LOG_WARNING
, "Out of resources\n");
1673 ast_mutex_unlock(&iaxsl
[x
]);
1677 ast_mutex_unlock(&iaxsl
[x
]);
1683 static int find_callno(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int full_frame
) {
1685 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 0, full_frame
);
1688 static int find_callno_locked(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int new, int sockfd
, int full_frame
) {
1690 return __find_callno(callno
, dcallno
, sin
, new, sockfd
, 1, full_frame
);
1694 * \brief Queue a frame to a call's owning asterisk channel
1696 * \pre This function assumes that iaxsl[callno] is locked when called.
1698 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1699 * was valid before calling it, it may no longer be valid after calling it.
1700 * This function may unlock and lock the mutex associated with this callno,
1701 * meaning that another thread may grab it and destroy the call.
1703 static int iax2_queue_frame(int callno
, struct ast_frame
*f
)
1706 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1707 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1708 /* Avoid deadlock by pausing and trying again */
1709 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1711 ast_queue_frame(iaxs
[callno
]->owner
, f
);
1712 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1722 * \brief Queue a hangup frame on the ast_channel owner
1724 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1725 * is active for the given call number.
1727 * \pre Assumes lock for callno is already held.
1729 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1730 * was valid before calling it, it may no longer be valid after calling it.
1731 * This function may unlock and lock the mutex associated with this callno,
1732 * meaning that another thread may grab it and destroy the call.
1734 static int iax2_queue_hangup(int callno
)
1737 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1738 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1739 /* Avoid deadlock by pausing and trying again */
1740 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1742 ast_queue_hangup(iaxs
[callno
]->owner
);
1743 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1753 * \brief Queue a control frame on the ast_channel owner
1755 * This function queues a control frame on the owner of the IAX2 pvt struct that
1756 * is active for the given call number.
1758 * \pre Assumes lock for callno is already held.
1760 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1761 * was valid before calling it, it may no longer be valid after calling it.
1762 * This function may unlock and lock the mutex associated with this callno,
1763 * meaning that another thread may grab it and destroy the call.
1765 static int iax2_queue_control_data(int callno
,
1766 enum ast_control_frame_type control
, const void *data
, size_t datalen
)
1769 if (iaxs
[callno
] && iaxs
[callno
]->owner
) {
1770 if (ast_mutex_trylock(&iaxs
[callno
]->owner
->lock
)) {
1771 /* Avoid deadlock by pausing and trying again */
1772 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
1774 ast_queue_control_data(iaxs
[callno
]->owner
, control
, data
, datalen
);
1775 ast_mutex_unlock(&iaxs
[callno
]->owner
->lock
);
1783 static void destroy_firmware(struct iax_firmware
*cur
)
1785 /* Close firmware */
1787 munmap((void*)cur
->fwh
, ntohl(cur
->fwh
->datalen
) + sizeof(*(cur
->fwh
)));
1793 static int try_firmware(char *s
)
1796 struct iax_firmware
*cur
;
1801 struct ast_iax2_firmware_header
*fwh
, fwh2
;
1802 struct MD5Context md5
;
1803 unsigned char sum
[16];
1804 unsigned char buf
[1024];
1808 s2
= alloca(strlen(s
) + 100);
1810 ast_log(LOG_WARNING
, "Alloca failed!\n");
1813 last
= strrchr(s
, '/');
1818 snprintf(s2
, strlen(s
) + 100, "/var/tmp/%s-%ld", last
, (unsigned long)ast_random());
1819 res
= stat(s
, &stbuf
);
1821 ast_log(LOG_WARNING
, "Failed to stat '%s': %s\n", s
, strerror(errno
));
1824 /* Make sure it's not a directory */
1825 if (S_ISDIR(stbuf
.st_mode
))
1827 ifd
= open(s
, O_RDONLY
);
1829 ast_log(LOG_WARNING
, "Cannot open '%s': %s\n", s
, strerror(errno
));
1832 fd
= open(s2
, O_RDWR
| O_CREAT
| O_EXCL
, 0600);
1834 ast_log(LOG_WARNING
, "Cannot open '%s' for writing: %s\n", s2
, strerror(errno
));
1838 /* Unlink our newly created file */
1841 /* Now copy the firmware into it */
1842 len
= stbuf
.st_size
;
1845 if (chunk
> sizeof(buf
))
1846 chunk
= sizeof(buf
);
1847 res
= read(ifd
, buf
, chunk
);
1849 ast_log(LOG_WARNING
, "Only read %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1854 res
= write(fd
, buf
, chunk
);
1856 ast_log(LOG_WARNING
, "Only write %d of %d bytes of data :(: %s\n", res
, chunk
, strerror(errno
));
1864 /* Return to the beginning */
1865 lseek(fd
, 0, SEEK_SET
);
1866 if ((res
= read(fd
, &fwh2
, sizeof(fwh2
))) != sizeof(fwh2
)) {
1867 ast_log(LOG_WARNING
, "Unable to read firmware header in '%s'\n", s
);
1871 if (ntohl(fwh2
.magic
) != IAX_FIRMWARE_MAGIC
) {
1872 ast_log(LOG_WARNING
, "'%s' is not a valid firmware file\n", s
);
1876 if (ntohl(fwh2
.datalen
) != (stbuf
.st_size
- sizeof(fwh2
))) {
1877 ast_log(LOG_WARNING
, "Invalid data length in firmware '%s'\n", s
);
1881 if (fwh2
.devname
[sizeof(fwh2
.devname
) - 1] || ast_strlen_zero((char *)fwh2
.devname
)) {
1882 ast_log(LOG_WARNING
, "No or invalid device type specified for '%s'\n", s
);
1886 fwh
= (struct ast_iax2_firmware_header
*)mmap(NULL
, stbuf
.st_size
, PROT_READ
, MAP_PRIVATE
, fd
, 0);
1887 if (fwh
== (void *) -1) {
1888 ast_log(LOG_WARNING
, "mmap failed: %s\n", strerror(errno
));
1893 MD5Update(&md5
, fwh
->data
, ntohl(fwh
->datalen
));
1894 MD5Final(sum
, &md5
);
1895 if (memcmp(sum
, fwh
->chksum
, sizeof(sum
))) {
1896 ast_log(LOG_WARNING
, "Firmware file '%s' fails checksum\n", s
);
1897 munmap((void*)fwh
, stbuf
.st_size
);
1903 if (!strcmp((char *)cur
->fwh
->devname
, (char *)fwh
->devname
)) {
1904 /* Found a candidate */
1905 if (cur
->dead
|| (ntohs(cur
->fwh
->version
) < ntohs(fwh
->version
)))
1906 /* The version we have on loaded is older, load this one instead */
1908 /* This version is no newer than what we have. Don't worry about it.
1909 We'll consider it a proper load anyhow though */
1910 munmap((void*)fwh
, stbuf
.st_size
);
1917 /* Allocate a new one and link it */
1918 if ((cur
= ast_calloc(1, sizeof(*cur
)))) {
1920 cur
->next
= waresl
.wares
;
1926 munmap((void*)cur
->fwh
, cur
->mmaplen
);
1932 cur
->mmaplen
= stbuf
.st_size
;
1938 static int iax_check_version(char *dev
)
1941 struct iax_firmware
*cur
;
1942 if (!ast_strlen_zero(dev
)) {
1943 ast_mutex_lock(&waresl
.lock
);
1946 if (!strcmp(dev
, (char *)cur
->fwh
->devname
)) {
1947 res
= ntohs(cur
->fwh
->version
);
1952 ast_mutex_unlock(&waresl
.lock
);
1957 static int iax_firmware_append(struct iax_ie_data
*ied
, const unsigned char *dev
, unsigned int desc
)
1960 unsigned int bs
= desc
& 0xff;
1961 unsigned int start
= (desc
>> 8) & 0xffffff;
1963 struct iax_firmware
*cur
;
1964 if (!ast_strlen_zero((char *)dev
) && bs
) {
1966 ast_mutex_lock(&waresl
.lock
);
1969 if (!strcmp((char *)dev
, (char *)cur
->fwh
->devname
)) {
1970 iax_ie_append_int(ied
, IAX_IE_FWBLOCKDESC
, desc
);
1971 if (start
< ntohl(cur
->fwh
->datalen
)) {
1972 bytes
= ntohl(cur
->fwh
->datalen
) - start
;
1975 iax_ie_append_raw(ied
, IAX_IE_FWBLOCKDATA
, cur
->fwh
->data
+ start
, bytes
);
1978 iax_ie_append(ied
, IAX_IE_FWBLOCKDATA
);
1988 ast_mutex_unlock(&waresl
.lock
);
1994 static void reload_firmware(int unload
)
1996 struct iax_firmware
*cur
, *curl
, *curp
;
2001 /* Mark all as dead */
2002 ast_mutex_lock(&waresl
.lock
);
2009 /* Now that we've freed them, load the new ones */
2011 snprintf(dir
, sizeof(dir
), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR
);
2014 while((de
= readdir(fwd
))) {
2015 if (de
->d_name
[0] != '.') {
2016 snprintf(fn
, sizeof(fn
), "%s/%s", dir
, de
->d_name
);
2017 if (!try_firmware(fn
)) {
2018 if (option_verbose
> 1)
2019 ast_verbose(VERBOSE_PREFIX_2
"Loaded firmware '%s'\n", de
->d_name
);
2025 ast_log(LOG_WARNING
, "Error opening firmware directory '%s': %s\n", dir
, strerror(errno
));
2028 /* Clean up leftovers */
2040 destroy_firmware(curl
);
2045 ast_mutex_unlock(&waresl
.lock
);
2049 * \note This function assumes that iaxsl[callno] is locked when called.
2051 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2052 * was valid before calling it, it may no longer be valid after calling it.
2053 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2054 * associated with this callno, meaning that another thread may grab it and destroy the call.
2056 static int __do_deliver(void *data
)
2058 /* Just deliver the packet by using queueing. This is called by
2059 the IAX thread with the iaxsl lock held. */
2060 struct iax_frame
*fr
= data
;
2062 ast_clear_flag(&fr
->af
, AST_FRFLAG_HAS_TIMING_INFO
);
2063 if (iaxs
[fr
->callno
] && !ast_test_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
))
2064 iax2_queue_frame(fr
->callno
, &fr
->af
);
2065 /* Free our iax frame */
2066 iax2_frame_free(fr
);
2067 /* And don't run again */
2071 static int handle_error(void)
2073 /* XXX Ideally we should figure out why an error occured and then abort those
2074 rather than continuing to try. Unfortunately, the published interface does
2075 not seem to work XXX */
2077 struct sockaddr_in
*sin
;
2080 struct sock_extended_err e
;
2085 m
.msg_controllen
= sizeof(e
);
2087 res
= recvmsg(netsocket
, &m
, MSG_ERRQUEUE
);
2089 ast_log(LOG_WARNING
, "Error detected, but unable to read error: %s\n", strerror(errno
));
2091 if (m
.msg_controllen
) {
2092 sin
= (struct sockaddr_in
*)SO_EE_OFFENDER(&e
);
2094 ast_log(LOG_WARNING
, "Receive error from %s\n", ast_inet_ntoa(sin
->sin_addr
));
2096 ast_log(LOG_WARNING
, "No address detected??\n");
2098 ast_log(LOG_WARNING
, "Local error: %s\n", strerror(e
.ee_errno
));
2105 static int transmit_trunk(struct iax_frame
*f
, struct sockaddr_in
*sin
, int sockfd
)
2108 res
= sendto(sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)sin
,
2112 ast_log(LOG_DEBUG
, "Received error: %s\n", strerror(errno
));
2119 static int send_packet(struct iax_frame
*f
)
2122 int callno
= f
->callno
;
2124 /* Don't send if there was an error, but return error instead */
2125 if (!callno
|| !iaxs
[callno
] || iaxs
[callno
]->error
)
2128 /* Called with iaxsl held */
2129 if (option_debug
> 2 && iaxdebug
)
2130 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
));
2133 iax_showframe(f
, NULL
, 0, &iaxs
[callno
]->transfer
, f
->datalen
- sizeof(struct ast_iax2_full_hdr
));
2134 res
= sendto(iaxs
[callno
]->sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)&iaxs
[callno
]->transfer
,
2135 sizeof(iaxs
[callno
]->transfer
));
2138 iax_showframe(f
, NULL
, 0, &iaxs
[callno
]->addr
, f
->datalen
- sizeof(struct ast_iax2_full_hdr
));
2139 res
= sendto(iaxs
[callno
]->sockfd
, f
->data
, f
->datalen
, 0,(struct sockaddr
*)&iaxs
[callno
]->addr
,
2140 sizeof(iaxs
[callno
]->addr
));
2143 if (option_debug
&& iaxdebug
)
2144 ast_log(LOG_DEBUG
, "Received error: %s\n", strerror(errno
));
2152 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2153 * for the given call number may disappear during its execution.
2155 static int iax2_predestroy(int callno
)
2157 struct ast_channel
*c
;
2158 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
2162 if (!ast_test_flag(pvt
, IAX_ALREADYGONE
)) {
2163 iax2_destroy_helper(pvt
);
2164 ast_set_flag(pvt
, IAX_ALREADYGONE
);
2169 iax2_queue_hangup(callno
);
2171 ast_module_unref(ast_module_info
->self
);
2176 static int update_packet(struct iax_frame
*f
)
2178 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2179 struct ast_iax2_full_hdr
*fh
= f
->data
;
2180 /* Mark this as a retransmission */
2181 fh
->dcallno
= ntohs(IAX_FLAG_RETRANS
| f
->dcallno
);
2183 f
->iseqno
= iaxs
[f
->callno
]->iseqno
;
2184 fh
->iseqno
= f
->iseqno
;
2188 static int attempt_transmit(const void *data
);
2189 static void __attempt_transmit(const void *data
)
2191 /* Attempt to transmit the frame to the remote peer...
2192 Called without iaxsl held. */
2193 struct iax_frame
*f
= (struct iax_frame
*)data
;
2195 int callno
= f
->callno
;
2196 /* Make sure this call is still active */
2198 ast_mutex_lock(&iaxsl
[callno
]);
2199 if (callno
&& iaxs
[callno
]) {
2200 if ((f
->retries
< 0) /* Already ACK'd */ ||
2201 (f
->retries
>= max_retries
) /* Too many attempts */) {
2202 /* Record an error if we've transmitted too many times */
2203 if (f
->retries
>= max_retries
) {
2205 /* Transfer timeout */
2206 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, NULL
, 0, -1);
2207 } else if (f
->final
) {
2209 iax2_destroy(callno
);
2211 if (iaxs
[callno
]->owner
)
2212 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
);
2213 iaxs
[callno
]->error
= ETIMEDOUT
;
2214 if (iaxs
[callno
]->owner
) {
2215 struct ast_frame fr
= { 0, };
2217 fr
.frametype
= AST_FRAME_CONTROL
;
2218 fr
.subclass
= AST_CONTROL_HANGUP
;
2219 iax2_queue_frame(callno
, &fr
); // XXX
2220 /* Remember, owner could disappear */
2221 if (iaxs
[callno
] && iaxs
[callno
]->owner
)
2222 iaxs
[callno
]->owner
->hangupcause
= AST_CAUSE_DESTINATION_OUT_OF_ORDER
;
2224 if (iaxs
[callno
]->reg
) {
2225 memset(&iaxs
[callno
]->reg
->us
, 0, sizeof(iaxs
[callno
]->reg
->us
));
2226 iaxs
[callno
]->reg
->regstate
= REG_STATE_TIMEOUT
;
2227 iaxs
[callno
]->reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
2229 iax2_destroy(callno
);
2236 /* Update it if it needs it */
2238 /* Attempt transmission */
2241 /* Try again later after 10 times as long */
2243 if (f
->retrytime
> MAX_RETRY_TIME
)
2244 f
->retrytime
= MAX_RETRY_TIME
;
2245 /* Transfer messages max out at one second */
2246 if (f
->transfer
&& (f
->retrytime
> 1000))
2247 f
->retrytime
= 1000;
2248 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
2251 /* Make sure it gets freed */
2256 ast_mutex_unlock(&iaxsl
[callno
]);
2257 /* Do not try again */
2259 /* Don't attempt delivery, just remove it from the queue */
2260 AST_LIST_LOCK(&iaxq
.queue
);
2261 AST_LIST_REMOVE(&iaxq
.queue
, f
, list
);
2263 AST_LIST_UNLOCK(&iaxq
.queue
);
2265 /* Free the IAX frame */
2270 static int attempt_transmit(const void *data
)
2272 #ifdef SCHED_MULTITHREADED
2273 if (schedule_action(__attempt_transmit
, data
))
2275 __attempt_transmit(data
);
2279 static int iax2_prune_realtime(int fd
, int argc
, char *argv
[])
2281 struct iax2_peer
*peer
;
2284 return RESULT_SHOWUSAGE
;
2285 if (!strcmp(argv
[3],"all")) {
2287 ast_cli(fd
, "OK cache is flushed.\n");
2288 } else if ((peer
= find_peer(argv
[3], 0))) {
2289 if(ast_test_flag(peer
, IAX_RTCACHEFRIENDS
)) {
2290 ast_set_flag(peer
, IAX_RTAUTOCLEAR
);
2291 expire_registry(peer_ref(peer
));
2292 ast_cli(fd
, "OK peer %s was removed from the cache.\n", argv
[3]);
2294 ast_cli(fd
, "SORRY peer %s is not eligible for this operation.\n", argv
[3]);
2298 ast_cli(fd
, "SORRY peer %s was not found in the cache.\n", argv
[3]);
2301 return RESULT_SUCCESS
;
2304 static int iax2_test_losspct(int fd
, int argc
, char *argv
[])
2307 return RESULT_SHOWUSAGE
;
2309 test_losspct
= atoi(argv
[3]);
2311 return RESULT_SUCCESS
;
2315 static int iax2_test_late(int fd
, int argc
, char *argv
[])
2318 return RESULT_SHOWUSAGE
;
2320 test_late
= atoi(argv
[3]);
2322 return RESULT_SUCCESS
;
2325 static int iax2_test_resync(int fd
, int argc
, char *argv
[])
2328 return RESULT_SHOWUSAGE
;
2330 test_resync
= atoi(argv
[3]);
2332 return RESULT_SUCCESS
;
2335 static int iax2_test_jitter(int fd
, int argc
, char *argv
[])
2337 if (argc
< 4 || argc
> 5)
2338 return RESULT_SHOWUSAGE
;
2340 test_jit
= atoi(argv
[3]);
2342 test_jitpct
= atoi(argv
[4]);
2344 return RESULT_SUCCESS
;
2346 #endif /* IAXTESTS */
2348 /*! \brief peer_status: Report Peer status in character string */
2349 /* returns 1 if peer is online, -1 if unmonitored */
2350 static int peer_status(struct iax2_peer
*peer
, char *status
, int statuslen
)
2354 if (peer
->lastms
< 0) {
2355 ast_copy_string(status
, "UNREACHABLE", statuslen
);
2356 } else if (peer
->lastms
> peer
->maxms
) {
2357 snprintf(status
, statuslen
, "LAGGED (%d ms)", peer
->lastms
);
2359 } else if (peer
->lastms
) {
2360 snprintf(status
, statuslen
, "OK (%d ms)", peer
->lastms
);
2363 ast_copy_string(status
, "UNKNOWN", statuslen
);
2366 ast_copy_string(status
, "Unmonitored", statuslen
);
2372 /*! \brief Show one peer in detail */
2373 static int iax2_show_peer(int fd
, int argc
, char *argv
[])
2377 struct iax2_peer
*peer
;
2378 char codec_buf
[512];
2379 int x
= 0, codec
= 0, load_realtime
= 0;
2382 return RESULT_SHOWUSAGE
;
2384 load_realtime
= (argc
== 5 && !strcmp(argv
[4], "load")) ? 1 : 0;
2386 peer
= find_peer(argv
[3], load_realtime
);
2389 ast_cli(fd
, " * Name : %s\n", peer
->name
);
2390 ast_cli(fd
, " Secret : %s\n", ast_strlen_zero(peer
->secret
)?"<Not set>":"<Set>");
2391 ast_cli(fd
, " Context : %s\n", peer
->context
);
2392 ast_cli(fd
, " Mailbox : %s\n", peer
->mailbox
);
2393 ast_cli(fd
, " Dynamic : %s\n", ast_test_flag(peer
, IAX_DYNAMIC
) ? "Yes":"No");
2394 ast_cli(fd
, " Callerid : %s\n", ast_callerid_merge(cbuf
, sizeof(cbuf
), peer
->cid_name
, peer
->cid_num
, "<unspecified>"));
2395 ast_cli(fd
, " Expire : %d\n", peer
->expire
);
2396 ast_cli(fd
, " ACL : %s\n", (peer
->ha
?"Yes":"No"));
2397 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
));
2398 ast_cli(fd
, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer
->defaddr
.sin_addr
), ntohs(peer
->defaddr
.sin_port
));
2399 ast_cli(fd
, " Username : %s\n", peer
->username
);
2400 ast_cli(fd
, " Codecs : ");
2401 ast_getformatname_multiple(codec_buf
, sizeof(codec_buf
) -1, peer
->capability
);
2402 ast_cli(fd
, "%s\n", codec_buf
);
2404 ast_cli(fd
, " Codec Order : (");
2405 for(x
= 0; x
< 32 ; x
++) {
2406 codec
= ast_codec_pref_index(&peer
->prefs
,x
);
2409 ast_cli(fd
, "%s", ast_getformatname(codec
));
2410 if(x
< 31 && ast_codec_pref_index(&peer
->prefs
,x
+1))
2415 ast_cli(fd
, "none");
2418 ast_cli(fd
, " Status : ");
2419 peer_status(peer
, status
, sizeof(status
));
2420 ast_cli(fd
, "%s\n",status
);
2421 ast_cli(fd
, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer
->pokefreqok
, peer
->pokefreqnotok
, peer
->smoothing
? "On" : "Off");
2425 ast_cli(fd
,"Peer %s not found.\n", argv
[3]);
2429 return RESULT_SUCCESS
;
2432 static char *complete_iax2_show_peer(const char *line
, const char *word
, int pos
, int state
)
2435 struct iax2_peer
*peer
;
2437 int wordlen
= strlen(word
);
2438 struct ao2_iterator i
;
2440 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2444 i
= ao2_iterator_init(peers
, 0);
2445 while ((peer
= ao2_iterator_next(&i
))) {
2446 if (!strncasecmp(peer
->name
, word
, wordlen
) && ++which
> state
) {
2447 res
= ast_strdup(peer
->name
);
2457 static int iax2_show_stats(int fd
, int argc
, char *argv
[])
2459 struct iax_frame
*cur
;
2460 int cnt
= 0, dead
=0, final
=0;
2463 return RESULT_SHOWUSAGE
;
2465 AST_LIST_LOCK(&iaxq
.queue
);
2466 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
2467 if (cur
->retries
< 0)
2473 AST_LIST_UNLOCK(&iaxq
.queue
);
2475 ast_cli(fd
, " IAX Statistics\n");
2476 ast_cli(fd
, "---------------------\n");
2477 ast_cli(fd
, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2478 ast_cli(fd
, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead
, final
, cnt
);
2480 return RESULT_SUCCESS
;
2483 static int iax2_show_cache(int fd
, int argc
, char *argv
[])
2485 struct iax2_dpcache
*dp
;
2486 char tmp
[1024], *pc
;
2490 gettimeofday(&tv
, NULL
);
2491 ast_mutex_lock(&dpcache_lock
);
2493 ast_cli(fd
, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2495 s
= dp
->expiry
.tv_sec
- tv
.tv_sec
;
2497 if (dp
->flags
& CACHE_FLAG_EXISTS
)
2498 strncat(tmp
, "EXISTS|", sizeof(tmp
) - strlen(tmp
) - 1);
2499 if (dp
->flags
& CACHE_FLAG_NONEXISTENT
)
2500 strncat(tmp
, "NONEXISTENT|", sizeof(tmp
) - strlen(tmp
) - 1);
2501 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
2502 strncat(tmp
, "CANEXIST|", sizeof(tmp
) - strlen(tmp
) - 1);
2503 if (dp
->flags
& CACHE_FLAG_PENDING
)
2504 strncat(tmp
, "PENDING|", sizeof(tmp
) - strlen(tmp
) - 1);
2505 if (dp
->flags
& CACHE_FLAG_TIMEOUT
)
2506 strncat(tmp
, "TIMEOUT|", sizeof(tmp
) - strlen(tmp
) - 1);
2507 if (dp
->flags
& CACHE_FLAG_TRANSMITTED
)
2508 strncat(tmp
, "TRANSMITTED|", sizeof(tmp
) - strlen(tmp
) - 1);
2509 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
2510 strncat(tmp
, "MATCHMORE|", sizeof(tmp
) - strlen(tmp
) - 1);
2511 if (dp
->flags
& CACHE_FLAG_UNKNOWN
)
2512 strncat(tmp
, "UNKNOWN|", sizeof(tmp
) - strlen(tmp
) - 1);
2513 /* Trim trailing pipe */
2514 if (!ast_strlen_zero(tmp
))
2515 tmp
[strlen(tmp
) - 1] = '\0';
2517 ast_copy_string(tmp
, "(none)", sizeof(tmp
));
2519 pc
= strchr(dp
->peercontext
, '@');
2521 pc
= dp
->peercontext
;
2524 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
2525 if (dp
->waiters
[x
] > -1)
2528 ast_cli(fd
, "%-20.20s %-12.12s %-9d %-8d %s\n", pc
, dp
->exten
, s
, y
, tmp
);
2530 ast_cli(fd
, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc
, dp
->exten
, "(expired)", y
, tmp
);
2533 ast_mutex_unlock(&dpcache_lock
);
2534 return RESULT_SUCCESS
;
2537 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
);
2539 static void unwrap_timestamp(struct iax_frame
*fr
)
2541 /* Video mini frames only encode the lower 15 bits of the session
2542 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
2543 const int ts_shift
= (fr
->af
.frametype
== AST_FRAME_VIDEO
) ? 15 : 16;
2544 const int lower_mask
= (1 << ts_shift
) - 1;
2545 const int upper_mask
= ~lower_mask
;
2546 const int last_upper
= iaxs
[fr
->callno
]->last
& upper_mask
;
2548 if ( (fr
->ts
& upper_mask
) == last_upper
) {
2549 const int x
= fr
->ts
- iaxs
[fr
->callno
]->last
;
2550 const int threshold
= (ts_shift
== 15) ? 25000 : 50000;
2552 if (x
< -threshold
) {
2553 /* Sudden big jump backwards in timestamp:
2554 What likely happened here is that miniframe timestamp has circled but we haven't
2555 gotten the update from the main packet. We'll just pretend that we did, and
2556 update the timestamp appropriately. */
2557 fr
->ts
= (last_upper
+ (1 << ts_shift
)) | (fr
->ts
& lower_mask
);
2558 if (option_debug
&& iaxdebug
)
2559 ast_log(LOG_DEBUG
, "schedule_delivery: pushed forward timestamp\n");
2560 } else if (x
> threshold
) {
2561 /* Sudden apparent big jump forwards in timestamp:
2562 What's likely happened is this is an old miniframe belonging to the previous
2563 top 15 or 16-bit timestamp that has turned up out of order.
2564 Adjust the timestamp appropriately. */
2565 fr
->ts
= (last_upper
- (1 << ts_shift
)) | (fr
->ts
& lower_mask
);
2566 if (option_debug
&& iaxdebug
)
2567 ast_log(LOG_DEBUG
, "schedule_delivery: pushed back timestamp\n");
2572 static int get_from_jb(const void *p
);
2574 static void update_jbsched(struct chan_iax2_pvt
*pvt
)
2578 when
= ast_tvdiff_ms(ast_tvnow(), pvt
->rxcore
);
2580 when
= jb_next(pvt
->jb
) - when
;
2582 AST_SCHED_DEL(sched
, pvt
->jbid
);
2585 /* XXX should really just empty until when > 0.. */
2589 pvt
->jbid
= iax2_sched_add(sched
, when
, get_from_jb
, CALLNO_TO_PTR(pvt
->callno
));
2592 static void __get_from_jb(const void *p
)
2594 int callno
= PTR_TO_CALLNO(p
);
2595 struct chan_iax2_pvt
*pvt
= NULL
;
2596 struct iax_frame
*fr
;
2603 /* Make sure we have a valid private structure before going on */
2604 ast_mutex_lock(&iaxsl
[callno
]);
2608 ast_mutex_unlock(&iaxsl
[callno
]);
2614 gettimeofday(&tv
,NULL
);
2615 /* round up a millisecond since ast_sched_runq does; */
2616 /* prevents us from spinning while waiting for our now */
2617 /* to catch up with runq's now */
2620 now
= ast_tvdiff_ms(tv
, pvt
->rxcore
);
2622 if(now
>= (next
= jb_next(pvt
->jb
))) {
2623 ret
= jb_get(pvt
->jb
,&frame
,now
,ast_codec_interp_len(pvt
->voiceformat
));
2628 /* __do_deliver() can cause the call to disappear */
2633 struct ast_frame af
= { 0, };
2635 /* create an interpolation frame */
2636 af
.frametype
= AST_FRAME_VOICE
;
2637 af
.subclass
= pvt
->voiceformat
;
2638 af
.samples
= frame
.ms
* 8;
2639 af
.src
= "IAX2 JB interpolation";
2640 af
.delivery
= ast_tvadd(pvt
->rxcore
, ast_samp2tv(next
, 1000));
2641 af
.offset
= AST_FRIENDLY_OFFSET
;
2643 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2644 * which we'd need to malloc, and then it would free it. That seems like a drag */
2645 if (!ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
)) {
2646 iax2_queue_frame(callno
, &af
);
2647 /* iax2_queue_frame() could cause the call to disappear */
2653 iax2_frame_free(frame
.data
);
2660 /* shouldn't happen */
2665 update_jbsched(pvt
);
2666 ast_mutex_unlock(&iaxsl
[callno
]);
2669 static int get_from_jb(const void *data
)
2671 #ifdef SCHED_MULTITHREADED
2672 if (schedule_action(__get_from_jb
, data
))
2674 __get_from_jb(data
);
2679 * \note This function assumes fr->callno is locked
2681 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2682 * was valid before calling it, it may no longer be valid after calling it.
2684 static int schedule_delivery(struct iax_frame
*fr
, int updatehistory
, int fromtrunk
, unsigned int *tsout
)
2689 struct ast_channel
*owner
= NULL
;
2690 struct ast_channel
*bridge
= NULL
;
2692 /* Attempt to recover wrapped timestamps */
2693 unwrap_timestamp(fr
);
2695 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2696 if ( !fromtrunk
&& !ast_tvzero(iaxs
[fr
->callno
]->rxcore
))
2697 fr
->af
.delivery
= ast_tvadd(iaxs
[fr
->callno
]->rxcore
, ast_samp2tv(fr
->ts
, 1000));
2701 ast_log(LOG_DEBUG
, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2703 fr
->af
.delivery
= ast_tv(0,0);
2706 type
= JB_TYPE_CONTROL
;
2709 if(fr
->af
.frametype
== AST_FRAME_VOICE
) {
2710 type
= JB_TYPE_VOICE
;
2711 len
= ast_codec_get_samples(&fr
->af
) / 8;
2712 } else if(fr
->af
.frametype
== AST_FRAME_CNG
) {
2713 type
= JB_TYPE_SILENCE
;
2716 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_USEJITTERBUF
)) ) {
2723 if ((owner
= iaxs
[fr
->callno
]->owner
))
2724 bridge
= ast_bridged_channel(owner
);
2726 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2727 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2728 if ( (!ast_test_flag(iaxs
[fr
->callno
], IAX_FORCEJITTERBUF
)) && owner
&& bridge
&& (bridge
->tech
->properties
& AST_CHAN_TP_WANTSJITTER
) ) {
2731 /* deliver any frames in the jb */
2732 while (jb_getall(iaxs
[fr
->callno
]->jb
, &frame
) == JB_OK
) {
2733 __do_deliver(frame
.data
);
2734 /* __do_deliver() can make the call disappear */
2735 if (!iaxs
[fr
->callno
])
2739 jb_reset(iaxs
[fr
->callno
]->jb
);
2741 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->jbid
);
2743 /* deliver this frame now */
2750 /* insert into jitterbuffer */
2751 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2752 ret
= jb_put(iaxs
[fr
->callno
]->jb
, fr
, type
, len
, fr
->ts
,
2753 calc_rxstamp(iaxs
[fr
->callno
],fr
->ts
));
2754 if (ret
== JB_DROP
) {
2756 } else if (ret
== JB_SCHED
) {
2757 update_jbsched(iaxs
[fr
->callno
]);
2762 /* Free our iax frame */
2763 iax2_frame_free(fr
);
2769 static int iax2_transmit(struct iax_frame
*fr
)
2771 /* Lock the queue and place this packet at the end */
2772 /* By setting this to 0, the network thread will send it for us, and
2773 queue retransmission if necessary */
2775 AST_LIST_LOCK(&iaxq
.queue
);
2776 AST_LIST_INSERT_TAIL(&iaxq
.queue
, fr
, list
);
2778 AST_LIST_UNLOCK(&iaxq
.queue
);
2779 /* Wake up the network and scheduler thread */
2780 if (netthreadid
!= AST_PTHREADT_NULL
)
2781 pthread_kill(netthreadid
, SIGURG
);
2782 signal_condition(&sched_lock
, &sched_cond
);
2788 static int iax2_digit_begin(struct ast_channel
*c
, char digit
)
2790 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_BEGIN
, digit
, 0, NULL
, 0, -1);
2793 static int iax2_digit_end(struct ast_channel
*c
, char digit
, unsigned int duration
)
2795 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_DTMF_END
, digit
, 0, NULL
, 0, -1);
2798 static int iax2_sendtext(struct ast_channel
*c
, const char *text
)
2801 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_TEXT
,
2802 0, 0, (unsigned char *)text
, strlen(text
) + 1, -1);
2805 static int iax2_sendimage(struct ast_channel
*c
, struct ast_frame
*img
)
2807 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_IMAGE
, img
->subclass
, 0, img
->data
, img
->datalen
, -1);
2810 static int iax2_sendhtml(struct ast_channel
*c
, int subclass
, const char *data
, int datalen
)
2812 return send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_HTML
, subclass
, 0, (unsigned char *)data
, datalen
, -1);
2815 static int iax2_fixup(struct ast_channel
*oldchannel
, struct ast_channel
*newchan
)
2817 unsigned short callno
= PTR_TO_CALLNO(newchan
->tech_pvt
);
2818 ast_mutex_lock(&iaxsl
[callno
]);
2820 iaxs
[callno
]->owner
= newchan
;
2822 ast_log(LOG_WARNING
, "Uh, this isn't a good sign...\n");
2823 ast_mutex_unlock(&iaxsl
[callno
]);
2828 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2829 * so do not call this with a pvt lock held.
2831 static struct iax2_peer
*realtime_peer(const char *peername
, struct sockaddr_in
*sin
)
2833 struct ast_variable
*var
= NULL
;
2834 struct ast_variable
*tmp
;
2835 struct iax2_peer
*peer
=NULL
;
2836 time_t regseconds
= 0, nowtime
;
2840 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", "dynamic", NULL
);
2842 var
= ast_load_realtime("iaxpeers", "name", peername
, "host", ast_inet_ntoa(sin
->sin_addr
), NULL
);
2845 sprintf(porta
, "%d", ntohs(sin
->sin_port
));
2846 var
= ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2848 /* We'll need the peer name in order to build the structure! */
2849 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2850 if (!strcasecmp(tmp
->name
, "name"))
2851 peername
= tmp
->value
;
2855 if (!var
&& peername
) { /* Last ditch effort */
2856 var
= ast_load_realtime("iaxpeers", "name", peername
, NULL
);
2858 * If this one loaded something, then we need to ensure that the host
2859 * field matched. The only reason why we can't have this as a criteria
2860 * is because we only have the IP address and the host field might be
2861 * set as a name (and the reverse PTR might not match).
2864 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2865 if (!strcasecmp(tmp
->name
, "host")) {
2866 struct ast_hostent ahp
;
2868 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
2870 ast_variables_destroy(var
);
2881 peer
= build_peer(peername
, var
, NULL
, ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
) ? 0 : 1);
2884 ast_variables_destroy(var
);
2888 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2889 /* Make sure it's not a user only... */
2890 if (!strcasecmp(tmp
->name
, "type")) {
2891 if (strcasecmp(tmp
->value
, "friend") &&
2892 strcasecmp(tmp
->value
, "peer")) {
2893 /* Whoops, we weren't supposed to exist! */
2894 peer
= peer_unref(peer
);
2897 } else if (!strcasecmp(tmp
->name
, "regseconds")) {
2898 ast_get_time_t(tmp
->value
, ®seconds
, 0, NULL
);
2899 } else if (!strcasecmp(tmp
->name
, "ipaddr")) {
2900 inet_aton(tmp
->value
, &(peer
->addr
.sin_addr
));
2901 } else if (!strcasecmp(tmp
->name
, "port")) {
2902 peer
->addr
.sin_port
= htons(atoi(tmp
->value
));
2903 } else if (!strcasecmp(tmp
->name
, "host")) {
2904 if (!strcasecmp(tmp
->value
, "dynamic"))
2909 ast_variables_destroy(var
);
2914 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
2915 ast_copy_flags(peer
, &globalflags
, IAX_RTAUTOCLEAR
|IAX_RTCACHEFRIENDS
);
2916 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
)) {
2917 if (peer
->expire
> -1) {
2918 if (!ast_sched_del(sched
, peer
->expire
)) {
2923 peer
->expire
= iax2_sched_add(sched
, (global_rtautoclear
) * 1000, expire_registry
, peer_ref(peer
));
2924 if (peer
->expire
== -1)
2927 ao2_link(peers
, peer
);
2928 if (ast_test_flag(peer
, IAX_DYNAMIC
))
2929 reg_source_db(peer
);
2931 ast_set_flag(peer
, IAX_TEMPONLY
);
2934 if (!ast_test_flag(&globalflags
, IAX_RTIGNOREREGEXPIRE
) && dynamic
) {
2936 if ((nowtime
- regseconds
) > IAX_DEFAULT_REG_EXPIRE
) {
2937 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
2938 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
2940 ast_log(LOG_DEBUG
, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2941 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
2945 ast_log(LOG_DEBUG
, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2946 peername
, (int)(nowtime
- regseconds
), (int)regseconds
, (int)nowtime
);
2953 static struct iax2_user
*realtime_user(const char *username
, struct sockaddr_in
*sin
)
2955 struct ast_variable
*var
;
2956 struct ast_variable
*tmp
;
2957 struct iax2_user
*user
=NULL
;
2959 var
= ast_load_realtime("iaxusers", "name", username
, "host", "dynamic", NULL
);
2961 var
= ast_load_realtime("iaxusers", "name", username
, "host", ast_inet_ntoa(sin
->sin_addr
), NULL
);
2964 snprintf(porta
, sizeof(porta
), "%d", ntohs(sin
->sin_port
));
2965 var
= ast_load_realtime("iaxusers", "name", username
, "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2967 var
= ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", porta
, NULL
);
2969 if (!var
) { /* Last ditch effort */
2970 var
= ast_load_realtime("iaxusers", "name", username
, NULL
);
2972 * If this one loaded something, then we need to ensure that the host
2973 * field matched. The only reason why we can't have this as a criteria
2974 * is because we only have the IP address and the host field might be
2975 * set as a name (and the reverse PTR might not match).
2978 for (tmp
= var
; tmp
; tmp
= tmp
->next
) {
2979 if (!strcasecmp(tmp
->name
, "host")) {
2980 struct ast_hostent ahp
;
2982 if (!(hp
= ast_gethostbyname(tmp
->value
, &ahp
)) || (memcmp(&hp
->h_addr
, &sin
->sin_addr
, sizeof(hp
->h_addr
)))) {
2984 ast_variables_destroy(var
);
2997 /* Make sure it's not a peer only... */
2998 if (!strcasecmp(tmp
->name
, "type")) {
2999 if (strcasecmp(tmp
->value
, "friend") &&
3000 strcasecmp(tmp
->value
, "user")) {
3007 user
= build_user(username
, var
, NULL
, !ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
));
3009 ast_variables_destroy(var
);
3014 if (ast_test_flag((&globalflags
), IAX_RTCACHEFRIENDS
)) {
3015 ast_set_flag(user
, IAX_RTCACHEFRIENDS
);
3016 ao2_link(users
, user
);
3018 ast_set_flag(user
, IAX_TEMPONLY
);
3024 static void realtime_update_peer(const char *peername
, struct sockaddr_in
*sin
, time_t regtime
)
3027 char regseconds
[20];
3029 snprintf(regseconds
, sizeof(regseconds
), "%d", (int)regtime
);
3030 snprintf(port
, sizeof(port
), "%d", ntohs(sin
->sin_port
));
3031 ast_update_realtime("iaxpeers", "name", peername
,
3032 "ipaddr", ast_inet_ntoa(sin
->sin_addr
), "port", port
,
3033 "regseconds", regseconds
, NULL
);
3036 struct create_addr_info
{
3049 char context
[AST_MAX_CONTEXT
];
3050 char peercontext
[AST_MAX_CONTEXT
];
3051 char mohinterpret
[MAX_MUSICCLASS
];
3052 char mohsuggest
[MAX_MUSICCLASS
];
3055 static int create_addr(const char *peername
, struct ast_channel
*c
, struct sockaddr_in
*sin
, struct create_addr_info
*cai
)
3057 struct ast_hostent ahp
;
3059 struct iax2_peer
*peer
;
3061 struct ast_codec_pref ourprefs
;
3063 ast_clear_flag(cai
, IAX_SENDANI
| IAX_TRUNK
);
3064 cai
->sockfd
= defaultsockfd
;
3066 sin
->sin_family
= AF_INET
;
3068 if (!(peer
= find_peer(peername
, 1))) {
3071 hp
= ast_gethostbyname(peername
, &ahp
);
3073 memcpy(&sin
->sin_addr
, hp
->h_addr
, sizeof(sin
->sin_addr
));
3074 sin
->sin_port
= htons(IAX_DEFAULT_PORTNO
);
3075 /* use global iax prefs for unknown peer/user */
3076 /* But move the calling channel's native codec to the top of the preference list */
3077 memcpy(&ourprefs
, &prefs
, sizeof(ourprefs
));
3079 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
3080 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
3083 ast_log(LOG_WARNING
, "No such host: %s\n", peername
);
3090 /* if the peer has no address (current or default), return failure */
3091 if (!(peer
->addr
.sin_addr
.s_addr
|| peer
->defaddr
.sin_addr
.s_addr
))
3094 /* if the peer is being monitored and is currently unreachable, return failure */
3095 if (peer
->maxms
&& ((peer
->lastms
> peer
->maxms
) || (peer
->lastms
< 0)))
3098 ast_copy_flags(cai
, peer
, IAX_SENDANI
| IAX_TRUNK
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
3099 cai
->maxtime
= peer
->maxms
;
3100 cai
->capability
= peer
->capability
;
3101 cai
->encmethods
= peer
->encmethods
;
3102 cai
->sockfd
= peer
->sockfd
;
3103 cai
->adsi
= peer
->adsi
;
3104 memcpy(&ourprefs
, &peer
->prefs
, sizeof(ourprefs
));
3105 /* Move the calling channel's native codec to the top of the preference list */
3107 ast_log(LOG_DEBUG
, "prepending %x to prefs\n", c
->nativeformats
);
3108 ast_codec_pref_prepend(&ourprefs
, c
->nativeformats
, 1);
3110 ast_codec_pref_convert(&ourprefs
, cai
->prefs
, sizeof(cai
->prefs
), 1);
3111 ast_copy_string(cai
->context
, peer
->context
, sizeof(cai
->context
));
3112 ast_copy_string(cai
->peercontext
, peer
->peercontext
, sizeof(cai
->peercontext
));
3113 ast_copy_string(cai
->username
, peer
->username
, sizeof(cai
->username
));
3114 ast_copy_string(cai
->timezone
, peer
->zonetag
, sizeof(cai
->timezone
));
3115 ast_copy_string(cai
->outkey
, peer
->outkey
, sizeof(cai
->outkey
));
3116 ast_copy_string(cai
->mohinterpret
, peer
->mohinterpret
, sizeof(cai
->mohinterpret
));
3117 ast_copy_string(cai
->mohsuggest
, peer
->mohsuggest
, sizeof(cai
->mohsuggest
));
3118 if (ast_strlen_zero(peer
->dbsecret
)) {
3119 ast_copy_string(cai
->secret
, peer
->secret
, sizeof(cai
->secret
));
3124 family
= ast_strdupa(peer
->dbsecret
);
3125 key
= strchr(family
, '/');
3128 if (!key
|| ast_db_get(family
, key
, cai
->secret
, sizeof(cai
->secret
))) {
3129 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", peer
->dbsecret
);
3134 if (peer
->addr
.sin_addr
.s_addr
) {
3135 sin
->sin_addr
= peer
->addr
.sin_addr
;
3136 sin
->sin_port
= peer
->addr
.sin_port
;
3138 sin
->sin_addr
= peer
->defaddr
.sin_addr
;
3139 sin
->sin_port
= peer
->defaddr
.sin_port
;
3150 static void __auto_congest(const void *nothing
)
3152 int callno
= PTR_TO_CALLNO(nothing
);
3153 struct ast_frame f
= { AST_FRAME_CONTROL
, AST_CONTROL_CONGESTION
};
3154 ast_mutex_lock(&iaxsl
[callno
]);
3156 iaxs
[callno
]->initid
= -1;
3157 iax2_queue_frame(callno
, &f
);
3158 ast_log(LOG_NOTICE
, "Auto-congesting call due to slow response\n");
3160 ast_mutex_unlock(&iaxsl
[callno
]);
3163 static int auto_congest(const void *data
)
3165 #ifdef SCHED_MULTITHREADED
3166 if (schedule_action(__auto_congest
, data
))
3168 __auto_congest(data
);
3172 static unsigned int iax2_datetime(const char *tz
)
3178 if (!ast_strlen_zero(tz
))
3179 ast_localtime(&t
, &tm
, tz
);
3181 ast_localtime(&t
, &tm
, NULL
);
3182 tmp
= (tm
.tm_sec
>> 1) & 0x1f; /* 5 bits of seconds */
3183 tmp
|= (tm
.tm_min
& 0x3f) << 5; /* 6 bits of minutes */
3184 tmp
|= (tm
.tm_hour
& 0x1f) << 11; /* 5 bits of hours */
3185 tmp
|= (tm
.tm_mday
& 0x1f) << 16; /* 5 bits of day of month */
3186 tmp
|= ((tm
.tm_mon
+ 1) & 0xf) << 21; /* 4 bits of month */
3187 tmp
|= ((tm
.tm_year
- 100) & 0x7f) << 25; /* 7 bits of year */
3191 struct parsed_dial_string
{
3202 static int send_apathetic_reply(unsigned short callno
, unsigned short dcallno
, struct sockaddr_in
*sin
, int command
, int ts
, unsigned char seqno
)
3204 struct ast_iax2_full_hdr f
= { .scallno
= htons(0x8000 | callno
), .dcallno
= htons(dcallno
),
3205 .ts
= htonl(ts
), .iseqno
= seqno
, .oseqno
= seqno
, .type
= AST_FRAME_IAX
,
3206 .csub
= compress_subclass(command
) };
3208 return sendto(defaultsockfd
, &f
, sizeof(f
), 0, (struct sockaddr
*)sin
, sizeof(*sin
));
3212 * \brief Parses an IAX dial string into its component parts.
3213 * \param data the string to be parsed
3214 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3217 * This function parses the string and fills the structure
3218 * with pointers to its component parts. The input string
3221 * \note This function supports both plaintext passwords and RSA
3222 * key names; if the password string is formatted as '[keyname]',
3223 * then the keyname will be placed into the key field, and the
3224 * password field will be set to NULL.
3226 * \note The dial string format is:
3227 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3229 static void parse_dial_string(char *data
, struct parsed_dial_string
*pds
)
3231 if (ast_strlen_zero(data
))
3234 pds
->peer
= strsep(&data
, "/");
3235 pds
->exten
= strsep(&data
, "/");
3236 pds
->options
= data
;
3240 pds
->exten
= strsep(&data
, "@");
3241 pds
->context
= data
;
3244 if (strchr(pds
->peer
, '@')) {
3246 pds
->username
= strsep(&data
, "@");
3250 if (pds
->username
) {
3251 data
= pds
->username
;
3252 pds
->username
= strsep(&data
, ":");
3253 pds
->password
= data
;
3257 pds
->peer
= strsep(&data
, ":");
3260 /* check for a key name wrapped in [] in the secret position, if found,
3261 move it to the key field instead
3263 if (pds
->password
&& (pds
->password
[0] == '[')) {
3264 pds
->key
= ast_strip_quoted(pds
->password
, "[", "]");
3265 pds
->password
= NULL
;
3269 static int iax2_call(struct ast_channel
*c
, char *dest
, int timeout
)
3271 struct sockaddr_in sin
;
3272 char *l
=NULL
, *n
=NULL
, *tmpstr
;
3273 struct iax_ie_data ied
;
3274 char *defaultrdest
= "s";
3275 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3276 struct parsed_dial_string pds
;
3277 struct create_addr_info cai
;
3279 if ((c
->_state
!= AST_STATE_DOWN
) && (c
->_state
!= AST_STATE_RESERVED
)) {
3280 ast_log(LOG_WARNING
, "Channel is already in use (%s)?\n", c
->name
);
3284 memset(&cai
, 0, sizeof(cai
));
3285 cai
.encmethods
= iax2_encryption
;
3287 memset(&pds
, 0, sizeof(pds
));
3288 tmpstr
= ast_strdupa(dest
);
3289 parse_dial_string(tmpstr
, &pds
);
3291 if (ast_strlen_zero(pds
.peer
)) {
3292 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", dest
);
3297 pds
.exten
= defaultrdest
;
3300 if (create_addr(pds
.peer
, c
, &sin
, &cai
)) {
3301 ast_log(LOG_WARNING
, "No address associated with '%s'\n", pds
.peer
);
3305 if (!pds
.username
&& !ast_strlen_zero(cai
.username
))
3306 pds
.username
= cai
.username
;
3307 if (!pds
.password
&& !ast_strlen_zero(cai
.secret
))
3308 pds
.password
= cai
.secret
;
3309 if (!pds
.key
&& !ast_strlen_zero(cai
.outkey
))
3310 pds
.key
= cai
.outkey
;
3311 if (!pds
.context
&& !ast_strlen_zero(cai
.peercontext
))
3312 pds
.context
= cai
.peercontext
;
3314 /* Keep track of the context for outgoing calls too */
3315 ast_copy_string(c
->context
, cai
.context
, sizeof(c
->context
));
3318 sin
.sin_port
= htons(atoi(pds
.port
));
3321 n
= c
->cid
.cid_name
;
3323 /* Now build request */
3324 memset(&ied
, 0, sizeof(ied
));
3326 /* On new call, first IE MUST be IAX version of caller */
3327 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
3328 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, pds
.exten
);
3329 if (pds
.options
&& strchr(pds
.options
, 'a')) {
3330 /* Request auto answer */
3331 iax_ie_append(&ied
, IAX_IE_AUTOANSWER
);
3334 iax_ie_append_str(&ied
, IAX_IE_CODEC_PREFS
, cai
.prefs
);
3337 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, l
);
3338 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3341 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, c
->cid
.cid_pres
);
3343 iax_ie_append_byte(&ied
, IAX_IE_CALLINGPRES
, AST_PRES_NUMBER_NOT_AVAILABLE
);
3346 iax_ie_append_byte(&ied
, IAX_IE_CALLINGTON
, c
->cid
.cid_ton
);
3347 iax_ie_append_short(&ied
, IAX_IE_CALLINGTNS
, c
->cid
.cid_tns
);
3350 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, n
);
3351 if (ast_test_flag(iaxs
[callno
], IAX_SENDANI
) && c
->cid
.cid_ani
)
3352 iax_ie_append_str(&ied
, IAX_IE_CALLING_ANI
, c
->cid
.cid_ani
);
3354 if (!ast_strlen_zero(c
->language
))
3355 iax_ie_append_str(&ied
, IAX_IE_LANGUAGE
, c
->language
);
3356 if (!ast_strlen_zero(c
->cid
.cid_dnid
))
3357 iax_ie_append_str(&ied
, IAX_IE_DNID
, c
->cid
.cid_dnid
);
3358 if (!ast_strlen_zero(c
->cid
.cid_rdnis
))
3359 iax_ie_append_str(&ied
, IAX_IE_RDNIS
, c
->cid
.cid_rdnis
);
3362 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.context
);
3365 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
3368 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, cai
.encmethods
);
3370 ast_mutex_lock(&iaxsl
[callno
]);
3372 if (!ast_strlen_zero(c
->context
))
3373 ast_string_field_set(iaxs
[callno
], context
, c
->context
);
3376 ast_string_field_set(iaxs
[callno
], username
, pds
.username
);
3378 iaxs
[callno
]->encmethods
= cai
.encmethods
;
3380 iaxs
[callno
]->adsi
= cai
.adsi
;
3382 ast_string_field_set(iaxs
[callno
], mohinterpret
, cai
.mohinterpret
);
3383 ast_string_field_set(iaxs
[callno
], mohsuggest
, cai
.mohsuggest
);
3386 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
3388 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
3390 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, c
->nativeformats
);
3391 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, iaxs
[callno
]->capability
);
3392 iax_ie_append_short(&ied
, IAX_IE_ADSICPE
, c
->adsicpe
);
3393 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(cai
.timezone
));
3395 if (iaxs
[callno
]->maxtime
) {
3396 /* Initialize pingtime and auto-congest time */
3397 iaxs
[callno
]->pingtime
= iaxs
[callno
]->maxtime
/ 2;
3398 iaxs
[callno
]->initid
= iax2_sched_add(sched
, iaxs
[callno
]->maxtime
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3399 } else if (autokill
) {
3400 iaxs
[callno
]->pingtime
= autokill
/ 2;
3401 iaxs
[callno
]->initid
= iax2_sched_add(sched
, autokill
* 2, auto_congest
, CALLNO_TO_PTR(callno
));
3404 /* send the command using the appropriate socket for this peer */
3405 iaxs
[callno
]->sockfd
= cai
.sockfd
;
3407 /* Transmit the string in a "NEW" request */
3408 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
3410 ast_mutex_unlock(&iaxsl
[callno
]);
3411 ast_setstate(c
, AST_STATE_RINGING
);
3416 static int iax2_hangup(struct ast_channel
*c
)
3418 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3419 struct iax_ie_data ied
;
3420 memset(&ied
, 0, sizeof(ied
));
3421 ast_mutex_lock(&iaxsl
[callno
]);
3422 if (callno
&& iaxs
[callno
]) {
3424 ast_log(LOG_DEBUG
, "We're hanging up %s now...\n", c
->name
);
3425 /* Send the hangup unless we have had a transmission error or are already gone */
3426 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, (unsigned char)c
->hangupcause
);
3427 if (!iaxs
[callno
]->error
&& !ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
)) {
3428 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
3429 if (!iaxs
[callno
]) {
3430 ast_mutex_unlock(&iaxsl
[callno
]);
3434 /* Explicitly predestroy it */
3435 iax2_predestroy(callno
);
3436 /* If we were already gone to begin with, destroy us now */
3439 ast_log(LOG_DEBUG
, "Really destroying %s now...\n", c
->name
);
3440 iax2_destroy(callno
);
3442 } else if (c
->tech_pvt
) {
3443 /* If this call no longer exists, but the channel still
3444 * references it we need to set the channel's tech_pvt to null
3445 * to avoid ast_channel_free() trying to free it.
3449 ast_mutex_unlock(&iaxsl
[callno
]);
3450 if (option_verbose
> 2)
3451 ast_verbose(VERBOSE_PREFIX_3
"Hungup '%s'\n", c
->name
);
3455 static int iax2_setoption(struct ast_channel
*c
, int option
, void *data
, int datalen
)
3457 struct ast_option_header
*h
;
3461 case AST_OPTION_TXGAIN
:
3462 case AST_OPTION_RXGAIN
:
3463 /* these two cannot be sent, because they require a result */
3467 if (!(h
= ast_malloc(datalen
+ sizeof(*h
))))
3470 h
->flag
= AST_OPTION_FLAG_REQUEST
;
3471 h
->option
= htons(option
);
3472 memcpy(h
->data
, data
, datalen
);
3473 res
= send_command_locked(PTR_TO_CALLNO(c
->tech_pvt
), AST_FRAME_CONTROL
,
3474 AST_CONTROL_OPTION
, 0, (unsigned char *) h
,
3475 datalen
+ sizeof(*h
), -1);
3481 static struct ast_frame
*iax2_read(struct ast_channel
*c
)
3483 ast_log(LOG_NOTICE
, "I should never be called!\n");
3484 return &ast_null_frame
;
3487 static int iax2_start_transfer(unsigned short callno0
, unsigned short callno1
, int mediaonly
)
3490 struct iax_ie_data ied0
;
3491 struct iax_ie_data ied1
;
3492 unsigned int transferid
= (unsigned int)ast_random();
3493 memset(&ied0
, 0, sizeof(ied0
));
3494 iax_ie_append_addr(&ied0
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno1
]->addr
);
3495 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[callno1
]->peercallno
);
3496 iax_ie_append_int(&ied0
, IAX_IE_TRANSFERID
, transferid
);
3498 memset(&ied1
, 0, sizeof(ied1
));
3499 iax_ie_append_addr(&ied1
, IAX_IE_APPARENT_ADDR
, &iaxs
[callno0
]->addr
);
3500 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[callno0
]->peercallno
);
3501 iax_ie_append_int(&ied1
, IAX_IE_TRANSFERID
, transferid
);
3503 res
= send_command(iaxs
[callno0
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied0
.buf
, ied0
.pos
, -1);
3506 res
= send_command(iaxs
[callno1
], AST_FRAME_IAX
, IAX_COMMAND_TXREQ
, 0, ied1
.buf
, ied1
.pos
, -1);
3509 iaxs
[callno0
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3510 iaxs
[callno1
]->transferring
= mediaonly
? TRANSFER_MBEGIN
: TRANSFER_BEGIN
;
3514 static void lock_both(unsigned short callno0
, unsigned short callno1
)
3516 ast_mutex_lock(&iaxsl
[callno0
]);
3517 while (ast_mutex_trylock(&iaxsl
[callno1
])) {
3518 DEADLOCK_AVOIDANCE(&iaxsl
[callno0
]);
3522 static void unlock_both(unsigned short callno0
, unsigned short callno1
)
3524 ast_mutex_unlock(&iaxsl
[callno1
]);
3525 ast_mutex_unlock(&iaxsl
[callno0
]);
3528 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
)
3530 struct ast_channel
*cs
[3];
3531 struct ast_channel
*who
, *other
;
3534 int transferstarted
=0;
3535 struct ast_frame
*f
;
3536 unsigned short callno0
= PTR_TO_CALLNO(c0
->tech_pvt
);
3537 unsigned short callno1
= PTR_TO_CALLNO(c1
->tech_pvt
);
3538 struct timeval waittimer
= {0, 0}, tv
;
3540 lock_both(callno0
, callno1
);
3541 if (!iaxs
[callno0
] || !iaxs
[callno1
]) {
3542 unlock_both(callno0
, callno1
);
3543 return AST_BRIDGE_FAILED
;
3545 /* Put them in native bridge mode */
3546 if (!flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) {
3547 iaxs
[callno0
]->bridgecallno
= callno1
;
3548 iaxs
[callno1
]->bridgecallno
= callno0
;
3550 unlock_both(callno0
, callno1
);
3552 /* If not, try to bridge until we can execute a transfer, if we can */
3555 for (/* ever */;;) {
3556 /* Check in case we got masqueraded into */
3557 if ((c0
->tech
!= &iax2_tech
) || (c1
->tech
!= &iax2_tech
)) {
3558 if (option_verbose
> 2)
3559 ast_verbose(VERBOSE_PREFIX_3
"Can't masquerade, we're different...\n");
3560 /* Remove from native mode */
3561 if (c0
->tech
== &iax2_tech
) {
3562 ast_mutex_lock(&iaxsl
[callno0
]);
3563 iaxs
[callno0
]->bridgecallno
= 0;
3564 ast_mutex_unlock(&iaxsl
[callno0
]);
3566 if (c1
->tech
== &iax2_tech
) {
3567 ast_mutex_lock(&iaxsl
[callno1
]);
3568 iaxs
[callno1
]->bridgecallno
= 0;
3569 ast_mutex_unlock(&iaxsl
[callno1
]);
3571 return AST_BRIDGE_FAILED_NOWARN
;
3573 if (c0
->nativeformats
!= c1
->nativeformats
) {
3574 if (option_verbose
> 2) {
3577 ast_getformatname_multiple(buf0
, sizeof(buf0
) -1, c0
->nativeformats
);
3578 ast_getformatname_multiple(buf1
, sizeof(buf1
) -1, c1
->nativeformats
);
3579 ast_verbose(VERBOSE_PREFIX_3
"Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0
->nativeformats
, buf0
, c1
->nativeformats
, buf1
);
3581 /* Remove from native mode */
3582 lock_both(callno0
, callno1
);
3584 iaxs
[callno0
]->bridgecallno
= 0;
3586 iaxs
[callno1
]->bridgecallno
= 0;
3587 unlock_both(callno0
, callno1
);
3588 return AST_BRIDGE_FAILED_NOWARN
;
3590 /* check if transfered and if we really want native bridging */
3591 if (!transferstarted
&& !ast_test_flag(iaxs
[callno0
], IAX_NOTRANSFER
) && !ast_test_flag(iaxs
[callno1
], IAX_NOTRANSFER
)) {
3592 /* Try the transfer */
3593 if (iax2_start_transfer(callno0
, callno1
, (flags
& (AST_BRIDGE_DTMF_CHANNEL_0
| AST_BRIDGE_DTMF_CHANNEL_1
)) ||
3594 ast_test_flag(iaxs
[callno0
], IAX_TRANSFERMEDIA
) | ast_test_flag(iaxs
[callno1
], IAX_TRANSFERMEDIA
)))
3595 ast_log(LOG_WARNING
, "Unable to start the transfer\n");
3596 transferstarted
= 1;
3598 if ((iaxs
[callno0
]->transferring
== TRANSFER_RELEASED
) && (iaxs
[callno1
]->transferring
== TRANSFER_RELEASED
)) {
3599 /* Call has been transferred. We're no longer involved */
3600 gettimeofday(&tv
, NULL
);
3601 if (ast_tvzero(waittimer
)) {
3603 } else if (tv
.tv_sec
- waittimer
.tv_sec
> IAX_LINGER_TIMEOUT
) {
3604 c0
->_softhangup
|= AST_SOFTHANGUP_DEV
;
3605 c1
->_softhangup
|= AST_SOFTHANGUP_DEV
;
3608 res
= AST_BRIDGE_COMPLETE
;
3613 who
= ast_waitfor_n(cs
, 2, &to
);
3614 if (timeoutms
> -1) {
3615 timeoutms
-= (1000 - to
);
3621 res
= AST_BRIDGE_RETRY
;
3624 if (ast_check_hangup(c0
) || ast_check_hangup(c1
)) {
3625 res
= AST_BRIDGE_FAILED
;
3634 res
= AST_BRIDGE_COMPLETE
;
3637 if ((f
->frametype
== AST_FRAME_CONTROL
) && !(flags
& AST_BRIDGE_IGNORE_SIGS
)) {
3640 res
= AST_BRIDGE_COMPLETE
;
3643 other
= (who
== c0
) ? c1
: c0
; /* the 'other' channel */
3644 if ((f
->frametype
== AST_FRAME_VOICE
) ||
3645 (f
->frametype
== AST_FRAME_TEXT
) ||
3646 (f
->frametype
== AST_FRAME_VIDEO
) ||
3647 (f
->frametype
== AST_FRAME_IMAGE
) ||
3648 (f
->frametype
== AST_FRAME_DTMF
)) {
3649 /* monitored dtmf take out of the bridge.
3650 * check if we monitor the specific source.
3652 int monitored_source
= (who
== c0
) ? AST_BRIDGE_DTMF_CHANNEL_0
: AST_BRIDGE_DTMF_CHANNEL_1
;
3653 if (f
->frametype
== AST_FRAME_DTMF
&& (flags
& monitored_source
)) {
3656 res
= AST_BRIDGE_COMPLETE
;
3657 /* Remove from native mode */
3660 /* everything else goes to the other side */
3661 ast_write(other
, f
);
3664 /* Swap who gets priority */
3669 lock_both(callno0
, callno1
);
3671 iaxs
[callno0
]->bridgecallno
= 0;
3673 iaxs
[callno1
]->bridgecallno
= 0;
3674 unlock_both(callno0
, callno1
);
3678 static int iax2_answer(struct ast_channel
*c
)
3680 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3682 ast_log(LOG_DEBUG
, "Answering IAX2 call\n");
3683 return send_command_locked(callno
, AST_FRAME_CONTROL
, AST_CONTROL_ANSWER
, 0, NULL
, 0, -1);
3686 static int iax2_indicate(struct ast_channel
*c
, int condition
, const void *data
, size_t datalen
)
3688 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3689 struct chan_iax2_pvt
*pvt
;
3692 if (option_debug
&& iaxdebug
)
3693 ast_log(LOG_DEBUG
, "Indicating condition %d\n", condition
);
3695 ast_mutex_lock(&iaxsl
[callno
]);
3698 if (!pvt
->peercallno
) {
3699 /* We don't know the remote side's call number, yet. :( */
3701 while (count
-- && pvt
&& !pvt
->peercallno
) {
3702 DEADLOCK_AVOIDANCE(&iaxsl
[callno
]);
3705 if (!pvt
->peercallno
) {
3711 switch (condition
) {
3712 case AST_CONTROL_HOLD
:
3713 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
3714 ast_moh_start(c
, data
, pvt
->mohinterpret
);
3718 case AST_CONTROL_UNHOLD
:
3719 if (strcasecmp(pvt
->mohinterpret
, "passthrough")) {
3725 res
= send_command(pvt
, AST_FRAME_CONTROL
, condition
, 0, data
, datalen
, -1);
3728 ast_mutex_unlock(&iaxsl
[callno
]);
3733 static int iax2_transfer(struct ast_channel
*c
, const char *dest
)
3735 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
3736 struct iax_ie_data ied
;
3737 char tmp
[256], *context
;
3738 ast_copy_string(tmp
, dest
, sizeof(tmp
));
3739 context
= strchr(tmp
, '@');
3744 memset(&ied
, 0, sizeof(ied
));
3745 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, tmp
);
3747 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, context
);
3749 ast_log(LOG_DEBUG
, "Transferring '%s' to '%s'\n", c
->name
, dest
);
3750 return send_command_locked(callno
, AST_FRAME_IAX
, IAX_COMMAND_TRANSFER
, 0, ied
.buf
, ied
.pos
, -1);
3753 static int iax2_getpeertrunk(struct sockaddr_in sin
)
3755 struct iax2_peer
*peer
;
3757 struct ao2_iterator i
;
3759 i
= ao2_iterator_init(peers
, 0);
3760 while ((peer
= ao2_iterator_next(&i
))) {
3761 if ((peer
->addr
.sin_addr
.s_addr
== sin
.sin_addr
.s_addr
) &&
3762 (peer
->addr
.sin_port
== sin
.sin_port
)) {
3763 res
= ast_test_flag(peer
, IAX_TRUNK
);
3773 /*! \brief Create new call, interface with the PBX core */
3774 static struct ast_channel
*ast_iax2_new(int callno
, int state
, int capability
)
3776 struct ast_channel
*tmp
;
3777 struct chan_iax2_pvt
*i
;
3778 struct ast_variable
*v
= NULL
;
3780 if (!(i
= iaxs
[callno
])) {
3781 ast_log(LOG_WARNING
, "No IAX2 pvt found for callno '%d' !\n", callno
);
3785 /* Don't hold call lock */
3786 ast_mutex_unlock(&iaxsl
[callno
]);
3787 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
);
3788 ast_mutex_lock(&iaxsl
[callno
]);
3789 if (i
!= iaxs
[callno
]) {
3791 /* unlock and relock iaxsl[callno] to preserve locking order */
3792 ast_mutex_unlock(&iaxsl
[callno
]);
3793 ast_channel_free(tmp
);
3794 ast_mutex_lock(&iaxsl
[callno
]);
3801 tmp
->tech
= &iax2_tech
;
3802 /* We can support any format by default, until we get restricted */
3803 tmp
->nativeformats
= capability
;
3804 tmp
->readformat
= tmp
->rawreadformat
= ast_best_codec(capability
);
3805 tmp
->writeformat
= tmp
->rawwriteformat
= ast_best_codec(capability
);
3806 tmp
->tech_pvt
= CALLNO_TO_PTR(i
->callno
);
3808 /* Don't use ast_set_callerid() here because it will
3809 * generate a NewCallerID event before the NewChannel event */
3810 if (!ast_strlen_zero(i
->ani
))
3811 tmp
->cid
.cid_ani
= ast_strdup(i
->ani
);
3813 tmp
->cid
.cid_ani
= ast_strdup(i
->cid_num
);
3814 tmp
->cid
.cid_dnid
= ast_strdup(i
->dnid
);
3815 tmp
->cid
.cid_rdnis
= ast_strdup(i
->rdnis
);
3816 tmp
->cid
.cid_pres
= i
->calling_pres
;
3817 tmp
->cid
.cid_ton
= i
->calling_ton
;
3818 tmp
->cid
.cid_tns
= i
->calling_tns
;
3819 if (!ast_strlen_zero(i
->language
))
3820 ast_string_field_set(tmp
, language
, i
->language
);
3821 if (!ast_strlen_zero(i
->accountcode
))
3822 ast_string_field_set(tmp
, accountcode
, i
->accountcode
);
3824 tmp
->amaflags
= i
->amaflags
;
3825 ast_copy_string(tmp
->context
, i
->context
, sizeof(tmp
->context
));
3826 ast_copy_string(tmp
->exten
, i
->exten
, sizeof(tmp
->exten
));
3828 tmp
->adsicpe
= i
->peeradsicpe
;
3830 tmp
->adsicpe
= AST_ADSI_UNAVAILABLE
;
3832 i
->capability
= capability
;
3834 for (v
= i
->vars
; v
; v
= v
->next
)
3835 pbx_builtin_setvar_helper(tmp
, v
->name
, v
->value
);
3837 if (state
!= AST_STATE_DOWN
) {
3838 if (ast_pbx_start(tmp
)) {
3839 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmp
->name
);
3846 ast_module_ref(ast_module_info
->self
);
3851 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer
*tpeer
, int sampms
, struct timeval
*tv
)
3853 unsigned long int mssincetx
; /* unsigned to handle overflows */
3856 tpeer
->trunkact
= *tv
;
3857 mssincetx
= ast_tvdiff_ms(*tv
, tpeer
->lasttxtime
);
3858 if (mssincetx
> 5000 || ast_tvzero(tpeer
->txtrunktime
)) {
3859 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3860 tpeer
->txtrunktime
= *tv
;
3861 tpeer
->lastsent
= 999999;
3863 /* Update last transmit time now */
3864 tpeer
->lasttxtime
= *tv
;
3866 /* Calculate ms offset */
3867 ms
= ast_tvdiff_ms(*tv
, tpeer
->txtrunktime
);
3868 /* Predict from last value */
3869 pred
= tpeer
->lastsent
+ sampms
;
3870 if (abs(ms
- pred
) < MAX_TIMESTAMP_SKEW
)
3873 /* We never send the same timestamp twice, so fudge a little if we must */
3874 if (ms
== tpeer
->lastsent
)
3875 ms
= tpeer
->lastsent
+ 1;
3876 tpeer
->lastsent
= ms
;
3880 static unsigned int fix_peerts(struct timeval
*tv
, int callno
, unsigned int ts
)
3882 long ms
; /* NOT unsigned */
3883 if (ast_tvzero(iaxs
[callno
]->rxcore
)) {
3884 /* Initialize rxcore time if appropriate */
3885 gettimeofday(&iaxs
[callno
]->rxcore
, NULL
);
3886 /* Round to nearest 20ms so traces look pretty */
3887 iaxs
[callno
]->rxcore
.tv_usec
-= iaxs
[callno
]->rxcore
.tv_usec
% 20000;
3889 /* Calculate difference between trunk and channel */
3890 ms
= ast_tvdiff_ms(*tv
, iaxs
[callno
]->rxcore
);
3891 /* Return as the sum of trunk time and the difference between trunk and real time */
3895 static unsigned int calc_timestamp(struct chan_iax2_pvt
*p
, unsigned int ts
, struct ast_frame
*f
)
3901 struct timeval
*delivery
= NULL
;
3904 /* What sort of frame do we have?: voice is self-explanatory
3905 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3906 non-genuine frames are CONTROL frames [ringing etc], DTMF
3907 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3908 the others need a timestamp slaved to the voice frames so that they go in sequence
3911 if (f
->frametype
== AST_FRAME_VOICE
) {
3913 delivery
= &f
->delivery
;
3914 } else if (f
->frametype
== AST_FRAME_IAX
) {
3916 } else if (f
->frametype
== AST_FRAME_CNG
) {
3920 if (ast_tvzero(p
->offset
)) {
3921 gettimeofday(&p
->offset
, NULL
);
3922 /* Round to nearest 20ms for nice looking traces */
3923 p
->offset
.tv_usec
-= p
->offset
.tv_usec
% 20000;
3925 /* If the timestamp is specified, just send it as is */
3928 /* If we have a time that the frame arrived, always use it to make our timestamp */
3929 if (delivery
&& !ast_tvzero(*delivery
)) {
3930 ms
= ast_tvdiff_ms(*delivery
, p
->offset
);
3931 if (option_debug
> 2 && iaxdebug
)
3932 ast_log(LOG_DEBUG
, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p
->callno
, iaxs
[p
->callno
]->peercallno
);
3934 ms
= ast_tvdiff_ms(ast_tvnow(), p
->offset
);
3938 /* On a voice frame, use predicted values if appropriate */
3939 if (p
->notsilenttx
&& abs(ms
- p
->nextpred
) <= MAX_TIMESTAMP_SKEW
) {
3940 /* Adjust our txcore, keeping voice and non-voice synchronized */
3942 When we send voice, we usually send "calculated" timestamps worked out
3943 on the basis of the number of samples sent. When we send other frames,
3944 we usually send timestamps worked out from the real clock.
3945 The problem is that they can tend to drift out of step because the
3946 source channel's clock and our clock may not be exactly at the same rate.
3947 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3948 for this call. Moving it adjusts timestamps for non-voice frames.
3949 We make the adjustment in the style of a moving average. Each time we
3950 adjust p->offset by 10% of the difference between our clock-derived
3951 timestamp and the predicted timestamp. That's why you see "10000"
3952 below even though IAX2 timestamps are in milliseconds.
3953 The use of a moving average avoids offset moving too radically.
3954 Generally, "adjust" roams back and forth around 0, with offset hardly
3955 changing at all. But if a consistent different starts to develop it
3956 will be eliminated over the course of 10 frames (200-300msecs)
3958 adjust
= (ms
- p
->nextpred
);
3960 p
->offset
= ast_tvsub(p
->offset
, ast_samp2tv(abs(adjust
), 10000));
3961 else if (adjust
> 0)
3962 p
->offset
= ast_tvadd(p
->offset
, ast_samp2tv(adjust
, 10000));
3965 p
->nextpred
= ms
; /*f->samples / 8;*/
3966 if (p
->nextpred
<= p
->lastsent
)
3967 p
->nextpred
= p
->lastsent
+ 3;
3971 /* in this case, just use the actual
3972 * time, since we're either way off
3973 * (shouldn't happen), or we're ending a
3974 * silent period -- and seed the next
3975 * predicted time. Also, round ms to the
3976 * next multiple of frame size (so our
3977 * silent periods are multiples of
3978 * frame size too) */
3980 if (option_debug
&& iaxdebug
&& abs(ms
- p
->nextpred
) > MAX_TIMESTAMP_SKEW
)
3981 ast_log(LOG_DEBUG
, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3982 abs(ms
- p
->nextpred
), MAX_TIMESTAMP_SKEW
);
3984 if (f
->samples
>= 8) /* check to make sure we dont core dump */
3986 int diff
= ms
% (f
->samples
/ 8);
3988 ms
+= f
->samples
/8 - diff
;
3994 } else if ( f
->frametype
== AST_FRAME_VIDEO
) {
3996 * IAX2 draft 03 says that timestamps MUST be in order.
3997 * It does not say anything about several frames having the same timestamp
3998 * When transporting video, we can have a frame that spans multiple iax packets
3999 * (so called slices), so it would make sense to use the same timestamp for all of
4001 * We do want to make sure that frames don't go backwards though
4003 if ( (unsigned int)ms
< p
->lastsent
)
4006 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
4007 it's a genuine frame */
4009 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
4010 if (ms
<= p
->lastsent
)
4011 ms
= p
->lastsent
+ 3;
4012 } else if (abs(ms
- p
->lastsent
) <= MAX_TIMESTAMP_SKEW
) {
4013 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
4014 ms
= p
->lastsent
+ 3;
4020 p
->nextpred
= p
->nextpred
+ f
->samples
/ 8;
4024 static unsigned int calc_rxstamp(struct chan_iax2_pvt
*p
, unsigned int offset
)
4026 /* Returns where in "receive time" we are. That is, how many ms
4027 since we received (or would have received) the frame with timestamp 0 */
4031 #endif /* IAXTESTS */
4032 /* Setup rxcore if necessary */
4033 if (ast_tvzero(p
->rxcore
)) {
4034 p
->rxcore
= ast_tvnow();
4035 if (option_debug
&& iaxdebug
)
4036 ast_log(LOG_DEBUG
, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
4037 p
->callno
, (int)(p
->rxcore
.tv_sec
), (int)(p
->rxcore
.tv_usec
), offset
);
4038 p
->rxcore
= ast_tvsub(p
->rxcore
, ast_samp2tv(offset
, 1000));
4040 if (option_debug
&& iaxdebug
)
4041 ast_log(LOG_DEBUG
, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
4042 p
->callno
, (int)(p
->rxcore
.tv_sec
),(int)( p
->rxcore
.tv_usec
));
4046 ms
= ast_tvdiff_ms(ast_tvnow(), p
->rxcore
);
4049 if (!test_jitpct
|| ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_jitpct
)) {
4050 jit
= (int)((float)test_jit
* ast_random() / (RAND_MAX
+ 1.0));
4051 if ((int)(2.0 * ast_random() / (RAND_MAX
+ 1.0)))
4060 #endif /* IAXTESTS */
4064 static struct iax2_trunk_peer
*find_tpeer(struct sockaddr_in
*sin
, int fd
)
4066 struct iax2_trunk_peer
*tpeer
;
4068 /* Finds and locks trunk peer */
4069 ast_mutex_lock(&tpeerlock
);
4070 for (tpeer
= tpeers
; tpeer
; tpeer
= tpeer
->next
) {
4071 /* We don't lock here because tpeer->addr *never* changes */
4072 if (!inaddrcmp(&tpeer
->addr
, sin
)) {
4073 ast_mutex_lock(&tpeer
->lock
);
4078 if ((tpeer
= ast_calloc(1, sizeof(*tpeer
)))) {
4079 ast_mutex_init(&tpeer
->lock
);
4080 tpeer
->lastsent
= 9999;
4081 memcpy(&tpeer
->addr
, sin
, sizeof(tpeer
->addr
));
4082 tpeer
->trunkact
= ast_tvnow();
4083 ast_mutex_lock(&tpeer
->lock
);
4084 tpeer
->next
= tpeers
;
4088 setsockopt(tpeer
->sockfd
, SOL_SOCKET
, SO_NO_CHECK
, &nochecksums
, sizeof(nochecksums
));
4091 ast_log(LOG_DEBUG
, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer
->addr
.sin_addr
), ntohs(tpeer
->addr
.sin_port
));
4094 ast_mutex_unlock(&tpeerlock
);
4098 static int iax2_trunk_queue(struct chan_iax2_pvt
*pvt
, struct iax_frame
*fr
)
4100 struct ast_frame
*f
;
4101 struct iax2_trunk_peer
*tpeer
;
4103 struct ast_iax2_meta_trunk_entry
*met
;
4104 struct ast_iax2_meta_trunk_mini
*mtm
;
4107 tpeer
= find_tpeer(&pvt
->addr
, pvt
->sockfd
);
4109 if (tpeer
->trunkdatalen
+ f
->datalen
+ 4 >= tpeer
->trunkdataalloc
) {
4110 /* Need to reallocate space */
4111 if (tpeer
->trunkdataalloc
< MAX_TRUNKDATA
) {
4112 if (!(tmp
= ast_realloc(tpeer
->trunkdata
, tpeer
->trunkdataalloc
+ DEFAULT_TRUNKDATA
+ IAX2_TRUNK_PREFACE
))) {
4113 ast_mutex_unlock(&tpeer
->lock
);
4117 tpeer
->trunkdataalloc
+= DEFAULT_TRUNKDATA
;
4118 tpeer
->trunkdata
= tmp
;
4120 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
);
4122 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
));
4123 ast_mutex_unlock(&tpeer
->lock
);
4128 /* Append to meta frame */
4129 ptr
= tpeer
->trunkdata
+ IAX2_TRUNK_PREFACE
+ tpeer
->trunkdatalen
;
4130 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
)) {
4131 mtm
= (struct ast_iax2_meta_trunk_mini
*)ptr
;
4132 mtm
->len
= htons(f
->datalen
);
4133 mtm
->mini
.callno
= htons(pvt
->callno
);
4134 mtm
->mini
.ts
= htons(0xffff & fr
->ts
);
4135 ptr
+= sizeof(struct ast_iax2_meta_trunk_mini
);
4136 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_mini
);
4138 met
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
4139 /* Store call number and length in meta header */
4140 met
->callno
= htons(pvt
->callno
);
4141 met
->len
= htons(f
->datalen
);
4142 /* Advance pointers/decrease length past trunk entry header */
4143 ptr
+= sizeof(struct ast_iax2_meta_trunk_entry
);
4144 tpeer
->trunkdatalen
+= sizeof(struct ast_iax2_meta_trunk_entry
);
4146 /* Copy actual trunk data */
4147 memcpy(ptr
, f
->data
, f
->datalen
);
4148 tpeer
->trunkdatalen
+= f
->datalen
;
4151 ast_mutex_unlock(&tpeer
->lock
);
4156 static void build_enc_keys(const unsigned char *digest
, aes_encrypt_ctx
*ecx
, aes_decrypt_ctx
*dcx
)
4158 aes_encrypt_key128(digest
, ecx
);
4159 aes_decrypt_key128(digest
, dcx
);
4162 static void memcpy_decrypt(unsigned char *dst
, const unsigned char *src
, int len
, aes_decrypt_ctx
*dcx
)
4165 /* Debug with "fake encryption" */
4168 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
4170 dst
[x
] = src
[x
] ^ 0xff;
4172 unsigned char lastblock
[16] = { 0 };
4175 aes_decrypt(src
, dst
, dcx
);
4177 dst
[x
] ^= lastblock
[x
];
4178 memcpy(lastblock
, src
, sizeof(lastblock
));
4186 static void memcpy_encrypt(unsigned char *dst
, const unsigned char *src
, int len
, aes_encrypt_ctx
*ecx
)
4189 /* Debug with "fake encryption" */
4192 ast_log(LOG_WARNING
, "len should be multiple of 16, not %d!\n", len
);
4194 dst
[x
] = src
[x
] ^ 0xff;
4196 unsigned char curblock
[16] = { 0 };
4200 curblock
[x
] ^= src
[x
];
4201 aes_encrypt(curblock
, dst
, ecx
);
4202 memcpy(curblock
, dst
, sizeof(curblock
));
4210 static int decode_frame(aes_decrypt_ctx
*dcx
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4213 unsigned char *workspace
;
4215 workspace
= alloca(*datalen
);
4216 memset(f
, 0, sizeof(*f
));
4217 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4218 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4219 if (*datalen
< 16 + sizeof(struct ast_iax2_full_hdr
))
4222 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), dcx
);
4224 padding
= 16 + (workspace
[15] & 0xf);
4225 if (option_debug
&& iaxdebug
)
4226 ast_log(LOG_DEBUG
, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen
, padding
, workspace
[15]);
4227 if (*datalen
< padding
+ sizeof(struct ast_iax2_full_hdr
))
4230 *datalen
-= padding
;
4231 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4232 f
->frametype
= fh
->type
;
4233 if (f
->frametype
== AST_FRAME_VIDEO
) {
4234 f
->subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
4236 f
->subclass
= uncompress_subclass(fh
->csub
);
4239 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4240 if (option_debug
&& iaxdebug
)
4241 ast_log(LOG_DEBUG
, "Decoding mini with length %d\n", *datalen
);
4242 if (*datalen
< 16 + sizeof(struct ast_iax2_mini_hdr
))
4245 memcpy_decrypt(workspace
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), dcx
);
4246 padding
= 16 + (workspace
[15] & 0x0f);
4247 if (*datalen
< padding
+ sizeof(struct ast_iax2_mini_hdr
))
4249 *datalen
-= padding
;
4250 memcpy(efh
->encdata
, workspace
+ padding
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4255 static int encrypt_frame(aes_encrypt_ctx
*ecx
, struct ast_iax2_full_hdr
*fh
, unsigned char *poo
, int *datalen
)
4258 unsigned char *workspace
;
4259 workspace
= alloca(*datalen
+ 32);
4262 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
4263 struct ast_iax2_full_enc_hdr
*efh
= (struct ast_iax2_full_enc_hdr
*)fh
;
4264 if (option_debug
&& iaxdebug
)
4265 ast_log(LOG_DEBUG
, "Encoding full frame %d/%d with length %d\n", fh
->type
, fh
->csub
, *datalen
);
4266 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_full_enc_hdr
)) % 16);
4267 padding
= 16 + (padding
& 0xf);
4268 memcpy(workspace
, poo
, padding
);
4269 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
));
4270 workspace
[15] &= 0xf0;
4271 workspace
[15] |= (padding
& 0xf);
4272 if (option_debug
&& iaxdebug
)
4273 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]);
4274 *datalen
+= padding
;
4275 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_full_enc_hdr
), ecx
);
4276 if (*datalen
>= 32 + sizeof(struct ast_iax2_full_enc_hdr
))
4277 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4279 struct ast_iax2_mini_enc_hdr
*efh
= (struct ast_iax2_mini_enc_hdr
*)fh
;
4280 if (option_debug
&& iaxdebug
)
4281 ast_log(LOG_DEBUG
, "Encoding mini frame with length %d\n", *datalen
);
4282 padding
= 16 - ((*datalen
- sizeof(struct ast_iax2_mini_enc_hdr
)) % 16);
4283 padding
= 16 + (padding
& 0xf);
4284 memcpy(workspace
, poo
, padding
);
4285 memcpy(workspace
+ padding
, efh
->encdata
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
));
4286 workspace
[15] &= 0xf0;
4287 workspace
[15] |= (padding
& 0x0f);
4288 *datalen
+= padding
;
4289 memcpy_encrypt(efh
->encdata
, workspace
, *datalen
- sizeof(struct ast_iax2_mini_enc_hdr
), ecx
);
4290 if (*datalen
>= 32 + sizeof(struct ast_iax2_mini_enc_hdr
))
4291 memcpy(poo
, workspace
+ *datalen
- 32, 32);
4296 static int decrypt_frame(int callno
, struct ast_iax2_full_hdr
*fh
, struct ast_frame
*f
, int *datalen
)
4299 if (!ast_test_flag(iaxs
[callno
], IAX_KEYPOPULATED
)) {
4300 /* Search for possible keys, given secrets */
4301 struct MD5Context md5
;
4302 unsigned char digest
[16];
4303 char *tmppw
, *stringp
;
4305 tmppw
= ast_strdupa(iaxs
[callno
]->secret
);
4307 while ((tmppw
= strsep(&stringp
, ";"))) {
4309 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
4310 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
4311 MD5Final(digest
, &md5
);
4312 build_enc_keys(digest
, &iaxs
[callno
]->ecx
, &iaxs
[callno
]->dcx
);
4313 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4315 ast_set_flag(iaxs
[callno
], IAX_KEYPOPULATED
);
4320 res
= decode_frame(&iaxs
[callno
]->dcx
, fh
, f
, datalen
);
4324 static int iax2_send(struct chan_iax2_pvt
*pvt
, struct ast_frame
*f
, unsigned int ts
, int seqno
, int now
, int transfer
, int final
)
4326 /* Queue a packet for delivery on a given private structure. Use "ts" for
4327 timestamp, or calculate if ts is 0. Send immediately without retransmission
4328 or delayed, with retransmission */
4329 struct ast_iax2_full_hdr
*fh
;
4330 struct ast_iax2_mini_hdr
*mh
;
4331 struct ast_iax2_video_hdr
*vh
;
4333 struct iax_frame fr2
;
4334 unsigned char buffer
[4096];
4336 struct iax_frame
*fr
;
4339 unsigned int lastsent
;
4342 frb
.fr2
.afdatalen
= sizeof(frb
.buffer
);
4345 ast_log(LOG_WARNING
, "No private structure for packet?\n");
4349 lastsent
= pvt
->lastsent
;
4351 /* Calculate actual timestamp */
4352 fts
= calc_timestamp(pvt
, ts
, f
);
4354 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4355 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4356 * increment the "predicted timestamps" for voice, if we're predecting */
4357 if(f
->frametype
== AST_FRAME_VOICE
&& f
->datalen
== 0)
4361 if ((ast_test_flag(pvt
, IAX_TRUNK
) ||
4362 (((fts
& 0xFFFF0000L
) == (lastsent
& 0xFFFF0000L
)) ||
4363 ((fts
& 0xFFFF0000L
) == ((lastsent
+ 0x10000) & 0xFFFF0000L
))))
4364 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4365 (f
->frametype
== AST_FRAME_VOICE
)
4366 /* is a voice frame */ &&
4367 (f
->subclass
== pvt
->svoiceformat
)
4368 /* is the same type */ ) {
4369 /* Force immediate rather than delayed transmission */
4371 /* Mark that mini-style frame is appropriate */
4374 if ( f
->frametype
== AST_FRAME_VIDEO
) {
4376 * If the lower 15 bits of the timestamp roll over, or if
4377 * the video format changed then send a full frame.
4378 * Otherwise send a mini video frame
4380 if (((fts
& 0xFFFF8000L
) == (pvt
->lastvsent
& 0xFFFF8000L
)) &&
4381 ((f
->subclass
& ~0x1) == pvt
->svideoformat
)
4389 pvt
->lastvsent
= fts
;
4391 /* Allocate an iax_frame */
4395 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
));
4397 ast_log(LOG_WARNING
, "Out of memory\n");
4400 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4401 iax_frame_wrap(fr
, f
);
4404 fr
->callno
= pvt
->callno
;
4405 fr
->transfer
= transfer
;
4408 /* We need a full frame */
4412 fr
->oseqno
= pvt
->oseqno
++;
4413 fr
->iseqno
= pvt
->iseqno
;
4414 fh
= (struct ast_iax2_full_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_full_hdr
));
4415 fh
->scallno
= htons(fr
->callno
| IAX_FLAG_FULL
);
4416 fh
->ts
= htonl(fr
->ts
);
4417 fh
->oseqno
= fr
->oseqno
;
4421 fh
->iseqno
= fr
->iseqno
;
4422 /* Keep track of the last thing we've acknowledged */
4424 pvt
->aseqno
= fr
->iseqno
;
4425 fh
->type
= fr
->af
.frametype
& 0xFF;
4426 if (fr
->af
.frametype
== AST_FRAME_VIDEO
)
4427 fh
->csub
= compress_subclass(fr
->af
.subclass
& ~0x1) | ((fr
->af
.subclass
& 0x1) << 6);
4429 fh
->csub
= compress_subclass(fr
->af
.subclass
);
4431 fr
->dcallno
= pvt
->transfercallno
;
4433 fr
->dcallno
= pvt
->peercallno
;
4434 fh
->dcallno
= htons(fr
->dcallno
);
4435 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_full_hdr
);
4438 /* Retry after 2x the ping time has passed */
4439 fr
->retrytime
= pvt
->pingtime
* 2;
4440 if (fr
->retrytime
< MIN_RETRY_TIME
)
4441 fr
->retrytime
= MIN_RETRY_TIME
;
4442 if (fr
->retrytime
> MAX_RETRY_TIME
)
4443 fr
->retrytime
= MAX_RETRY_TIME
;
4444 /* Acks' don't get retried */
4445 if ((f
->frametype
== AST_FRAME_IAX
) && (f
->subclass
== IAX_COMMAND_ACK
))
4447 else if (f
->frametype
== AST_FRAME_VOICE
)
4448 pvt
->svoiceformat
= f
->subclass
;
4449 else if (f
->frametype
== AST_FRAME_VIDEO
)
4450 pvt
->svideoformat
= f
->subclass
& ~0x1;
4451 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4452 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4455 iax_showframe(fr
, NULL
, 2, &pvt
->transfer
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4457 iax_showframe(fr
, NULL
, 2, &pvt
->addr
, fr
->datalen
- sizeof(struct ast_iax2_full_hdr
));
4459 encrypt_frame(&pvt
->ecx
, fh
, pvt
->semirand
, &fr
->datalen
);
4461 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4465 res
= send_packet(fr
);
4467 res
= iax2_transmit(fr
);
4469 if (ast_test_flag(pvt
, IAX_TRUNK
)) {
4470 iax2_trunk_queue(pvt
, fr
);
4472 } else if (fr
->af
.frametype
== AST_FRAME_VIDEO
) {
4473 /* Video frame have no sequence number */
4476 vh
= (struct ast_iax2_video_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_video_hdr
));
4478 vh
->callno
= htons(0x8000 | fr
->callno
);
4479 vh
->ts
= htons((fr
->ts
& 0x7FFF) | (fr
->af
.subclass
& 0x1 ? 0x8000 : 0));
4480 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_video_hdr
);
4483 res
= send_packet(fr
);
4485 /* Mini-frames have no sequence number */
4488 /* Mini frame will do */
4489 mh
= (struct ast_iax2_mini_hdr
*)(fr
->af
.data
- sizeof(struct ast_iax2_mini_hdr
));
4490 mh
->callno
= htons(fr
->callno
);
4491 mh
->ts
= htons(fr
->ts
& 0xFFFF);
4492 fr
->datalen
= fr
->af
.datalen
+ sizeof(struct ast_iax2_mini_hdr
);
4495 if (pvt
->transferring
== TRANSFER_MEDIAPASS
)
4497 if (ast_test_flag(pvt
, IAX_ENCRYPTED
)) {
4498 if (ast_test_flag(pvt
, IAX_KEYPOPULATED
)) {
4499 encrypt_frame(&pvt
->ecx
, (struct ast_iax2_full_hdr
*)mh
, pvt
->semirand
, &fr
->datalen
);
4501 ast_log(LOG_WARNING
, "Supposed to send packet encrypted, but no key?\n");
4503 res
= send_packet(fr
);
4509 static int iax2_show_users(int fd
, int argc
, char *argv
[])
4512 int havepattern
= 0;
4514 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4515 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4517 struct iax2_user
*user
= NULL
;
4520 struct ao2_iterator i
;
4524 if (!strcasecmp(argv
[3], "like")) {
4525 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
4526 return RESULT_SHOWUSAGE
;
4529 return RESULT_SHOWUSAGE
;
4533 return RESULT_SHOWUSAGE
;
4536 ast_cli(fd
, FORMAT
, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4537 i
= ao2_iterator_init(users
, 0);
4538 for (user
= ao2_iterator_next(&i
); user
;
4539 user_unref(user
), user
= ao2_iterator_next(&i
)) {
4540 if (havepattern
&& regexec(®exbuf
, user
->name
, 0, NULL
, 0))
4543 if (!ast_strlen_zero(user
->secret
)) {
4544 ast_copy_string(auth
,user
->secret
,sizeof(auth
));
4545 } else if (!ast_strlen_zero(user
->inkeys
)) {
4546 snprintf(auth
, sizeof(auth
), "Key: %-15.15s ", user
->inkeys
);
4548 ast_copy_string(auth
, "-no secret-", sizeof(auth
));
4550 if(ast_test_flag(user
,IAX_CODEC_NOCAP
))
4552 else if(ast_test_flag(user
,IAX_CODEC_NOPREFS
))
4555 pstr
= ast_test_flag(user
,IAX_CODEC_USER_FIRST
) ? "Caller" : "Host";
4557 ast_cli(fd
, FORMAT2
, user
->name
, auth
, user
->authmethods
,
4558 user
->contexts
? user
->contexts
->context
: context
,
4559 user
->ha
? "Yes" : "No", pstr
);
4565 return RESULT_SUCCESS
;
4570 static int __iax2_show_peers(int manager
, int fd
, struct mansession
*s
, int argc
, char *argv
[])
4573 int havepattern
= 0;
4574 int total_peers
= 0;
4575 int online_peers
= 0;
4576 int offline_peers
= 0;
4577 int unmonitored_peers
= 0;
4578 struct ao2_iterator i
;
4580 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4581 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4583 struct iax2_peer
*peer
= NULL
;
4585 int registeredonly
=0;
4586 char *term
= manager
? "\r\n" : "\n";
4590 if (!strcasecmp(argv
[3], "registered"))
4593 return RESULT_SHOWUSAGE
;
4594 if (!strcasecmp(argv
[4], "like")) {
4595 if (regcomp(®exbuf
, argv
[5], REG_EXTENDED
| REG_NOSUB
))
4596 return RESULT_SHOWUSAGE
;
4599 return RESULT_SHOWUSAGE
;
4602 if (!strcasecmp(argv
[3], "like")) {
4603 if (regcomp(®exbuf
, argv
[4], REG_EXTENDED
| REG_NOSUB
))
4604 return RESULT_SHOWUSAGE
;
4607 return RESULT_SHOWUSAGE
;
4610 if (!strcasecmp(argv
[3], "registered"))
4613 return RESULT_SHOWUSAGE
;
4618 return RESULT_SHOWUSAGE
;
4623 astman_append(s
, FORMAT2
, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term
);
4625 ast_cli(fd
, FORMAT2
, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term
);
4627 i
= ao2_iterator_init(peers
, 0);
4628 for (peer
= ao2_iterator_next(&i
); peer
;
4629 peer_unref(peer
), peer
= ao2_iterator_next(&i
)) {
4635 if (registeredonly
&& !peer
->addr
.sin_addr
.s_addr
)
4637 if (havepattern
&& regexec(®exbuf
, peer
->name
, 0, NULL
, 0))
4640 if (!ast_strlen_zero(peer
->username
))
4641 snprintf(name
, sizeof(name
), "%s/%s", peer
->name
, peer
->username
);
4643 ast_copy_string(name
, peer
->name
, sizeof(name
));
4645 retstatus
= peer_status(peer
, status
, sizeof(status
));
4648 else if (!retstatus
)
4651 unmonitored_peers
++;
4653 ast_copy_string(nm
, ast_inet_ntoa(peer
->mask
), sizeof(nm
));
4655 snprintf(srch
, sizeof(srch
), FORMAT
, name
,
4656 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
4657 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4659 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4660 peer
->encmethods
? "(E)" : " ", status
, term
);
4663 astman_append(s
, FORMAT
, name
,
4664 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa( peer
->addr
.sin_addr
) : "(Unspecified)",
4665 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4667 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4668 peer
->encmethods
? "(E)" : " ", status
, term
);
4670 ast_cli(fd
, FORMAT
, name
,
4671 peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "(Unspecified)",
4672 ast_test_flag(peer
, IAX_DYNAMIC
) ? "(D)" : "(S)",
4674 ntohs(peer
->addr
.sin_port
), ast_test_flag(peer
, IAX_TRUNK
) ? "(T)" : " ",
4675 peer
->encmethods
? "(E)" : " ", status
, term
);
4680 astman_append(s
,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers
, online_peers
, offline_peers
, unmonitored_peers
, term
);
4682 ast_cli(fd
,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers
, online_peers
, offline_peers
, unmonitored_peers
, term
);
4687 return RESULT_SUCCESS
;
4692 static int iax2_show_threads(int fd
, int argc
, char *argv
[])
4694 struct iax2_thread
*thread
= NULL
;
4696 int threadcount
= 0, dynamiccount
= 0;
4700 return RESULT_SHOWUSAGE
;
4702 ast_cli(fd
, "IAX2 Thread Information\n");
4704 ast_cli(fd
, "Idle Threads:\n");
4705 AST_LIST_LOCK(&idle_list
);
4706 AST_LIST_TRAVERSE(&idle_list
, thread
, list
) {
4707 #ifdef DEBUG_SCHED_MULTITHREAD
4708 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4709 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4711 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
4712 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4716 AST_LIST_UNLOCK(&idle_list
);
4717 ast_cli(fd
, "Active Threads:\n");
4718 AST_LIST_LOCK(&active_list
);
4719 AST_LIST_TRAVERSE(&active_list
, thread
, list
) {
4720 if (thread
->type
== IAX_TYPE_DYNAMIC
)
4724 #ifdef DEBUG_SCHED_MULTITHREAD
4725 ast_cli(fd
, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4726 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4728 ast_cli(fd
, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4729 type
, thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4733 AST_LIST_UNLOCK(&active_list
);
4734 ast_cli(fd
, "Dynamic Threads:\n");
4735 AST_LIST_LOCK(&dynamic_list
);
4736 AST_LIST_TRAVERSE(&dynamic_list
, thread
, list
) {
4737 #ifdef DEBUG_SCHED_MULTITHREAD
4738 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4739 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
, thread
->curfunc
);
4741 ast_cli(fd
, "Thread %d: state=%d, update=%d, actions=%d\n",
4742 thread
->threadnum
, thread
->iostate
, (int)(t
- thread
->checktime
), thread
->actions
);
4746 AST_LIST_UNLOCK(&dynamic_list
);
4747 ast_cli(fd
, "%d of %d threads accounted for with %d dynamic threads\n", threadcount
, iaxthreadcount
, dynamiccount
);
4748 return RESULT_SUCCESS
;
4751 static int iax2_show_peers(int fd
, int argc
, char *argv
[])
4753 return __iax2_show_peers(0, fd
, NULL
, argc
, argv
);
4755 static int manager_iax2_show_netstats(struct mansession
*s
, const struct message
*m
)
4757 ast_cli_netstats(s
, -1, 0);
4758 astman_append(s
, "\r\n");
4759 return RESULT_SUCCESS
;
4762 static int iax2_show_firmware(int fd
, int argc
, char *argv
[])
4764 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4765 #if !defined(__FreeBSD__)
4766 #define FORMAT "%-15.15s %-15d %-15d\n"
4767 #else /* __FreeBSD__ */
4768 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4769 #endif /* __FreeBSD__ */
4770 struct iax_firmware
*cur
;
4771 if ((argc
!= 3) && (argc
!= 4))
4772 return RESULT_SHOWUSAGE
;
4773 ast_mutex_lock(&waresl
.lock
);
4775 ast_cli(fd
, FORMAT2
, "Device", "Version", "Size");
4776 for (cur
= waresl
.wares
;cur
;cur
= cur
->next
) {
4777 if ((argc
== 3) || (!strcasecmp(argv
[3], (char *)cur
->fwh
->devname
)))
4778 ast_cli(fd
, FORMAT
, cur
->fwh
->devname
, ntohs(cur
->fwh
->version
),
4779 (int)ntohl(cur
->fwh
->datalen
));
4781 ast_mutex_unlock(&waresl
.lock
);
4782 return RESULT_SUCCESS
;
4787 /* JDG: callback to display iax peers in manager */
4788 static int manager_iax2_show_peers(struct mansession
*s
, const struct message
*m
)
4790 char *a
[] = { "iax2", "show", "users" };
4792 const char *id
= astman_get_header(m
,"ActionID");
4794 if (!ast_strlen_zero(id
))
4795 astman_append(s
, "ActionID: %s\r\n",id
);
4796 ret
= __iax2_show_peers(1, -1, s
, 3, a
);
4797 astman_append(s
, "\r\n\r\n" );
4801 static char *regstate2str(int regstate
)
4804 case REG_STATE_UNREGISTERED
:
4805 return "Unregistered";
4806 case REG_STATE_REGSENT
:
4807 return "Request Sent";
4808 case REG_STATE_AUTHSENT
:
4809 return "Auth. Sent";
4810 case REG_STATE_REGISTERED
:
4811 return "Registered";
4812 case REG_STATE_REJECTED
:
4814 case REG_STATE_TIMEOUT
:
4816 case REG_STATE_NOAUTH
:
4817 return "No Authentication";
4823 static int iax2_show_registry(int fd
, int argc
, char *argv
[])
4825 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4826 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4827 struct iax2_registry
*reg
= NULL
;
4832 return RESULT_SHOWUSAGE
;
4833 ast_cli(fd
, FORMAT2
, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4834 AST_LIST_LOCK(®istrations
);
4835 AST_LIST_TRAVERSE(®istrations
, reg
, entry
) {
4836 snprintf(host
, sizeof(host
), "%s:%d", ast_inet_ntoa(reg
->addr
.sin_addr
), ntohs(reg
->addr
.sin_port
));
4837 if (reg
->us
.sin_addr
.s_addr
)
4838 snprintf(perceived
, sizeof(perceived
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
4840 ast_copy_string(perceived
, "<Unregistered>", sizeof(perceived
));
4841 ast_cli(fd
, FORMAT
, host
,
4842 (reg
->dnsmgr
) ? "Y" : "N",
4843 reg
->username
, perceived
, reg
->refresh
, regstate2str(reg
->regstate
));
4845 AST_LIST_UNLOCK(®istrations
);
4846 return RESULT_SUCCESS
;
4851 static int iax2_show_channels(int fd
, int argc
, char *argv
[])
4853 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4854 #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"
4855 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4860 return RESULT_SHOWUSAGE
;
4861 ast_cli(fd
, FORMAT2
, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4862 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
4863 ast_mutex_lock(&iaxsl
[x
]);
4865 int lag
, jitter
, localdelay
;
4868 if(ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
4869 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
4870 jitter
= jbinfo
.jitter
;
4871 localdelay
= jbinfo
.current
- jbinfo
.min
;
4876 lag
= iaxs
[x
]->remote_rr
.delay
;
4878 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4879 ast_inet_ntoa(iaxs
[x
]->addr
.sin_addr
),
4880 S_OR(iaxs
[x
]->username
, "(None)"),
4881 iaxs
[x
]->callno
, iaxs
[x
]->peercallno
,
4882 iaxs
[x
]->oseqno
, iaxs
[x
]->iseqno
,
4886 ast_getformatname(iaxs
[x
]->voiceformat
) );
4889 ast_mutex_unlock(&iaxsl
[x
]);
4891 ast_cli(fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
4892 return RESULT_SUCCESS
;
4898 static int ast_cli_netstats(struct mansession
*s
, int fd
, int limit_fmt
)
4902 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
4903 ast_mutex_lock(&iaxsl
[x
]);
4905 int localjitter
, localdelay
, locallost
, locallosspct
, localdropped
, localooo
;
4909 if(ast_test_flag(iaxs
[x
], IAX_USEJITTERBUF
)) {
4910 jb_getinfo(iaxs
[x
]->jb
, &jbinfo
);
4911 localjitter
= jbinfo
.jitter
;
4912 localdelay
= jbinfo
.current
- jbinfo
.min
;
4913 locallost
= jbinfo
.frames_lost
;
4914 locallosspct
= jbinfo
.losspct
/1000;
4915 localdropped
= jbinfo
.frames_dropped
;
4916 localooo
= jbinfo
.frames_ooo
;
4926 fmt
= "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4928 fmt
= "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4931 astman_append(s
, fmt
,
4932 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4940 iaxs
[x
]->frames_received
/1000,
4941 iaxs
[x
]->remote_rr
.jitter
,
4942 iaxs
[x
]->remote_rr
.delay
,
4943 iaxs
[x
]->remote_rr
.losscnt
,
4944 iaxs
[x
]->remote_rr
.losspct
,
4945 iaxs
[x
]->remote_rr
.dropped
,
4946 iaxs
[x
]->remote_rr
.ooo
,
4947 iaxs
[x
]->remote_rr
.packets
/1000);
4950 iaxs
[x
]->owner
? iaxs
[x
]->owner
->name
: "(None)",
4958 iaxs
[x
]->frames_received
/1000,
4959 iaxs
[x
]->remote_rr
.jitter
,
4960 iaxs
[x
]->remote_rr
.delay
,
4961 iaxs
[x
]->remote_rr
.losscnt
,
4962 iaxs
[x
]->remote_rr
.losspct
,
4963 iaxs
[x
]->remote_rr
.dropped
,
4964 iaxs
[x
]->remote_rr
.ooo
,
4965 iaxs
[x
]->remote_rr
.packets
/1000
4969 ast_mutex_unlock(&iaxsl
[x
]);
4974 static int iax2_show_netstats(int fd
, int argc
, char *argv
[])
4978 return RESULT_SHOWUSAGE
;
4979 ast_cli(fd
, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4980 ast_cli(fd
, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4981 numchans
= ast_cli_netstats(NULL
, fd
, 1);
4982 ast_cli(fd
, "%d active IAX channel%s\n", numchans
, (numchans
!= 1) ? "s" : "");
4983 return RESULT_SUCCESS
;
4986 static int iax2_do_debug(int fd
, int argc
, char *argv
[])
4988 if (argc
< 2 || argc
> 3)
4989 return RESULT_SHOWUSAGE
;
4991 ast_cli(fd
, "IAX2 Debugging Enabled\n");
4992 return RESULT_SUCCESS
;
4995 static int iax2_do_trunk_debug(int fd
, int argc
, char *argv
[])
4997 if (argc
< 3 || argc
> 4)
4998 return RESULT_SHOWUSAGE
;
5000 ast_cli(fd
, "IAX2 Trunk Debug Requested\n");
5001 return RESULT_SUCCESS
;
5004 static int iax2_do_jb_debug(int fd
, int argc
, char *argv
[])
5006 if (argc
< 3 || argc
> 4)
5007 return RESULT_SHOWUSAGE
;
5008 jb_setoutput(jb_error_output
, jb_warning_output
, jb_debug_output
);
5009 ast_cli(fd
, "IAX2 Jitterbuffer Debugging Enabled\n");
5010 return RESULT_SUCCESS
;
5013 static int iax2_no_debug(int fd
, int argc
, char *argv
[])
5015 if (argc
< 3 || argc
> 4)
5016 return RESULT_SHOWUSAGE
;
5018 ast_cli(fd
, "IAX2 Debugging Disabled\n");
5019 return RESULT_SUCCESS
;
5022 static int iax2_no_trunk_debug(int fd
, int argc
, char *argv
[])
5024 if (argc
< 4 || argc
> 5)
5025 return RESULT_SHOWUSAGE
;
5027 ast_cli(fd
, "IAX2 Trunk Debugging Disabled\n");
5028 return RESULT_SUCCESS
;
5031 static int iax2_no_jb_debug(int fd
, int argc
, char *argv
[])
5033 if (argc
< 4 || argc
> 5)
5034 return RESULT_SHOWUSAGE
;
5035 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
5036 jb_debug_output("\n");
5037 ast_cli(fd
, "IAX2 Jitterbuffer Debugging Disabled\n");
5038 return RESULT_SUCCESS
;
5041 static int iax2_write(struct ast_channel
*c
, struct ast_frame
*f
)
5043 unsigned short callno
= PTR_TO_CALLNO(c
->tech_pvt
);
5045 ast_mutex_lock(&iaxsl
[callno
]);
5047 /* If there's an outstanding error, return failure now */
5048 if (!iaxs
[callno
]->error
) {
5049 if (ast_test_flag(iaxs
[callno
], IAX_ALREADYGONE
))
5051 /* Don't waste bandwidth sending null frames */
5052 else if (f
->frametype
== AST_FRAME_NULL
)
5054 else if ((f
->frametype
== AST_FRAME_VOICE
) && ast_test_flag(iaxs
[callno
], IAX_QUELCH
))
5056 else if (!ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
5059 /* Simple, just queue for transmission */
5060 res
= iax2_send(iaxs
[callno
], f
, 0, -1, 0, 0, 0);
5063 ast_log(LOG_DEBUG
, "Write error: %s\n", strerror(errno
));
5066 /* If it's already gone, just return */
5067 ast_mutex_unlock(&iaxsl
[callno
]);
5071 static int __send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
,
5072 int now
, int transfer
, int final
)
5074 struct ast_frame f
= { 0, };
5077 f
.subclass
= command
;
5078 f
.datalen
= datalen
;
5079 f
.src
= __FUNCTION__
;
5080 f
.data
= (void *) data
;
5082 return iax2_send(i
, &f
, ts
, seqno
, now
, transfer
, final
);
5085 static int send_command(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5087 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 0);
5090 static int send_command_locked(unsigned short callno
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
, int seqno
)
5093 ast_mutex_lock(&iaxsl
[callno
]);
5094 res
= send_command(iaxs
[callno
], type
, command
, ts
, data
, datalen
, seqno
);
5095 ast_mutex_unlock(&iaxsl
[callno
]);
5100 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5101 * the pvt struct for the given call number may disappear during its
5104 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
)
5106 int call_num
= i
->callno
;
5107 /* It is assumed that the callno has already been locked */
5108 iax2_predestroy(i
->callno
);
5109 if (!iaxs
[call_num
])
5111 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 0, 0, 1);
5114 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
)
5116 return __send_command(i
, type
, command
, ts
, data
, datalen
, seqno
, 1, 0, 0);
5119 static int send_command_transfer(struct chan_iax2_pvt
*i
, char type
, int command
, unsigned int ts
, const unsigned char *data
, int datalen
)
5121 return __send_command(i
, type
, command
, ts
, data
, datalen
, 0, 0, 1, 0);
5124 static int apply_context(struct iax2_context
*con
, const char *context
)
5127 if (!strcmp(con
->context
, context
) || !strcmp(con
->context
, "*"))
5135 static int check_access(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
5137 /* Start pessimistic */
5140 struct iax2_user
*user
= NULL
, *best
= NULL
;
5142 int gotcapability
= 0;
5143 struct ast_variable
*v
= NULL
, *tmpvar
= NULL
;
5144 struct ao2_iterator i
;
5148 if (ies
->called_number
)
5149 ast_string_field_set(iaxs
[callno
], exten
, ies
->called_number
);
5150 if (ies
->calling_number
) {
5151 ast_shrink_phone_number(ies
->calling_number
);
5152 ast_string_field_set(iaxs
[callno
], cid_num
, ies
->calling_number
);
5154 if (ies
->calling_name
)
5155 ast_string_field_set(iaxs
[callno
], cid_name
, ies
->calling_name
);
5156 if (ies
->calling_ani
)
5157 ast_string_field_set(iaxs
[callno
], ani
, ies
->calling_ani
);
5159 ast_string_field_set(iaxs
[callno
], dnid
, ies
->dnid
);
5161 ast_string_field_set(iaxs
[callno
], rdnis
, ies
->rdnis
);
5162 if (ies
->called_context
)
5163 ast_string_field_set(iaxs
[callno
], context
, ies
->called_context
);
5165 ast_string_field_set(iaxs
[callno
], language
, ies
->language
);
5167 ast_string_field_set(iaxs
[callno
], username
, ies
->username
);
5168 if (ies
->calling_ton
> -1)
5169 iaxs
[callno
]->calling_ton
= ies
->calling_ton
;
5170 if (ies
->calling_tns
> -1)
5171 iaxs
[callno
]->calling_tns
= ies
->calling_tns
;
5172 if (ies
->calling_pres
> -1)
5173 iaxs
[callno
]->calling_pres
= ies
->calling_pres
;
5175 iaxs
[callno
]->peerformat
= ies
->format
;
5177 iaxs
[callno
]->peeradsicpe
= ies
->adsicpe
;
5178 if (ies
->capability
) {
5180 iaxs
[callno
]->peercapability
= ies
->capability
;
5183 version
= ies
->version
;
5185 /* Use provided preferences until told otherwise for actual preferences */
5186 if(ies
->codec_prefs
) {
5187 ast_codec_pref_convert(&iaxs
[callno
]->rprefs
, ies
->codec_prefs
, 32, 0);
5188 ast_codec_pref_convert(&iaxs
[callno
]->prefs
, ies
->codec_prefs
, 32, 0);
5192 iaxs
[callno
]->peercapability
= iaxs
[callno
]->peerformat
;
5193 if (version
> IAX_PROTO_VERSION
) {
5194 ast_log(LOG_WARNING
, "Peer '%s' has too new a protocol version (%d) for me\n",
5195 ast_inet_ntoa(sin
->sin_addr
), version
);
5198 /* Search the userlist for a compatible entry, and fill in the rest */
5199 i
= ao2_iterator_init(users
, 0);
5200 while ((user
= ao2_iterator_next(&i
))) {
5201 if ((ast_strlen_zero(iaxs
[callno
]->username
) || /* No username specified */
5202 !strcmp(iaxs
[callno
]->username
, user
->name
)) /* Or this username specified */
5203 && ast_apply_ha(user
->ha
, sin
) /* Access is permitted from this IP */
5204 && (ast_strlen_zero(iaxs
[callno
]->context
) || /* No context specified */
5205 apply_context(user
->contexts
, iaxs
[callno
]->context
))) { /* Context is permitted */
5206 if (!ast_strlen_zero(iaxs
[callno
]->username
)) {
5207 /* Exact match, stop right now. */
5212 } else if (ast_strlen_zero(user
->secret
) && ast_strlen_zero(user
->dbsecret
) && ast_strlen_zero(user
->inkeys
)) {
5213 /* No required authentication */
5215 /* There was host authentication and we passed, bonus! */
5216 if (bestscore
< 4) {
5224 /* No host access, but no secret, either, not bad */
5225 if (bestscore
< 3) {
5235 /* Authentication, but host access too, eh, it's something.. */
5236 if (bestscore
< 2) {
5244 /* Authentication and no host access... This is our baseline */
5245 if (bestscore
< 1) {
5258 if (!user
&& !ast_strlen_zero(iaxs
[callno
]->username
)) {
5259 user
= realtime_user(iaxs
[callno
]->username
, sin
);
5260 if (user
&& !ast_strlen_zero(iaxs
[callno
]->context
) && /* No context specified */
5261 !apply_context(user
->contexts
, iaxs
[callno
]->context
)) { /* Context is permitted */
5262 user
= user_unref(user
);
5266 /* We found our match (use the first) */
5268 for (v
= user
->vars
; v
; v
= v
->next
) {
5269 if((tmpvar
= ast_variable_new(v
->name
, v
->value
))) {
5270 tmpvar
->next
= iaxs
[callno
]->vars
;
5271 iaxs
[callno
]->vars
= tmpvar
;
5274 /* If a max AUTHREQ restriction is in place, activate it */
5275 if (user
->maxauthreq
> 0)
5276 ast_set_flag(iaxs
[callno
], IAX_MAXAUTHREQ
);
5277 iaxs
[callno
]->prefs
= user
->prefs
;
5278 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_USER_FIRST
);
5279 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOPREFS
);
5280 ast_copy_flags(iaxs
[callno
], user
, IAX_CODEC_NOCAP
);
5281 iaxs
[callno
]->encmethods
= user
->encmethods
;
5282 /* Store the requested username if not specified */
5283 if (ast_strlen_zero(iaxs
[callno
]->username
))
5284 ast_string_field_set(iaxs
[callno
], username
, user
->name
);
5285 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5286 ast_copy_flags(iaxs
[callno
], user
, IAX_TRUNK
);
5287 iaxs
[callno
]->capability
= user
->capability
;
5288 /* And use the default context */
5289 if (ast_strlen_zero(iaxs
[callno
]->context
)) {
5291 ast_string_field_set(iaxs
[callno
], context
, user
->contexts
->context
);
5293 ast_string_field_set(iaxs
[callno
], context
, context
);
5295 /* And any input keys */
5296 ast_string_field_set(iaxs
[callno
], inkeys
, user
->inkeys
);
5297 /* And the permitted authentication methods */
5298 iaxs
[callno
]->authmethods
= user
->authmethods
;
5299 iaxs
[callno
]->adsi
= user
->adsi
;
5300 /* If the user has callerid, override the remote caller id. */
5301 if (ast_test_flag(user
, IAX_HASCALLERID
)) {
5302 iaxs
[callno
]->calling_tns
= 0;
5303 iaxs
[callno
]->calling_ton
= 0;
5304 ast_string_field_set(iaxs
[callno
], cid_num
, user
->cid_num
);
5305 ast_string_field_set(iaxs
[callno
], cid_name
, user
->cid_name
);
5306 ast_string_field_set(iaxs
[callno
], ani
, user
->cid_num
);
5307 iaxs
[callno
]->calling_pres
= AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN
;
5308 } else if (ast_strlen_zero(iaxs
[callno
]->cid_num
) && ast_strlen_zero(iaxs
[callno
]->cid_name
)) {
5309 iaxs
[callno
]->calling_pres
= AST_PRES_NUMBER_NOT_AVAILABLE
;
5310 } /* else user is allowed to set their own CID settings */
5311 if (!ast_strlen_zero(user
->accountcode
))
5312 ast_string_field_set(iaxs
[callno
], accountcode
, user
->accountcode
);
5313 if (!ast_strlen_zero(user
->mohinterpret
))
5314 ast_string_field_set(iaxs
[callno
], mohinterpret
, user
->mohinterpret
);
5315 if (!ast_strlen_zero(user
->mohsuggest
))
5316 ast_string_field_set(iaxs
[callno
], mohsuggest
, user
->mohsuggest
);
5318 iaxs
[callno
]->amaflags
= user
->amaflags
;
5319 if (!ast_strlen_zero(user
->language
))
5320 ast_string_field_set(iaxs
[callno
], language
, user
->language
);
5321 ast_copy_flags(iaxs
[callno
], user
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
5322 /* Keep this check last */
5323 if (!ast_strlen_zero(user
->dbsecret
)) {
5324 char *family
, *key
=NULL
;
5326 family
= ast_strdupa(user
->dbsecret
);
5327 key
= strchr(family
, '/');
5332 if (!key
|| ast_db_get(family
, key
, buf
, sizeof(buf
)))
5333 ast_log(LOG_WARNING
, "Unable to retrieve database password for family/key '%s'!\n", user
->dbsecret
);
5335 ast_string_field_set(iaxs
[callno
], secret
, buf
);
5337 ast_string_field_set(iaxs
[callno
], secret
, user
->secret
);
5339 user
= user_unref(user
);
5341 ast_set2_flag(iaxs
[callno
], iax2_getpeertrunk(*sin
), IAX_TRUNK
);
5345 static int raw_hangup(struct sockaddr_in
*sin
, unsigned short src
, unsigned short dst
, int sockfd
)
5347 struct ast_iax2_full_hdr fh
;
5348 fh
.scallno
= htons(src
| IAX_FLAG_FULL
);
5349 fh
.dcallno
= htons(dst
);
5353 fh
.type
= AST_FRAME_IAX
;
5354 fh
.csub
= compress_subclass(IAX_COMMAND_INVAL
);
5356 iax_showframe(NULL
, &fh
, 0, sin
, 0);
5358 ast_log(LOG_DEBUG
, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5359 ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), src
, dst
);
5360 return sendto(sockfd
, &fh
, sizeof(fh
), 0, (struct sockaddr
*)sin
, sizeof(*sin
));
5363 static void merge_encryption(struct chan_iax2_pvt
*p
, unsigned int enc
)
5365 /* Select exactly one common encryption if there are any */
5366 p
->encmethods
&= enc
;
5367 if (p
->encmethods
) {
5368 if (p
->encmethods
& IAX_ENCRYPT_AES128
)
5369 p
->encmethods
= IAX_ENCRYPT_AES128
;
5376 * \pre iaxsl[call_num] is locked
5378 * \note Since this function calls send_command_final(), the pvt struct for the given
5379 * call number may disappear while executing this function.
5381 static int authenticate_request(int call_num
)
5383 struct iax_ie_data ied
;
5384 int res
= -1, authreq_restrict
= 0;
5386 struct chan_iax2_pvt
*p
= iaxs
[call_num
];
5388 memset(&ied
, 0, sizeof(ied
));
5390 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5391 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
5392 struct iax2_user
*user
, tmp_user
= {
5393 .name
= p
->username
,
5396 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
5398 if (user
->curauthreq
== user
->maxauthreq
)
5399 authreq_restrict
= 1;
5402 user
= user_unref(user
);
5406 /* If the AUTHREQ limit test failed, send back an error */
5407 if (authreq_restrict
) {
5408 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Unauthenticated call limit reached");
5409 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_CALL_REJECTED
);
5410 send_command_final(p
, AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied
.buf
, ied
.pos
, -1);
5414 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
5415 if (p
->authmethods
& (IAX_AUTH_MD5
| IAX_AUTH_RSA
)) {
5416 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
5417 ast_string_field_set(p
, challenge
, challenge
);
5418 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5419 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, p
->challenge
);
5422 iax_ie_append_short(&ied
, IAX_IE_ENCRYPTION
, p
->encmethods
);
5424 iax_ie_append_str(&ied
,IAX_IE_USERNAME
, p
->username
);
5426 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREQ
, 0, ied
.buf
, ied
.pos
, -1);
5429 ast_set_flag(p
, IAX_ENCRYPTED
);
5434 static int authenticate_verify(struct chan_iax2_pvt
*p
, struct iax_ies
*ies
)
5436 char requeststr
[256];
5437 char md5secret
[256] = "";
5438 char secret
[256] = "";
5439 char rsasecret
[256] = "";
5442 struct iax2_user
*user
, tmp_user
= {
5443 .name
= p
->username
,
5446 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
5448 if (ast_test_flag(p
, IAX_MAXAUTHREQ
)) {
5449 ast_atomic_fetchadd_int(&user
->curauthreq
, -1);
5450 ast_clear_flag(p
, IAX_MAXAUTHREQ
);
5452 ast_string_field_set(p
, host
, user
->name
);
5453 user
= user_unref(user
);
5456 if (!ast_test_flag(&p
->state
, IAX_STATE_AUTHENTICATED
))
5459 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
5460 if (ies
->md5_result
)
5461 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
5462 if (ies
->rsa_result
)
5463 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
5464 if ((p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(rsasecret
) && !ast_strlen_zero(p
->inkeys
)) {
5465 struct ast_key
*key
;
5469 ast_copy_string(tmpkey
, p
->inkeys
, sizeof(tmpkey
));
5471 keyn
= strsep(&stringp
, ":");
5473 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
5474 if (key
&& !ast_check_signature(key
, p
->challenge
, rsasecret
)) {
5478 ast_log(LOG_WARNING
, "requested inkey '%s' for RSA authentication does not exist\n", keyn
);
5479 keyn
= strsep(&stringp
, ":");
5481 } else if (p
->authmethods
& IAX_AUTH_MD5
) {
5482 struct MD5Context md5
;
5483 unsigned char digest
[16];
5484 char *tmppw
, *stringp
;
5486 tmppw
= ast_strdupa(p
->secret
);
5488 while((tmppw
= strsep(&stringp
, ";"))) {
5490 MD5Update(&md5
, (unsigned char *)p
->challenge
, strlen(p
->challenge
));
5491 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
5492 MD5Final(digest
, &md5
);
5493 /* If they support md5, authenticate with it. */
5495 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5496 if (!strcasecmp(requeststr
, md5secret
)) {
5501 } else if (p
->authmethods
& IAX_AUTH_PLAINTEXT
) {
5502 if (!strcmp(secret
, p
->secret
))
5508 /*! \brief Verify inbound registration */
5509 static int register_verify(int callno
, struct sockaddr_in
*sin
, struct iax_ies
*ies
)
5511 char requeststr
[256] = "";
5512 char peer
[256] = "";
5513 char md5secret
[256] = "";
5514 char rsasecret
[256] = "";
5515 char secret
[256] = "";
5516 struct iax2_peer
*p
= NULL
;
5517 struct ast_key
*key
;
5523 ast_clear_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
);
5524 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5526 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
5528 ast_copy_string(secret
, ies
->password
, sizeof(secret
));
5529 if (ies
->md5_result
)
5530 ast_copy_string(md5secret
, ies
->md5_result
, sizeof(md5secret
));
5531 if (ies
->rsa_result
)
5532 ast_copy_string(rsasecret
, ies
->rsa_result
, sizeof(rsasecret
));
5534 expire
= ies
->refresh
;
5536 if (ast_strlen_zero(peer
)) {
5537 ast_log(LOG_NOTICE
, "Empty registration from %s\n", ast_inet_ntoa(sin
->sin_addr
));
5541 /* SLD: first call to lookup peer during registration */
5542 ast_mutex_unlock(&iaxsl
[callno
]);
5543 p
= find_peer(peer
, 1);
5544 ast_mutex_lock(&iaxsl
[callno
]);
5545 if (!p
|| !iaxs
[callno
]) {
5546 if (authdebug
&& !p
)
5547 ast_log(LOG_NOTICE
, "No registration for peer '%s' (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
5551 if (!ast_test_flag(p
, IAX_DYNAMIC
)) {
5553 ast_log(LOG_NOTICE
, "Peer '%s' is not dynamic (from %s)\n", peer
, ast_inet_ntoa(sin
->sin_addr
));
5557 if (!ast_apply_ha(p
->ha
, sin
)) {
5559 ast_log(LOG_NOTICE
, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
5562 if (!inaddrcmp(&p
->addr
, sin
))
5563 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_UNCHANGED
);
5564 ast_string_field_set(iaxs
[callno
], secret
, p
->secret
);
5565 ast_string_field_set(iaxs
[callno
], inkeys
, p
->inkeys
);
5566 /* Check secret against what we have on file */
5567 if (!ast_strlen_zero(rsasecret
) && (p
->authmethods
& IAX_AUTH_RSA
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
5568 if (!ast_strlen_zero(p
->inkeys
)) {
5571 ast_copy_string(tmpkeys
, p
->inkeys
, sizeof(tmpkeys
));
5573 keyn
= strsep(&stringp
, ":");
5575 key
= ast_key_get(keyn
, AST_KEY_PUBLIC
);
5576 if (key
&& !ast_check_signature(key
, iaxs
[callno
]->challenge
, rsasecret
)) {
5577 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5580 ast_log(LOG_WARNING
, "requested inkey '%s' does not exist\n", keyn
);
5581 keyn
= strsep(&stringp
, ":");
5585 ast_log(LOG_NOTICE
, "Host %s failed RSA authentication with inkeys '%s'\n", peer
, p
->inkeys
);
5590 ast_log(LOG_NOTICE
, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer
);
5593 } else if (!ast_strlen_zero(md5secret
) && (p
->authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(iaxs
[callno
]->challenge
)) {
5594 struct MD5Context md5
;
5595 unsigned char digest
[16];
5596 char *tmppw
, *stringp
;
5598 tmppw
= ast_strdupa(p
->secret
);
5600 while((tmppw
= strsep(&stringp
, ";"))) {
5602 MD5Update(&md5
, (unsigned char *)iaxs
[callno
]->challenge
, strlen(iaxs
[callno
]->challenge
));
5603 MD5Update(&md5
, (unsigned char *)tmppw
, strlen(tmppw
));
5604 MD5Final(digest
, &md5
);
5606 sprintf(requeststr
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5607 if (!strcasecmp(requeststr
, md5secret
))
5611 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5614 ast_log(LOG_NOTICE
, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
, requeststr
, md5secret
);
5617 } else if (!ast_strlen_zero(secret
) && (p
->authmethods
& IAX_AUTH_PLAINTEXT
)) {
5618 /* They've provided a plain text password and we support that */
5619 if (strcmp(secret
, p
->secret
)) {
5621 ast_log(LOG_NOTICE
, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin
->sin_addr
), p
->name
);
5624 ast_set_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
);
5625 } else if (!ast_strlen_zero(md5secret
) || !ast_strlen_zero(secret
)) {
5627 ast_log(LOG_NOTICE
, "Inappropriate authentication received\n");
5630 ast_string_field_set(iaxs
[callno
], peer
, peer
);
5631 /* Choose lowest expiry number */
5632 if (expire
&& (expire
< iaxs
[callno
]->expiry
))
5633 iaxs
[callno
]->expiry
= expire
;
5635 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
5646 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
)
5650 if (!ast_strlen_zero(keyn
)) {
5651 if (!(authmethods
& IAX_AUTH_RSA
)) {
5652 if (ast_strlen_zero(secret
))
5653 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
));
5654 } else if (ast_strlen_zero(challenge
)) {
5655 ast_log(LOG_NOTICE
, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin
->sin_addr
));
5658 struct ast_key
*key
;
5659 key
= ast_key_get(keyn
, AST_KEY_PRIVATE
);
5661 ast_log(LOG_NOTICE
, "Unable to find private key '%s'\n", keyn
);
5663 if (ast_sign(key
, (char*)challenge
, sig
)) {
5664 ast_log(LOG_NOTICE
, "Unable to sign challenge with key\n");
5667 iax_ie_append_str(ied
, IAX_IE_RSA_RESULT
, sig
);
5674 if (res
&& !ast_strlen_zero(secret
)) {
5675 if ((authmethods
& IAX_AUTH_MD5
) && !ast_strlen_zero(challenge
)) {
5676 struct MD5Context md5
;
5677 unsigned char digest
[16];
5680 MD5Update(&md5
, (unsigned char *)challenge
, strlen(challenge
));
5681 MD5Update(&md5
, (unsigned char *)secret
, strlen(secret
));
5682 MD5Final(digest
, &md5
);
5683 /* If they support md5, authenticate with it. */
5685 sprintf(digres
+ (x
<< 1), "%2.2x", digest
[x
]); /* safe */
5687 build_enc_keys(digest
, ecx
, dcx
);
5688 iax_ie_append_str(ied
, IAX_IE_MD5_RESULT
, digres
);
5690 } else if (authmethods
& IAX_AUTH_PLAINTEXT
) {
5691 iax_ie_append_str(ied
, IAX_IE_PASSWORD
, secret
);
5694 ast_log(LOG_NOTICE
, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin
->sin_addr
), authmethods
);
5700 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5701 * so do not call this function with a pvt lock held.
5703 static int authenticate_reply(struct chan_iax2_pvt
*p
, struct sockaddr_in
*sin
, struct iax_ies
*ies
, const char *override
, const char *okey
)
5705 struct iax2_peer
*peer
= NULL
;
5706 /* Start pessimistic */
5708 int authmethods
= 0;
5709 struct iax_ie_data ied
;
5710 uint16_t callno
= p
->callno
;
5712 memset(&ied
, 0, sizeof(ied
));
5715 ast_string_field_set(p
, username
, ies
->username
);
5717 ast_string_field_set(p
, challenge
, ies
->challenge
);
5718 if (ies
->authmethods
)
5719 authmethods
= ies
->authmethods
;
5720 if (authmethods
& IAX_AUTH_MD5
)
5721 merge_encryption(p
, ies
->encmethods
);
5725 /* Check for override RSA authentication first */
5726 if (!ast_strlen_zero(override
) || !ast_strlen_zero(okey
)) {
5727 /* Normal password authentication */
5728 res
= authenticate(p
->challenge
, override
, okey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5730 struct ao2_iterator i
= ao2_iterator_init(peers
, 0);
5731 while ((peer
= ao2_iterator_next(&i
))) {
5732 if ((ast_strlen_zero(p
->peer
) || !strcmp(p
->peer
, peer
->name
))
5733 /* No peer specified at our end, or this is the peer */
5734 && (ast_strlen_zero(peer
->username
) || (!strcmp(peer
->username
, p
->username
)))
5735 /* No username specified in peer rule, or this is the right username */
5736 && (!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
)))
5737 /* No specified host, or this is our host */
5739 res
= authenticate(p
->challenge
, peer
->secret
, peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5748 /* We checked our list and didn't find one. It's unlikely, but possible,
5749 that we're trying to authenticate *to* a realtime peer */
5750 const char *peer_name
= ast_strdupa(p
->peer
);
5751 ast_mutex_unlock(&iaxsl
[callno
]);
5752 if ((peer
= realtime_peer(peer_name
, NULL
))) {
5753 ast_mutex_lock(&iaxsl
[callno
]);
5754 if (!(p
= iaxs
[callno
])) {
5758 res
= authenticate(p
->challenge
, peer
->secret
,peer
->outkey
, authmethods
, &ied
, sin
, &p
->ecx
, &p
->dcx
);
5762 ast_mutex_lock(&iaxsl
[callno
]);
5763 if (!(p
= iaxs
[callno
]))
5768 if (ies
->encmethods
)
5769 ast_set_flag(p
, IAX_ENCRYPTED
| IAX_KEYPOPULATED
);
5771 res
= send_command(p
, AST_FRAME_IAX
, IAX_COMMAND_AUTHREP
, 0, ied
.buf
, ied
.pos
, -1);
5775 static int iax2_do_register(struct iax2_registry
*reg
);
5777 static void __iax2_do_register_s(const void *data
)
5779 struct iax2_registry
*reg
= (struct iax2_registry
*)data
;
5781 iax2_do_register(reg
);
5784 static int iax2_do_register_s(const void *data
)
5786 #ifdef SCHED_MULTITHREADED
5787 if (schedule_action(__iax2_do_register_s
, data
))
5789 __iax2_do_register_s(data
);
5793 static int try_transfer(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
5797 struct iax_ie_data ied
;
5798 struct sockaddr_in
new;
5801 memset(&ied
, 0, sizeof(ied
));
5802 if (ies
->apparent_addr
)
5803 bcopy(ies
->apparent_addr
, &new, sizeof(new));
5805 newcall
= ies
->callno
;
5806 if (!newcall
|| !new.sin_addr
.s_addr
|| !new.sin_port
) {
5807 ast_log(LOG_WARNING
, "Invalid transfer request\n");
5810 pvt
->transfercallno
= newcall
;
5811 memcpy(&pvt
->transfer
, &new, sizeof(pvt
->transfer
));
5812 inet_aton(newip
, &pvt
->transfer
.sin_addr
);
5813 pvt
->transfer
.sin_family
= AF_INET
;
5814 pvt
->transferring
= TRANSFER_BEGIN
;
5815 pvt
->transferid
= ies
->transferid
;
5816 if (ies
->transferid
)
5817 iax_ie_append_int(&ied
, IAX_IE_TRANSFERID
, ies
->transferid
);
5818 send_command_transfer(pvt
, AST_FRAME_IAX
, IAX_COMMAND_TXCNT
, 0, ied
.buf
, ied
.pos
);
5822 static int complete_dpreply(struct chan_iax2_pvt
*pvt
, struct iax_ies
*ies
)
5824 char exten
[256] = "";
5825 int status
= CACHE_FLAG_UNKNOWN
;
5826 int expiry
= iaxdefaultdpcache
;
5829 struct iax2_dpcache
*dp
, *prev
;
5831 if (ies
->called_number
)
5832 ast_copy_string(exten
, ies
->called_number
, sizeof(exten
));
5834 if (ies
->dpstatus
& IAX_DPSTATUS_EXISTS
)
5835 status
= CACHE_FLAG_EXISTS
;
5836 else if (ies
->dpstatus
& IAX_DPSTATUS_CANEXIST
)
5837 status
= CACHE_FLAG_CANEXIST
;
5838 else if (ies
->dpstatus
& IAX_DPSTATUS_NONEXISTENT
)
5839 status
= CACHE_FLAG_NONEXISTENT
;
5841 if (ies
->dpstatus
& IAX_DPSTATUS_IGNOREPAT
) {
5842 /* Don't really do anything with this */
5845 expiry
= ies
->refresh
;
5846 if (ies
->dpstatus
& IAX_DPSTATUS_MATCHMORE
)
5847 matchmore
= CACHE_FLAG_MATCHMORE
;
5848 ast_mutex_lock(&dpcache_lock
);
5850 dp
= pvt
->dpentries
;
5852 if (!strcmp(dp
->exten
, exten
)) {
5855 prev
->peer
= dp
->peer
;
5857 pvt
->dpentries
= dp
->peer
;
5860 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ expiry
;
5861 if (dp
->flags
& CACHE_FLAG_PENDING
) {
5862 dp
->flags
&= ~CACHE_FLAG_PENDING
;
5863 dp
->flags
|= status
;
5864 dp
->flags
|= matchmore
;
5866 /* Wake up waiters */
5867 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
5868 if (dp
->waiters
[x
] > -1)
5869 write(dp
->waiters
[x
], "asdf", 4);
5874 ast_mutex_unlock(&dpcache_lock
);
5878 static int complete_transfer(int callno
, struct iax_ies
*ies
)
5881 struct chan_iax2_pvt
*pvt
= iaxs
[callno
];
5882 struct iax_frame
*cur
;
5886 peercallno
= ies
->callno
;
5888 if (peercallno
< 1) {
5889 ast_log(LOG_WARNING
, "Invalid transfer request\n");
5892 memcpy(&pvt
->addr
, &pvt
->transfer
, sizeof(pvt
->addr
));
5893 memset(&pvt
->transfer
, 0, sizeof(pvt
->transfer
));
5894 /* Reset sequence numbers */
5900 if (pvt
->peercallno
) {
5901 remove_by_peercallno(pvt
);
5903 pvt
->peercallno
= peercallno
;
5904 store_by_peercallno(pvt
);
5906 pvt
->transferring
= TRANSFER_NONE
;
5907 pvt
->svoiceformat
= -1;
5908 pvt
->voiceformat
= 0;
5909 pvt
->svideoformat
= -1;
5910 pvt
->videoformat
= 0;
5911 pvt
->transfercallno
= -1;
5912 memset(&pvt
->rxcore
, 0, sizeof(pvt
->rxcore
));
5913 memset(&pvt
->offset
, 0, sizeof(pvt
->offset
));
5914 /* reset jitterbuffer */
5915 while(jb_getall(pvt
->jb
,&frame
) == JB_OK
)
5916 iax2_frame_free(frame
.data
);
5922 pvt
->pingtime
= DEFAULT_RETRY_TIME
;
5923 AST_LIST_LOCK(&iaxq
.queue
);
5924 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
5925 /* We must cancel any packets that would have been transmitted
5926 because now we're talking to someone new. It's okay, they
5927 were transmitted to someone that didn't care anyway. */
5928 if (callno
== cur
->callno
)
5931 AST_LIST_UNLOCK(&iaxq
.queue
);
5935 /*! \brief Acknowledgment received for OUR registration */
5936 static int iax2_ack_registry(struct iax_ies
*ies
, struct sockaddr_in
*sin
, int callno
)
5938 struct iax2_registry
*reg
;
5939 /* Start pessimistic */
5940 char peer
[256] = "";
5943 char ourip
[256] = "<Unspecified>";
5944 struct sockaddr_in oldus
;
5945 struct sockaddr_in us
;
5948 memset(&us
, 0, sizeof(us
));
5949 if (ies
->apparent_addr
)
5950 bcopy(ies
->apparent_addr
, &us
, sizeof(us
));
5952 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
5954 refresh
= ies
->refresh
;
5955 if (ies
->calling_number
) {
5956 /* We don't do anything with it really, but maybe we should */
5958 reg
= iaxs
[callno
]->reg
;
5960 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registry '%s'\n", peer
);
5963 memcpy(&oldus
, ®
->us
, sizeof(oldus
));
5964 oldmsgs
= reg
->messages
;
5965 if (inaddrcmp(®
->addr
, sin
)) {
5966 ast_log(LOG_WARNING
, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
5969 memcpy(®
->us
, &us
, sizeof(reg
->us
));
5970 if (ies
->msgcount
>= 0)
5971 reg
->messages
= ies
->msgcount
& 0xffff; /* only low 16 bits are used in the transmission of the IE */
5972 /* always refresh the registration at the interval requested by the server
5973 we are registering to
5975 reg
->refresh
= refresh
;
5976 AST_SCHED_DEL(sched
, reg
->expire
);
5977 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
5978 if (inaddrcmp(&oldus
, ®
->us
) || (reg
->messages
!= oldmsgs
)) {
5979 if (option_verbose
> 2) {
5980 if (reg
->messages
> 255)
5981 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new and %d old messages waiting", reg
->messages
& 0xff, reg
->messages
>> 8);
5982 else if (reg
->messages
> 1)
5983 snprintf(msgstatus
, sizeof(msgstatus
), " with %d new messages waiting\n", reg
->messages
);
5984 else if (reg
->messages
> 0)
5985 snprintf(msgstatus
, sizeof(msgstatus
), " with 1 new message waiting\n");
5987 snprintf(msgstatus
, sizeof(msgstatus
), " with no messages waiting\n");
5988 snprintf(ourip
, sizeof(ourip
), "%s:%d", ast_inet_ntoa(reg
->us
.sin_addr
), ntohs(reg
->us
.sin_port
));
5989 ast_verbose(VERBOSE_PREFIX_3
"Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin
->sin_addr
), ourip
, msgstatus
);
5991 manager_event(EVENT_FLAG_SYSTEM
, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin
->sin_addr
));
5993 reg
->regstate
= REG_STATE_REGISTERED
;
5997 static int iax2_register(char *value
, int lineno
)
5999 struct iax2_registry
*reg
;
6001 char *username
, *hostname
, *secret
;
6007 ast_copy_string(copy
, value
, sizeof(copy
));
6009 username
= strsep(&stringp
, "@");
6010 hostname
= strsep(&stringp
, "@");
6012 ast_log(LOG_WARNING
, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno
);
6016 username
= strsep(&stringp
, ":");
6017 secret
= strsep(&stringp
, ":");
6019 hostname
= strsep(&stringp
, ":");
6020 porta
= strsep(&stringp
, ":");
6022 if (porta
&& !atoi(porta
)) {
6023 ast_log(LOG_WARNING
, "%s is not a valid port number at line %d\n", porta
, lineno
);
6026 if (!(reg
= ast_calloc(1, sizeof(*reg
))))
6028 if (ast_dnsmgr_lookup(hostname
, ®
->addr
.sin_addr
, ®
->dnsmgr
) < 0) {
6032 ast_copy_string(reg
->username
, username
, sizeof(reg
->username
));
6034 ast_copy_string(reg
->secret
, secret
, sizeof(reg
->secret
));
6036 reg
->refresh
= IAX_DEFAULT_REG_EXPIRE
;
6037 reg
->addr
.sin_family
= AF_INET
;
6038 reg
->addr
.sin_port
= porta
? htons(atoi(porta
)) : htons(IAX_DEFAULT_PORTNO
);
6039 AST_LIST_LOCK(®istrations
);
6040 AST_LIST_INSERT_HEAD(®istrations
, reg
, entry
);
6041 AST_LIST_UNLOCK(®istrations
);
6046 static void register_peer_exten(struct iax2_peer
*peer
, int onoff
)
6049 char *stringp
, *ext
;
6050 if (!ast_strlen_zero(regcontext
)) {
6051 ast_copy_string(multi
, S_OR(peer
->regexten
, peer
->name
), sizeof(multi
));
6053 while((ext
= strsep(&stringp
, "&"))) {
6055 if (!ast_exists_extension(NULL
, regcontext
, ext
, 1, NULL
))
6056 ast_add_extension(regcontext
, 1, ext
, 1, NULL
, NULL
,
6057 "Noop", ast_strdup(peer
->name
), ast_free
, "IAX2");
6059 ast_context_remove_extension(regcontext
, ext
, 1, NULL
);
6063 static void prune_peers(void);
6065 static void unlink_peer(struct iax2_peer
*peer
)
6067 if (peer
->expire
> -1) {
6068 if (!ast_sched_del(sched
, peer
->expire
)) {
6074 if (peer
->pokeexpire
> -1) {
6075 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
6076 peer
->pokeexpire
= -1;
6081 ao2_unlink(peers
, peer
);
6084 static void __expire_registry(const void *data
)
6086 struct iax2_peer
*peer
= (struct iax2_peer
*) data
;
6094 ast_log(LOG_DEBUG
, "Expiring registration for peer '%s'\n", peer
->name
);
6095 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(peer
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
)))
6096 realtime_update_peer(peer
->name
, &peer
->addr
, 0);
6097 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer
->name
);
6098 /* Reset the address */
6099 memset(&peer
->addr
, 0, sizeof(peer
->addr
));
6100 /* Reset expiry value */
6101 peer
->expiry
= min_reg_expire
;
6102 if (!ast_test_flag(peer
, IAX_TEMPONLY
))
6103 ast_db_del("IAX/Registry", peer
->name
);
6104 register_peer_exten(peer
, 0);
6105 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
6107 iax2_regfunk(peer
->name
, 0);
6109 if (ast_test_flag(peer
, IAX_RTAUTOCLEAR
))
6115 static int expire_registry(const void *data
)
6117 #ifdef SCHED_MULTITHREADED
6118 if (schedule_action(__expire_registry
, data
))
6120 __expire_registry(data
);
6124 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
);
6126 static void reg_source_db(struct iax2_peer
*p
)
6131 if (!ast_test_flag(p
, IAX_TEMPONLY
) && (!ast_db_get("IAX/Registry", p
->name
, data
, sizeof(data
)))) {
6132 c
= strchr(data
, ':');
6136 if (inet_aton(data
, &in
)) {
6141 if (option_verbose
> 2)
6142 ast_verbose(VERBOSE_PREFIX_3
"Seeding '%s' at %s:%d for %d\n", p
->name
,
6143 ast_inet_ntoa(in
), atoi(c
), atoi(d
));
6144 iax2_poke_peer(p
, 0);
6145 p
->expiry
= atoi(d
);
6146 memset(&p
->addr
, 0, sizeof(p
->addr
));
6147 p
->addr
.sin_family
= AF_INET
;
6148 p
->addr
.sin_addr
= in
;
6149 p
->addr
.sin_port
= htons(atoi(c
));
6150 if (p
->expire
> -1) {
6151 if (!ast_sched_del(sched
, p
->expire
)) {
6156 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
6157 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
6158 if (p
->expire
== -1)
6161 iax2_regfunk(p
->name
, 1);
6162 register_peer_exten(p
, 1);
6171 * \pre iaxsl[callno] is locked
6173 * \note Since this function calls send_command_final(), the pvt struct for
6174 * the given call number may disappear while executing this function.
6176 static int update_registry(struct sockaddr_in
*sin
, int callno
, char *devtype
, int fd
, unsigned short refresh
)
6178 /* Called from IAX thread only, with proper iaxsl lock */
6179 struct iax_ie_data ied
;
6180 struct iax2_peer
*p
;
6184 const char *peer_name
;
6187 memset(&ied
, 0, sizeof(ied
));
6189 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
6191 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6192 ast_mutex_unlock(&iaxsl
[callno
]);
6193 if (!(p
= find_peer(peer_name
, 1))) {
6194 ast_mutex_lock(&iaxsl
[callno
]);
6195 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
6198 ast_mutex_lock(&iaxsl
[callno
]);
6202 if (ast_test_flag((&globalflags
), IAX_RTUPDATE
) && (ast_test_flag(p
, IAX_TEMPONLY
|IAX_RTCACHEFRIENDS
))) {
6203 if (sin
->sin_addr
.s_addr
) {
6206 realtime_update_peer(peer_name
, sin
, nowtime
);
6208 realtime_update_peer(peer_name
, sin
, 0);
6211 if (inaddrcmp(&p
->addr
, sin
)) {
6213 iax2_regfunk(p
->name
, 1);
6214 /* Stash the IP address from which they registered */
6215 memcpy(&p
->addr
, sin
, sizeof(p
->addr
));
6216 snprintf(data
, sizeof(data
), "%s:%d:%d", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
), p
->expiry
);
6217 if (!ast_test_flag(p
, IAX_TEMPONLY
) && sin
->sin_addr
.s_addr
) {
6218 ast_db_put("IAX/Registry", p
->name
, data
);
6219 if (option_verbose
> 2)
6220 ast_verbose(VERBOSE_PREFIX_3
"Registered IAX2 '%s' (%s) at %s:%d\n", p
->name
,
6221 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin
->sin_addr
), ntohs(sin
->sin_port
));
6222 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p
->name
);
6223 register_peer_exten(p
, 1);
6224 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
6225 } else if (!ast_test_flag(p
, IAX_TEMPONLY
)) {
6226 if (option_verbose
> 2)
6227 ast_verbose(VERBOSE_PREFIX_3
"Unregistered IAX2 '%s' (%s)\n", p
->name
,
6228 ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_AUTHENTICATED
) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6229 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p
->name
);
6230 register_peer_exten(p
, 0);
6231 ast_db_del("IAX/Registry", p
->name
);
6232 ast_device_state_changed("IAX2/%s", p
->name
); /* Activate notification */
6234 /* Update the host */
6235 /* Verify that the host is really there */
6236 iax2_poke_peer(p
, callno
);
6239 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6240 if (!iaxs
[callno
]) {
6245 /* Store socket fd */
6247 /* Setup the expiry */
6248 if (p
->expire
> -1) {
6249 if (!ast_sched_del(sched
, p
->expire
)) {
6254 /* treat an unspecified refresh interval as the minimum */
6256 refresh
= min_reg_expire
;
6257 if (refresh
> max_reg_expire
) {
6258 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6259 p
->name
, max_reg_expire
, refresh
);
6260 p
->expiry
= max_reg_expire
;
6261 } else if (refresh
< min_reg_expire
) {
6262 ast_log(LOG_NOTICE
, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6263 p
->name
, min_reg_expire
, refresh
);
6264 p
->expiry
= min_reg_expire
;
6266 p
->expiry
= refresh
;
6268 if (p
->expiry
&& sin
->sin_addr
.s_addr
) {
6269 p
->expire
= iax2_sched_add(sched
, (p
->expiry
+ 10) * 1000, expire_registry
, peer_ref(p
));
6270 if (p
->expire
== -1)
6273 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, p
->name
);
6274 iax_ie_append_int(&ied
, IAX_IE_DATETIME
, iax2_datetime(p
->zonetag
));
6275 if (sin
->sin_addr
.s_addr
) {
6276 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, p
->expiry
);
6277 iax_ie_append_addr(&ied
, IAX_IE_APPARENT_ADDR
, &p
->addr
);
6278 if (!ast_strlen_zero(p
->mailbox
)) {
6280 ast_app_inboxcount(p
->mailbox
, &new, &old
);
6285 msgcount
= (old
<< 8) | new;
6286 iax_ie_append_short(&ied
, IAX_IE_MSGCOUNT
, msgcount
);
6288 if (ast_test_flag(p
, IAX_HASCALLERID
)) {
6289 iax_ie_append_str(&ied
, IAX_IE_CALLING_NUMBER
, p
->cid_num
);
6290 iax_ie_append_str(&ied
, IAX_IE_CALLING_NAME
, p
->cid_name
);
6293 version
= iax_check_version(devtype
);
6295 iax_ie_append_short(&ied
, IAX_IE_FIRMWAREVER
, version
);
6302 return res
? res
: send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGACK
, 0, ied
.buf
, ied
.pos
, -1);
6305 static int registry_authrequest(int callno
)
6307 struct iax_ie_data ied
;
6308 struct iax2_peer
*p
;
6310 const char *peer_name
;
6313 peer_name
= ast_strdupa(iaxs
[callno
]->peer
);
6315 /* SLD: third call to find_peer in registration */
6316 ast_mutex_unlock(&iaxsl
[callno
]);
6317 p
= find_peer(peer_name
, 1);
6318 ast_mutex_lock(&iaxsl
[callno
]);
6322 ast_log(LOG_WARNING
, "No such peer '%s'\n", peer_name
);
6326 memset(&ied
, 0, sizeof(ied
));
6327 iax_ie_append_short(&ied
, IAX_IE_AUTHMETHODS
, p
->authmethods
);
6328 if (p
->authmethods
& (IAX_AUTH_RSA
| IAX_AUTH_MD5
)) {
6329 /* Build the challenge */
6330 snprintf(challenge
, sizeof(challenge
), "%d", (int)ast_random());
6331 ast_string_field_set(iaxs
[callno
], challenge
, challenge
);
6332 iax_ie_append_str(&ied
, IAX_IE_CHALLENGE
, iaxs
[callno
]->challenge
);
6334 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, peer_name
);
6341 return res
? res
: send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGAUTH
, 0, ied
.buf
, ied
.pos
, -1);;
6344 static int registry_rerequest(struct iax_ies
*ies
, int callno
, struct sockaddr_in
*sin
)
6346 struct iax2_registry
*reg
;
6347 /* Start pessimistic */
6348 struct iax_ie_data ied
;
6349 char peer
[256] = "";
6350 char challenge
[256] = "";
6352 int authmethods
= 0;
6353 if (ies
->authmethods
)
6354 authmethods
= ies
->authmethods
;
6356 ast_copy_string(peer
, ies
->username
, sizeof(peer
));
6358 ast_copy_string(challenge
, ies
->challenge
, sizeof(challenge
));
6359 memset(&ied
, 0, sizeof(ied
));
6360 reg
= iaxs
[callno
]->reg
;
6362 if (inaddrcmp(®
->addr
, sin
)) {
6363 ast_log(LOG_WARNING
, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin
->sin_addr
));
6366 if (ast_strlen_zero(reg
->secret
)) {
6367 ast_log(LOG_NOTICE
, "No secret associated with peer '%s'\n", reg
->username
);
6368 reg
->regstate
= REG_STATE_NOAUTH
;
6371 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
6372 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
6373 if (reg
->secret
[0] == '[') {
6375 ast_copy_string(tmpkey
, reg
->secret
+ 1, sizeof(tmpkey
));
6376 tmpkey
[strlen(tmpkey
) - 1] = '\0';
6377 res
= authenticate(challenge
, NULL
, tmpkey
, authmethods
, &ied
, sin
, NULL
, NULL
);
6379 res
= authenticate(challenge
, reg
->secret
, NULL
, authmethods
, &ied
, sin
, NULL
, NULL
);
6381 reg
->regstate
= REG_STATE_AUTHSENT
;
6382 return send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
6385 ast_log(LOG_WARNING
, "Registry acknowledge on unknown registery '%s'\n", peer
);
6387 ast_log(LOG_NOTICE
, "Can't reregister without a reg\n");
6391 static void stop_stuff(int callno
)
6393 iax2_destroy_helper(iaxs
[callno
]);
6396 static void __auth_reject(const void *nothing
)
6398 /* Called from IAX thread only, without iaxs lock */
6399 int callno
= (int)(long)(nothing
);
6400 struct iax_ie_data ied
;
6401 ast_mutex_lock(&iaxsl
[callno
]);
6403 memset(&ied
, 0, sizeof(ied
));
6404 if (iaxs
[callno
]->authfail
== IAX_COMMAND_REGREJ
) {
6405 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Registration Refused");
6406 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_REJECTED
);
6407 } else if (iaxs
[callno
]->authfail
== IAX_COMMAND_REJECT
) {
6408 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "No authority found");
6409 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
6411 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, iaxs
[callno
]->authfail
, 0, ied
.buf
, ied
.pos
, -1);
6413 ast_mutex_unlock(&iaxsl
[callno
]);
6416 static int auth_reject(const void *data
)
6418 int callno
= (int)(long)(data
);
6419 ast_mutex_lock(&iaxsl
[callno
]);
6421 iaxs
[callno
]->authid
= -1;
6422 ast_mutex_unlock(&iaxsl
[callno
]);
6423 #ifdef SCHED_MULTITHREADED
6424 if (schedule_action(__auth_reject
, data
))
6426 __auth_reject(data
);
6430 static int auth_fail(int callno
, int failcode
)
6432 /* Schedule sending the authentication failure in one second, to prevent
6435 iaxs
[callno
]->authfail
= failcode
;
6437 AST_SCHED_DEL(sched
, iaxs
[callno
]->authid
);
6438 iaxs
[callno
]->authid
= iax2_sched_add(sched
, 1000, auth_reject
, (void *)(long)callno
);
6440 auth_reject((void *)(long)callno
);
6445 static void __auto_hangup(const void *nothing
)
6447 /* Called from IAX thread only, without iaxs lock */
6448 int callno
= (int)(long)(nothing
);
6449 struct iax_ie_data ied
;
6450 ast_mutex_lock(&iaxsl
[callno
]);
6452 memset(&ied
, 0, sizeof(ied
));
6453 iax_ie_append_str(&ied
, IAX_IE_CAUSE
, "Timeout");
6454 iax_ie_append_byte(&ied
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_USER_RESPONSE
);
6455 send_command_final(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_HANGUP
, 0, ied
.buf
, ied
.pos
, -1);
6457 ast_mutex_unlock(&iaxsl
[callno
]);
6460 static int auto_hangup(const void *data
)
6462 int callno
= (int)(long)(data
);
6463 ast_mutex_lock(&iaxsl
[callno
]);
6465 iaxs
[callno
]->autoid
= -1;
6467 ast_mutex_unlock(&iaxsl
[callno
]);
6468 #ifdef SCHED_MULTITHREADED
6469 if (schedule_action(__auto_hangup
, data
))
6471 __auto_hangup(data
);
6475 static void iax2_dprequest(struct iax2_dpcache
*dp
, int callno
)
6477 struct iax_ie_data ied
;
6478 /* Auto-hangup with 30 seconds of inactivity */
6479 AST_SCHED_DEL(sched
, iaxs
[callno
]->autoid
);
6480 iaxs
[callno
]->autoid
= iax2_sched_add(sched
, 30000, auto_hangup
, (void *)(long)callno
);
6481 memset(&ied
, 0, sizeof(ied
));
6482 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, dp
->exten
);
6483 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREQ
, 0, ied
.buf
, ied
.pos
, -1);
6484 dp
->flags
|= CACHE_FLAG_TRANSMITTED
;
6487 static int iax2_vnak(int callno
)
6489 return send_command_immediate(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_VNAK
, 0, NULL
, 0, iaxs
[callno
]->iseqno
);
6492 static void vnak_retransmit(int callno
, int last
)
6494 struct iax_frame
*f
;
6496 AST_LIST_LOCK(&iaxq
.queue
);
6497 AST_LIST_TRAVERSE(&iaxq
.queue
, f
, list
) {
6498 /* Send a copy immediately */
6499 if ((f
->callno
== callno
) && iaxs
[f
->callno
] &&
6500 ((unsigned char ) (f
->oseqno
- last
) < 128) &&
6501 (f
->retries
>= 0)) {
6505 AST_LIST_UNLOCK(&iaxq
.queue
);
6508 static void __iax2_poke_peer_s(const void *data
)
6510 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
6511 iax2_poke_peer(peer
, 0);
6515 static int iax2_poke_peer_s(const void *data
)
6517 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
6518 peer
->pokeexpire
= -1;
6519 #ifdef SCHED_MULTITHREADED
6520 if (schedule_action(__iax2_poke_peer_s
, data
))
6522 __iax2_poke_peer_s(data
);
6526 static int send_trunk(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
6529 struct iax_frame
*fr
;
6530 struct ast_iax2_meta_hdr
*meta
;
6531 struct ast_iax2_meta_trunk_hdr
*mth
;
6534 /* Point to frame */
6535 fr
= (struct iax_frame
*)tpeer
->trunkdata
;
6536 /* Point to meta data */
6537 meta
= (struct ast_iax2_meta_hdr
*)fr
->afdata
;
6538 mth
= (struct ast_iax2_meta_trunk_hdr
*)meta
->data
;
6539 if (tpeer
->trunkdatalen
) {
6540 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6542 meta
->metacmd
= IAX_META_TRUNK
;
6543 if (ast_test_flag(&globalflags
, IAX_TRUNKTIMESTAMPS
))
6544 meta
->cmddata
= IAX_META_TRUNK_MINI
;
6546 meta
->cmddata
= IAX_META_TRUNK_SUPERMINI
;
6547 mth
->ts
= htonl(calc_txpeerstamp(tpeer
, trunkfreq
, now
));
6548 /* And the rest of the ast_iax2 header */
6549 fr
->direction
= DIRECTION_OUTGRESS
;
6552 /* Any appropriate call will do */
6553 fr
->data
= fr
->afdata
;
6554 fr
->datalen
= tpeer
->trunkdatalen
+ sizeof(struct ast_iax2_meta_hdr
) + sizeof(struct ast_iax2_meta_trunk_hdr
);
6555 res
= transmit_trunk(fr
, &tpeer
->addr
, tpeer
->sockfd
);
6556 calls
= tpeer
->calls
;
6559 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
));
6561 /* Reset transmit trunk side data */
6562 tpeer
->trunkdatalen
= 0;
6570 static inline int iax2_trunk_expired(struct iax2_trunk_peer
*tpeer
, struct timeval
*now
)
6572 /* Drop when trunk is about 5 seconds idle */
6573 if (now
->tv_sec
> tpeer
->trunkact
.tv_sec
+ 5)
6578 static int timing_read(int *id
, int fd
, short events
, void *cbdata
)
6582 struct iax2_trunk_peer
*tpeer
, *prev
= NULL
, *drop
=NULL
;
6585 #ifdef DAHDI_TIMERACK
6590 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA
);
6591 gettimeofday(&now
, NULL
);
6592 if (events
& AST_IO_PRI
) {
6593 #ifdef DAHDI_TIMERACK
6594 /* Great, this is a timing interface, just call the ioctl */
6595 if (ioctl(fd
, DAHDI_TIMERACK
, &x
)) {
6596 ast_log(LOG_WARNING
, "Unable to acknowledge timer. IAX trunking will fail!\n");
6602 /* Read and ignore from the pseudo channel for timing */
6603 res
= read(fd
, buf
, sizeof(buf
));
6605 ast_log(LOG_WARNING
, "Unable to read from timing fd\n");
6609 /* For each peer that supports trunking... */
6610 ast_mutex_lock(&tpeerlock
);
6615 ast_mutex_lock(&tpeer
->lock
);
6616 /* We can drop a single tpeer per pass. That makes all this logic
6617 substantially easier */
6618 if (!drop
&& iax2_trunk_expired(tpeer
, &now
)) {
6619 /* Take it out of the list, but don't free it yet, because it
6622 prev
->next
= tpeer
->next
;
6624 tpeers
= tpeer
->next
;
6627 res
= send_trunk(tpeer
, &now
);
6629 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
);
6633 ast_mutex_unlock(&tpeer
->lock
);
6635 tpeer
= tpeer
->next
;
6637 ast_mutex_unlock(&tpeerlock
);
6639 ast_mutex_lock(&drop
->lock
);
6640 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6641 because by the time they could get tpeerlock, we've already grabbed it */
6643 ast_log(LOG_DEBUG
, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop
->addr
.sin_addr
), ntohs(drop
->addr
.sin_port
));
6644 if (drop
->trunkdata
) {
6645 free(drop
->trunkdata
);
6646 drop
->trunkdata
= NULL
;
6648 ast_mutex_unlock(&drop
->lock
);
6649 ast_mutex_destroy(&drop
->lock
);
6654 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed
, totalcalls
);
6661 char context
[AST_MAX_EXTENSION
];
6662 char callednum
[AST_MAX_EXTENSION
];
6666 static void dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
, int skiplock
)
6668 unsigned short dpstatus
= 0;
6669 struct iax_ie_data ied1
;
6672 memset(&ied1
, 0, sizeof(ied1
));
6673 mm
= ast_matchmore_extension(NULL
, context
, callednum
, 1, callerid
);
6674 /* Must be started */
6675 if (!strcmp(callednum
, ast_parking_ext()) || ast_exists_extension(NULL
, context
, callednum
, 1, callerid
)) {
6676 dpstatus
= IAX_DPSTATUS_EXISTS
;
6677 } else if (ast_canmatch_extension(NULL
, context
, callednum
, 1, callerid
)) {
6678 dpstatus
= IAX_DPSTATUS_CANEXIST
;
6680 dpstatus
= IAX_DPSTATUS_NONEXISTENT
;
6682 if (ast_ignore_pattern(context
, callednum
))
6683 dpstatus
|= IAX_DPSTATUS_IGNOREPAT
;
6685 dpstatus
|= IAX_DPSTATUS_MATCHMORE
;
6687 ast_mutex_lock(&iaxsl
[callno
]);
6689 iax_ie_append_str(&ied1
, IAX_IE_CALLED_NUMBER
, callednum
);
6690 iax_ie_append_short(&ied1
, IAX_IE_DPSTATUS
, dpstatus
);
6691 iax_ie_append_short(&ied1
, IAX_IE_REFRESH
, iaxdefaultdpcache
);
6692 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_DPREP
, 0, ied1
.buf
, ied1
.pos
, -1);
6695 ast_mutex_unlock(&iaxsl
[callno
]);
6698 static void *dp_lookup_thread(void *data
)
6700 /* Look up for dpreq */
6701 struct dpreq_data
*dpr
= data
;
6702 dp_lookup(dpr
->callno
, dpr
->context
, dpr
->callednum
, dpr
->callerid
, 0);
6704 free(dpr
->callerid
);
6709 static void spawn_dp_lookup(int callno
, const char *context
, const char *callednum
, const char *callerid
)
6711 pthread_t newthread
;
6712 struct dpreq_data
*dpr
;
6713 pthread_attr_t attr
;
6715 if (!(dpr
= ast_calloc(1, sizeof(*dpr
))))
6718 pthread_attr_init(&attr
);
6719 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
6721 dpr
->callno
= callno
;
6722 ast_copy_string(dpr
->context
, context
, sizeof(dpr
->context
));
6723 ast_copy_string(dpr
->callednum
, callednum
, sizeof(dpr
->callednum
));
6725 dpr
->callerid
= ast_strdup(callerid
);
6726 if (ast_pthread_create(&newthread
, &attr
, dp_lookup_thread
, dpr
)) {
6727 ast_log(LOG_WARNING
, "Unable to start lookup thread!\n");
6730 pthread_attr_destroy(&attr
);
6734 struct ast_channel
*chan1
;
6735 struct ast_channel
*chan2
;
6738 static void *iax_park_thread(void *stuff
)
6740 struct ast_channel
*chan1
, *chan2
;
6742 struct ast_frame
*f
;
6749 f
= ast_read(chan1
);
6752 res
= ast_park_call(chan1
, chan2
, 0, &ext
);
6754 ast_log(LOG_NOTICE
, "Parked on extension '%d'\n", ext
);
6758 static int iax_park(struct ast_channel
*chan1
, struct ast_channel
*chan2
)
6761 struct ast_channel
*chan1m
, *chan2m
;
6763 chan1m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan1
->exten
, chan1
->context
, chan1
->amaflags
, "Parking/%s", chan1
->name
);
6764 chan2m
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, chan2
->accountcode
, chan2
->exten
, chan2
->context
, chan2
->amaflags
, "IAXPeer/%s",chan2
->name
);
6765 if (chan2m
&& chan1m
) {
6766 /* Make formats okay */
6767 chan1m
->readformat
= chan1
->readformat
;
6768 chan1m
->writeformat
= chan1
->writeformat
;
6769 ast_channel_masquerade(chan1m
, chan1
);
6770 /* Setup the extensions and such */
6771 ast_copy_string(chan1m
->context
, chan1
->context
, sizeof(chan1m
->context
));
6772 ast_copy_string(chan1m
->exten
, chan1
->exten
, sizeof(chan1m
->exten
));
6773 chan1m
->priority
= chan1
->priority
;
6775 /* We make a clone of the peer channel too, so we can play
6776 back the announcement */
6777 /* Make formats okay */
6778 chan2m
->readformat
= chan2
->readformat
;
6779 chan2m
->writeformat
= chan2
->writeformat
;
6780 ast_channel_masquerade(chan2m
, chan2
);
6781 /* Setup the extensions and such */
6782 ast_copy_string(chan2m
->context
, chan2
->context
, sizeof(chan2m
->context
));
6783 ast_copy_string(chan2m
->exten
, chan2
->exten
, sizeof(chan2m
->exten
));
6784 chan2m
->priority
= chan2
->priority
;
6785 if (ast_do_masquerade(chan2m
)) {
6786 ast_log(LOG_WARNING
, "Masquerade failed :(\n");
6797 if ((d
= ast_calloc(1, sizeof(*d
)))) {
6798 pthread_attr_t attr
;
6800 pthread_attr_init(&attr
);
6801 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
6805 if (!ast_pthread_create_background(&th
, &attr
, iax_park_thread
, d
)) {
6806 pthread_attr_destroy(&attr
);
6809 pthread_attr_destroy(&attr
);
6816 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
);
6818 static int check_provisioning(struct sockaddr_in
*sin
, int sockfd
, char *si
, unsigned int ver
)
6820 unsigned int ourver
;
6822 snprintf(rsi
, sizeof(rsi
), "si-%s", si
);
6823 if (iax_provision_version(&ourver
, rsi
, 1))
6826 ast_log(LOG_DEBUG
, "Service identifier '%s', we think '%08x', they think '%08x'\n", si
, ourver
, ver
);
6828 iax2_provision(sin
, sockfd
, NULL
, rsi
, 1);
6832 static void construct_rr(struct chan_iax2_pvt
*pvt
, struct iax_ie_data
*iep
)
6835 jb_getinfo(pvt
->jb
, &stats
);
6837 memset(iep
, 0, sizeof(*iep
));
6839 iax_ie_append_int(iep
,IAX_IE_RR_JITTER
, stats
.jitter
);
6840 if(stats
.frames_in
== 0) stats
.frames_in
= 1;
6841 iax_ie_append_int(iep
,IAX_IE_RR_LOSS
, ((0xff & (stats
.losspct
/1000)) << 24 | (stats
.frames_lost
& 0x00ffffff)));
6842 iax_ie_append_int(iep
,IAX_IE_RR_PKTS
, stats
.frames_in
);
6843 iax_ie_append_short(iep
,IAX_IE_RR_DELAY
, stats
.current
- stats
.min
);
6844 iax_ie_append_int(iep
,IAX_IE_RR_DROPPED
, stats
.frames_dropped
);
6845 iax_ie_append_int(iep
,IAX_IE_RR_OOO
, stats
.frames_ooo
);
6848 static void save_rr(struct iax_frame
*fr
, struct iax_ies
*ies
)
6850 iaxs
[fr
->callno
]->remote_rr
.jitter
= ies
->rr_jitter
;
6851 iaxs
[fr
->callno
]->remote_rr
.losspct
= ies
->rr_loss
>> 24;
6852 iaxs
[fr
->callno
]->remote_rr
.losscnt
= ies
->rr_loss
& 0xffffff;
6853 iaxs
[fr
->callno
]->remote_rr
.packets
= ies
->rr_pkts
;
6854 iaxs
[fr
->callno
]->remote_rr
.delay
= ies
->rr_delay
;
6855 iaxs
[fr
->callno
]->remote_rr
.dropped
= ies
->rr_dropped
;
6856 iaxs
[fr
->callno
]->remote_rr
.ooo
= ies
->rr_ooo
;
6859 static int socket_process(struct iax2_thread
*thread
);
6862 * \brief Handle any deferred full frames for this thread
6864 static void handle_deferred_full_frames(struct iax2_thread
*thread
)
6866 struct iax2_pkt_buf
*pkt_buf
;
6868 ast_mutex_lock(&thread
->lock
);
6870 while ((pkt_buf
= AST_LIST_REMOVE_HEAD(&thread
->full_frames
, entry
))) {
6871 ast_mutex_unlock(&thread
->lock
);
6873 thread
->buf
= pkt_buf
->buf
;
6874 thread
->buf_len
= pkt_buf
->len
;
6875 thread
->buf_size
= pkt_buf
->len
+ 1;
6877 socket_process(thread
);
6882 ast_mutex_lock(&thread
->lock
);
6885 ast_mutex_unlock(&thread
->lock
);
6889 * \brief Queue the last read full frame for processing by a certain thread
6891 * If there are already any full frames queued, they are sorted
6892 * by sequence number.
6894 static void defer_full_frame(struct iax2_thread
*from_here
, struct iax2_thread
*to_here
)
6896 struct iax2_pkt_buf
*pkt_buf
, *cur_pkt_buf
;
6897 struct ast_iax2_full_hdr
*fh
, *cur_fh
;
6899 if (!(pkt_buf
= ast_calloc(1, sizeof(*pkt_buf
) + from_here
->buf_len
)))
6902 pkt_buf
->len
= from_here
->buf_len
;
6903 memcpy(pkt_buf
->buf
, from_here
->buf
, pkt_buf
->len
);
6905 fh
= (struct ast_iax2_full_hdr
*) pkt_buf
->buf
;
6906 ast_mutex_lock(&to_here
->lock
);
6907 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here
->full_frames
, cur_pkt_buf
, entry
) {
6908 cur_fh
= (struct ast_iax2_full_hdr
*) cur_pkt_buf
->buf
;
6909 if (fh
->oseqno
< cur_fh
->oseqno
) {
6910 AST_LIST_INSERT_BEFORE_CURRENT(&to_here
->full_frames
, pkt_buf
, entry
);
6914 AST_LIST_TRAVERSE_SAFE_END
6917 AST_LIST_INSERT_TAIL(&to_here
->full_frames
, pkt_buf
, entry
);
6919 ast_mutex_unlock(&to_here
->lock
);
6922 static int socket_read(int *id
, int fd
, short events
, void *cbdata
)
6924 struct iax2_thread
*thread
;
6927 static time_t last_errtime
= 0;
6928 struct ast_iax2_full_hdr
*fh
;
6930 if (!(thread
= find_idle_thread())) {
6932 if (t
!= last_errtime
&& option_debug
)
6933 ast_log(LOG_DEBUG
, "Out of idle IAX2 threads for I/O, pausing!\n");
6939 len
= sizeof(thread
->iosin
);
6941 thread
->buf_len
= recvfrom(fd
, thread
->readbuf
, sizeof(thread
->readbuf
), 0, (struct sockaddr
*) &thread
->iosin
, &len
);
6942 thread
->buf_size
= sizeof(thread
->readbuf
);
6943 thread
->buf
= thread
->readbuf
;
6944 if (thread
->buf_len
< 0) {
6945 if (errno
!= ECONNREFUSED
&& errno
!= EAGAIN
)
6946 ast_log(LOG_WARNING
, "Error: %s\n", strerror(errno
));
6948 thread
->iostate
= IAX_IOSTATE_IDLE
;
6949 signal_condition(&thread
->lock
, &thread
->cond
);
6952 if (test_losspct
&& ((100.0 * ast_random() / (RAND_MAX
+ 1.0)) < test_losspct
)) { /* simulate random loss condition */
6953 thread
->iostate
= IAX_IOSTATE_IDLE
;
6954 signal_condition(&thread
->lock
, &thread
->cond
);
6958 /* Determine if this frame is a full frame; if so, and any thread is currently
6959 processing a full frame for the same callno from this peer, then drop this
6960 frame (and the peer will retransmit it) */
6961 fh
= (struct ast_iax2_full_hdr
*) thread
->buf
;
6962 if (ntohs(fh
->scallno
) & IAX_FLAG_FULL
) {
6963 struct iax2_thread
*cur
= NULL
;
6964 uint16_t callno
= ntohs(fh
->scallno
) & ~IAX_FLAG_FULL
;
6966 AST_LIST_LOCK(&active_list
);
6967 AST_LIST_TRAVERSE(&active_list
, cur
, list
) {
6968 if ((cur
->ffinfo
.callno
== callno
) &&
6969 !inaddrcmp(&cur
->ffinfo
.sin
, &thread
->iosin
))
6973 /* we found another thread processing a full frame for this call,
6974 so queue it up for processing later. */
6975 defer_full_frame(thread
, cur
);
6976 AST_LIST_UNLOCK(&active_list
);
6977 thread
->iostate
= IAX_IOSTATE_IDLE
;
6978 signal_condition(&thread
->lock
, &thread
->cond
);
6981 /* this thread is going to process this frame, so mark it */
6982 thread
->ffinfo
.callno
= callno
;
6983 memcpy(&thread
->ffinfo
.sin
, &thread
->iosin
, sizeof(thread
->ffinfo
.sin
));
6984 thread
->ffinfo
.type
= fh
->type
;
6985 thread
->ffinfo
.csub
= fh
->csub
;
6987 AST_LIST_UNLOCK(&active_list
);
6990 /* Mark as ready and send on its way */
6991 thread
->iostate
= IAX_IOSTATE_READY
;
6992 #ifdef DEBUG_SCHED_MULTITHREAD
6993 ast_copy_string(thread
->curfunc
, "socket_process", sizeof(thread
->curfunc
));
6995 signal_condition(&thread
->lock
, &thread
->cond
);
7000 static int socket_process(struct iax2_thread
*thread
)
7002 struct sockaddr_in sin
;
7004 int updatehistory
=1;
7005 int new = NEW_PREVENT
;
7008 struct ast_iax2_full_hdr
*fh
= (struct ast_iax2_full_hdr
*)thread
->buf
;
7009 struct ast_iax2_mini_hdr
*mh
= (struct ast_iax2_mini_hdr
*)thread
->buf
;
7010 struct ast_iax2_meta_hdr
*meta
= (struct ast_iax2_meta_hdr
*)thread
->buf
;
7011 struct ast_iax2_video_hdr
*vh
= (struct ast_iax2_video_hdr
*)thread
->buf
;
7012 struct ast_iax2_meta_trunk_hdr
*mth
;
7013 struct ast_iax2_meta_trunk_entry
*mte
;
7014 struct ast_iax2_meta_trunk_mini
*mtm
;
7015 struct iax_frame
*fr
;
7016 struct iax_frame
*cur
;
7017 struct ast_frame f
= { 0, };
7018 struct ast_channel
*c
;
7019 struct iax2_dpcache
*dp
;
7020 struct iax2_peer
*peer
;
7021 struct iax2_trunk_peer
*tpeer
;
7022 struct timeval rxtrunktime
;
7024 struct iax_ie_data ied0
, ied1
;
7030 char empty
[32]=""; /* Safety measure */
7031 struct iax_frame
*duped_fr
;
7032 char host_pref_buf
[128];
7033 char caller_pref_buf
[128];
7034 struct ast_codec_pref pref
;
7035 char *using_prefs
= "mine";
7037 /* allocate an iax_frame with 4096 bytes of data buffer */
7038 fr
= alloca(sizeof(*fr
) + 4096);
7039 memset(fr
, 0, sizeof(*fr
));
7040 fr
->afdatalen
= 4096; /* From alloca() above */
7042 /* Copy frequently used parameters to the stack */
7043 res
= thread
->buf_len
;
7045 memcpy(&sin
, &thread
->iosin
, sizeof(sin
));
7047 if (res
< sizeof(*mh
)) {
7048 ast_log(LOG_WARNING
, "midget packet received (%d of %zd min)\n", res
, sizeof(*mh
));
7051 if ((vh
->zeros
== 0) && (ntohs(vh
->callno
) & 0x8000)) {
7052 if (res
< sizeof(*vh
)) {
7053 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
));
7057 /* This is a video frame, get call number */
7058 fr
->callno
= find_callno(ntohs(vh
->callno
) & ~0x8000, dcallno
, &sin
, new, fd
, 0);
7060 } else if ((meta
->zeros
== 0) && !(ntohs(meta
->metacmd
) & 0x8000)) {
7061 unsigned char metatype
;
7063 if (res
< sizeof(*meta
)) {
7064 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
));
7068 /* This is a meta header */
7069 switch(meta
->metacmd
) {
7070 case IAX_META_TRUNK
:
7071 if (res
< (sizeof(*meta
) + sizeof(*mth
))) {
7072 ast_log(LOG_WARNING
, "midget meta trunk packet received (%d of %zd min)\n", res
,
7073 sizeof(*meta
) + sizeof(*mth
));
7076 mth
= (struct ast_iax2_meta_trunk_hdr
*)(meta
->data
);
7077 ts
= ntohl(mth
->ts
);
7078 metatype
= meta
->cmddata
;
7079 res
-= (sizeof(*meta
) + sizeof(*mth
));
7081 tpeer
= find_tpeer(&sin
, fd
);
7083 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
));
7086 tpeer
->trunkact
= ast_tvnow();
7087 if (!ts
|| ast_tvzero(tpeer
->rxtrunktime
))
7088 tpeer
->rxtrunktime
= tpeer
->trunkact
;
7089 rxtrunktime
= tpeer
->rxtrunktime
;
7090 ast_mutex_unlock(&tpeer
->lock
);
7091 while(res
>= sizeof(*mte
)) {
7092 /* Process channels */
7093 unsigned short callno
, trunked_ts
, len
;
7095 if (metatype
== IAX_META_TRUNK_MINI
) {
7096 mtm
= (struct ast_iax2_meta_trunk_mini
*)ptr
;
7097 ptr
+= sizeof(*mtm
);
7098 res
-= sizeof(*mtm
);
7099 len
= ntohs(mtm
->len
);
7100 callno
= ntohs(mtm
->mini
.callno
);
7101 trunked_ts
= ntohs(mtm
->mini
.ts
);
7102 } else if (metatype
== IAX_META_TRUNK_SUPERMINI
) {
7103 mte
= (struct ast_iax2_meta_trunk_entry
*)ptr
;
7104 ptr
+= sizeof(*mte
);
7105 res
-= sizeof(*mte
);
7106 len
= ntohs(mte
->len
);
7107 callno
= ntohs(mte
->callno
);
7110 ast_log(LOG_WARNING
, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin
.sin_addr
), ntohs(sin
.sin_port
));
7113 /* Stop if we don't have enough data */
7116 fr
->callno
= find_callno_locked(callno
& ~IAX_FLAG_FULL
, 0, &sin
, NEW_PREVENT
, fd
, 0);
7118 /* If it's a valid call, deliver the contents. If not, we
7119 drop it, since we don't have a scallno to use for an INVAL */
7120 /* Process as a mini frame */
7121 memset(&f
, 0, sizeof(f
));
7122 f
.frametype
= AST_FRAME_VOICE
;
7123 if (iaxs
[fr
->callno
]) {
7124 if (iaxs
[fr
->callno
]->voiceformat
> 0) {
7125 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
7127 if (f
.datalen
>= 0) {
7131 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | (trunked_ts
& 0xffff);
7133 fr
->ts
= fix_peerts(&rxtrunktime
, fr
->callno
, ts
);
7134 /* Don't pass any packets until we're started */
7135 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7138 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
))
7139 f
.samples
= ast_codec_get_samples(&f
);
7140 iax_frame_wrap(fr
, &f
);
7141 duped_fr
= iaxfrdup2(fr
);
7143 schedule_delivery(duped_fr
, updatehistory
, 1, &fr
->ts
);
7145 /* It is possible for the pvt structure to go away after we call schedule_delivery */
7146 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
7147 iaxs
[fr
->callno
]->last
= fr
->ts
;
7149 if (option_debug
&& iaxdebug
)
7150 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
7155 ast_log(LOG_WARNING
, "Datalen < 0?\n");
7158 ast_log(LOG_WARNING
, "Received trunked frame before first full voice frame\n");
7159 iax2_vnak(fr
->callno
);
7162 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7172 #ifdef DEBUG_SUPPORT
7173 if (iaxdebug
&& (res
>= sizeof(*fh
)))
7174 iax_showframe(NULL
, fh
, 1, &sin
, res
- sizeof(*fh
));
7176 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7177 if (res
< sizeof(*fh
)) {
7178 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
));
7182 /* Get the destination call number */
7183 dcallno
= ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
;
7184 /* Retrieve the type and subclass */
7185 f
.frametype
= fh
->type
;
7186 if (f
.frametype
== AST_FRAME_VIDEO
) {
7187 f
.subclass
= uncompress_subclass(fh
->csub
& ~0x40) | ((fh
->csub
>> 6) & 0x1);
7189 f
.subclass
= uncompress_subclass(fh
->csub
);
7192 /* Deal with POKE/PONG without allocating a callno */
7193 if (f
.frametype
== AST_FRAME_IAX
&& f
.subclass
== IAX_COMMAND_POKE
) {
7194 /* Reply back with a PONG, but don't care about the result. */
7195 send_apathetic_reply(1, ntohs(fh
->scallno
), &sin
, IAX_COMMAND_PONG
, ntohs(fh
->ts
), fh
->oseqno
);
7197 } else if (f
.frametype
== AST_FRAME_IAX
&& f
.subclass
== IAX_COMMAND_ACK
&& dcallno
== 1) {
7202 if ((f
.frametype
== AST_FRAME_IAX
) && ((f
.subclass
== IAX_COMMAND_NEW
) || (f
.subclass
== IAX_COMMAND_REGREQ
) ||
7203 (f
.subclass
== IAX_COMMAND_POKE
) || (f
.subclass
== IAX_COMMAND_FWDOWNL
) ||
7204 (f
.subclass
== IAX_COMMAND_REGREL
)))
7207 /* Don't know anything about it yet */
7208 f
.frametype
= AST_FRAME_NULL
;
7213 int check_dcallno
= 0;
7216 * We enforce accurate destination call numbers for all full frames except
7217 * LAGRQ and PING commands. This is because older versions of Asterisk
7218 * schedule these commands to get sent very quickly, and they will sometimes
7219 * be sent before they receive the first frame from the other side. When
7220 * that happens, it doesn't contain the destination call number. However,
7221 * not checking it for these frames is safe.
7223 * Discussed in the following thread:
7224 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
7227 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7228 check_dcallno
= f
.frametype
== AST_FRAME_IAX
? (f
.subclass
!= IAX_COMMAND_PING
&& f
.subclass
!= IAX_COMMAND_LAGRQ
) : 1;
7231 fr
->callno
= find_callno(ntohs(mh
->callno
) & ~IAX_FLAG_FULL
, dcallno
, &sin
, new, fd
, check_dcallno
);
7235 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7237 if (!fr
->callno
|| !iaxs
[fr
->callno
]) {
7238 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7239 frame, reply with an inval */
7240 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7241 /* We can only raw hangup control frames */
7242 if (((f
.subclass
!= IAX_COMMAND_INVAL
) &&
7243 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7244 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7245 (f
.subclass
!= IAX_COMMAND_FWDOWNL
))||
7246 (f
.frametype
!= AST_FRAME_IAX
))
7247 raw_hangup(&sin
, ntohs(fh
->dcallno
) & ~IAX_FLAG_RETRANS
, ntohs(mh
->callno
) & ~IAX_FLAG_FULL
,
7251 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7254 if (ast_test_flag(iaxs
[fr
->callno
], IAX_ENCRYPTED
)) {
7255 if (decrypt_frame(fr
->callno
, fh
, &f
, &res
)) {
7256 ast_log(LOG_NOTICE
, "Packet Decrypt Failed!\n");
7257 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7260 #ifdef DEBUG_SUPPORT
7262 iax_showframe(NULL
, fh
, 3, &sin
, res
- sizeof(*fh
));
7266 /* count this frame */
7267 iaxs
[fr
->callno
]->frames_received
++;
7269 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) && !minivid
&&
7270 f
.subclass
!= IAX_COMMAND_TXCNT
&& /* for attended transfer */
7271 f
.subclass
!= IAX_COMMAND_TXACC
) { /* for attended transfer */
7272 unsigned short new_peercallno
;
7274 new_peercallno
= (unsigned short) (ntohs(mh
->callno
) & ~IAX_FLAG_FULL
);
7275 if (new_peercallno
&& new_peercallno
!= iaxs
[fr
->callno
]->peercallno
) {
7276 if (iaxs
[fr
->callno
]->peercallno
) {
7277 remove_by_peercallno(iaxs
[fr
->callno
]);
7279 iaxs
[fr
->callno
]->peercallno
= new_peercallno
;
7280 store_by_peercallno(iaxs
[fr
->callno
]);
7283 if (ntohs(mh
->callno
) & IAX_FLAG_FULL
) {
7284 if (option_debug
&& iaxdebug
)
7285 ast_log(LOG_DEBUG
, "Received packet %d, (%d, %d)\n", fh
->oseqno
, f
.frametype
, f
.subclass
);
7286 /* Check if it's out of order (and not an ACK or INVAL) */
7287 fr
->oseqno
= fh
->oseqno
;
7288 fr
->iseqno
= fh
->iseqno
;
7289 fr
->ts
= ntohl(fh
->ts
);
7293 ast_log(LOG_DEBUG
, "Simulating frame ts resync, was %u now %u\n", fr
->ts
, fr
->ts
+ test_resync
);
7294 fr
->ts
+= test_resync
;
7296 #endif /* IAXTESTS */
7298 if ( (ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) ||
7299 ( (f
.frametype
!= AST_FRAME_VOICE
) && ! (f
.frametype
== AST_FRAME_IAX
&&
7300 (f
.subclass
== IAX_COMMAND_NEW
||
7301 f
.subclass
== IAX_COMMAND_AUTHREQ
||
7302 f
.subclass
== IAX_COMMAND_ACCEPT
||
7303 f
.subclass
== IAX_COMMAND_REJECT
)) ) )
7305 if ((ntohs(fh
->dcallno
) & IAX_FLAG_RETRANS
) || (f
.frametype
!= AST_FRAME_VOICE
))
7307 if ((iaxs
[fr
->callno
]->iseqno
!= fr
->oseqno
) &&
7308 (iaxs
[fr
->callno
]->iseqno
||
7309 ((f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7310 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
7311 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
7312 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
7313 (f
.subclass
!= IAX_COMMAND_TXACC
)) ||
7314 (f
.frametype
!= AST_FRAME_IAX
))) {
7316 ((f
.subclass
!= IAX_COMMAND_ACK
) &&
7317 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
7318 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7319 (f
.subclass
!= IAX_COMMAND_TXREADY
) && /* for attended transfer */
7320 (f
.subclass
!= IAX_COMMAND_TXREL
) && /* for attended transfer */
7321 (f
.subclass
!= IAX_COMMAND_UNQUELCH
) && /* for attended transfer */
7322 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7323 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
7324 (f
.frametype
!= AST_FRAME_IAX
)) {
7325 /* If it's not an ACK packet, it's out of order. */
7327 ast_log(LOG_DEBUG
, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7328 iaxs
[fr
->callno
]->iseqno
, fr
->oseqno
, f
.frametype
, f
.subclass
);
7329 /* Check to see if we need to request retransmission,
7330 * and take sequence number wraparound into account */
7331 if ((unsigned char) (iaxs
[fr
->callno
]->iseqno
- fr
->oseqno
) < 128) {
7332 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7333 if ((f
.frametype
!= AST_FRAME_IAX
) ||
7334 ((f
.subclass
!= IAX_COMMAND_ACK
) && (f
.subclass
!= IAX_COMMAND_INVAL
))) {
7336 ast_log(LOG_DEBUG
, "Acking anyway\n");
7337 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7338 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7339 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7342 /* Send a VNAK requesting retransmission */
7343 iax2_vnak(fr
->callno
);
7345 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7349 /* Increment unless it's an ACK or VNAK */
7350 if (((f
.subclass
!= IAX_COMMAND_ACK
) &&
7351 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
7352 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
7353 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
7354 (f
.subclass
!= IAX_COMMAND_VNAK
)) ||
7355 (f
.frametype
!= AST_FRAME_IAX
))
7356 iaxs
[fr
->callno
]->iseqno
++;
7359 if (res
< sizeof(*fh
)) {
7360 ast_log(LOG_WARNING
, "midget packet received (%d of %zd min)\n", res
, sizeof(*fh
));
7361 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7364 /* Ensure text frames are NULL-terminated */
7365 if (f
.frametype
== AST_FRAME_TEXT
&& thread
->buf
[res
- 1] != '\0') {
7366 if (res
< thread
->buf_size
)
7367 thread
->buf
[res
++] = '\0';
7368 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7369 thread
->buf
[res
- 1] = '\0';
7371 f
.datalen
= res
- sizeof(*fh
);
7373 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7374 from the real peer, not the transfer peer */
7375 if (!inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) &&
7376 ((f
.subclass
!= IAX_COMMAND_INVAL
) ||
7377 (f
.frametype
!= AST_FRAME_IAX
))) {
7379 int call_to_destroy
;
7380 /* XXX This code is not very efficient. Surely there is a better way which still
7381 properly handles boundary conditions? XXX */
7382 /* First we have to qualify that the ACKed value is within our window */
7383 for (x
=iaxs
[fr
->callno
]->rseqno
; x
!= iaxs
[fr
->callno
]->oseqno
; x
++)
7384 if (fr
->iseqno
== x
)
7386 if ((x
!= iaxs
[fr
->callno
]->oseqno
) || (iaxs
[fr
->callno
]->oseqno
== fr
->iseqno
)) {
7387 /* The acknowledgement is within our window. Time to acknowledge everything
7389 for (x
=iaxs
[fr
->callno
]->rseqno
; x
!= fr
->iseqno
; x
++) {
7390 /* Ack the packet with the given timestamp */
7391 if (option_debug
&& iaxdebug
)
7392 ast_log(LOG_DEBUG
, "Cancelling transmission of packet %d\n", x
);
7393 call_to_destroy
= 0;
7394 AST_LIST_LOCK(&iaxq
.queue
);
7395 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
7396 /* If it's our call, and our timestamp, mark -1 retries */
7397 if ((fr
->callno
== cur
->callno
) && (x
== cur
->oseqno
)) {
7399 /* Destroy call if this is the end */
7401 call_to_destroy
= fr
->callno
;
7404 AST_LIST_UNLOCK(&iaxq
.queue
);
7405 if (call_to_destroy
) {
7406 if (iaxdebug
&& option_debug
)
7407 ast_log(LOG_DEBUG
, "Really destroying %d, having been acked on final message\n", call_to_destroy
);
7408 ast_mutex_lock(&iaxsl
[call_to_destroy
]);
7409 iax2_destroy(call_to_destroy
);
7410 ast_mutex_unlock(&iaxsl
[call_to_destroy
]);
7413 /* Note how much we've received acknowledgement for */
7414 if (iaxs
[fr
->callno
])
7415 iaxs
[fr
->callno
]->rseqno
= fr
->iseqno
;
7417 /* Stop processing now */
7418 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7421 } else if (option_debug
)
7422 ast_log(LOG_DEBUG
, "Received iseqno %d not within window %d->%d\n", fr
->iseqno
, iaxs
[fr
->callno
]->rseqno
, iaxs
[fr
->callno
]->oseqno
);
7424 if (inaddrcmp(&sin
, &iaxs
[fr
->callno
]->addr
) &&
7425 ((f
.frametype
!= AST_FRAME_IAX
) ||
7426 ((f
.subclass
!= IAX_COMMAND_TXACC
) &&
7427 (f
.subclass
!= IAX_COMMAND_TXCNT
)))) {
7428 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7429 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7434 if (f
.frametype
== AST_FRAME_IAX
) {
7435 if (iax_parse_ies(&ies
, thread
->buf
+ sizeof(*fh
), f
.datalen
)) {
7436 ast_log(LOG_WARNING
, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin
.sin_addr
));
7437 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7443 f
.data
= thread
->buf
+ sizeof(*fh
);
7445 if (f
.frametype
== AST_FRAME_IAX
)
7449 memset(&ies
, 0, sizeof(ies
));
7452 /* when we receive the first full frame for a new incoming channel,
7453 it is safe to start the PBX on the channel because we have now
7454 completed a 3-way handshake with the peer */
7455 if ((f
.frametype
== AST_FRAME_VOICE
) ||
7456 (f
.frametype
== AST_FRAME_VIDEO
) ||
7457 (f
.frametype
== AST_FRAME_IAX
)) {
7458 if (ast_test_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
)) {
7459 ast_clear_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
7460 if (!ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->chosenformat
)) {
7461 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7467 if (f
.frametype
== AST_FRAME_VOICE
) {
7468 if (f
.subclass
!= iaxs
[fr
->callno
]->voiceformat
) {
7469 iaxs
[fr
->callno
]->voiceformat
= f
.subclass
;
7471 ast_log(LOG_DEBUG
, "Ooh, voice format changed to %d\n", f
.subclass
);
7472 if (iaxs
[fr
->callno
]->owner
) {
7475 if (ast_mutex_trylock(&iaxs
[fr
->callno
]->owner
->lock
)) {
7476 DEADLOCK_AVOIDANCE(&iaxsl
[fr
->callno
]);
7477 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner
;
7479 if (iaxs
[fr
->callno
]) {
7480 if (iaxs
[fr
->callno
]->owner
) {
7481 orignative
= iaxs
[fr
->callno
]->owner
->nativeformats
;
7482 iaxs
[fr
->callno
]->owner
->nativeformats
= f
.subclass
;
7483 if (iaxs
[fr
->callno
]->owner
->readformat
)
7484 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
7485 iaxs
[fr
->callno
]->owner
->nativeformats
= orignative
;
7486 ast_mutex_unlock(&iaxs
[fr
->callno
]->owner
->lock
);
7490 ast_log(LOG_DEBUG
, "Neat, somebody took away the channel at a magical time but i found it!\n");
7491 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7497 if (f
.frametype
== AST_FRAME_VIDEO
) {
7498 if (f
.subclass
!= iaxs
[fr
->callno
]->videoformat
) {
7500 ast_log(LOG_DEBUG
, "Ooh, video format changed to %d\n", f
.subclass
& ~0x1);
7501 iaxs
[fr
->callno
]->videoformat
= f
.subclass
& ~0x1;
7504 if (f
.frametype
== AST_FRAME_IAX
) {
7505 AST_SCHED_DEL(sched
, iaxs
[fr
->callno
]->initid
);
7506 /* Handle the IAX pseudo frame itself */
7507 if (option_debug
&& iaxdebug
)
7508 ast_log(LOG_DEBUG
, "IAX subclass %d received\n", f
.subclass
);
7510 /* Update last ts unless the frame's timestamp originated with us. */
7511 if (iaxs
[fr
->callno
]->last
< fr
->ts
&&
7512 f
.subclass
!= IAX_COMMAND_ACK
&&
7513 f
.subclass
!= IAX_COMMAND_PONG
&&
7514 f
.subclass
!= IAX_COMMAND_LAGRP
) {
7515 iaxs
[fr
->callno
]->last
= fr
->ts
;
7516 if (option_debug
&& iaxdebug
)
7517 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
7520 switch(f
.subclass
) {
7521 case IAX_COMMAND_ACK
:
7524 case IAX_COMMAND_QUELCH
:
7525 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7526 /* Generate Manager Hold event, if necessary*/
7527 if (iaxs
[fr
->callno
]->owner
) {
7528 manager_event(EVENT_FLAG_CALL
, "Hold",
7531 iaxs
[fr
->callno
]->owner
->name
,
7532 iaxs
[fr
->callno
]->owner
->uniqueid
);
7535 ast_set_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
7536 if (ies
.musiconhold
) {
7537 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
7538 const char *mohsuggest
= iaxs
[fr
->callno
]->mohsuggest
;
7539 iax2_queue_control_data(fr
->callno
, AST_CONTROL_HOLD
,
7540 S_OR(mohsuggest
, NULL
),
7541 !ast_strlen_zero(mohsuggest
) ? strlen(mohsuggest
) + 1 : 0);
7542 if (!iaxs
[fr
->callno
]) {
7543 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7550 case IAX_COMMAND_UNQUELCH
:
7551 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
7552 /* Generate Manager Unhold event, if necessary*/
7553 if (iaxs
[fr
->callno
]->owner
&& ast_test_flag(iaxs
[fr
->callno
], IAX_QUELCH
)) {
7554 manager_event(EVENT_FLAG_CALL
, "Unhold",
7557 iaxs
[fr
->callno
]->owner
->name
,
7558 iaxs
[fr
->callno
]->owner
->uniqueid
);
7561 ast_clear_flag(iaxs
[fr
->callno
], IAX_QUELCH
);
7562 if (iaxs
[fr
->callno
]->owner
&& ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) {
7563 iax2_queue_control_data(fr
->callno
, AST_CONTROL_UNHOLD
, NULL
, 0);
7564 if (!iaxs
[fr
->callno
]) {
7565 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7571 case IAX_COMMAND_TXACC
:
7572 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) {
7573 /* Ack the packet with the given timestamp */
7574 AST_LIST_LOCK(&iaxq
.queue
);
7575 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
7576 /* Cancel any outstanding txcnt's */
7577 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
))
7580 AST_LIST_UNLOCK(&iaxq
.queue
);
7581 memset(&ied1
, 0, sizeof(ied1
));
7582 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->callno
);
7583 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREADY
, 0, ied1
.buf
, ied1
.pos
, -1);
7584 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
7587 case IAX_COMMAND_NEW
:
7588 /* Ignore if it's already up */
7589 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
))
7591 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
7592 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7593 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
7594 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7595 if (!iaxs
[fr
->callno
]) {
7596 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7600 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7601 if (ast_test_flag(iaxs
[fr
->callno
], IAX_TRUNK
)) {
7603 if ((new_callno
= make_trunk(fr
->callno
, 1)) != -1)
7604 fr
->callno
= new_callno
;
7606 /* For security, always ack immediately */
7608 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7609 if (check_access(fr
->callno
, &sin
, &ies
)) {
7610 /* They're not allowed on */
7611 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
7613 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
);
7616 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7617 const char *context
, *exten
, *cid_num
;
7619 context
= ast_strdupa(iaxs
[fr
->callno
]->context
);
7620 exten
= ast_strdupa(iaxs
[fr
->callno
]->exten
);
7621 cid_num
= ast_strdupa(iaxs
[fr
->callno
]->cid_num
);
7623 /* This might re-enter the IAX code and need the lock */
7624 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7625 exists
= ast_exists_extension(NULL
, context
, exten
, 1, cid_num
);
7626 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7628 if (!iaxs
[fr
->callno
]) {
7629 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7634 if (ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) {
7635 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
7636 memset(&ied0
, 0, sizeof(ied0
));
7637 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
7638 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
7639 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7640 if (!iaxs
[fr
->callno
]) {
7641 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7645 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
);
7647 /* Select an appropriate format */
7649 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7650 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7651 using_prefs
= "reqonly";
7653 using_prefs
= "disabled";
7655 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
7656 memset(&pref
, 0, sizeof(pref
));
7657 strcpy(caller_pref_buf
, "disabled");
7658 strcpy(host_pref_buf
, "disabled");
7660 using_prefs
= "mine";
7661 /* If the information elements are in here... use them */
7662 if (ies
.codec_prefs
)
7663 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
7664 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7665 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7666 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7667 pref
= iaxs
[fr
->callno
]->rprefs
;
7668 using_prefs
= "caller";
7670 pref
= iaxs
[fr
->callno
]->prefs
;
7673 pref
= iaxs
[fr
->callno
]->prefs
;
7675 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
7676 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
7677 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
7680 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7681 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
7683 memset(&ied0
, 0, sizeof(ied0
));
7684 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7685 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7686 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7687 if (!iaxs
[fr
->callno
]) {
7688 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7692 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
7693 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
);
7695 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
);
7699 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
7700 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
7703 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
7704 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
7705 memset(&pref
, 0, sizeof(pref
));
7706 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7707 strcpy(caller_pref_buf
,"disabled");
7708 strcpy(host_pref_buf
,"disabled");
7710 using_prefs
= "mine";
7711 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
7712 /* Do the opposite of what we tried above. */
7713 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
7714 pref
= iaxs
[fr
->callno
]->prefs
;
7716 pref
= iaxs
[fr
->callno
]->rprefs
;
7717 using_prefs
= "caller";
7719 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
7721 } else /* if no codec_prefs IE do it the old way */
7722 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7727 memset(&ied0
, 0, sizeof(ied0
));
7728 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7729 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7730 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
7731 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7732 if (!iaxs
[fr
->callno
]) {
7733 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7737 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
);
7738 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
7744 /* No authentication required, let them in */
7745 memset(&ied1
, 0, sizeof(ied1
));
7746 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
7747 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
7748 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
7749 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7750 if (option_verbose
> 2)
7751 ast_verbose(VERBOSE_PREFIX_3
"Accepting UNAUTHENTICATED call from %s:\n"
7752 "%srequested format = %s,\n"
7753 "%srequested prefs = %s,\n"
7754 "%sactual format = %s,\n"
7755 "%shost prefs = %s,\n"
7756 "%spriority = %s\n",
7757 ast_inet_ntoa(sin
.sin_addr
),
7759 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
7763 ast_getformatname(format
),
7769 iaxs
[fr
->callno
]->chosenformat
= format
;
7770 ast_set_flag(iaxs
[fr
->callno
], IAX_DELAYPBXSTART
);
7772 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
7773 /* If this is a TBD call, we're ready but now what... */
7774 if (option_verbose
> 2)
7775 ast_verbose(VERBOSE_PREFIX_3
"Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
7781 if (iaxs
[fr
->callno
]->authmethods
& IAX_AUTH_MD5
)
7782 merge_encryption(iaxs
[fr
->callno
],ies
.encmethods
);
7784 iaxs
[fr
->callno
]->encmethods
= 0;
7785 if (!authenticate_request(fr
->callno
) && iaxs
[fr
->callno
])
7786 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
);
7787 if (!iaxs
[fr
->callno
]) {
7788 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7792 case IAX_COMMAND_DPREQ
:
7793 /* Request status in the dialplan */
7794 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
) &&
7795 !ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
) && ies
.called_number
) {
7797 /* Spawn a thread for the lookup */
7798 spawn_dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
);
7800 /* Just look it up */
7801 dp_lookup(fr
->callno
, iaxs
[fr
->callno
]->context
, ies
.called_number
, iaxs
[fr
->callno
]->cid_num
, 1);
7805 case IAX_COMMAND_HANGUP
:
7806 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
7808 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received hangup\n", fr
->callno
);
7809 /* Set hangup cause according to remote */
7810 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
7811 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
7812 /* Send ack immediately, before we destroy */
7813 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7814 iax2_destroy(fr
->callno
);
7816 case IAX_COMMAND_REJECT
:
7817 /* Set hangup cause according to remote */
7818 if (ies
.causecode
&& iaxs
[fr
->callno
]->owner
)
7819 iaxs
[fr
->callno
]->owner
->hangupcause
= ies
.causecode
;
7821 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
7822 if (iaxs
[fr
->callno
]->owner
&& authdebug
)
7823 ast_log(LOG_WARNING
, "Call rejected by %s: %s\n",
7824 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
),
7825 ies
.cause
? ies
.cause
: "<Unknown>");
7827 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received reject\n",
7830 /* Send ack immediately, before we destroy */
7831 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
,
7832 fr
->ts
, NULL
, 0, fr
->iseqno
);
7833 if (!ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
))
7834 iaxs
[fr
->callno
]->error
= EPERM
;
7835 iax2_destroy(fr
->callno
);
7837 case IAX_COMMAND_TRANSFER
:
7839 struct ast_channel
*bridged_chan
;
7841 if (iaxs
[fr
->callno
]->owner
&& (bridged_chan
= ast_bridged_channel(iaxs
[fr
->callno
]->owner
)) && ies
.called_number
) {
7842 /* Set BLINDTRANSFER channel variables */
7844 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7845 pbx_builtin_setvar_helper(iaxs
[fr
->callno
]->owner
, "BLINDTRANSFER", bridged_chan
->name
);
7846 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7847 if (!iaxs
[fr
->callno
]) {
7848 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7852 pbx_builtin_setvar_helper(bridged_chan
, "BLINDTRANSFER", iaxs
[fr
->callno
]->owner
->name
);
7853 if (!strcmp(ies
.called_number
, ast_parking_ext())) {
7854 struct ast_channel
*saved_channel
= iaxs
[fr
->callno
]->owner
;
7855 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7856 if (iax_park(bridged_chan
, saved_channel
)) {
7857 ast_log(LOG_WARNING
, "Failed to park call on '%s'\n", bridged_chan
->name
);
7859 ast_log(LOG_DEBUG
, "Parked call on '%s'\n", bridged_chan
->name
);
7861 ast_mutex_lock(&iaxsl
[fr
->callno
]);
7863 if (ast_async_goto(bridged_chan
, iaxs
[fr
->callno
]->context
, ies
.called_number
, 1))
7864 ast_log(LOG_WARNING
, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan
->name
,
7865 ies
.called_number
, iaxs
[fr
->callno
]->context
);
7867 ast_log(LOG_DEBUG
, "Async goto of '%s' to '%s@%s' started\n", bridged_chan
->name
,
7868 ies
.called_number
, iaxs
[fr
->callno
]->context
);
7871 ast_log(LOG_DEBUG
, "Async goto not applicable on call %d\n", fr
->callno
);
7875 case IAX_COMMAND_ACCEPT
:
7876 /* Ignore if call is already up or needs authentication or is a TBD */
7877 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
| IAX_STATE_AUTHENTICATED
))
7879 if (ast_test_flag(iaxs
[fr
->callno
], IAX_PROVISION
)) {
7880 /* Send ack immediately, before we destroy */
7881 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
7882 iax2_destroy(fr
->callno
);
7886 iaxs
[fr
->callno
]->peerformat
= ies
.format
;
7888 if (iaxs
[fr
->callno
]->owner
)
7889 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->owner
->nativeformats
;
7891 iaxs
[fr
->callno
]->peerformat
= iaxs
[fr
->callno
]->capability
;
7893 if (option_verbose
> 2)
7894 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
));
7895 if (!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
)) {
7896 memset(&ied0
, 0, sizeof(ied0
));
7897 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
7898 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
7899 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
7900 if (!iaxs
[fr
->callno
]) {
7901 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7905 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
);
7907 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
7908 if (iaxs
[fr
->callno
]->owner
) {
7909 /* Switch us to use a compatible format */
7910 iaxs
[fr
->callno
]->owner
->nativeformats
= iaxs
[fr
->callno
]->peerformat
;
7911 if (option_verbose
> 2)
7912 ast_verbose(VERBOSE_PREFIX_3
"Format for call is %s\n", ast_getformatname(iaxs
[fr
->callno
]->owner
->nativeformats
));
7914 if (ast_mutex_trylock(&iaxs
[fr
->callno
]->owner
->lock
)) {
7915 DEADLOCK_AVOIDANCE(&iaxsl
[fr
->callno
]);
7916 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) goto retryowner2
;
7919 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->owner
) {
7920 /* Setup read/write formats properly. */
7921 if (iaxs
[fr
->callno
]->owner
->writeformat
)
7922 ast_set_write_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->writeformat
);
7923 if (iaxs
[fr
->callno
]->owner
->readformat
)
7924 ast_set_read_format(iaxs
[fr
->callno
]->owner
, iaxs
[fr
->callno
]->owner
->readformat
);
7925 ast_mutex_unlock(&iaxs
[fr
->callno
]->owner
->lock
);
7929 if (iaxs
[fr
->callno
]) {
7930 ast_mutex_lock(&dpcache_lock
);
7931 dp
= iaxs
[fr
->callno
]->dpentries
;
7933 if (!(dp
->flags
& CACHE_FLAG_TRANSMITTED
)) {
7934 iax2_dprequest(dp
, fr
->callno
);
7938 ast_mutex_unlock(&dpcache_lock
);
7941 case IAX_COMMAND_POKE
:
7942 /* Send back a pong packet with the original timestamp */
7943 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, NULL
, 0, -1);
7944 if (!iaxs
[fr
->callno
]) {
7945 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
7949 case IAX_COMMAND_PING
:
7951 struct iax_ie_data pingied
;
7952 construct_rr(iaxs
[fr
->callno
], &pingied
);
7953 /* Send back a pong packet with the original timestamp */
7954 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_PONG
, fr
->ts
, pingied
.buf
, pingied
.pos
, -1);
7957 case IAX_COMMAND_PONG
:
7958 /* Calculate ping time */
7959 iaxs
[fr
->callno
]->pingtime
= calc_timestamp(iaxs
[fr
->callno
], 0, &f
) - fr
->ts
;
7963 if (iaxs
[fr
->callno
]->peerpoke
) {
7964 peer
= iaxs
[fr
->callno
]->peerpoke
;
7965 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
)) {
7966 if (iaxs
[fr
->callno
]->pingtime
<= peer
->maxms
) {
7967 ast_log(LOG_NOTICE
, "Peer '%s' is now REACHABLE! Time: %d\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7968 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7969 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
7971 } else if ((peer
->historicms
> 0) && (peer
->historicms
<= peer
->maxms
)) {
7972 if (iaxs
[fr
->callno
]->pingtime
> peer
->maxms
) {
7973 ast_log(LOG_NOTICE
, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7974 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer
->name
, iaxs
[fr
->callno
]->pingtime
);
7975 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
7978 peer
->lastms
= iaxs
[fr
->callno
]->pingtime
;
7979 if (peer
->smoothing
&& (peer
->lastms
> -1))
7980 peer
->historicms
= (iaxs
[fr
->callno
]->pingtime
+ peer
->historicms
) / 2;
7981 else if (peer
->smoothing
&& peer
->lastms
< 0)
7982 peer
->historicms
= (0 + peer
->historicms
) / 2;
7984 peer
->historicms
= iaxs
[fr
->callno
]->pingtime
;
7986 /* Remove scheduled iax2_poke_noanswer */
7987 if (peer
->pokeexpire
> -1) {
7988 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
7990 peer
->pokeexpire
= -1;
7993 /* Schedule the next cycle */
7994 if ((peer
->lastms
< 0) || (peer
->historicms
> peer
->maxms
))
7995 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
7997 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqok
, iax2_poke_peer_s
, peer_ref(peer
));
7998 if (peer
->pokeexpire
== -1)
8000 /* and finally send the ack */
8001 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8002 /* And wrap up the qualify call */
8003 iax2_destroy(fr
->callno
);
8006 ast_log(LOG_DEBUG
, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer
->name
, peer
->lastms
, peer
->historicms
, peer
->maxms
);
8009 case IAX_COMMAND_LAGRQ
:
8010 case IAX_COMMAND_LAGRP
:
8015 iax_frame_wrap(fr
, &f
);
8016 if(f
.subclass
== IAX_COMMAND_LAGRQ
) {
8017 /* Received a LAGRQ - echo back a LAGRP */
8018 fr
->af
.subclass
= IAX_COMMAND_LAGRP
;
8019 iax2_send(iaxs
[fr
->callno
], &fr
->af
, fr
->ts
, -1, 0, 0, 0);
8021 /* Received LAGRP in response to our LAGRQ */
8023 /* This is a reply we've been given, actually measure the difference */
8024 ts
= calc_timestamp(iaxs
[fr
->callno
], 0, &fr
->af
);
8025 iaxs
[fr
->callno
]->lag
= ts
- fr
->ts
;
8026 if (option_debug
&& iaxdebug
)
8027 ast_log(LOG_DEBUG
, "Peer %s lag measured as %dms\n",
8028 ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
), iaxs
[fr
->callno
]->lag
);
8031 case IAX_COMMAND_AUTHREQ
:
8032 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
8033 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>");
8036 if (authenticate_reply(iaxs
[fr
->callno
], &iaxs
[fr
->callno
]->addr
, &ies
, iaxs
[fr
->callno
]->secret
, iaxs
[fr
->callno
]->outkey
)) {
8037 struct ast_frame hangup_fr
= { .frametype
= AST_FRAME_CONTROL
,
8038 .subclass
= AST_CONTROL_HANGUP
,
8040 ast_log(LOG_WARNING
,
8041 "I don't know how to authenticate %s to %s\n",
8042 ies
.username
? ies
.username
: "<unknown>", ast_inet_ntoa(iaxs
[fr
->callno
]->addr
.sin_addr
));
8043 iax2_queue_frame(fr
->callno
, &hangup_fr
);
8045 if (!iaxs
[fr
->callno
]) {
8046 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8050 case IAX_COMMAND_AUTHREP
:
8051 /* For security, always ack immediately */
8053 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8054 /* Ignore once we've started */
8055 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
| IAX_STATE_TBD
)) {
8056 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>");
8059 if (authenticate_verify(iaxs
[fr
->callno
], &ies
)) {
8061 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
);
8062 memset(&ied0
, 0, sizeof(ied0
));
8063 auth_fail(fr
->callno
, IAX_COMMAND_REJECT
);
8066 if (strcasecmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
8067 /* This might re-enter the IAX code and need the lock */
8068 exists
= ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
);
8071 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD") && !exists
) {
8073 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
);
8074 memset(&ied0
, 0, sizeof(ied0
));
8075 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
8076 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
8077 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8078 if (!iaxs
[fr
->callno
]) {
8079 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8083 /* Select an appropriate format */
8084 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
8085 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
8086 using_prefs
= "reqonly";
8088 using_prefs
= "disabled";
8090 format
= iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
;
8091 memset(&pref
, 0, sizeof(pref
));
8092 strcpy(caller_pref_buf
, "disabled");
8093 strcpy(host_pref_buf
, "disabled");
8095 using_prefs
= "mine";
8096 if (ies
.codec_prefs
)
8097 ast_codec_pref_convert(&iaxs
[fr
->callno
]->rprefs
, ies
.codec_prefs
, 32, 0);
8098 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
8099 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
8100 pref
= iaxs
[fr
->callno
]->rprefs
;
8101 using_prefs
= "caller";
8103 pref
= iaxs
[fr
->callno
]->prefs
;
8105 } else /* if no codec_prefs IE do it the old way */
8106 pref
= iaxs
[fr
->callno
]->prefs
;
8108 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->capability
& iaxs
[fr
->callno
]->peercapability
, 0);
8109 ast_codec_pref_string(&iaxs
[fr
->callno
]->rprefs
, caller_pref_buf
, sizeof(caller_pref_buf
) - 1);
8110 ast_codec_pref_string(&iaxs
[fr
->callno
]->prefs
, host_pref_buf
, sizeof(host_pref_buf
) - 1);
8113 if(!ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
8115 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
);
8116 format
= iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
;
8120 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
8121 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
);
8123 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
);
8125 memset(&ied0
, 0, sizeof(ied0
));
8126 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
8127 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
8128 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8129 if (!iaxs
[fr
->callno
]) {
8130 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8135 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
)) {
8136 if(!(iaxs
[fr
->callno
]->peerformat
& iaxs
[fr
->callno
]->capability
))
8139 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOPREFS
)) {
8140 using_prefs
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ? "reqonly" : "disabled";
8141 memset(&pref
, 0, sizeof(pref
));
8142 format
= ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
) ?
8143 iaxs
[fr
->callno
]->peerformat
: ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8144 strcpy(caller_pref_buf
,"disabled");
8145 strcpy(host_pref_buf
,"disabled");
8147 using_prefs
= "mine";
8148 if (ast_codec_pref_index(&iaxs
[fr
->callno
]->rprefs
, 0)) {
8149 /* Do the opposite of what we tried above. */
8150 if (ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_USER_FIRST
)) {
8151 pref
= iaxs
[fr
->callno
]->prefs
;
8153 pref
= iaxs
[fr
->callno
]->rprefs
;
8154 using_prefs
= "caller";
8156 format
= ast_codec_choose(&pref
, iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
, 1);
8157 } else /* if no codec_prefs IE do it the old way */
8158 format
= ast_best_codec(iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8162 ast_log(LOG_ERROR
, "No best format in 0x%x???\n", iaxs
[fr
->callno
]->peercapability
& iaxs
[fr
->callno
]->capability
);
8164 if(ast_test_flag(iaxs
[fr
->callno
], IAX_CODEC_NOCAP
))
8165 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
);
8167 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
);
8169 memset(&ied0
, 0, sizeof(ied0
));
8170 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "Unable to negotiate codec");
8171 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL
);
8172 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8173 if (!iaxs
[fr
->callno
]) {
8174 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8181 /* Authentication received */
8182 memset(&ied1
, 0, sizeof(ied1
));
8183 iax_ie_append_int(&ied1
, IAX_IE_FORMAT
, format
);
8184 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACCEPT
, 0, ied1
.buf
, ied1
.pos
, -1);
8185 if (strcmp(iaxs
[fr
->callno
]->exten
, "TBD")) {
8186 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8187 if (option_verbose
> 2)
8188 ast_verbose(VERBOSE_PREFIX_3
"Accepting AUTHENTICATED call from %s:\n"
8189 "%srequested format = %s,\n"
8190 "%srequested prefs = %s,\n"
8191 "%sactual format = %s,\n"
8192 "%shost prefs = %s,\n"
8193 "%spriority = %s\n",
8194 ast_inet_ntoa(sin
.sin_addr
),
8196 ast_getformatname(iaxs
[fr
->callno
]->peerformat
),
8200 ast_getformatname(format
),
8206 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8207 if(!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, format
)))
8208 iax2_destroy(fr
->callno
);
8210 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
8211 /* If this is a TBD call, we're ready but now what... */
8212 if (option_verbose
> 2)
8213 ast_verbose(VERBOSE_PREFIX_3
"Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin
.sin_addr
));
8218 case IAX_COMMAND_DIAL
:
8219 if (ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
)) {
8220 ast_clear_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_TBD
);
8221 ast_string_field_set(iaxs
[fr
->callno
], exten
, ies
.called_number
? ies
.called_number
: "s");
8222 if (!ast_exists_extension(NULL
, iaxs
[fr
->callno
]->context
, iaxs
[fr
->callno
]->exten
, 1, iaxs
[fr
->callno
]->cid_num
)) {
8224 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
);
8225 memset(&ied0
, 0, sizeof(ied0
));
8226 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No such context/extension");
8227 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_NO_ROUTE_DESTINATION
);
8228 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8229 if (!iaxs
[fr
->callno
]) {
8230 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8234 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8235 if (option_verbose
> 2)
8236 ast_verbose(VERBOSE_PREFIX_3
"Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin
.sin_addr
), iaxs
[fr
->callno
]->peerformat
);
8237 ast_set_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
);
8238 send_command(iaxs
[fr
->callno
], AST_FRAME_CONTROL
, AST_CONTROL_PROGRESS
, 0, NULL
, 0, -1);
8239 if(!(c
= ast_iax2_new(fr
->callno
, AST_STATE_RING
, iaxs
[fr
->callno
]->peerformat
)))
8240 iax2_destroy(fr
->callno
);
8244 case IAX_COMMAND_INVAL
:
8245 iaxs
[fr
->callno
]->error
= ENOTCONN
;
8247 ast_log(LOG_DEBUG
, "Immediately destroying %d, having received INVAL\n", fr
->callno
);
8248 iax2_destroy(fr
->callno
);
8250 ast_log(LOG_DEBUG
, "Destroying call %d\n", fr
->callno
);
8252 case IAX_COMMAND_VNAK
:
8254 ast_log(LOG_DEBUG
, "Received VNAK: resending outstanding frames\n");
8255 /* Force retransmission */
8256 vnak_retransmit(fr
->callno
, fr
->iseqno
);
8258 case IAX_COMMAND_REGREQ
:
8259 case IAX_COMMAND_REGREL
:
8260 /* For security, always ack immediately */
8262 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8263 if (register_verify(fr
->callno
, &sin
, &ies
)) {
8264 if (!iaxs
[fr
->callno
]) {
8265 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8268 /* Send delayed failure */
8269 auth_fail(fr
->callno
, IAX_COMMAND_REGREJ
);
8272 if (!iaxs
[fr
->callno
]) {
8273 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8276 if ((ast_strlen_zero(iaxs
[fr
->callno
]->secret
) && ast_strlen_zero(iaxs
[fr
->callno
]->inkeys
)) ||
8277 ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_AUTHENTICATED
| IAX_STATE_UNCHANGED
)) {
8278 if (f
.subclass
== IAX_COMMAND_REGREL
)
8279 memset(&sin
, 0, sizeof(sin
));
8280 if (update_registry(&sin
, fr
->callno
, ies
.devicetype
, fd
, ies
.refresh
))
8281 ast_log(LOG_WARNING
, "Registry error\n");
8282 if (!iaxs
[fr
->callno
]) {
8283 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8286 if (ies
.provverpres
&& ies
.serviceident
&& sin
.sin_addr
.s_addr
) {
8287 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8288 check_provisioning(&sin
, fd
, ies
.serviceident
, ies
.provver
);
8289 ast_mutex_lock(&iaxsl
[fr
->callno
]);
8290 if (!iaxs
[fr
->callno
]) {
8291 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8297 registry_authrequest(fr
->callno
);
8298 if (!iaxs
[fr
->callno
]) {
8299 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8303 case IAX_COMMAND_REGACK
:
8304 if (iax2_ack_registry(&ies
, &sin
, fr
->callno
))
8305 ast_log(LOG_WARNING
, "Registration failure\n");
8306 /* Send ack immediately, before we destroy */
8307 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8308 iax2_destroy(fr
->callno
);
8310 case IAX_COMMAND_REGREJ
:
8311 if (iaxs
[fr
->callno
]->reg
) {
8313 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
));
8314 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>");
8316 iaxs
[fr
->callno
]->reg
->regstate
= REG_STATE_REJECTED
;
8318 /* Send ack immediately, before we destroy */
8319 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8320 iax2_destroy(fr
->callno
);
8322 case IAX_COMMAND_REGAUTH
:
8323 /* Authentication request */
8324 if (registry_rerequest(&ies
, fr
->callno
, &sin
)) {
8325 memset(&ied0
, 0, sizeof(ied0
));
8326 iax_ie_append_str(&ied0
, IAX_IE_CAUSE
, "No authority found");
8327 iax_ie_append_byte(&ied0
, IAX_IE_CAUSECODE
, AST_CAUSE_FACILITY_NOT_SUBSCRIBED
);
8328 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8329 if (!iaxs
[fr
->callno
]) {
8330 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8335 case IAX_COMMAND_TXREJ
:
8336 iaxs
[fr
->callno
]->transferring
= 0;
8337 if (option_verbose
> 2)
8338 ast_verbose(VERBOSE_PREFIX_3
"Channel '%s' unable to transfer\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8339 memset(&iaxs
[fr
->callno
]->transfer
, 0, sizeof(iaxs
[fr
->callno
]->transfer
));
8340 if (iaxs
[fr
->callno
]->bridgecallno
) {
8341 if (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
) {
8342 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= 0;
8343 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREJ
, 0, NULL
, 0, -1);
8347 case IAX_COMMAND_TXREADY
:
8348 if ((iaxs
[fr
->callno
]->transferring
== TRANSFER_BEGIN
) ||
8349 (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)) {
8350 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_MBEGIN
)
8351 iaxs
[fr
->callno
]->transferring
= TRANSFER_MREADY
;
8353 iaxs
[fr
->callno
]->transferring
= TRANSFER_READY
;
8354 if (option_verbose
> 2)
8355 ast_verbose(VERBOSE_PREFIX_3
"Channel '%s' ready to transfer\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>");
8356 if (iaxs
[fr
->callno
]->bridgecallno
) {
8357 if ((iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_READY
) ||
8358 (iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
== TRANSFER_MREADY
)) {
8359 /* They're both ready, now release them. */
8360 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_MREADY
) {
8361 if (option_verbose
> 2)
8362 ast_verbose(VERBOSE_PREFIX_3
"Attempting media bridge of %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
8363 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
8365 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_MEDIA
;
8366 iaxs
[fr
->callno
]->transferring
= TRANSFER_MEDIA
;
8368 memset(&ied0
, 0, sizeof(ied0
));
8369 memset(&ied1
, 0, sizeof(ied1
));
8370 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
8371 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
8372 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied0
.buf
, ied0
.pos
, -1);
8373 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXMEDIA
, 0, ied1
.buf
, ied1
.pos
, -1);
8375 if (option_verbose
> 2)
8376 ast_verbose(VERBOSE_PREFIX_3
"Releasing %s and %s\n", iaxs
[fr
->callno
]->owner
? iaxs
[fr
->callno
]->owner
->name
: "<Unknown>",
8377 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
? iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->owner
->name
: "<Unknown>");
8379 iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->transferring
= TRANSFER_RELEASED
;
8380 iaxs
[fr
->callno
]->transferring
= TRANSFER_RELEASED
;
8381 ast_set_flag(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], IAX_ALREADYGONE
);
8382 ast_set_flag(iaxs
[fr
->callno
], IAX_ALREADYGONE
);
8384 /* Stop doing lag & ping requests */
8385 stop_stuff(fr
->callno
);
8386 stop_stuff(iaxs
[fr
->callno
]->bridgecallno
);
8388 memset(&ied0
, 0, sizeof(ied0
));
8389 memset(&ied1
, 0, sizeof(ied1
));
8390 iax_ie_append_short(&ied0
, IAX_IE_CALLNO
, iaxs
[iaxs
[fr
->callno
]->bridgecallno
]->peercallno
);
8391 iax_ie_append_short(&ied1
, IAX_IE_CALLNO
, iaxs
[fr
->callno
]->peercallno
);
8392 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied0
.buf
, ied0
.pos
, -1);
8393 send_command(iaxs
[iaxs
[fr
->callno
]->bridgecallno
], AST_FRAME_IAX
, IAX_COMMAND_TXREL
, 0, ied1
.buf
, ied1
.pos
, -1);
8400 case IAX_COMMAND_TXREQ
:
8401 try_transfer(iaxs
[fr
->callno
], &ies
);
8403 case IAX_COMMAND_TXCNT
:
8404 if (iaxs
[fr
->callno
]->transferring
)
8405 send_command_transfer(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_TXACC
, 0, NULL
, 0);
8407 case IAX_COMMAND_TXREL
:
8408 /* Send ack immediately, rather than waiting until we've changed addresses */
8409 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8410 complete_transfer(fr
->callno
, &ies
);
8411 stop_stuff(fr
->callno
); /* for attended transfer to work with libiax */
8413 case IAX_COMMAND_TXMEDIA
:
8414 if (iaxs
[fr
->callno
]->transferring
== TRANSFER_READY
) {
8415 AST_LIST_LOCK(&iaxq
.queue
);
8416 AST_LIST_TRAVERSE(&iaxq
.queue
, cur
, list
) {
8417 /* Cancel any outstanding frames and start anew */
8418 if ((fr
->callno
== cur
->callno
) && (cur
->transfer
)) {
8422 AST_LIST_UNLOCK(&iaxq
.queue
);
8423 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8424 iaxs
[fr
->callno
]->transferring
= TRANSFER_MEDIAPASS
;
8427 case IAX_COMMAND_DPREP
:
8428 complete_dpreply(iaxs
[fr
->callno
], &ies
);
8430 case IAX_COMMAND_UNSUPPORT
:
8431 ast_log(LOG_NOTICE
, "Peer did not understand our iax command '%d'\n", ies
.iax_unknown
);
8433 case IAX_COMMAND_FWDOWNL
:
8434 /* Firmware download */
8435 if (!ast_test_flag(&globalflags
, IAX_ALLOWFWDOWNLOAD
)) {
8436 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_UNSUPPORT
, 0, NULL
, 0, -1);
8439 memset(&ied0
, 0, sizeof(ied0
));
8440 res
= iax_firmware_append(&ied0
, (unsigned char *)ies
.devicetype
, ies
.fwdesc
);
8442 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_REJECT
, 0, ied0
.buf
, ied0
.pos
, -1);
8444 send_command_final(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
8446 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_FWDATA
, 0, ied0
.buf
, ied0
.pos
, -1);
8447 if (!iaxs
[fr
->callno
]) {
8448 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8454 ast_log(LOG_DEBUG
, "Unknown IAX command %d on %d/%d\n", f
.subclass
, fr
->callno
, iaxs
[fr
->callno
]->peercallno
);
8455 memset(&ied0
, 0, sizeof(ied0
));
8456 iax_ie_append_byte(&ied0
, IAX_IE_IAX_UNKNOWN
, f
.subclass
);
8457 send_command(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_UNSUPPORT
, 0, ied0
.buf
, ied0
.pos
, -1);
8459 /* Don't actually pass these frames along */
8460 if ((f
.subclass
!= IAX_COMMAND_ACK
) &&
8461 (f
.subclass
!= IAX_COMMAND_TXCNT
) &&
8462 (f
.subclass
!= IAX_COMMAND_TXACC
) &&
8463 (f
.subclass
!= IAX_COMMAND_INVAL
) &&
8464 (f
.subclass
!= IAX_COMMAND_VNAK
)) {
8465 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
8466 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8468 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8471 /* Unless this is an ACK or INVAL frame, ack it */
8472 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->aseqno
!= iaxs
[fr
->callno
]->iseqno
)
8473 send_command_immediate(iaxs
[fr
->callno
], AST_FRAME_IAX
, IAX_COMMAND_ACK
, fr
->ts
, NULL
, 0,fr
->iseqno
);
8474 } else if (minivid
) {
8475 f
.frametype
= AST_FRAME_VIDEO
;
8476 if (iaxs
[fr
->callno
]->videoformat
> 0)
8477 f
.subclass
= iaxs
[fr
->callno
]->videoformat
| (ntohs(vh
->ts
) & 0x8000 ? 1 : 0);
8479 ast_log(LOG_WARNING
, "Received mini frame before first full video frame\n");
8480 iax2_vnak(fr
->callno
);
8481 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8484 f
.datalen
= res
- sizeof(*vh
);
8486 f
.data
= thread
->buf
+ sizeof(*vh
);
8491 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | ((ntohs(vh
->ts
) + test_resync
) & 0x7fff);
8493 #endif /* IAXTESTS */
8494 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF8000L
) | (ntohs(vh
->ts
) & 0x7fff);
8497 f
.frametype
= AST_FRAME_VOICE
;
8498 if (iaxs
[fr
->callno
]->voiceformat
> 0)
8499 f
.subclass
= iaxs
[fr
->callno
]->voiceformat
;
8502 ast_log(LOG_DEBUG
, "Received mini frame before first full voice frame\n");
8503 iax2_vnak(fr
->callno
);
8504 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8507 f
.datalen
= res
- sizeof(struct ast_iax2_mini_hdr
);
8508 if (f
.datalen
< 0) {
8509 ast_log(LOG_WARNING
, "Datalen < 0?\n");
8510 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8514 f
.data
= thread
->buf
+ sizeof(*mh
);
8519 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ((ntohs(mh
->ts
) + test_resync
) & 0xffff);
8521 #endif /* IAXTESTS */
8522 fr
->ts
= (iaxs
[fr
->callno
]->last
& 0xFFFF0000L
) | ntohs(mh
->ts
);
8523 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8525 /* Don't pass any packets until we're started */
8526 if (!ast_test_flag(&iaxs
[fr
->callno
]->state
, IAX_STATE_STARTED
)) {
8527 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8535 if (f
.datalen
&& (f
.frametype
== AST_FRAME_VOICE
)) {
8536 f
.samples
= ast_codec_get_samples(&f
);
8537 /* We need to byteswap incoming slinear samples from network byte order */
8538 if (f
.subclass
== AST_FORMAT_SLINEAR
)
8539 ast_frame_byteswap_be(&f
);
8542 iax_frame_wrap(fr
, &f
);
8544 /* If this is our most recent packet, use it as our basis for timestamping */
8545 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
8546 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8549 if (option_debug
&& iaxdebug
&& iaxs
[fr
->callno
])
8550 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
);
8551 fr
->outoforder
= -1;
8553 fr
->cacheable
= ((f
.frametype
== AST_FRAME_VOICE
) || (f
.frametype
== AST_FRAME_VIDEO
));
8554 duped_fr
= iaxfrdup2(fr
);
8556 schedule_delivery(duped_fr
, updatehistory
, 0, &fr
->ts
);
8558 if (iaxs
[fr
->callno
] && iaxs
[fr
->callno
]->last
< fr
->ts
) {
8559 iaxs
[fr
->callno
]->last
= fr
->ts
;
8561 if (option_debug
&& iaxdebug
)
8562 ast_log(LOG_DEBUG
, "For call=%d, set last=%d\n", fr
->callno
, fr
->ts
);
8566 /* Always run again */
8567 ast_mutex_unlock(&iaxsl
[fr
->callno
]);
8571 /* Function to clean up process thread if it is cancelled */
8572 static void iax2_process_thread_cleanup(void *data
)
8574 struct iax2_thread
*thread
= data
;
8575 ast_mutex_destroy(&thread
->lock
);
8576 ast_cond_destroy(&thread
->cond
);
8578 ast_atomic_dec_and_test(&iaxactivethreadcount
);
8581 static void *iax2_process_thread(void *data
)
8583 struct iax2_thread
*thread
= data
;
8586 int put_into_idle
= 0;
8588 ast_atomic_fetchadd_int(&iaxactivethreadcount
,1);
8589 pthread_cleanup_push(iax2_process_thread_cleanup
, data
);
8591 /* Wait for something to signal us to be awake */
8592 ast_mutex_lock(&thread
->lock
);
8594 /* Flag that we're ready to accept signals */
8595 thread
->ready_for_signal
= 1;
8597 /* Put into idle list if applicable */
8599 insert_idle_thread(thread
);
8601 if (thread
->type
== IAX_TYPE_DYNAMIC
) {
8602 struct iax2_thread
*t
= NULL
;
8603 /* Wait to be signalled or time out */
8604 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8605 ts
.tv_sec
= tv
.tv_sec
;
8606 ts
.tv_nsec
= tv
.tv_usec
* 1000;
8607 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
) {
8608 /* This thread was never put back into the available dynamic
8609 * thread list, so just go away. */
8610 if (!put_into_idle
) {
8611 ast_mutex_unlock(&thread
->lock
);
8614 AST_LIST_LOCK(&dynamic_list
);
8615 /* Account for the case where this thread is acquired *right* after a timeout */
8616 if ((t
= AST_LIST_REMOVE(&dynamic_list
, thread
, list
)))
8617 iaxdynamicthreadcount
--;
8618 AST_LIST_UNLOCK(&dynamic_list
);
8620 /* This dynamic thread timed out waiting for a task and was
8621 * not acquired immediately after the timeout,
8622 * so it's time to go away. */
8623 ast_mutex_unlock(&thread
->lock
);
8626 /* Someone grabbed our thread *right* after we timed out.
8627 * Wait for them to set us up with something to do and signal
8628 * us to continue. */
8629 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8630 ts
.tv_sec
= tv
.tv_sec
;
8631 ts
.tv_nsec
= tv
.tv_usec
* 1000;
8632 if (ast_cond_timedwait(&thread
->cond
, &thread
->lock
, &ts
) == ETIMEDOUT
)
8634 ast_mutex_unlock(&thread
->lock
);
8639 ast_cond_wait(&thread
->cond
, &thread
->lock
);
8642 /* Go back into our respective list */
8645 ast_mutex_unlock(&thread
->lock
);
8647 if (thread
->iostate
== IAX_IOSTATE_IDLE
)
8650 /* Add ourselves to the active list now */
8651 AST_LIST_LOCK(&active_list
);
8652 AST_LIST_INSERT_HEAD(&active_list
, thread
, list
);
8653 AST_LIST_UNLOCK(&active_list
);
8655 /* See what we need to do */
8656 switch(thread
->iostate
) {
8657 case IAX_IOSTATE_READY
:
8659 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
8660 socket_process(thread
);
8661 handle_deferred_full_frames(thread
);
8663 case IAX_IOSTATE_SCHEDREADY
:
8665 thread
->iostate
= IAX_IOSTATE_PROCESSING
;
8666 #ifdef SCHED_MULTITHREADED
8667 thread
->schedfunc(thread
->scheddata
);
8671 time(&thread
->checktime
);
8672 thread
->iostate
= IAX_IOSTATE_IDLE
;
8673 #ifdef DEBUG_SCHED_MULTITHREAD
8674 thread
->curfunc
[0]='\0';
8677 /* Now... remove ourselves from the active list, and return to the idle list */
8678 AST_LIST_LOCK(&active_list
);
8679 AST_LIST_REMOVE(&active_list
, thread
, list
);
8680 AST_LIST_UNLOCK(&active_list
);
8682 /* Make sure another frame didn't sneak in there after we thought we were done. */
8683 handle_deferred_full_frames(thread
);
8686 /*!\note For some reason, idle threads are exiting without being removed
8687 * from an idle list, which is causing memory corruption. Forcibly remove
8688 * it from the list, if it's there.
8690 AST_LIST_LOCK(&idle_list
);
8691 AST_LIST_REMOVE(&idle_list
, thread
, list
);
8692 AST_LIST_UNLOCK(&idle_list
);
8694 AST_LIST_LOCK(&dynamic_list
);
8695 AST_LIST_REMOVE(&dynamic_list
, thread
, list
);
8696 AST_LIST_UNLOCK(&dynamic_list
);
8698 /* I am exiting here on my own volition, I need to clean up my own data structures
8699 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8701 pthread_cleanup_pop(1);
8706 static int iax2_do_register(struct iax2_registry
*reg
)
8708 struct iax_ie_data ied
;
8709 if (option_debug
&& iaxdebug
)
8710 ast_log(LOG_DEBUG
, "Sending registration request for '%s'\n", reg
->username
);
8713 ((reg
->regstate
== REG_STATE_TIMEOUT
) || !reg
->addr
.sin_addr
.s_addr
)) {
8714 /* Maybe the IP has changed, force DNS refresh */
8715 ast_dnsmgr_refresh(reg
->dnsmgr
);
8719 * if IP has Changed, free allocated call to create a new one with new IP
8720 * call has the pointer to IP and must be updated to the new one
8722 if (reg
->dnsmgr
&& ast_dnsmgr_changed(reg
->dnsmgr
) && (reg
->callno
> 0)) {
8723 int callno
= reg
->callno
;
8724 ast_mutex_lock(&iaxsl
[callno
]);
8725 iax2_destroy(callno
);
8726 ast_mutex_unlock(&iaxsl
[callno
]);
8729 if (!reg
->addr
.sin_addr
.s_addr
) {
8730 if (option_debug
&& iaxdebug
)
8731 ast_log(LOG_DEBUG
, "Unable to send registration request for '%s' without IP address\n", reg
->username
);
8732 /* Setup the next registration attempt */
8733 AST_SCHED_DEL(sched
, reg
->expire
);
8734 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
8740 ast_log(LOG_DEBUG
, "Allocate call number\n");
8741 reg
->callno
= find_callno_locked(0, 0, ®
->addr
, NEW_FORCE
, defaultsockfd
, 0);
8742 if (reg
->callno
< 1) {
8743 ast_log(LOG_WARNING
, "Unable to create call for registration\n");
8745 } else if (option_debug
)
8746 ast_log(LOG_DEBUG
, "Registration created on call %d\n", reg
->callno
);
8747 iaxs
[reg
->callno
]->reg
= reg
;
8748 ast_mutex_unlock(&iaxsl
[reg
->callno
]);
8750 /* Schedule the next registration attempt */
8751 AST_SCHED_DEL(sched
, reg
->expire
);
8752 /* Setup the next registration a little early */
8753 reg
->expire
= iax2_sched_add(sched
, (5 * reg
->refresh
/ 6) * 1000, iax2_do_register_s
, reg
);
8754 /* Send the request */
8755 memset(&ied
, 0, sizeof(ied
));
8756 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, reg
->username
);
8757 iax_ie_append_short(&ied
, IAX_IE_REFRESH
, reg
->refresh
);
8758 send_command(iaxs
[reg
->callno
],AST_FRAME_IAX
, IAX_COMMAND_REGREQ
, 0, ied
.buf
, ied
.pos
, -1);
8759 reg
->regstate
= REG_STATE_REGSENT
;
8763 static char *iax2_prov_complete_template_3rd(const char *line
, const char *word
, int pos
, int state
)
8767 return iax_prov_complete_template(line
, word
, pos
, state
);
8770 static int iax2_provision(struct sockaddr_in
*end
, int sockfd
, char *dest
, const char *template, int force
)
8772 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8773 is found for template */
8774 struct iax_ie_data provdata
;
8775 struct iax_ie_data ied
;
8777 struct sockaddr_in sin
;
8779 struct create_addr_info cai
;
8781 memset(&cai
, 0, sizeof(cai
));
8784 ast_log(LOG_DEBUG
, "Provisioning '%s' from template '%s'\n", dest
, template);
8786 if (iax_provision_build(&provdata
, &sig
, template, force
)) {
8788 ast_log(LOG_DEBUG
, "No provisioning found for template '%s'\n", template);
8793 memcpy(&sin
, end
, sizeof(sin
));
8794 cai
.sockfd
= sockfd
;
8795 } else if (create_addr(dest
, NULL
, &sin
, &cai
))
8798 /* Build the rest of the message */
8799 memset(&ied
, 0, sizeof(ied
));
8800 iax_ie_append_raw(&ied
, IAX_IE_PROVISIONING
, provdata
.buf
, provdata
.pos
);
8802 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
8807 /* Schedule autodestruct in case they don't ever give us anything back */
8808 AST_SCHED_DEL(sched
, iaxs
[callno
]->autoid
);
8809 iaxs
[callno
]->autoid
= iax2_sched_add(sched
, 15000, auto_hangup
, (void *)(long)callno
);
8810 ast_set_flag(iaxs
[callno
], IAX_PROVISION
);
8811 /* Got a call number now, so go ahead and send the provisioning information */
8812 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_PROVISION
, 0, ied
.buf
, ied
.pos
, -1);
8814 ast_mutex_unlock(&iaxsl
[callno
]);
8819 static char *papp
= "IAX2Provision";
8820 static char *psyn
= "Provision a calling IAXy with a given template";
8821 static char *pdescrip
=
8822 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8823 "the calling entity is in fact an IAXy) with the given template or\n"
8824 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8827 \ingroup applications
8829 static int iax2_prov_app(struct ast_channel
*chan
, void *data
)
8835 unsigned short callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
8836 if (ast_strlen_zero(data
))
8838 sdata
= ast_strdupa(data
);
8839 opts
= strchr(sdata
, '|');
8843 if (chan
->tech
!= &iax2_tech
) {
8844 ast_log(LOG_NOTICE
, "Can't provision a non-IAX device!\n");
8847 if (!callno
|| !iaxs
[callno
] || !iaxs
[callno
]->addr
.sin_addr
.s_addr
) {
8848 ast_log(LOG_NOTICE
, "Can't provision something with no IP?\n");
8851 res
= iax2_provision(&iaxs
[callno
]->addr
, iaxs
[callno
]->sockfd
, NULL
, sdata
, force
);
8852 if (option_verbose
> 2)
8853 ast_verbose(VERBOSE_PREFIX_3
"Provisioned IAXY at '%s' with '%s'= %d\n",
8854 ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
),
8860 static int iax2_prov_cmd(int fd
, int argc
, char *argv
[])
8865 return RESULT_SHOWUSAGE
;
8867 if (!strcasecmp(argv
[4], "forced"))
8870 return RESULT_SHOWUSAGE
;
8872 res
= iax2_provision(NULL
, -1, argv
[2], argv
[3], force
);
8874 ast_cli(fd
, "Unable to find peer/address '%s'\n", argv
[2]);
8876 ast_cli(fd
, "No template (including wildcard) matching '%s'\n", argv
[3]);
8878 ast_cli(fd
, "Provisioning '%s' with template '%s'%s\n", argv
[2], argv
[3], force
? ", forced" : "");
8879 return RESULT_SUCCESS
;
8882 static void __iax2_poke_noanswer(const void *data
)
8884 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
8887 if (peer
->lastms
> -1) {
8888 ast_log(LOG_NOTICE
, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer
->name
, peer
->lastms
);
8889 manager_event(EVENT_FLAG_SYSTEM
, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer
->name
, peer
->lastms
);
8890 ast_device_state_changed("IAX2/%s", peer
->name
); /* Activate notification */
8892 if ((callno
= peer
->callno
) > 0) {
8893 ast_mutex_lock(&iaxsl
[callno
]);
8894 iax2_destroy(callno
);
8895 ast_mutex_unlock(&iaxsl
[callno
]);
8899 /* Try again quickly */
8900 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_peer_s
, peer_ref(peer
));
8901 if (peer
->pokeexpire
== -1)
8905 static int iax2_poke_noanswer(const void *data
)
8907 struct iax2_peer
*peer
= (struct iax2_peer
*)data
;
8908 peer
->pokeexpire
= -1;
8909 #ifdef SCHED_MULTITHREADED
8910 if (schedule_action(__iax2_poke_noanswer
, data
))
8912 __iax2_poke_noanswer(data
);
8917 static int iax2_poke_peer_cb(void *obj
, void *arg
, int flags
)
8919 struct iax2_peer
*peer
= obj
;
8921 iax2_poke_peer(peer
, 0);
8926 static int iax2_poke_peer(struct iax2_peer
*peer
, int heldcall
)
8929 if (!peer
->maxms
|| (!peer
->addr
.sin_addr
.s_addr
&& !peer
->dnsmgr
)) {
8930 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8931 immediately after clearing things out */
8933 peer
->historicms
= 0;
8934 peer
->pokeexpire
= -1;
8939 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
8940 if ((callno
= peer
->callno
) > 0) {
8941 ast_log(LOG_NOTICE
, "Still have a callno...\n");
8942 ast_mutex_lock(&iaxsl
[callno
]);
8943 iax2_destroy(callno
);
8944 ast_mutex_unlock(&iaxsl
[callno
]);
8947 ast_mutex_unlock(&iaxsl
[heldcall
]);
8948 callno
= peer
->callno
= find_callno(0, 0, &peer
->addr
, NEW_FORCE
, peer
->sockfd
, 0);
8950 ast_mutex_lock(&iaxsl
[heldcall
]);
8951 if (peer
->callno
< 1) {
8952 ast_log(LOG_WARNING
, "Unable to allocate call for poking peer '%s'\n", peer
->name
);
8956 /* Speed up retransmission times for this qualify call */
8957 iaxs
[peer
->callno
]->pingtime
= peer
->maxms
/ 4 + 1;
8958 iaxs
[peer
->callno
]->peerpoke
= peer
;
8960 /* Remove any pending pokeexpire task */
8961 if (peer
->pokeexpire
> -1) {
8962 if (!ast_sched_del(sched
, peer
->pokeexpire
)) {
8963 peer
->pokeexpire
= -1;
8968 /* Queue up a new task to handle no reply */
8969 /* If the host is already unreachable then use the unreachable interval instead */
8970 if (peer
->lastms
< 0) {
8971 peer
->pokeexpire
= iax2_sched_add(sched
, peer
->pokefreqnotok
, iax2_poke_noanswer
, peer_ref(peer
));
8973 peer
->pokeexpire
= iax2_sched_add(sched
, DEFAULT_MAXMS
* 2, iax2_poke_noanswer
, peer_ref(peer
));
8975 if (peer
->pokeexpire
== -1)
8978 /* And send the poke */
8979 ast_mutex_lock(&iaxsl
[callno
]);
8981 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_POKE
, 0, NULL
, 0, -1);
8983 ast_mutex_unlock(&iaxsl
[callno
]);
8988 static void free_context(struct iax2_context
*con
)
8990 struct iax2_context
*conl
;
8998 static struct ast_channel
*iax2_request(const char *type
, int format
, void *data
, int *cause
)
9003 struct sockaddr_in sin
;
9004 struct ast_channel
*c
;
9005 struct parsed_dial_string pds
;
9006 struct create_addr_info cai
;
9009 memset(&pds
, 0, sizeof(pds
));
9010 tmpstr
= ast_strdupa(data
);
9011 parse_dial_string(tmpstr
, &pds
);
9013 if (ast_strlen_zero(pds
.peer
)) {
9014 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
9018 memset(&cai
, 0, sizeof(cai
));
9019 cai
.capability
= iax2_capability
;
9021 ast_copy_flags(&cai
, &globalflags
, IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
9023 /* Populate our address from the given */
9024 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
)) {
9025 *cause
= AST_CAUSE_UNREGISTERED
;
9030 sin
.sin_port
= htons(atoi(pds
.port
));
9032 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
9034 ast_log(LOG_WARNING
, "Unable to create call\n");
9035 *cause
= AST_CAUSE_CONGESTION
;
9039 /* If this is a trunk, update it now */
9040 ast_copy_flags(iaxs
[callno
], &cai
, IAX_TRUNK
| IAX_SENDANI
| IAX_NOTRANSFER
| IAX_TRANSFERMEDIA
| IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
9041 if (ast_test_flag(&cai
, IAX_TRUNK
)) {
9043 if ((new_callno
= make_trunk(callno
, 1)) != -1)
9044 callno
= new_callno
;
9046 iaxs
[callno
]->maxtime
= cai
.maxtime
;
9048 ast_string_field_set(iaxs
[callno
], host
, pds
.peer
);
9050 c
= ast_iax2_new(callno
, AST_STATE_DOWN
, cai
.capability
);
9052 ast_mutex_unlock(&iaxsl
[callno
]);
9055 /* Choose a format we can live with */
9056 if (c
->nativeformats
& format
)
9057 c
->nativeformats
&= format
;
9059 native
= c
->nativeformats
;
9061 res
= ast_translator_best_choice(&fmt
, &native
);
9063 ast_log(LOG_WARNING
, "Unable to create translator path for %s to %s on %s\n",
9064 ast_getformatname(c
->nativeformats
), ast_getformatname(fmt
), c
->name
);
9068 c
->nativeformats
= native
;
9070 c
->readformat
= ast_best_codec(c
->nativeformats
);
9071 c
->writeformat
= c
->readformat
;
9077 static void *sched_thread(void *ignore
)
9085 pthread_testcancel();
9086 ast_mutex_lock(&sched_lock
);
9087 res
= ast_sched_wait(sched
);
9088 if ((res
> 1000) || (res
< 0))
9090 tv
= ast_tvadd(ast_tvnow(), ast_samp2tv(res
, 1000));
9091 ts
.tv_sec
= tv
.tv_sec
;
9092 ts
.tv_nsec
= tv
.tv_usec
* 1000;
9093 ast_cond_timedwait(&sched_cond
, &sched_lock
, &ts
);
9094 ast_mutex_unlock(&sched_lock
);
9095 pthread_testcancel();
9097 count
= ast_sched_runq(sched
);
9098 if (option_debug
&& count
>= 20)
9099 ast_log(LOG_DEBUG
, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count
);
9104 static void *network_thread(void *ignore
)
9106 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
9107 from the network, and queue them for delivery to the channels */
9108 int res
, count
, wakeup
;
9109 struct iax_frame
*f
;
9112 ast_io_add(io
, timingfd
, timing_read
, AST_IO_IN
| AST_IO_PRI
, NULL
);
9115 pthread_testcancel();
9117 /* Go through the queue, sending messages which have not yet been
9118 sent, and scheduling retransmissions if appropriate */
9119 AST_LIST_LOCK(&iaxq
.queue
);
9122 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq
.queue
, f
, list
) {
9126 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
9127 if (ast_mutex_trylock(&iaxsl
[f
->callno
])) {
9134 if (iaxs
[f
->callno
]) {
9139 ast_mutex_unlock(&iaxsl
[f
->callno
]);
9141 if (f
->retries
< 0) {
9142 /* This is not supposed to be retransmitted */
9143 AST_LIST_REMOVE_CURRENT(&iaxq
.queue
, list
);
9145 /* Free the iax frame */
9148 /* We need reliable delivery. Schedule a retransmission */
9150 f
->retrans
= iax2_sched_add(sched
, f
->retrytime
, attempt_transmit
, f
);
9153 AST_LIST_TRAVERSE_SAFE_END
9154 AST_LIST_UNLOCK(&iaxq
.queue
);
9156 pthread_testcancel();
9158 if (option_debug
&& count
>= 20)
9159 ast_log(LOG_DEBUG
, "chan_iax2: Sent %d queued outbound frames all at once\n", count
);
9161 /* Now do the IO, and run scheduled tasks */
9162 res
= ast_io_wait(io
, wakeup
);
9164 if (option_debug
&& res
>= 20)
9165 ast_log(LOG_DEBUG
, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res
);
9171 static int start_network_thread(void)
9173 pthread_attr_t attr
;
9174 int threadcount
= 0;
9176 for (x
= 0; x
< iaxthreadcount
; x
++) {
9177 struct iax2_thread
*thread
= ast_calloc(1, sizeof(struct iax2_thread
));
9179 thread
->type
= IAX_TYPE_POOL
;
9180 thread
->threadnum
= ++threadcount
;
9181 ast_mutex_init(&thread
->lock
);
9182 ast_cond_init(&thread
->cond
, NULL
);
9183 pthread_attr_init(&attr
);
9184 pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
9185 if (ast_pthread_create(&thread
->threadid
, &attr
, iax2_process_thread
, thread
)) {
9186 ast_log(LOG_WARNING
, "Failed to create new thread!\n");
9190 AST_LIST_LOCK(&idle_list
);
9191 AST_LIST_INSERT_TAIL(&idle_list
, thread
, list
);
9192 AST_LIST_UNLOCK(&idle_list
);
9195 ast_pthread_create_background(&schedthreadid
, NULL
, sched_thread
, NULL
);
9196 ast_pthread_create_background(&netthreadid
, NULL
, network_thread
, NULL
);
9197 if (option_verbose
> 1)
9198 ast_verbose(VERBOSE_PREFIX_2
"%d helper threads started\n", threadcount
);
9202 static struct iax2_context
*build_context(char *context
)
9204 struct iax2_context
*con
;
9206 if ((con
= ast_calloc(1, sizeof(*con
))))
9207 ast_copy_string(con
->context
, context
, sizeof(con
->context
));
9212 static int get_auth_methods(char *value
)
9215 if (strstr(value
, "rsa"))
9216 methods
|= IAX_AUTH_RSA
;
9217 if (strstr(value
, "md5"))
9218 methods
|= IAX_AUTH_MD5
;
9219 if (strstr(value
, "plaintext"))
9220 methods
|= IAX_AUTH_PLAINTEXT
;
9225 /*! \brief Check if address can be used as packet source.
9226 \return 0 address available, 1 address unavailable, -1 error
9228 static int check_srcaddr(struct sockaddr
*sa
, socklen_t salen
)
9233 sd
= socket(AF_INET
, SOCK_DGRAM
, 0);
9235 ast_log(LOG_ERROR
, "Socket: %s\n", strerror(errno
));
9239 res
= bind(sd
, sa
, salen
);
9242 ast_log(LOG_DEBUG
, "Can't bind: %s\n", strerror(errno
));
9251 /*! \brief Parse the "sourceaddress" value,
9252 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9254 static int peer_set_srcaddr(struct iax2_peer
*peer
, const char *srcaddr
)
9256 struct sockaddr_in sin
;
9258 int port
= IAX_DEFAULT_PORTNO
;
9259 int sockfd
= defaultsockfd
;
9264 if (!(tmp
= ast_strdupa(srcaddr
)))
9267 addr
= strsep(&tmp
, ":");
9271 port
= atoi(portstr
);
9273 port
= IAX_DEFAULT_PORTNO
;
9276 if (!ast_get_ip(&sin
, addr
)) {
9277 struct ast_netsock
*sock
;
9281 sin
.sin_family
= AF_INET
;
9282 res
= check_srcaddr((struct sockaddr
*) &sin
, sizeof(sin
));
9284 /* ip address valid. */
9285 sin
.sin_port
= htons(port
);
9286 if (!(sock
= ast_netsock_find(netsock
, &sin
)))
9287 sock
= ast_netsock_find(outsock
, &sin
);
9289 sockfd
= ast_netsock_sockfd(sock
);
9292 unsigned int orig_saddr
= sin
.sin_addr
.s_addr
;
9293 /* INADDR_ANY matches anyway! */
9294 sin
.sin_addr
.s_addr
= INADDR_ANY
;
9295 if (ast_netsock_find(netsock
, &sin
)) {
9296 sin
.sin_addr
.s_addr
= orig_saddr
;
9297 sock
= ast_netsock_bind(outsock
, io
, srcaddr
, port
, tos
, socket_read
, NULL
);
9299 sockfd
= ast_netsock_sockfd(sock
);
9300 ast_netsock_unref(sock
);
9310 peer
->sockfd
= sockfd
;
9312 if (nonlocal
== 1) {
9313 ast_log(LOG_WARNING
, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9314 srcaddr
, peer
->name
);
9316 } else if (nonlocal
== 2) {
9317 ast_log(LOG_WARNING
, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9318 srcaddr
, peer
->name
);
9322 ast_log(LOG_DEBUG
, "Using sourceaddress %s for '%s'\n", srcaddr
, peer
->name
);
9327 static void peer_destructor(void *obj
)
9329 struct iax2_peer
*peer
= obj
;
9330 int callno
= peer
->callno
;
9332 ast_free_ha(peer
->ha
);
9335 ast_mutex_lock(&iaxsl
[callno
]);
9336 iax2_destroy(callno
);
9337 ast_mutex_unlock(&iaxsl
[callno
]);
9340 register_peer_exten(peer
, 0);
9343 ast_dnsmgr_release(peer
->dnsmgr
);
9345 ast_string_field_free_memory(peer
);
9348 /*! \brief Create peer structure based on configuration */
9349 static struct iax2_peer
*build_peer(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
9351 struct iax2_peer
*peer
= NULL
;
9352 struct ast_ha
*oldha
= NULL
;
9356 struct iax2_peer tmp_peer
= {
9361 peer
= ao2_find(peers
, &tmp_peer
, OBJ_POINTER
);
9362 if (peer
&& !ast_test_flag(peer
, IAX_DELME
))
9373 } else if ((peer
= ao2_alloc(sizeof(*peer
), peer_destructor
))) {
9375 peer
->pokeexpire
= -1;
9376 peer
->sockfd
= defaultsockfd
;
9377 if (ast_string_field_init(peer
, 32))
9378 peer
= peer_unref(peer
);
9383 ast_copy_flags(peer
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
);
9384 peer
->encmethods
= iax2_encryption
;
9386 ast_string_field_set(peer
,secret
,"");
9388 ast_string_field_set(peer
, name
, name
);
9389 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
9390 peer
->expiry
= min_reg_expire
;
9392 peer
->prefs
= prefs
;
9393 peer
->capability
= iax2_capability
;
9394 peer
->smoothing
= 0;
9395 peer
->pokefreqok
= DEFAULT_FREQ_OK
;
9396 peer
->pokefreqnotok
= DEFAULT_FREQ_NOTOK
;
9397 ast_string_field_set(peer
,context
,"");
9398 ast_string_field_set(peer
,peercontext
,"");
9399 ast_clear_flag(peer
, IAX_HASCALLERID
);
9400 ast_string_field_set(peer
, cid_name
, "");
9401 ast_string_field_set(peer
, cid_num
, "");
9409 if (!strcasecmp(v
->name
, "secret")) {
9410 ast_string_field_set(peer
, secret
, v
->value
);
9411 } else if (!strcasecmp(v
->name
, "mailbox")) {
9412 ast_string_field_set(peer
, mailbox
, v
->value
);
9413 } else if (!strcasecmp(v
->name
, "hasvoicemail")) {
9414 if (ast_true(v
->value
) && ast_strlen_zero(peer
->mailbox
)) {
9415 ast_string_field_set(peer
, mailbox
, name
);
9417 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
9418 ast_string_field_set(peer
, mohinterpret
, v
->value
);
9419 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
9420 ast_string_field_set(peer
, mohsuggest
, v
->value
);
9421 } else if (!strcasecmp(v
->name
, "dbsecret")) {
9422 ast_string_field_set(peer
, dbsecret
, v
->value
);
9423 } else if (!strcasecmp(v
->name
, "trunk")) {
9424 ast_set2_flag(peer
, ast_true(v
->value
), IAX_TRUNK
);
9425 if (ast_test_flag(peer
, IAX_TRUNK
) && (timingfd
< 0)) {
9426 ast_log(LOG_WARNING
, "Unable to support trunking on peer '%s' without timing\n", peer
->name
);
9427 ast_clear_flag(peer
, IAX_TRUNK
);
9429 } else if (!strcasecmp(v
->name
, "auth")) {
9430 peer
->authmethods
= get_auth_methods(v
->value
);
9431 } else if (!strcasecmp(v
->name
, "encryption")) {
9432 peer
->encmethods
= get_encrypt_methods(v
->value
);
9433 } else if (!strcasecmp(v
->name
, "notransfer")) {
9434 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9435 ast_clear_flag(peer
, IAX_TRANSFERMEDIA
);
9436 ast_set2_flag(peer
, ast_true(v
->value
), IAX_NOTRANSFER
);
9437 } else if (!strcasecmp(v
->name
, "transfer")) {
9438 if (!strcasecmp(v
->value
, "mediaonly")) {
9439 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
9440 } else if (ast_true(v
->value
)) {
9441 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
9443 ast_set_flags_to(peer
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
9444 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
9445 ast_set2_flag(peer
, ast_true(v
->value
), IAX_USEJITTERBUF
);
9446 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
9447 ast_set2_flag(peer
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
9448 } else if (!strcasecmp(v
->name
, "host")) {
9449 if (!strcasecmp(v
->value
, "dynamic")) {
9450 /* They'll register with us */
9451 ast_set_flag(peer
, IAX_DYNAMIC
);
9453 /* Initialize stuff iff we're not found, otherwise
9454 we keep going with what we had */
9455 memset(&peer
->addr
.sin_addr
, 0, 4);
9456 if (peer
->addr
.sin_port
) {
9457 /* If we've already got a port, make it the default rather than absolute */
9458 peer
->defaddr
.sin_port
= peer
->addr
.sin_port
;
9459 peer
->addr
.sin_port
= 0;
9463 /* Non-dynamic. Make sure we become that way if we're not */
9464 AST_SCHED_DEL(sched
, peer
->expire
);
9465 ast_clear_flag(peer
, IAX_DYNAMIC
);
9466 if (ast_dnsmgr_lookup(v
->value
, &peer
->addr
.sin_addr
, &peer
->dnsmgr
))
9467 return peer_unref(peer
);
9468 if (!peer
->addr
.sin_port
)
9469 peer
->addr
.sin_port
= htons(IAX_DEFAULT_PORTNO
);
9472 inet_aton("255.255.255.255", &peer
->mask
);
9473 } else if (!strcasecmp(v
->name
, "defaultip")) {
9474 if (ast_get_ip(&peer
->defaddr
, v
->value
))
9475 return peer_unref(peer
);
9476 } else if (!strcasecmp(v
->name
, "sourceaddress")) {
9477 peer_set_srcaddr(peer
, v
->value
);
9478 } else if (!strcasecmp(v
->name
, "permit") ||
9479 !strcasecmp(v
->name
, "deny")) {
9480 peer
->ha
= ast_append_ha(v
->name
, v
->value
, peer
->ha
);
9481 } else if (!strcasecmp(v
->name
, "mask")) {
9483 inet_aton(v
->value
, &peer
->mask
);
9484 } else if (!strcasecmp(v
->name
, "context")) {
9485 ast_string_field_set(peer
, context
, v
->value
);
9486 } else if (!strcasecmp(v
->name
, "regexten")) {
9487 ast_string_field_set(peer
, regexten
, v
->value
);
9488 } else if (!strcasecmp(v
->name
, "peercontext")) {
9489 ast_string_field_set(peer
, peercontext
, v
->value
);
9490 } else if (!strcasecmp(v
->name
, "port")) {
9491 if (ast_test_flag(peer
, IAX_DYNAMIC
))
9492 peer
->defaddr
.sin_port
= htons(atoi(v
->value
));
9494 peer
->addr
.sin_port
= htons(atoi(v
->value
));
9495 } else if (!strcasecmp(v
->name
, "username")) {
9496 ast_string_field_set(peer
, username
, v
->value
);
9497 } else if (!strcasecmp(v
->name
, "allow")) {
9498 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 1);
9499 } else if (!strcasecmp(v
->name
, "disallow")) {
9500 ast_parse_allow_disallow(&peer
->prefs
, &peer
->capability
, v
->value
, 0);
9501 } else if (!strcasecmp(v
->name
, "callerid")) {
9502 if (!ast_strlen_zero(v
->value
)) {
9505 ast_callerid_split(v
->value
, name2
, sizeof(name2
), num2
, sizeof(num2
));
9506 ast_string_field_set(peer
, cid_name
, name2
);
9507 ast_string_field_set(peer
, cid_num
, num2
);
9509 ast_string_field_set(peer
, cid_name
, "");
9510 ast_string_field_set(peer
, cid_num
, "");
9512 ast_set_flag(peer
, IAX_HASCALLERID
);
9513 } else if (!strcasecmp(v
->name
, "fullname")) {
9514 ast_string_field_set(peer
, cid_name
, S_OR(v
->value
, ""));
9515 ast_set_flag(peer
, IAX_HASCALLERID
);
9516 } else if (!strcasecmp(v
->name
, "cid_number")) {
9517 ast_string_field_set(peer
, cid_num
, S_OR(v
->value
, ""));
9518 ast_set_flag(peer
, IAX_HASCALLERID
);
9519 } else if (!strcasecmp(v
->name
, "sendani")) {
9520 ast_set2_flag(peer
, ast_true(v
->value
), IAX_SENDANI
);
9521 } else if (!strcasecmp(v
->name
, "inkeys")) {
9522 ast_string_field_set(peer
, inkeys
, v
->value
);
9523 } else if (!strcasecmp(v
->name
, "outkey")) {
9524 ast_string_field_set(peer
, outkey
, v
->value
);
9525 } else if (!strcasecmp(v
->name
, "qualify")) {
9526 if (!strcasecmp(v
->value
, "no")) {
9528 } else if (!strcasecmp(v
->value
, "yes")) {
9529 peer
->maxms
= DEFAULT_MAXMS
;
9530 } else if (sscanf(v
->value
, "%d", &peer
->maxms
) != 1) {
9531 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
);
9534 } else if (!strcasecmp(v
->name
, "qualifysmoothing")) {
9535 peer
->smoothing
= ast_true(v
->value
);
9536 } else if (!strcasecmp(v
->name
, "qualifyfreqok")) {
9537 if (sscanf(v
->value
, "%d", &peer
->pokefreqok
) != 1) {
9538 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
);
9540 } else if (!strcasecmp(v
->name
, "qualifyfreqnotok")) {
9541 if (sscanf(v
->value
, "%d", &peer
->pokefreqnotok
) != 1) {
9542 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
);
9543 } else ast_log(LOG_WARNING
, "Set peer->pokefreqnotok to %d\n", peer
->pokefreqnotok
);
9544 } else if (!strcasecmp(v
->name
, "timezone")) {
9545 ast_string_field_set(peer
, zonetag
, v
->value
);
9546 } else if (!strcasecmp(v
->name
, "adsi")) {
9547 peer
->adsi
= ast_true(v
->value
);
9548 }/* else if (strcasecmp(v->name,"type")) */
9549 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9556 if (!peer
->authmethods
)
9557 peer
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9558 ast_clear_flag(peer
, IAX_DELME
);
9559 /* Make sure these are IPv4 addresses */
9560 peer
->addr
.sin_family
= AF_INET
;
9567 static void user_destructor(void *obj
)
9569 struct iax2_user
*user
= obj
;
9571 ast_free_ha(user
->ha
);
9572 free_context(user
->contexts
);
9574 ast_variables_destroy(user
->vars
);
9577 ast_string_field_free_memory(user
);
9580 /*! \brief Create in-memory user structure from configuration */
9581 static struct iax2_user
*build_user(const char *name
, struct ast_variable
*v
, struct ast_variable
*alt
, int temponly
)
9583 struct iax2_user
*user
= NULL
;
9584 struct iax2_context
*con
, *conl
= NULL
;
9585 struct ast_ha
*oldha
= NULL
;
9586 struct iax2_context
*oldcon
= NULL
;
9589 int oldcurauthreq
= 0;
9590 char *varname
= NULL
, *varval
= NULL
;
9591 struct ast_variable
*tmpvar
= NULL
;
9592 struct iax2_user tmp_user
= {
9597 user
= ao2_find(users
, &tmp_user
, OBJ_POINTER
);
9598 if (user
&& !ast_test_flag(user
, IAX_DELME
))
9604 oldcurauthreq
= user
->curauthreq
;
9606 oldcon
= user
->contexts
;
9608 user
->contexts
= NULL
;
9610 /* Already in the list, remove it and it will be added back (or FREE'd) */
9611 ao2_unlink(users
, user
);
9613 user
= ao2_alloc(sizeof(*user
), user_destructor
);
9618 ast_string_field_free_memory(user
);
9619 memset(user
, 0, sizeof(struct iax2_user
));
9620 if (ast_string_field_init(user
, 32)) {
9621 user
= user_unref(user
);
9624 user
->maxauthreq
= maxauthreq
;
9625 user
->curauthreq
= oldcurauthreq
;
9626 user
->prefs
= prefs
;
9627 user
->capability
= iax2_capability
;
9628 user
->encmethods
= iax2_encryption
;
9630 ast_string_field_set(user
, name
, name
);
9631 ast_string_field_set(user
, language
, language
);
9632 ast_copy_flags(user
, &globalflags
, IAX_USEJITTERBUF
| IAX_FORCEJITTERBUF
| IAX_CODEC_USER_FIRST
| IAX_CODEC_NOPREFS
| IAX_CODEC_NOCAP
);
9633 ast_clear_flag(user
, IAX_HASCALLERID
);
9634 ast_string_field_set(user
, cid_name
, "");
9635 ast_string_field_set(user
, cid_num
, "");
9642 if (!strcasecmp(v
->name
, "context")) {
9643 con
= build_context(v
->value
);
9648 user
->contexts
= con
;
9651 } else if (!strcasecmp(v
->name
, "permit") ||
9652 !strcasecmp(v
->name
, "deny")) {
9653 user
->ha
= ast_append_ha(v
->name
, v
->value
, user
->ha
);
9654 } else if (!strcasecmp(v
->name
, "setvar")) {
9655 varname
= ast_strdupa(v
->value
);
9656 if (varname
&& (varval
= strchr(varname
,'='))) {
9659 if((tmpvar
= ast_variable_new(varname
, varval
))) {
9660 tmpvar
->next
= user
->vars
;
9661 user
->vars
= tmpvar
;
9664 } else if (!strcasecmp(v
->name
, "allow")) {
9665 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
, v
->value
, 1);
9666 } else if (!strcasecmp(v
->name
, "disallow")) {
9667 ast_parse_allow_disallow(&user
->prefs
, &user
->capability
,v
->value
, 0);
9668 } else if (!strcasecmp(v
->name
, "trunk")) {
9669 ast_set2_flag(user
, ast_true(v
->value
), IAX_TRUNK
);
9670 if (ast_test_flag(user
, IAX_TRUNK
) && (timingfd
< 0)) {
9671 ast_log(LOG_WARNING
, "Unable to support trunking on user '%s' without timing\n", user
->name
);
9672 ast_clear_flag(user
, IAX_TRUNK
);
9674 } else if (!strcasecmp(v
->name
, "auth")) {
9675 user
->authmethods
= get_auth_methods(v
->value
);
9676 } else if (!strcasecmp(v
->name
, "encryption")) {
9677 user
->encmethods
= get_encrypt_methods(v
->value
);
9678 } else if (!strcasecmp(v
->name
, "notransfer")) {
9679 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9680 ast_clear_flag(user
, IAX_TRANSFERMEDIA
);
9681 ast_set2_flag(user
, ast_true(v
->value
), IAX_NOTRANSFER
);
9682 } else if (!strcasecmp(v
->name
, "transfer")) {
9683 if (!strcasecmp(v
->value
, "mediaonly")) {
9684 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
9685 } else if (ast_true(v
->value
)) {
9686 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
9688 ast_set_flags_to(user
, IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
9689 } else if (!strcasecmp(v
->name
, "codecpriority")) {
9690 if(!strcasecmp(v
->value
, "caller"))
9691 ast_set_flag(user
, IAX_CODEC_USER_FIRST
);
9692 else if(!strcasecmp(v
->value
, "disabled"))
9693 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
9694 else if(!strcasecmp(v
->value
, "reqonly")) {
9695 ast_set_flag(user
, IAX_CODEC_NOCAP
);
9696 ast_set_flag(user
, IAX_CODEC_NOPREFS
);
9698 } else if (!strcasecmp(v
->name
, "jitterbuffer")) {
9699 ast_set2_flag(user
, ast_true(v
->value
), IAX_USEJITTERBUF
);
9700 } else if (!strcasecmp(v
->name
, "forcejitterbuffer")) {
9701 ast_set2_flag(user
, ast_true(v
->value
), IAX_FORCEJITTERBUF
);
9702 } else if (!strcasecmp(v
->name
, "dbsecret")) {
9703 ast_string_field_set(user
, dbsecret
, v
->value
);
9704 } else if (!strcasecmp(v
->name
, "secret")) {
9705 if (!ast_strlen_zero(user
->secret
)) {
9706 char *old
= ast_strdupa(user
->secret
);
9708 ast_string_field_build(user
, secret
, "%s;%s", old
, v
->value
);
9710 ast_string_field_set(user
, secret
, v
->value
);
9711 } else if (!strcasecmp(v
->name
, "callerid")) {
9712 if (!ast_strlen_zero(v
->value
) && strcasecmp(v
->value
, "asreceived")) {
9715 ast_callerid_split(v
->value
, name2
, sizeof(name2
), num2
, sizeof(num2
));
9716 ast_string_field_set(user
, cid_name
, name2
);
9717 ast_string_field_set(user
, cid_num
, num2
);
9718 ast_set_flag(user
, IAX_HASCALLERID
);
9720 ast_clear_flag(user
, IAX_HASCALLERID
);
9721 ast_string_field_set(user
, cid_name
, "");
9722 ast_string_field_set(user
, cid_num
, "");
9724 } else if (!strcasecmp(v
->name
, "fullname")) {
9725 if (!ast_strlen_zero(v
->value
)) {
9726 ast_string_field_set(user
, cid_name
, v
->value
);
9727 ast_set_flag(user
, IAX_HASCALLERID
);
9729 ast_string_field_set(user
, cid_name
, "");
9730 if (ast_strlen_zero(user
->cid_num
))
9731 ast_clear_flag(user
, IAX_HASCALLERID
);
9733 } else if (!strcasecmp(v
->name
, "cid_number")) {
9734 if (!ast_strlen_zero(v
->value
)) {
9735 ast_string_field_set(user
, cid_num
, v
->value
);
9736 ast_set_flag(user
, IAX_HASCALLERID
);
9738 ast_string_field_set(user
, cid_num
, "");
9739 if (ast_strlen_zero(user
->cid_name
))
9740 ast_clear_flag(user
, IAX_HASCALLERID
);
9742 } else if (!strcasecmp(v
->name
, "accountcode")) {
9743 ast_string_field_set(user
, accountcode
, v
->value
);
9744 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
9745 ast_string_field_set(user
, mohinterpret
, v
->value
);
9746 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
9747 ast_string_field_set(user
, mohsuggest
, v
->value
);
9748 } else if (!strcasecmp(v
->name
, "language")) {
9749 ast_string_field_set(user
, language
, v
->value
);
9750 } else if (!strcasecmp(v
->name
, "amaflags")) {
9751 format
= ast_cdr_amaflags2int(v
->value
);
9753 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
9755 user
->amaflags
= format
;
9757 } else if (!strcasecmp(v
->name
, "inkeys")) {
9758 ast_string_field_set(user
, inkeys
, v
->value
);
9759 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
9760 user
->maxauthreq
= atoi(v
->value
);
9761 if (user
->maxauthreq
< 0)
9762 user
->maxauthreq
= 0;
9763 } else if (!strcasecmp(v
->name
, "adsi")) {
9764 user
->adsi
= ast_true(v
->value
);
9765 }/* else if (strcasecmp(v->name,"type")) */
9766 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9773 if (!user
->authmethods
) {
9774 if (!ast_strlen_zero(user
->secret
)) {
9775 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9776 if (!ast_strlen_zero(user
->inkeys
))
9777 user
->authmethods
|= IAX_AUTH_RSA
;
9778 } else if (!ast_strlen_zero(user
->inkeys
)) {
9779 user
->authmethods
= IAX_AUTH_RSA
;
9781 user
->authmethods
= IAX_AUTH_MD5
| IAX_AUTH_PLAINTEXT
;
9784 ast_clear_flag(user
, IAX_DELME
);
9790 free_context(oldcon
);
9794 static int peer_delme_cb(void *obj
, void *arg
, int flags
)
9796 struct iax2_peer
*peer
= obj
;
9798 ast_set_flag(peer
, IAX_DELME
);
9803 static int user_delme_cb(void *obj
, void *arg
, int flags
)
9805 struct iax2_user
*user
= obj
;
9807 ast_set_flag(user
, IAX_DELME
);
9812 static void delete_users(void)
9814 struct iax2_registry
*reg
;
9816 ao2_callback(users
, 0, user_delme_cb
, NULL
);
9818 AST_LIST_LOCK(®istrations
);
9819 while ((reg
= AST_LIST_REMOVE_HEAD(®istrations
, entry
))) {
9820 ast_sched_del(sched
, reg
->expire
);
9822 int callno
= reg
->callno
;
9823 ast_mutex_lock(&iaxsl
[callno
]);
9825 iaxs
[callno
]->reg
= NULL
;
9826 iax2_destroy(callno
);
9828 ast_mutex_unlock(&iaxsl
[callno
]);
9831 ast_dnsmgr_release(reg
->dnsmgr
);
9834 AST_LIST_UNLOCK(®istrations
);
9836 ao2_callback(peers
, 0, peer_delme_cb
, NULL
);
9839 static void prune_users(void)
9841 struct iax2_user
*user
;
9842 struct ao2_iterator i
;
9844 i
= ao2_iterator_init(users
, 0);
9845 while ((user
= ao2_iterator_next(&i
))) {
9846 if (ast_test_flag(user
, IAX_DELME
))
9847 ao2_unlink(users
, user
);
9852 /* Prune peers who still are supposed to be deleted */
9853 static void prune_peers(void)
9855 struct iax2_peer
*peer
;
9856 struct ao2_iterator i
;
9858 i
= ao2_iterator_init(peers
, 0);
9859 while ((peer
= ao2_iterator_next(&i
))) {
9860 if (ast_test_flag(peer
, IAX_DELME
))
9866 static void set_timing(void)
9869 int bs
= trunkfreq
* 8;
9870 if (timingfd
> -1) {
9872 #ifdef DAHDI_TIMERACK
9873 ioctl(timingfd
, DAHDI_TIMERCONFIG
, &bs
) &&
9875 ioctl(timingfd
, DAHDI_SET_BLOCKSIZE
, &bs
))
9876 ast_log(LOG_WARNING
, "Unable to set blocksize on timing source\n");
9881 static void set_config_destroy(void)
9883 strcpy(accountcode
, "");
9884 strcpy(language
, "");
9885 strcpy(mohinterpret
, "default");
9886 strcpy(mohsuggest
, "");
9889 ast_clear_flag((&globalflags
), IAX_NOTRANSFER
);
9890 ast_clear_flag((&globalflags
), IAX_TRANSFERMEDIA
);
9891 ast_clear_flag((&globalflags
), IAX_USEJITTERBUF
);
9892 ast_clear_flag((&globalflags
), IAX_FORCEJITTERBUF
);
9896 /*! \brief Load configuration */
9897 static int set_config(char *config_file
, int reload
)
9899 struct ast_config
*cfg
, *ucfg
;
9900 int capability
=iax2_capability
;
9901 struct ast_variable
*v
;
9906 int portno
= IAX_DEFAULT_PORTNO
;
9908 struct iax2_user
*user
;
9909 struct iax2_peer
*peer
;
9910 struct ast_netsock
*ns
;
9912 static unsigned short int last_port
=0;
9915 cfg
= ast_config_load(config_file
);
9918 ast_log(LOG_ERROR
, "Unable to load config %s\n", config_file
);
9923 set_config_destroy();
9926 /* Reset global codec prefs */
9927 memset(&prefs
, 0 , sizeof(struct ast_codec_pref
));
9929 /* Reset Global Flags */
9930 memset(&globalflags
, 0, sizeof(globalflags
));
9931 ast_set_flag(&globalflags
, IAX_RTUPDATE
);
9937 min_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
9938 max_reg_expire
= IAX_DEFAULT_REG_EXPIRE
;
9942 v
= ast_variable_browse(cfg
, "general");
9944 /* Seed initial tos value */
9945 tosval
= ast_variable_retrieve(cfg
, "general", "tos");
9947 if (ast_str2tos(tosval
, &tos
))
9948 ast_log(LOG_WARNING
, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9951 if (!strcasecmp(v
->name
, "bindport")){
9953 ast_log(LOG_NOTICE
, "Ignoring bindport on reload\n");
9955 portno
= atoi(v
->value
);
9956 } else if (!strcasecmp(v
->name
, "pingtime"))
9957 ping_time
= atoi(v
->value
);
9958 else if (!strcasecmp(v
->name
, "iaxthreadcount")) {
9960 if (atoi(v
->value
) != iaxthreadcount
)
9961 ast_log(LOG_NOTICE
, "Ignoring any changes to iaxthreadcount during reload\n");
9963 iaxthreadcount
= atoi(v
->value
);
9964 if (iaxthreadcount
< 1) {
9965 ast_log(LOG_NOTICE
, "iaxthreadcount must be at least 1.\n");
9967 } else if (iaxthreadcount
> 256) {
9968 ast_log(LOG_NOTICE
, "limiting iaxthreadcount to 256\n");
9969 iaxthreadcount
= 256;
9972 } else if (!strcasecmp(v
->name
, "iaxmaxthreadcount")) {
9974 AST_LIST_LOCK(&dynamic_list
);
9975 iaxmaxthreadcount
= atoi(v
->value
);
9976 AST_LIST_UNLOCK(&dynamic_list
);
9978 iaxmaxthreadcount
= atoi(v
->value
);
9979 if (iaxmaxthreadcount
< 0) {
9980 ast_log(LOG_NOTICE
, "iaxmaxthreadcount must be at least 0.\n");
9981 iaxmaxthreadcount
= 0;
9982 } else if (iaxmaxthreadcount
> 256) {
9983 ast_log(LOG_NOTICE
, "Limiting iaxmaxthreadcount to 256\n");
9984 iaxmaxthreadcount
= 256;
9987 } else if (!strcasecmp(v
->name
, "nochecksums")) {
9989 if (ast_true(v
->value
))
9994 if (ast_true(v
->value
))
9995 ast_log(LOG_WARNING
, "Disabling RTP checksums is not supported on this operating system!\n");
9998 else if (!strcasecmp(v
->name
, "maxjitterbuffer"))
9999 maxjitterbuffer
= atoi(v
->value
);
10000 else if (!strcasecmp(v
->name
, "resyncthreshold"))
10001 resyncthreshold
= atoi(v
->value
);
10002 else if (!strcasecmp(v
->name
, "maxjitterinterps"))
10003 maxjitterinterps
= atoi(v
->value
);
10004 else if (!strcasecmp(v
->name
, "lagrqtime"))
10005 lagrq_time
= atoi(v
->value
);
10006 else if (!strcasecmp(v
->name
, "maxregexpire"))
10007 max_reg_expire
= atoi(v
->value
);
10008 else if (!strcasecmp(v
->name
, "minregexpire"))
10009 min_reg_expire
= atoi(v
->value
);
10010 else if (!strcasecmp(v
->name
, "bindaddr")) {
10012 ast_log(LOG_NOTICE
, "Ignoring bindaddr on reload\n");
10014 if (!(ns
= ast_netsock_bind(netsock
, io
, v
->value
, portno
, tos
, socket_read
, NULL
))) {
10015 ast_log(LOG_WARNING
, "Unable apply binding to '%s' at line %d\n", v
->value
, v
->lineno
);
10017 if (option_verbose
> 1) {
10018 if (strchr(v
->value
, ':'))
10019 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to '%s'\n", v
->value
);
10021 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to '%s:%d'\n", v
->value
, portno
);
10023 if (defaultsockfd
< 0)
10024 defaultsockfd
= ast_netsock_sockfd(ns
);
10025 ast_netsock_unref(ns
);
10028 } else if (!strcasecmp(v
->name
, "authdebug"))
10029 authdebug
= ast_true(v
->value
);
10030 else if (!strcasecmp(v
->name
, "encryption"))
10031 iax2_encryption
= get_encrypt_methods(v
->value
);
10032 else if (!strcasecmp(v
->name
, "notransfer")) {
10033 ast_log(LOG_NOTICE
, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
10034 ast_clear_flag((&globalflags
), IAX_TRANSFERMEDIA
);
10035 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_NOTRANSFER
);
10036 } else if (!strcasecmp(v
->name
, "transfer")) {
10037 if (!strcasecmp(v
->value
, "mediaonly")) {
10038 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_TRANSFERMEDIA
);
10039 } else if (ast_true(v
->value
)) {
10040 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, 0);
10042 ast_set_flags_to((&globalflags
), IAX_NOTRANSFER
|IAX_TRANSFERMEDIA
, IAX_NOTRANSFER
);
10043 } else if (!strcasecmp(v
->name
, "codecpriority")) {
10044 if(!strcasecmp(v
->value
, "caller"))
10045 ast_set_flag((&globalflags
), IAX_CODEC_USER_FIRST
);
10046 else if(!strcasecmp(v
->value
, "disabled"))
10047 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
10048 else if(!strcasecmp(v
->value
, "reqonly")) {
10049 ast_set_flag((&globalflags
), IAX_CODEC_NOCAP
);
10050 ast_set_flag((&globalflags
), IAX_CODEC_NOPREFS
);
10052 } else if (!strcasecmp(v
->name
, "jitterbuffer"))
10053 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_USEJITTERBUF
);
10054 else if (!strcasecmp(v
->name
, "forcejitterbuffer"))
10055 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_FORCEJITTERBUF
);
10056 else if (!strcasecmp(v
->name
, "delayreject"))
10057 delayreject
= ast_true(v
->value
);
10058 else if (!strcasecmp(v
->name
, "allowfwdownload"))
10059 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_ALLOWFWDOWNLOAD
);
10060 else if (!strcasecmp(v
->name
, "rtcachefriends"))
10061 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTCACHEFRIENDS
);
10062 else if (!strcasecmp(v
->name
, "rtignoreregexpire"))
10063 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTIGNOREREGEXPIRE
);
10064 else if (!strcasecmp(v
->name
, "rtupdate"))
10065 ast_set2_flag((&globalflags
), ast_true(v
->value
), IAX_RTUPDATE
);
10066 else if (!strcasecmp(v
->name
, "trunktimestamps"))
10067 ast_set2_flag(&globalflags
, ast_true(v
->value
), IAX_TRUNKTIMESTAMPS
);
10068 else if (!strcasecmp(v
->name
, "rtautoclear")) {
10069 int i
= atoi(v
->value
);
10071 global_rtautoclear
= i
;
10074 ast_set2_flag((&globalflags
), i
|| ast_true(v
->value
), IAX_RTAUTOCLEAR
);
10075 } else if (!strcasecmp(v
->name
, "trunkfreq")) {
10076 trunkfreq
= atoi(v
->value
);
10077 if (trunkfreq
< 10)
10079 } else if (!strcasecmp(v
->name
, "autokill")) {
10080 if (sscanf(v
->value
, "%d", &x
) == 1) {
10084 ast_log(LOG_NOTICE
, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v
->lineno
);
10085 } else if (ast_true(v
->value
)) {
10086 autokill
= DEFAULT_MAXMS
;
10090 } else if (!strcasecmp(v
->name
, "bandwidth")) {
10091 if (!strcasecmp(v
->value
, "low")) {
10092 capability
= IAX_CAPABILITY_LOWBANDWIDTH
;
10093 } else if (!strcasecmp(v
->value
, "medium")) {
10094 capability
= IAX_CAPABILITY_MEDBANDWIDTH
;
10095 } else if (!strcasecmp(v
->value
, "high")) {
10096 capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
10098 ast_log(LOG_WARNING
, "bandwidth must be either low, medium, or high\n");
10099 } else if (!strcasecmp(v
->name
, "allow")) {
10100 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 1);
10101 } else if (!strcasecmp(v
->name
, "disallow")) {
10102 ast_parse_allow_disallow(&prefs
, &capability
, v
->value
, 0);
10103 } else if (!strcasecmp(v
->name
, "register")) {
10104 iax2_register(v
->value
, v
->lineno
);
10105 } else if (!strcasecmp(v
->name
, "iaxcompat")) {
10106 iaxcompat
= ast_true(v
->value
);
10107 } else if (!strcasecmp(v
->name
, "regcontext")) {
10108 ast_copy_string(regcontext
, v
->value
, sizeof(regcontext
));
10109 /* Create context if it doesn't exist already */
10110 if (!ast_context_find(regcontext
))
10111 ast_context_create(NULL
, regcontext
, "IAX2");
10112 } else if (!strcasecmp(v
->name
, "tos")) {
10113 if (ast_str2tos(v
->value
, &tos
))
10114 ast_log(LOG_WARNING
, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v
->lineno
);
10115 } else if (!strcasecmp(v
->name
, "accountcode")) {
10116 ast_copy_string(accountcode
, v
->value
, sizeof(accountcode
));
10117 } else if (!strcasecmp(v
->name
, "mohinterpret")) {
10118 ast_copy_string(mohinterpret
, v
->value
, sizeof(mohinterpret
));
10119 } else if (!strcasecmp(v
->name
, "mohsuggest")) {
10120 ast_copy_string(mohsuggest
, v
->value
, sizeof(mohsuggest
));
10121 } else if (!strcasecmp(v
->name
, "amaflags")) {
10122 format
= ast_cdr_amaflags2int(v
->value
);
10124 ast_log(LOG_WARNING
, "Invalid AMA Flags: %s at line %d\n", v
->value
, v
->lineno
);
10128 } else if (!strcasecmp(v
->name
, "language")) {
10129 ast_copy_string(language
, v
->value
, sizeof(language
));
10130 } else if (!strcasecmp(v
->name
, "maxauthreq")) {
10131 maxauthreq
= atoi(v
->value
);
10132 if (maxauthreq
< 0)
10134 } else if (!strcasecmp(v
->name
, "adsi")) {
10135 adsi
= ast_true(v
->value
);
10136 } /*else if (strcasecmp(v->name,"type")) */
10137 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10141 if (defaultsockfd
< 0) {
10142 if (!(ns
= ast_netsock_bind(netsock
, io
, "0.0.0.0", portno
, tos
, socket_read
, NULL
))) {
10143 ast_log(LOG_ERROR
, "Unable to create network socket: %s\n", strerror(errno
));
10145 if (option_verbose
> 1)
10146 ast_verbose(VERBOSE_PREFIX_2
"Binding IAX2 to default address 0.0.0.0:%d\n", portno
);
10147 defaultsockfd
= ast_netsock_sockfd(ns
);
10148 ast_netsock_unref(ns
);
10152 ast_netsock_release(outsock
);
10153 outsock
= ast_netsock_list_alloc();
10155 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
10158 ast_netsock_init(outsock
);
10161 if (min_reg_expire
> max_reg_expire
) {
10162 ast_log(LOG_WARNING
, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
10163 min_reg_expire
, max_reg_expire
, max_reg_expire
);
10164 min_reg_expire
= max_reg_expire
;
10166 iax2_capability
= capability
;
10168 ucfg
= ast_config_load("users.conf");
10170 struct ast_variable
*gen
;
10172 int genregisteriax
;
10173 const char *hasiax
, *registeriax
;
10175 genhasiax
= ast_true(ast_variable_retrieve(ucfg
, "general", "hasiax"));
10176 genregisteriax
= ast_true(ast_variable_retrieve(ucfg
, "general", "registeriax"));
10177 gen
= ast_variable_browse(ucfg
, "general");
10178 cat
= ast_category_browse(ucfg
, NULL
);
10180 if (strcasecmp(cat
, "general")) {
10181 hasiax
= ast_variable_retrieve(ucfg
, cat
, "hasiax");
10182 registeriax
= ast_variable_retrieve(ucfg
, cat
, "registeriax");
10183 if (ast_true(hasiax
) || (!hasiax
&& genhasiax
)) {
10184 /* Start with general parameters, then specific parameters, user and peer */
10185 user
= build_user(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
10187 __ao2_link(users
, user
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10188 user
= user_unref(user
);
10190 peer
= build_peer(cat
, gen
, ast_variable_browse(ucfg
, cat
), 0);
10192 if (ast_test_flag(peer
, IAX_DYNAMIC
))
10193 reg_source_db(peer
);
10194 __ao2_link(peers
, peer
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10195 peer
= peer_unref(peer
);
10198 if (ast_true(registeriax
) || (!registeriax
&& genregisteriax
)) {
10200 const char *host
= ast_variable_retrieve(ucfg
, cat
, "host");
10201 const char *username
= ast_variable_retrieve(ucfg
, cat
, "username");
10202 const char *secret
= ast_variable_retrieve(ucfg
, cat
, "secret");
10204 host
= ast_variable_retrieve(ucfg
, "general", "host");
10206 username
= ast_variable_retrieve(ucfg
, "general", "username");
10208 secret
= ast_variable_retrieve(ucfg
, "general", "secret");
10209 if (!ast_strlen_zero(username
) && !ast_strlen_zero(host
)) {
10210 if (!ast_strlen_zero(secret
))
10211 snprintf(tmp
, sizeof(tmp
), "%s:%s@%s", username
, secret
, host
);
10213 snprintf(tmp
, sizeof(tmp
), "%s@%s", username
, host
);
10214 iax2_register(tmp
, 0);
10218 cat
= ast_category_browse(ucfg
, cat
);
10220 ast_config_destroy(ucfg
);
10223 cat
= ast_category_browse(cfg
, NULL
);
10225 if (strcasecmp(cat
, "general")) {
10226 utype
= ast_variable_retrieve(cfg
, cat
, "type");
10228 if (!strcasecmp(utype
, "user") || !strcasecmp(utype
, "friend")) {
10229 user
= build_user(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
10231 __ao2_link(users
, user
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10232 user
= user_unref(user
);
10235 if (!strcasecmp(utype
, "peer") || !strcasecmp(utype
, "friend")) {
10236 peer
= build_peer(cat
, ast_variable_browse(cfg
, cat
), NULL
, 0);
10238 if (ast_test_flag(peer
, IAX_DYNAMIC
))
10239 reg_source_db(peer
);
10240 __ao2_link(peers
, peer
, (MAX_PEER_BUCKETS
== 1) ? 1 : 0);
10241 peer
= peer_unref(peer
);
10243 } else if (strcasecmp(utype
, "user")) {
10244 ast_log(LOG_WARNING
, "Unknown type '%s' for '%s' in %s\n", utype
, cat
, config_file
);
10247 ast_log(LOG_WARNING
, "Section '%s' lacks type\n", cat
);
10249 cat
= ast_category_browse(cfg
, cat
);
10251 ast_config_destroy(cfg
);
10256 static void poke_all_peers(void)
10258 struct ao2_iterator i
;
10259 struct iax2_peer
*peer
;
10261 i
= ao2_iterator_init(peers
, 0);
10262 while ((peer
= ao2_iterator_next(&i
))) {
10263 iax2_poke_peer(peer
, 0);
10267 static int reload_config(void)
10269 char *config
= "iax.conf";
10270 struct iax2_registry
*reg
;
10272 if (set_config(config
, 1) > 0) {
10275 AST_LIST_LOCK(®istrations
);
10276 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
10277 iax2_do_register(reg
);
10278 AST_LIST_UNLOCK(®istrations
);
10279 /* Qualify hosts, too */
10282 reload_firmware(0);
10283 iax_provision_reload();
10288 static int iax2_reload(int fd
, int argc
, char *argv
[])
10290 return reload_config();
10293 static int reload(void)
10295 return reload_config();
10298 static int cache_get_callno_locked(const char *data
)
10300 struct sockaddr_in sin
;
10303 struct iax_ie_data ied
;
10304 struct create_addr_info cai
;
10305 struct parsed_dial_string pds
;
10308 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
10309 /* Look for an *exact match* call. Once a call is negotiated, it can only
10310 look up entries for a single context */
10311 if (!ast_mutex_trylock(&iaxsl
[x
])) {
10312 if (iaxs
[x
] && !strcasecmp(data
, iaxs
[x
]->dproot
))
10314 ast_mutex_unlock(&iaxsl
[x
]);
10318 /* No match found, we need to create a new one */
10320 memset(&cai
, 0, sizeof(cai
));
10321 memset(&ied
, 0, sizeof(ied
));
10322 memset(&pds
, 0, sizeof(pds
));
10324 tmpstr
= ast_strdupa(data
);
10325 parse_dial_string(tmpstr
, &pds
);
10327 if (ast_strlen_zero(pds
.peer
)) {
10328 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", data
);
10332 /* Populate our address from the given */
10333 if (create_addr(pds
.peer
, NULL
, &sin
, &cai
))
10337 ast_log(LOG_DEBUG
, "peer: %s, username: %s, password: %s, context: %s\n",
10338 pds
.peer
, pds
.username
, pds
.password
, pds
.context
);
10340 callno
= find_callno_locked(0, 0, &sin
, NEW_FORCE
, cai
.sockfd
, 0);
10342 ast_log(LOG_WARNING
, "Unable to create call\n");
10346 ast_string_field_set(iaxs
[callno
], dproot
, data
);
10347 iaxs
[callno
]->capability
= IAX_CAPABILITY_FULLBANDWIDTH
;
10349 iax_ie_append_short(&ied
, IAX_IE_VERSION
, IAX_PROTO_VERSION
);
10350 iax_ie_append_str(&ied
, IAX_IE_CALLED_NUMBER
, "TBD");
10351 /* the string format is slightly different from a standard dial string,
10352 because the context appears in the 'exten' position
10355 iax_ie_append_str(&ied
, IAX_IE_CALLED_CONTEXT
, pds
.exten
);
10357 iax_ie_append_str(&ied
, IAX_IE_USERNAME
, pds
.username
);
10358 iax_ie_append_int(&ied
, IAX_IE_FORMAT
, IAX_CAPABILITY_FULLBANDWIDTH
);
10359 iax_ie_append_int(&ied
, IAX_IE_CAPABILITY
, IAX_CAPABILITY_FULLBANDWIDTH
);
10360 /* Keep password handy */
10362 ast_string_field_set(iaxs
[callno
], secret
, pds
.password
);
10364 ast_string_field_set(iaxs
[callno
], outkey
, pds
.key
);
10365 /* Start the call going */
10366 send_command(iaxs
[callno
], AST_FRAME_IAX
, IAX_COMMAND_NEW
, 0, ied
.buf
, ied
.pos
, -1);
10371 static struct iax2_dpcache
*find_cache(struct ast_channel
*chan
, const char *data
, const char *context
, const char *exten
, int priority
)
10373 struct iax2_dpcache
*dp
, *prev
= NULL
, *next
;
10382 struct ast_channel
*c
;
10383 struct ast_frame
*f
;
10384 gettimeofday(&tv
, NULL
);
10388 /* Expire old caches */
10389 if (ast_tvcmp(tv
, dp
->expiry
) > 0) {
10390 /* It's expired, let it disappear */
10392 prev
->next
= dp
->next
;
10394 dpcache
= dp
->next
;
10395 if (!dp
->peer
&& !(dp
->flags
& CACHE_FLAG_PENDING
) && !dp
->callno
) {
10396 /* Free memory and go again */
10399 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
);
10404 /* We found an entry that matches us! */
10405 if (!strcmp(dp
->peercontext
, data
) && !strcmp(dp
->exten
, exten
))
10411 /* No matching entry. Create a new one. */
10412 /* First, can we make a callno? */
10413 callno
= cache_get_callno_locked(data
);
10415 ast_log(LOG_WARNING
, "Unable to generate call for '%s'\n", data
);
10418 if (!(dp
= ast_calloc(1, sizeof(*dp
)))) {
10419 ast_mutex_unlock(&iaxsl
[callno
]);
10422 ast_copy_string(dp
->peercontext
, data
, sizeof(dp
->peercontext
));
10423 ast_copy_string(dp
->exten
, exten
, sizeof(dp
->exten
));
10424 gettimeofday(&dp
->expiry
, NULL
);
10425 dp
->orig
= dp
->expiry
;
10426 /* Expires in 30 mins by default */
10427 dp
->expiry
.tv_sec
+= iaxdefaultdpcache
;
10428 dp
->next
= dpcache
;
10429 dp
->flags
= CACHE_FLAG_PENDING
;
10430 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
10431 dp
->waiters
[x
] = -1;
10433 dp
->peer
= iaxs
[callno
]->dpentries
;
10434 iaxs
[callno
]->dpentries
= dp
;
10435 /* Send the request if we're already up */
10436 if (ast_test_flag(&iaxs
[callno
]->state
, IAX_STATE_STARTED
))
10437 iax2_dprequest(dp
, callno
);
10438 ast_mutex_unlock(&iaxsl
[callno
]);
10440 /* By here we must have a dp */
10441 if (dp
->flags
& CACHE_FLAG_PENDING
) {
10442 /* Okay, here it starts to get nasty. We need a pipe now to wait
10443 for a reply to come back so long as it's pending */
10444 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++) {
10445 /* Find an empty slot */
10446 if (dp
->waiters
[x
] < 0)
10449 if (x
>= sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0])) {
10450 ast_log(LOG_WARNING
, "No more waiter positions available\n");
10454 ast_log(LOG_WARNING
, "Unable to create pipe for comm\n");
10457 dp
->waiters
[x
] = com
[1];
10458 /* Okay, now we wait */
10459 timeout
= iaxdefaulttimeout
* 1000;
10460 /* Temporarily unlock */
10461 ast_mutex_unlock(&dpcache_lock
);
10462 /* Defer any dtmf */
10464 old
= ast_channel_defer_dtmf(chan
);
10467 c
= ast_waitfor_nandfds(&chan
, chan
? 1 : 0, &com
[0], 1, NULL
, &outfd
, &timeout
);
10476 /* Got hung up on, abort! */
10483 ast_log(LOG_WARNING
, "Timeout waiting for %s exten %s\n", data
, exten
);
10485 ast_mutex_lock(&dpcache_lock
);
10486 dp
->waiters
[x
] = -1;
10490 /* Don't interpret anything, just abort. Not sure what th epoint
10491 of undeferring dtmf on a hung up channel is but hey whatever */
10493 ast_channel_undefer_dtmf(chan
);
10496 if (!(dp
->flags
& CACHE_FLAG_TIMEOUT
)) {
10497 /* Now to do non-independent analysis the results of our wait */
10498 if (dp
->flags
& CACHE_FLAG_PENDING
) {
10499 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10500 pending. Don't let it take as long to timeout. */
10501 dp
->flags
&= ~CACHE_FLAG_PENDING
;
10502 dp
->flags
|= CACHE_FLAG_TIMEOUT
;
10503 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10504 systems without leaving it unavailable once the server comes back online */
10505 dp
->expiry
.tv_sec
= dp
->orig
.tv_sec
+ 60;
10506 for (x
=0;x
<sizeof(dp
->waiters
) / sizeof(dp
->waiters
[0]); x
++)
10507 if (dp
->waiters
[x
] > -1)
10508 write(dp
->waiters
[x
], "asdf", 4);
10511 /* Our caller will obtain the rest */
10513 ast_channel_undefer_dtmf(chan
);
10518 /*! \brief Part of the IAX2 switch interface */
10519 static int iax2_exists(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10521 struct iax2_dpcache
*dp
;
10524 ast_log(LOG_NOTICE
, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10526 if ((priority
!= 1) && (priority
!= 2))
10528 ast_mutex_lock(&dpcache_lock
);
10529 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10531 if (dp
->flags
& CACHE_FLAG_EXISTS
)
10534 ast_mutex_unlock(&dpcache_lock
);
10536 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10541 /*! \brief part of the IAX2 dial plan switch interface */
10542 static int iax2_canmatch(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10545 struct iax2_dpcache
*dp
;
10547 ast_log(LOG_NOTICE
, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10549 if ((priority
!= 1) && (priority
!= 2))
10551 ast_mutex_lock(&dpcache_lock
);
10552 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10554 if (dp
->flags
& CACHE_FLAG_CANEXIST
)
10557 ast_mutex_unlock(&dpcache_lock
);
10559 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10564 /*! \brief Part of the IAX2 Switch interface */
10565 static int iax2_matchmore(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10568 struct iax2_dpcache
*dp
;
10570 ast_log(LOG_NOTICE
, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context
, exten
, priority
, callerid
? callerid
: "<unknown>", data
);
10572 if ((priority
!= 1) && (priority
!= 2))
10574 ast_mutex_lock(&dpcache_lock
);
10575 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10577 if (dp
->flags
& CACHE_FLAG_MATCHMORE
)
10580 ast_mutex_unlock(&dpcache_lock
);
10582 ast_log(LOG_WARNING
, "Unable to make DP cache\n");
10587 /*! \brief Execute IAX2 dialplan switch */
10588 static int iax2_exec(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, const char *callerid
, const char *data
)
10593 struct iax2_dpcache
*dp
;
10594 struct ast_app
*dial
;
10596 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
);
10598 if (priority
== 2) {
10599 /* Indicate status, can be overridden in dialplan */
10600 const char *dialstatus
= pbx_builtin_getvar_helper(chan
, "DIALSTATUS");
10602 dial
= pbx_findapp(dialstatus
);
10604 pbx_exec(chan
, dial
, "");
10607 } else if (priority
!= 1)
10609 ast_mutex_lock(&dpcache_lock
);
10610 dp
= find_cache(chan
, data
, context
, exten
, priority
);
10612 if (dp
->flags
& CACHE_FLAG_EXISTS
) {
10613 ast_copy_string(odata
, data
, sizeof(odata
));
10614 ncontext
= strchr(odata
, '/');
10618 snprintf(req
, sizeof(req
), "IAX2/%s/%s@%s", odata
, exten
, ncontext
);
10620 snprintf(req
, sizeof(req
), "IAX2/%s/%s", odata
, exten
);
10622 if (option_verbose
> 2)
10623 ast_verbose(VERBOSE_PREFIX_3
"Executing Dial('%s')\n", req
);
10625 ast_mutex_unlock(&dpcache_lock
);
10626 ast_log(LOG_WARNING
, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten
, context
, data
);
10630 ast_mutex_unlock(&dpcache_lock
);
10631 dial
= pbx_findapp("Dial");
10633 return pbx_exec(chan
, dial
, req
);
10635 ast_log(LOG_WARNING
, "No dial application registered\n");
10640 static int function_iaxpeer(struct ast_channel
*chan
, char *cmd
, char *data
, char *buf
, size_t len
)
10642 struct iax2_peer
*peer
;
10643 char *peername
, *colname
;
10645 peername
= ast_strdupa(data
);
10647 /* if our channel, return the IP address of the endpoint of current channel */
10648 if (!strcmp(peername
,"CURRENTCHANNEL")) {
10649 unsigned short callno
;
10650 if (chan
->tech
!= &iax2_tech
)
10652 callno
= PTR_TO_CALLNO(chan
->tech_pvt
);
10653 ast_copy_string(buf
, iaxs
[callno
]->addr
.sin_addr
.s_addr
? ast_inet_ntoa(iaxs
[callno
]->addr
.sin_addr
) : "", len
);
10657 if ((colname
= strchr(peername
, ':'))) /*! \todo : will be removed after the 1.4 relese */
10659 else if ((colname
= strchr(peername
, '|')))
10664 if (!(peer
= find_peer(peername
, 1)))
10667 if (!strcasecmp(colname
, "ip")) {
10668 ast_copy_string(buf
, peer
->addr
.sin_addr
.s_addr
? ast_inet_ntoa(peer
->addr
.sin_addr
) : "", len
);
10669 } else if (!strcasecmp(colname
, "status")) {
10670 peer_status(peer
, buf
, len
);
10671 } else if (!strcasecmp(colname
, "mailbox")) {
10672 ast_copy_string(buf
, peer
->mailbox
, len
);
10673 } else if (!strcasecmp(colname
, "context")) {
10674 ast_copy_string(buf
, peer
->context
, len
);
10675 } else if (!strcasecmp(colname
, "expire")) {
10676 snprintf(buf
, len
, "%d", peer
->expire
);
10677 } else if (!strcasecmp(colname
, "dynamic")) {
10678 ast_copy_string(buf
, (ast_test_flag(peer
, IAX_DYNAMIC
) ? "yes" : "no"), len
);
10679 } else if (!strcasecmp(colname
, "callerid_name")) {
10680 ast_copy_string(buf
, peer
->cid_name
, len
);
10681 } else if (!strcasecmp(colname
, "callerid_num")) {
10682 ast_copy_string(buf
, peer
->cid_num
, len
);
10683 } else if (!strcasecmp(colname
, "codecs")) {
10684 ast_getformatname_multiple(buf
, len
-1, peer
->capability
);
10685 } else if (!strncasecmp(colname
, "codec[", 6)) {
10686 char *codecnum
, *ptr
;
10687 int index
= 0, codec
= 0;
10689 codecnum
= strchr(colname
, '[');
10692 if ((ptr
= strchr(codecnum
, ']'))) {
10695 index
= atoi(codecnum
);
10696 if((codec
= ast_codec_pref_index(&peer
->prefs
, index
))) {
10697 ast_copy_string(buf
, ast_getformatname(codec
), len
);
10710 struct ast_custom_function iaxpeer_function
= {
10712 .synopsis
= "Gets IAX peer information",
10713 .syntax
= "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10714 .read
= function_iaxpeer
,
10715 .desc
= "If peername specified, valid items are:\n"
10716 "- ip (default) The IP address.\n"
10717 "- status The peer's status (if qualify=yes)\n"
10718 "- mailbox The configured mailbox.\n"
10719 "- context The configured context.\n"
10720 "- expire The epoch time of the next expire.\n"
10721 "- dynamic Is it dynamic? (yes/no).\n"
10722 "- callerid_name The configured Caller ID name.\n"
10723 "- callerid_num The configured Caller ID number.\n"
10724 "- codecs The configured codecs.\n"
10725 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10727 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10732 /*! \brief Part of the device state notification system ---*/
10733 static int iax2_devicestate(void *data
)
10735 struct parsed_dial_string pds
;
10736 char *tmp
= ast_strdupa(data
);
10737 struct iax2_peer
*p
;
10738 int res
= AST_DEVICE_INVALID
;
10740 memset(&pds
, 0, sizeof(pds
));
10741 parse_dial_string(tmp
, &pds
);
10743 if (ast_strlen_zero(pds
.peer
)) {
10744 ast_log(LOG_WARNING
, "No peer provided in the IAX2 dial string '%s'\n", (char *) data
);
10748 if (option_debug
> 2)
10749 ast_log(LOG_DEBUG
, "Checking device state for device %s\n", pds
.peer
);
10751 /* SLD: FIXME: second call to find_peer during registration */
10752 if (!(p
= find_peer(pds
.peer
, 1)))
10755 res
= AST_DEVICE_UNAVAILABLE
;
10756 if (option_debug
> 2)
10757 ast_log(LOG_DEBUG
, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10758 pds
.peer
, p
->addr
.sin_addr
.s_addr
, p
->defaddr
.sin_addr
.s_addr
, p
->maxms
, p
->lastms
);
10760 if ((p
->addr
.sin_addr
.s_addr
|| p
->defaddr
.sin_addr
.s_addr
) &&
10761 (!p
->maxms
|| ((p
->lastms
> -1) && (p
->historicms
<= p
->maxms
)))) {
10762 /* Peer is registered, or have default IP address
10763 and a valid registration */
10764 if (p
->historicms
== 0 || p
->historicms
<= p
->maxms
)
10765 /* let the core figure out whether it is in use or not */
10766 res
= AST_DEVICE_UNKNOWN
;
10774 static struct ast_switch iax2_switch
=
10777 description
: "IAX Remote Dialplan Switch",
10778 exists
: iax2_exists
,
10779 canmatch
: iax2_canmatch
,
10781 matchmore
: iax2_matchmore
,
10784 static char show_stats_usage
[] =
10785 "Usage: iax2 show stats\n"
10786 " Display statistics on IAX channel driver.\n";
10788 static char show_cache_usage
[] =
10789 "Usage: iax2 show cache\n"
10790 " Display currently cached IAX Dialplan results.\n";
10792 static char show_peer_usage
[] =
10793 "Usage: iax2 show peer <name>\n"
10794 " Display details on specific IAX peer\n";
10796 static char prune_realtime_usage
[] =
10797 "Usage: iax2 prune realtime [<peername>|all]\n"
10798 " Prunes object(s) from the cache\n";
10800 static char iax2_reload_usage
[] =
10801 "Usage: iax2 reload\n"
10802 " Reloads IAX configuration from iax.conf\n";
10804 static char show_prov_usage
[] =
10805 "Usage: iax2 provision <host> <template> [forced]\n"
10806 " Provisions the given peer or IP address using a template\n"
10807 " matching either 'template' or '*' if the template is not\n"
10808 " found. If 'forced' is specified, even empty provisioning\n"
10809 " fields will be provisioned as empty fields.\n";
10811 static char show_users_usage
[] =
10812 "Usage: iax2 show users [like <pattern>]\n"
10813 " Lists all known IAX2 users.\n"
10814 " Optional regular expression pattern is used to filter the user list.\n";
10816 static char show_channels_usage
[] =
10817 "Usage: iax2 show channels\n"
10818 " Lists all currently active IAX channels.\n";
10820 static char show_netstats_usage
[] =
10821 "Usage: iax2 show netstats\n"
10822 " Lists network status for all currently active IAX channels.\n";
10824 static char show_threads_usage
[] =
10825 "Usage: iax2 show threads\n"
10826 " Lists status of IAX helper threads\n";
10828 static char show_peers_usage
[] =
10829 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10830 " Lists all known IAX2 peers.\n"
10831 " Optional 'registered' argument lists only peers with known addresses.\n"
10832 " Optional regular expression pattern is used to filter the peer list.\n";
10834 static char show_firmware_usage
[] =
10835 "Usage: iax2 show firmware\n"
10836 " Lists all known IAX firmware images.\n";
10838 static char show_reg_usage
[] =
10839 "Usage: iax2 show registry\n"
10840 " Lists all registration requests and status.\n";
10842 static char debug_usage
[] =
10843 "Usage: iax2 set debug\n"
10844 " Enables dumping of IAX packets for debugging purposes\n";
10846 static char no_debug_usage
[] =
10847 "Usage: iax2 set debug off\n"
10848 " Disables dumping of IAX packets for debugging purposes\n";
10850 static char debug_trunk_usage
[] =
10851 "Usage: iax2 set debug trunk\n"
10852 " Requests current status of IAX trunking\n";
10854 static char no_debug_trunk_usage
[] =
10855 "Usage: iax2 set debug trunk off\n"
10856 " Requests current status of IAX trunking\n";
10858 static char debug_jb_usage
[] =
10859 "Usage: iax2 set debug jb\n"
10860 " Enables jitterbuffer debugging information\n";
10862 static char no_debug_jb_usage
[] =
10863 "Usage: iax2 set debug jb off\n"
10864 " Disables jitterbuffer debugging information\n";
10866 static char iax2_test_losspct_usage
[] =
10867 "Usage: iax2 test losspct <percentage>\n"
10868 " For testing, throws away <percentage> percent of incoming packets\n";
10871 static char iax2_test_late_usage
[] =
10872 "Usage: iax2 test late <ms>\n"
10873 " For testing, count the next frame as <ms> ms late\n";
10875 static char iax2_test_resync_usage
[] =
10876 "Usage: iax2 test resync <ms>\n"
10877 " For testing, adjust all future frames by <ms> ms\n";
10879 static char iax2_test_jitter_usage
[] =
10880 "Usage: iax2 test jitter <ms> <pct>\n"
10881 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10882 #endif /* IAXTESTS */
10884 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated
= {
10885 { "iax2", "trunk", "debug", NULL
},
10886 iax2_do_trunk_debug
, NULL
,
10889 static struct ast_cli_entry cli_iax2_jb_debug_deprecated
= {
10890 { "iax2", "jb", "debug", NULL
},
10891 iax2_do_jb_debug
, NULL
,
10894 static struct ast_cli_entry cli_iax2_no_debug_deprecated
= {
10895 { "iax2", "no", "debug", NULL
},
10896 iax2_no_debug
, NULL
,
10899 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated
= {
10900 { "iax2", "no", "trunk", "debug", NULL
},
10901 iax2_no_trunk_debug
, NULL
,
10904 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated
= {
10905 { "iax2", "no", "jb", "debug", NULL
},
10906 iax2_no_jb_debug
, NULL
,
10909 static struct ast_cli_entry cli_iax2
[] = {
10910 { { "iax2", "show", "cache", NULL
},
10911 iax2_show_cache
, "Display IAX cached dialplan",
10912 show_cache_usage
, NULL
, },
10914 { { "iax2", "show", "channels", NULL
},
10915 iax2_show_channels
, "List active IAX channels",
10916 show_channels_usage
, NULL
, },
10918 { { "iax2", "show", "firmware", NULL
},
10919 iax2_show_firmware
, "List available IAX firmwares",
10920 show_firmware_usage
, NULL
, },
10922 { { "iax2", "show", "netstats", NULL
},
10923 iax2_show_netstats
, "List active IAX channel netstats",
10924 show_netstats_usage
, NULL
, },
10926 { { "iax2", "show", "peers", NULL
},
10927 iax2_show_peers
, "List defined IAX peers",
10928 show_peers_usage
, NULL
, },
10930 { { "iax2", "show", "registry", NULL
},
10931 iax2_show_registry
, "Display IAX registration status",
10932 show_reg_usage
, NULL
, },
10934 { { "iax2", "show", "stats", NULL
},
10935 iax2_show_stats
, "Display IAX statistics",
10936 show_stats_usage
, NULL
, },
10938 { { "iax2", "show", "threads", NULL
},
10939 iax2_show_threads
, "Display IAX helper thread info",
10940 show_threads_usage
, NULL
, },
10942 { { "iax2", "show", "users", NULL
},
10943 iax2_show_users
, "List defined IAX users",
10944 show_users_usage
, NULL
, },
10946 { { "iax2", "prune", "realtime", NULL
},
10947 iax2_prune_realtime
, "Prune a cached realtime lookup",
10948 prune_realtime_usage
, complete_iax2_show_peer
},
10950 { { "iax2", "reload", NULL
},
10951 iax2_reload
, "Reload IAX configuration",
10952 iax2_reload_usage
},
10954 { { "iax2", "show", "peer", NULL
},
10955 iax2_show_peer
, "Show details on specific IAX peer",
10956 show_peer_usage
, complete_iax2_show_peer
},
10958 { { "iax2", "set", "debug", NULL
},
10959 iax2_do_debug
, "Enable IAX debugging",
10962 { { "iax2", "set", "debug", "trunk", NULL
},
10963 iax2_do_trunk_debug
, "Enable IAX trunk debugging",
10964 debug_trunk_usage
, NULL
, &cli_iax2_trunk_debug_deprecated
},
10966 { { "iax2", "set", "debug", "jb", NULL
},
10967 iax2_do_jb_debug
, "Enable IAX jitterbuffer debugging",
10968 debug_jb_usage
, NULL
, &cli_iax2_jb_debug_deprecated
},
10970 { { "iax2", "set", "debug", "off", NULL
},
10971 iax2_no_debug
, "Disable IAX debugging",
10972 no_debug_usage
, NULL
, &cli_iax2_no_debug_deprecated
},
10974 { { "iax2", "set", "debug", "trunk", "off", NULL
},
10975 iax2_no_trunk_debug
, "Disable IAX trunk debugging",
10976 no_debug_trunk_usage
, NULL
, &cli_iax2_no_trunk_debug_deprecated
},
10978 { { "iax2", "set", "debug", "jb", "off", NULL
},
10979 iax2_no_jb_debug
, "Disable IAX jitterbuffer debugging",
10980 no_debug_jb_usage
, NULL
, &cli_iax2_no_jb_debug_deprecated
},
10982 { { "iax2", "test", "losspct", NULL
},
10983 iax2_test_losspct
, "Set IAX2 incoming frame loss percentage",
10984 iax2_test_losspct_usage
},
10986 { { "iax2", "provision", NULL
},
10987 iax2_prov_cmd
, "Provision an IAX device",
10988 show_prov_usage
, iax2_prov_complete_template_3rd
},
10991 { { "iax2", "test", "late", NULL
},
10992 iax2_test_late
, "Test the receipt of a late frame",
10993 iax2_test_late_usage
},
10995 { { "iax2", "test", "resync", NULL
},
10996 iax2_test_resync
, "Test a resync in received timestamps",
10997 iax2_test_resync_usage
},
10999 { { "iax2", "test", "jitter", NULL
},
11000 iax2_test_jitter
, "Simulates jitter for testing",
11001 iax2_test_jitter_usage
},
11002 #endif /* IAXTESTS */
11005 static int __unload_module(void)
11007 struct iax2_thread
*thread
= NULL
;
11010 /* Make sure threads do not hold shared resources when they are canceled */
11012 /* Grab the sched lock resource to keep it away from threads about to die */
11013 /* Cancel the network thread, close the net socket */
11014 if (netthreadid
!= AST_PTHREADT_NULL
) {
11015 AST_LIST_LOCK(&iaxq
.queue
);
11016 ast_mutex_lock(&sched_lock
);
11017 pthread_cancel(netthreadid
);
11018 ast_cond_signal(&sched_cond
);
11019 ast_mutex_unlock(&sched_lock
); /* Release the schedule lock resource */
11020 AST_LIST_UNLOCK(&iaxq
.queue
);
11021 pthread_join(netthreadid
, NULL
);
11023 if (schedthreadid
!= AST_PTHREADT_NULL
) {
11024 ast_mutex_lock(&sched_lock
);
11025 pthread_cancel(schedthreadid
);
11026 ast_cond_signal(&sched_cond
);
11027 ast_mutex_unlock(&sched_lock
);
11028 pthread_join(schedthreadid
, NULL
);
11031 /* Call for all threads to halt */
11032 AST_LIST_LOCK(&idle_list
);
11033 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list
, thread
, list
) {
11034 AST_LIST_REMOVE_CURRENT(&idle_list
, list
);
11035 pthread_cancel(thread
->threadid
);
11037 AST_LIST_TRAVERSE_SAFE_END
11038 AST_LIST_UNLOCK(&idle_list
);
11040 AST_LIST_LOCK(&active_list
);
11041 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list
, thread
, list
) {
11042 AST_LIST_REMOVE_CURRENT(&active_list
, list
);
11043 pthread_cancel(thread
->threadid
);
11045 AST_LIST_TRAVERSE_SAFE_END
11046 AST_LIST_UNLOCK(&active_list
);
11048 AST_LIST_LOCK(&dynamic_list
);
11049 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list
, thread
, list
) {
11050 AST_LIST_REMOVE_CURRENT(&dynamic_list
, list
);
11051 pthread_cancel(thread
->threadid
);
11053 AST_LIST_TRAVERSE_SAFE_END
11054 AST_LIST_UNLOCK(&dynamic_list
);
11056 AST_LIST_HEAD_DESTROY(&iaxq
.queue
);
11058 /* Wait for threads to exit */
11059 while(0 < iaxactivethreadcount
)
11062 ast_netsock_release(netsock
);
11063 ast_netsock_release(outsock
);
11064 for (x
= 0; x
< ARRAY_LEN(iaxs
); x
++) {
11069 ast_manager_unregister( "IAXpeers" );
11070 ast_manager_unregister( "IAXnetstats" );
11071 ast_unregister_application(papp
);
11072 ast_cli_unregister_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
11073 ast_unregister_switch(&iax2_switch
);
11074 ast_channel_unregister(&iax2_tech
);
11076 iax_provision_unload();
11077 sched_context_destroy(sched
);
11078 reload_firmware(1);
11080 ast_mutex_destroy(&waresl
.lock
);
11082 for (x
= 0; x
< ARRAY_LEN(iaxsl
); x
++) {
11083 ast_mutex_destroy(&iaxsl
[x
]);
11086 ao2_ref(peers
, -1);
11087 ao2_ref(users
, -1);
11088 ao2_ref(iax_peercallno_pvts
, -1);
11093 static int unload_module(void)
11095 ast_custom_function_unregister(&iaxpeer_function
);
11096 return __unload_module();
11099 static int peer_set_sock_cb(void *obj
, void *arg
, int flags
)
11101 struct iax2_peer
*peer
= obj
;
11103 if (peer
->sockfd
< 0)
11104 peer
->sockfd
= defaultsockfd
;
11109 static int pvt_hash_cb(const void *obj
, const int flags
)
11111 const struct chan_iax2_pvt
*pvt
= obj
;
11113 return pvt
->peercallno
;
11116 static int pvt_cmp_cb(void *obj
, void *arg
, int flags
)
11118 struct chan_iax2_pvt
*pvt
= obj
, *pvt2
= arg
;
11120 /* The frames_received field is used to hold whether we're matching
11121 * against a full frame or not ... */
11123 return match(&pvt2
->addr
, pvt2
->peercallno
, pvt2
->callno
, pvt
,
11124 pvt2
->frames_received
) ? CMP_MATCH
| CMP_STOP
: 0;
11127 /*! \brief Load IAX2 module, load configuraiton ---*/
11128 static int load_module(void)
11130 char *config
= "iax.conf";
11133 struct iax2_registry
*reg
= NULL
;
11135 peers
= ao2_container_alloc(MAX_PEER_BUCKETS
, peer_hash_cb
, peer_cmp_cb
);
11137 return AST_MODULE_LOAD_FAILURE
;
11138 users
= ao2_container_alloc(MAX_USER_BUCKETS
, user_hash_cb
, user_cmp_cb
);
11140 ao2_ref(peers
, -1);
11141 return AST_MODULE_LOAD_FAILURE
;
11143 iax_peercallno_pvts
= ao2_container_alloc(IAX_MAX_CALLS
, pvt_hash_cb
, pvt_cmp_cb
);
11144 if (!iax_peercallno_pvts
) {
11145 ao2_ref(peers
, -1);
11146 ao2_ref(users
, -1);
11147 return AST_MODULE_LOAD_FAILURE
;
11150 ast_custom_function_register(&iaxpeer_function
);
11152 iax_set_output(iax_debug_output
);
11153 iax_set_error(iax_error_output
);
11154 jb_setoutput(jb_error_output
, jb_warning_output
, NULL
);
11157 #ifdef ZAPTEL_TIMERACK
11158 timingfd
= open("/dev/zap/timer", O_RDWR
);
11161 timingfd
= open("/dev/zap/pseudo", O_RDWR
);
11163 ast_log(LOG_WARNING
, "Unable to open IAX timing interface: %s\n", strerror(errno
));
11164 #elif defined(HAVE_DAHDI)
11165 #ifdef DAHDI_TIMERACK
11166 timingfd
= open("/dev/dahdi/timer", O_RDWR
);
11169 timingfd
= open("/dev/dahdi/pseudo", O_RDWR
);
11171 ast_log(LOG_WARNING
, "Unable to open IAX timing interface: %s\n", strerror(errno
));
11174 memset(iaxs
, 0, sizeof(iaxs
));
11176 for (x
= 0; x
< ARRAY_LEN(iaxsl
); x
++) {
11177 ast_mutex_init(&iaxsl
[x
]);
11180 ast_cond_init(&sched_cond
, NULL
);
11182 io
= io_context_create();
11183 sched
= sched_context_create();
11185 if (!io
|| !sched
) {
11186 ast_log(LOG_ERROR
, "Out of memory\n");
11190 netsock
= ast_netsock_list_alloc();
11192 ast_log(LOG_ERROR
, "Could not allocate netsock list.\n");
11195 ast_netsock_init(netsock
);
11197 outsock
= ast_netsock_list_alloc();
11199 ast_log(LOG_ERROR
, "Could not allocate outsock list.\n");
11202 ast_netsock_init(outsock
);
11204 ast_mutex_init(&waresl
.lock
);
11206 AST_LIST_HEAD_INIT(&iaxq
.queue
);
11208 ast_cli_register_multiple(cli_iax2
, sizeof(cli_iax2
) / sizeof(struct ast_cli_entry
));
11210 ast_register_application(papp
, iax2_prov_app
, psyn
, pdescrip
);
11212 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers
, "List IAX Peers" );
11213 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats
, "Show IAX Netstats" );
11215 if(set_config(config
, 0) == -1)
11216 return AST_MODULE_LOAD_DECLINE
;
11218 if (ast_channel_register(&iax2_tech
)) {
11219 ast_log(LOG_ERROR
, "Unable to register channel class %s\n", "IAX2");
11224 if (ast_register_switch(&iax2_switch
))
11225 ast_log(LOG_ERROR
, "Unable to register IAX switch\n");
11227 res
= start_network_thread();
11229 if (option_verbose
> 1)
11230 ast_verbose(VERBOSE_PREFIX_2
"IAX Ready and Listening\n");
11232 ast_log(LOG_ERROR
, "Unable to start network thread\n");
11233 ast_netsock_release(netsock
);
11234 ast_netsock_release(outsock
);
11237 AST_LIST_LOCK(®istrations
);
11238 AST_LIST_TRAVERSE(®istrations
, reg
, entry
)
11239 iax2_do_register(reg
);
11240 AST_LIST_UNLOCK(®istrations
);
11242 ao2_callback(peers
, 0, peer_set_sock_cb
, NULL
);
11243 ao2_callback(peers
, 0, iax2_poke_peer_cb
, NULL
);
11245 reload_firmware(0);
11246 iax_provision_reload();
11250 AST_MODULE_INFO(ASTERISK_GPL_KEY
, AST_MODFLAG_DEFAULT
, "Inter Asterisk eXchange (Ver 2)",
11251 .load
= load_module
,
11252 .unload
= unload_module
,