Ignore some files generated from 1.6.x/trunk build
[asterisk-bristuff.git] / channels / chan_iax2.c
blob5d593dd0c20d741e92f2a41a5a4b067202305206
1 /*
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.
19 /*! \file
21 * \brief Implementation of Inter-Asterisk eXchange Version 2
23 * \author Mark Spencer <markster@digium.com>
25 * \par See also
26 * \arg \ref Config_iax
28 * \ingroup channel_drivers
31 /*** MODULEINFO
32 <use>dahdi</use>
33 <depend>res_features</depend>
34 ***/
36 #include "asterisk.h"
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
40 #include <stdlib.h>
41 #include <stdio.h>
42 #include <sys/types.h>
43 #include <sys/mman.h>
44 #include <dirent.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>
50 #include <sys/time.h>
51 #include <sys/signal.h>
52 #include <signal.h>
53 #include <string.h>
54 #include <strings.h>
55 #include <errno.h>
56 #include <unistd.h>
57 #include <netdb.h>
58 #include <fcntl.h>
59 #include <sys/stat.h>
60 #include <regex.h>
62 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
63 #include <sys/ioctl.h>
64 #include "asterisk/dahdi_compat.h"
65 #endif
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"
100 #include "iax2.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
115 #endif
117 #ifdef SO_NO_CHECK
118 static int nochecksums = 0;
119 #endif
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 */
136 #define GAMMA (0.01)
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;
176 /* Ethernet, etc */
177 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
178 /* T1, maybe ISDN */
179 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
180 ~AST_FORMAT_SLINEAR & \
181 ~AST_FORMAT_ULAW & \
182 ~AST_FORMAT_ALAW & \
183 ~AST_FORMAT_G722)
184 /* A modem */
185 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
186 ~AST_FORMAT_G726 & \
187 ~AST_FORMAT_G726_AAL2 & \
188 ~AST_FORMAT_ADPCM)
190 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
191 ~AST_FORMAT_G723_1)
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;
208 #ifdef IAXTESTS
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;
219 static int adsi = 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;
230 enum {
231 IAX_STATE_STARTED = (1 << 0),
232 IAX_STATE_AUTHENTICATED = (1 << 1),
233 IAX_STATE_TBD = (1 << 2),
234 IAX_STATE_UNCHANGED = (1 << 3),
235 } iax2_state;
237 struct iax2_context {
238 char context[AST_MAX_CONTEXT];
239 struct iax2_context *next;
242 enum {
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? */
272 } iax2_flags;
274 static int global_rtautoclear = 120;
276 static int reload_config(void);
277 static int iax2_reload(int fd, int argc, char *argv[]);
280 struct iax2_user {
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);
294 int authmethods;
295 int encmethods;
296 int amaflags;
297 int adsi;
298 unsigned int flags;
299 int capability;
300 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
301 int curauthreq; /*!< Current number of outstanding AUTHREQs */
302 struct ast_codec_pref prefs;
303 struct ast_ha *ha;
304 struct iax2_context *contexts;
305 struct ast_variable *vars;
308 struct iax2_peer {
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;
331 int formats;
332 int sockfd; /*!< Socket to use for transmission */
333 struct in_addr mask;
334 int adsi;
335 unsigned int flags;
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 */
346 /* Qualification */
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 */
357 struct ast_ha *ha;
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 {
363 ast_mutex_t lock;
364 int sockfd;
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;
376 int trunkerror;
377 int calls;
378 } *tpeers = NULL;
380 AST_MUTEX_DEFINE_STATIC(tpeerlock);
382 struct iax_firmware {
383 struct iax_firmware *next;
384 int fd;
385 int mmaplen;
386 int dead;
387 struct ast_iax2_firmware_header *fwh;
388 unsigned char *buf;
391 enum iax_reg_state {
392 REG_STATE_UNREGISTERED = 0,
393 REG_STATE_REGSENT,
394 REG_STATE_AUTHSENT,
395 REG_STATE_REGISTERED,
396 REG_STATE_REJECTED,
397 REG_STATE_TIMEOUT,
398 REG_STATE_NOAUTH
401 enum iax_transfer_state {
402 TRANSFER_NONE = 0,
403 TRANSFER_BEGIN,
404 TRANSFER_READY,
405 TRANSFER_RELEASED,
406 TRANSFER_PASSTHROUGH,
407 TRANSFER_MBEGIN,
408 TRANSFER_MREADY,
409 TRANSFER_MRELEASED,
410 TRANSFER_MPASSTHROUGH,
411 TRANSFER_MEDIA,
412 TRANSFER_MEDIAPASS
415 struct iax2_registry {
416 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
417 char username[80];
418 char secret[80]; /*!< Password or key name in []'s */
419 char random[80];
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;
453 struct iax_rr {
454 int jitter;
455 int losspct;
456 int losscnt;
457 int packets;
458 int delay;
459 int dropped;
460 int ooo;
463 struct chan_iax2_pvt {
464 /*! Socket to send/receive on for this call */
465 int sockfd;
466 /*! Last received voice format */
467 int voiceformat;
468 /*! Last received video format */
469 int videoformat;
470 /*! Last sent voice format */
471 int svoiceformat;
472 /*! Last sent video format */
473 int svideoformat;
474 /*! What we are capable of sending */
475 int capability;
476 /*! Last received timestamp */
477 unsigned int last;
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 */
485 int notsilenttx;
486 /*! Ping time */
487 unsigned int pingtime;
488 /*! Max time for initial response */
489 int maxtime;
490 /*! Peer Address */
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;
498 /*! Peer 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 */
503 int chosenformat;
504 /*! Peer selected format */
505 int peerformat;
506 /*! Peer capability */
507 int peercapability;
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 */
513 jitterbuf *jb;
514 /*! active jb read scheduler id */
515 int jbid;
516 /*! LAG */
517 int lag;
518 /*! Error, as discovered by the manager */
519 int error;
520 /*! Owner if we have one */
521 struct ast_channel *owner;
522 /*! What's our state? */
523 struct ast_flags state;
524 /*! Expiry (optional) */
525 int expiry;
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(
536 /*! Peer name */
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);
545 /*! DNID */
546 AST_STRING_FIELD(dnid);
547 /*! RDNIS */
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);
555 /*! MD5 challenge */
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 */
573 int authmethods;
574 /*! permitted encryption methods */
575 int encmethods;
576 /*! Encryption AES-128 Key */
577 aes_encrypt_ctx ecx;
578 /*! Decryption AES-128 Key */
579 aes_decrypt_ctx dcx;
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;
586 /*! IAX_ flags */
587 unsigned int flags;
588 int adsi;
590 /*! Transferring status */
591 enum iax_transfer_state transferring;
592 /*! Transfer identifier */
593 int transferid;
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 */
602 int peeradsicpe;
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) */
613 int calling_ton;
614 int calling_tns;
615 int calling_pres;
616 int amaflags;
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) */
622 int min;
623 /*! Dropped frame count: (just for stats) */
624 int frames_dropped;
625 /*! received frame count: (just for stats) */
626 int frames_received;
629 static struct ast_iax2_queue {
630 AST_LIST_HEAD(, iax_frame) queue;
631 int count;
632 } iaxq;
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. */
641 #ifdef LOW_MEMORY
642 #define MAX_PEER_BUCKETS 1
643 /* #define MAX_PEER_BUCKETS 17 */
644 #else
645 #define MAX_PEER_BUCKETS 1
646 /* #define MAX_PEER_BUCKETS 563 */
647 #endif
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;
655 ast_mutex_t lock;
656 } waresl;
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)
666 /*! Timed out */
667 #define CACHE_FLAG_TIMEOUT (1 << 4)
668 /*! Request transmitted */
669 #define CACHE_FLAG_TRANSMITTED (1 << 5)
670 /*! Timeout */
671 #define CACHE_FLAG_UNKNOWN (1 << 6)
672 /*! Matchmore */
673 #define CACHE_FLAG_MATCHMORE (1 << 7)
675 static struct iax2_dpcache {
676 char peercontext[AST_MAX_CONTEXT];
677 char exten[AST_MAX_EXTENSION];
678 struct timeval orig;
679 struct timeval expiry;
680 int flags;
681 unsigned short callno;
682 int waiters[256];
683 struct iax2_dpcache *next;
684 struct iax2_dpcache *peer; /*!< For linking in peers */
685 } *dpcache;
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;
704 size_t len;
705 unsigned char buf[1];
708 struct iax2_thread {
709 AST_LIST_ENTRY(iax2_thread) list;
710 int type;
711 int iostate;
712 #ifdef SCHED_MULTITHREADED
713 void (*schedfunc)(const void *);
714 const void *scheddata;
715 #endif
716 #ifdef DEBUG_SCHED_MULTITHREAD
717 char curfunc[80];
718 #endif
719 int actions;
720 pthread_t threadid;
721 int threadnum;
722 struct sockaddr_in iosin;
723 unsigned char readbuf[4096];
724 unsigned char *buf;
725 ssize_t buf_len;
726 size_t buf_size;
727 int iofd;
728 time_t checktime;
729 ast_mutex_t lock;
730 ast_cond_t cond;
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 */
736 struct {
737 unsigned short callno;
738 struct sockaddr_in sin;
739 unsigned char type;
740 unsigned char csub;
741 } ffinfo;
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;
748 /* Thread lists */
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)
764 if (iaxdebug)
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, ...)
775 va_list args;
776 char buf[1024];
778 va_start(args, fmt);
779 vsnprintf(buf, 1024, fmt, args);
780 va_end(args);
782 ast_log(LOG_ERROR, buf);
785 static void jb_warning_output(const char *fmt, ...)
787 va_list args;
788 char buf[1024];
790 va_start(args, fmt);
791 vsnprintf(buf, 1024, fmt, args);
792 va_end(args);
794 ast_log(LOG_WARNING, buf);
797 static void jb_debug_output(const char *fmt, ...)
799 va_list args;
800 char buf[1024];
802 va_start(args, fmt);
803 vsnprintf(buf, 1024, fmt, args);
804 va_end(args);
806 ast_verbose(buf);
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 = {
865 .type = "IAX2",
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,
876 .call = iax2_call,
877 .hangup = iax2_hangup,
878 .answer = iax2_answer,
879 .read = iax2_read,
880 .write = iax2_write,
881 .write_video = iax2_write,
882 .indicate = iax2_indicate,
883 .setoption = iax2_setoption,
884 .bridge = iax2_bridge,
885 .transfer = iax2_transfer,
886 .fixup = iax2_fixup,
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);
898 } else {
899 AST_LIST_LOCK(&idle_list);
900 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
901 AST_LIST_UNLOCK(&idle_list);
904 return;
907 static struct iax2_thread *find_idle_thread(void)
909 pthread_attr_t attr;
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)) {
932 free(thread);
933 thread = NULL;
934 } else {
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)
940 usleep(1);
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 */
949 if (thread)
950 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
952 return thread;
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;
960 static time_t t;
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));
970 #endif
971 signal_condition(&thread->lock, &thread->cond);
972 return 0;
974 time(&t);
975 if (t != lasterror && option_debug)
976 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for scheduling!\n");
977 lasterror = t;
979 return -1;
981 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
982 #endif
984 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
986 int res;
988 res = ast_sched_add(con, when, callback, data);
989 signal_condition(&sched_lock, &sched_cond);
991 return res;
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]);
1002 if (iaxs[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);
1006 } else {
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))
1021 #endif
1022 __send_ping(data);
1024 return 0;
1027 static int get_encrypt_methods(const char *s)
1029 int e;
1030 if (!strcasecmp(s, "aes128"))
1031 e = IAX_ENCRYPT_AES128;
1032 else if (ast_true(s))
1033 e = IAX_ENCRYPT_AES128;
1034 else
1035 e = 0;
1036 return e;
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]);
1047 if (iaxs[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);
1051 } else {
1052 /* I am the schedule, so I'm allowed to do this */
1053 iaxs[callno]->lagid = -1;
1055 } else {
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))
1066 #endif
1067 __send_lagrq(data);
1069 return 0;
1072 static unsigned char compress_subclass(int subclass)
1074 int x;
1075 int power=-1;
1076 /* If it's 128 or smaller, just return it */
1077 if (subclass < IAX_FLAG_SC_LOG)
1078 return subclass;
1079 /* Otherwise find its power */
1080 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1081 if (subclass & (1 << x)) {
1082 if (power > -1) {
1083 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1084 return 0;
1085 } else
1086 power = x;
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 */
1097 if (csub == 0xff)
1098 return -1;
1099 else
1100 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1102 else
1103 return csub;
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 = {
1154 .name = name,
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);
1163 return peer;
1166 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1168 ao2_ref(peer, +1);
1169 return peer;
1172 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1174 ao2_ref(peer, -1);
1175 return NULL;
1178 static inline struct iax2_user *user_ref(struct iax2_user *user)
1180 ao2_ref(user, +1);
1181 return user;
1184 static inline struct iax2_user *user_unref(struct iax2_user *user)
1186 ao2_ref(user, -1);
1187 return NULL;
1190 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1192 struct iax2_peer *peer = NULL;
1193 int res = 0;
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);
1201 peer_unref(peer);
1202 res = 1;
1203 break;
1205 peer_unref(peer);
1208 if (!peer) {
1209 peer = realtime_peer(NULL, &sin);
1210 if (peer) {
1211 ast_copy_string(host, peer->name, len);
1212 peer_unref(peer);
1213 res = 1;
1217 return res;
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);
1230 if (user) {
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");
1251 return;
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");
1261 return;
1264 ao2_unlink(iax_peercallno_pvts, pvt);
1267 static void update_max_trunk(void)
1269 int max = TRUNK_CALL_START;
1270 int x;
1272 /* XXX Prolly don't need locks here XXX */
1273 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1274 if (iaxs[x]) {
1275 max = x + 1;
1279 maxtrunkcall = max;
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);
1287 iax_frame_free(fr);
1290 static void iax2_destroy(int callno)
1292 struct chan_iax2_pvt *pvt;
1293 struct ast_channel *owner;
1295 retry:
1296 pvt = iaxs[callno];
1297 gettimeofday(&lastused[callno], NULL);
1299 owner = pvt ? pvt->owner : NULL;
1301 if (owner) {
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]);
1306 goto retry;
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;
1315 if (pvt) {
1316 if (!owner) {
1317 pvt->owner = NULL;
1318 } else {
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);
1329 if (!owner) {
1330 ao2_ref(pvt, -1);
1331 pvt = NULL;
1335 if (owner) {
1336 ast_mutex_unlock(&owner->lock);
1339 if (callno & 0x4000) {
1340 update_max_trunk();
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);
1351 /* Already gone */
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) {
1358 cur->retries = -1;
1361 AST_LIST_UNLOCK(&iaxq.queue);
1363 if (pvt->reg) {
1364 pvt->reg->callno = 0;
1367 if (!pvt->owner) {
1368 jb_frame frame;
1369 if (pvt->vars) {
1370 ast_variables_destroy(pvt->vars);
1371 pvt->vars = NULL;
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;
1386 jb_conf jbconf;
1388 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1389 return NULL;
1392 if (ast_string_field_init(tmp, 32)) {
1393 ao2_ref(tmp, -1);
1394 tmp = NULL;
1395 return NULL;
1398 tmp->prefs = prefs;
1399 tmp->callno = 0;
1400 tmp->peercallno = 0;
1401 tmp->transfercallno = 0;
1402 tmp->bridgecallno = 0;
1403 tmp->pingid = -1;
1404 tmp->lagid = -1;
1405 tmp->autoid = -1;
1406 tmp->authid = -1;
1407 tmp->initid = -1;
1409 ast_string_field_set(tmp,exten, "s");
1410 ast_string_field_set(tmp,host, host);
1412 tmp->jb = jb_new();
1413 tmp->jbid = -1;
1414 jbconf.max_jitterbuf = maxjitterbuffer;
1415 jbconf.resync_threshold = resyncthreshold;
1416 jbconf.max_contig_interp = maxjitterinterps;
1417 jb_setconf(tmp->jb,&jbconf);
1419 return tmp;
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);
1425 if (new) {
1426 size_t afdatalen = new->afdatalen;
1427 memcpy(new, fr, sizeof(*new));
1428 iax_frame_wrap(new, &fr->af);
1429 new->afdatalen = afdatalen;
1430 new->data = NULL;
1431 new->datalen = 0;
1432 new->direction = DIRECTION_INGRESS;
1433 new->retrans = -1;
1435 return new;
1438 #define NEW_PREVENT 0
1439 #define NEW_ALLOW 1
1440 #define NEW_FORCE 2
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 */
1450 return 1;
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))
1457 return 1;
1459 return 0;
1462 static void update_max_nontrunk(void)
1464 int max = 1;
1465 int x;
1466 /* XXX Prolly don't need locks here XXX */
1467 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1468 if (iaxs[x])
1469 max = x + 1;
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)
1478 int x;
1479 int res= 0;
1480 struct timeval now;
1481 if (iaxs[callno]->oseqno) {
1482 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1483 return -1;
1485 if (callno & TRUNK_CALL_START) {
1486 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1487 return -1;
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);
1505 if (locked)
1506 ast_mutex_unlock(&iaxsl[callno]);
1507 res = x;
1508 if (!locked)
1509 ast_mutex_unlock(&iaxsl[x]);
1510 break;
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");
1516 return -1;
1518 if (option_debug)
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 */
1521 update_max_trunk();
1522 update_max_nontrunk();
1523 return res;
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)
1531 int res = 0;
1532 int x;
1533 struct timeval now;
1534 char host[80];
1536 if (new <= NEW_ALLOW) {
1537 if (callno) {
1538 struct chan_iax2_pvt *pvt;
1539 struct chan_iax2_pvt tmp_pvt = {
1540 .callno = dcallno,
1541 .peercallno = callno,
1542 /* hack!! */
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]);
1552 res = pvt->callno;
1553 ao2_ref(pvt, -1);
1554 pvt = NULL;
1555 return res;
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;
1563 res = dcallno;
1564 store_by_peercallno(iaxs[dcallno]);
1565 return res;
1568 #ifdef IAX_OLD_FIND
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,
1572 which is bad.
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]);
1582 if (iaxs[x]) {
1583 /* Look for an exact match */
1584 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1585 res = x;
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]);
1594 if (iaxs[x]) {
1595 /* Look for an exact match */
1596 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1597 res = x;
1600 if (!res || !return_locked)
1601 ast_mutex_unlock(&iaxsl[x]);
1604 if (res) {
1605 ast_log(LOG_WARNING, "Old call search code found call number %d that was not in hash table!\n", res);
1607 #endif
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));
1621 now = ast_tvnow();
1622 start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1623 for (x = start; 1; x++) {
1624 if (x == TRUNK_CALL_START) {
1625 x = 1;
1626 continue;
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)) {
1632 found = 1;
1633 break;
1635 ast_mutex_unlock(&iaxsl[x]);
1637 if (x == start - 1) {
1638 break;
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");
1644 return 0;
1646 iaxs[x] = new_iax(sin, host);
1647 update_max_nontrunk();
1648 if (iaxs[x]) {
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]);
1671 } else {
1672 ast_log(LOG_WARNING, "Out of resources\n");
1673 ast_mutex_unlock(&iaxsl[x]);
1674 return 0;
1676 if (!return_locked)
1677 ast_mutex_unlock(&iaxsl[x]);
1678 res = x;
1680 return res;
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)
1705 for (;;) {
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]);
1710 } else {
1711 ast_queue_frame(iaxs[callno]->owner, f);
1712 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1713 break;
1715 } else
1716 break;
1718 return 0;
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)
1736 for (;;) {
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]);
1741 } else {
1742 ast_queue_hangup(iaxs[callno]->owner);
1743 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1744 break;
1746 } else
1747 break;
1749 return 0;
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)
1768 for (;;) {
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]);
1773 } else {
1774 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1775 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1776 break;
1778 } else
1779 break;
1781 return 0;
1783 static void destroy_firmware(struct iax_firmware *cur)
1785 /* Close firmware */
1786 if (cur->fwh) {
1787 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1789 close(cur->fd);
1790 free(cur);
1793 static int try_firmware(char *s)
1795 struct stat stbuf;
1796 struct iax_firmware *cur;
1797 int ifd;
1798 int fd;
1799 int res;
1801 struct ast_iax2_firmware_header *fwh, fwh2;
1802 struct MD5Context md5;
1803 unsigned char sum[16];
1804 unsigned char buf[1024];
1805 int len, chunk;
1806 char *s2;
1807 char *last;
1808 s2 = alloca(strlen(s) + 100);
1809 if (!s2) {
1810 ast_log(LOG_WARNING, "Alloca failed!\n");
1811 return -1;
1813 last = strrchr(s, '/');
1814 if (last)
1815 last++;
1816 else
1817 last = s;
1818 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1819 res = stat(s, &stbuf);
1820 if (res < 0) {
1821 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1822 return -1;
1824 /* Make sure it's not a directory */
1825 if (S_ISDIR(stbuf.st_mode))
1826 return -1;
1827 ifd = open(s, O_RDONLY);
1828 if (ifd < 0) {
1829 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1830 return -1;
1832 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
1833 if (fd < 0) {
1834 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1835 close(ifd);
1836 return -1;
1838 /* Unlink our newly created file */
1839 unlink(s2);
1841 /* Now copy the firmware into it */
1842 len = stbuf.st_size;
1843 while(len) {
1844 chunk = len;
1845 if (chunk > sizeof(buf))
1846 chunk = sizeof(buf);
1847 res = read(ifd, buf, chunk);
1848 if (res != chunk) {
1849 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1850 close(ifd);
1851 close(fd);
1852 return -1;
1854 res = write(fd, buf, chunk);
1855 if (res != chunk) {
1856 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1857 close(ifd);
1858 close(fd);
1859 return -1;
1861 len -= chunk;
1863 close(ifd);
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);
1868 close(fd);
1869 return -1;
1871 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1872 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1873 close(fd);
1874 return -1;
1876 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1877 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1878 close(fd);
1879 return -1;
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);
1883 close(fd);
1884 return -1;
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));
1889 close(fd);
1890 return -1;
1892 MD5Init(&md5);
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);
1898 close(fd);
1899 return -1;
1901 cur = waresl.wares;
1902 while(cur) {
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 */
1907 break;
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);
1911 close(fd);
1912 return 0;
1914 cur = cur->next;
1916 if (!cur) {
1917 /* Allocate a new one and link it */
1918 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1919 cur->fd = -1;
1920 cur->next = waresl.wares;
1921 waresl.wares = cur;
1924 if (cur) {
1925 if (cur->fwh) {
1926 munmap((void*)cur->fwh, cur->mmaplen);
1928 if (cur->fd > -1)
1929 close(cur->fd);
1930 cur->fwh = fwh;
1931 cur->fd = fd;
1932 cur->mmaplen = stbuf.st_size;
1933 cur->dead = 0;
1935 return 0;
1938 static int iax_check_version(char *dev)
1940 int res = 0;
1941 struct iax_firmware *cur;
1942 if (!ast_strlen_zero(dev)) {
1943 ast_mutex_lock(&waresl.lock);
1944 cur = waresl.wares;
1945 while(cur) {
1946 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1947 res = ntohs(cur->fwh->version);
1948 break;
1950 cur = cur->next;
1952 ast_mutex_unlock(&waresl.lock);
1954 return res;
1957 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1959 int res = -1;
1960 unsigned int bs = desc & 0xff;
1961 unsigned int start = (desc >> 8) & 0xffffff;
1962 unsigned int bytes;
1963 struct iax_firmware *cur;
1964 if (!ast_strlen_zero((char *)dev) && bs) {
1965 start *= bs;
1966 ast_mutex_lock(&waresl.lock);
1967 cur = waresl.wares;
1968 while(cur) {
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;
1973 if (bytes > bs)
1974 bytes = bs;
1975 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1976 } else {
1977 bytes = 0;
1978 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1980 if (bytes == bs)
1981 res = 0;
1982 else
1983 res = 1;
1984 break;
1986 cur = cur->next;
1988 ast_mutex_unlock(&waresl.lock);
1990 return res;
1994 static void reload_firmware(int unload)
1996 struct iax_firmware *cur, *curl, *curp;
1997 DIR *fwd;
1998 struct dirent *de;
1999 char dir[256];
2000 char fn[256];
2001 /* Mark all as dead */
2002 ast_mutex_lock(&waresl.lock);
2003 cur = waresl.wares;
2004 while(cur) {
2005 cur->dead = 1;
2006 cur = cur->next;
2009 /* Now that we've freed them, load the new ones */
2010 if (!unload) {
2011 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
2012 fwd = opendir(dir);
2013 if (fwd) {
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);
2023 closedir(fwd);
2024 } else
2025 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2028 /* Clean up leftovers */
2029 cur = waresl.wares;
2030 curp = NULL;
2031 while(cur) {
2032 curl = cur;
2033 cur = cur->next;
2034 if (curl->dead) {
2035 if (curp) {
2036 curp->next = cur;
2037 } else {
2038 waresl.wares = cur;
2040 destroy_firmware(curl);
2041 } else {
2042 curp = cur;
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;
2061 fr->retrans = -1;
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 */
2068 return 0;
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 */
2076 #if 0
2077 struct sockaddr_in *sin;
2078 int res;
2079 struct msghdr m;
2080 struct sock_extended_err e;
2081 m.msg_name = NULL;
2082 m.msg_namelen = 0;
2083 m.msg_iov = NULL;
2084 m.msg_control = &e;
2085 m.msg_controllen = sizeof(e);
2086 m.msg_flags = 0;
2087 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2088 if (res < 0)
2089 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2090 else {
2091 if (m.msg_controllen) {
2092 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2093 if (sin)
2094 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2095 else
2096 ast_log(LOG_WARNING, "No address detected??\n");
2097 } else {
2098 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2101 #endif
2102 return 0;
2105 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2107 int res;
2108 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2109 sizeof(*sin));
2110 if (res < 0) {
2111 if (option_debug)
2112 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
2113 handle_error();
2114 } else
2115 res = 0;
2116 return res;
2119 static int send_packet(struct iax_frame *f)
2121 int res;
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)
2126 return -1;
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));
2131 if (f->transfer) {
2132 if (iaxdebug)
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));
2136 } else {
2137 if (iaxdebug)
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));
2142 if (res < 0) {
2143 if (option_debug && iaxdebug)
2144 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
2145 handle_error();
2146 } else
2147 res = 0;
2148 return res;
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];
2160 if (!pvt)
2161 return -1;
2162 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2163 iax2_destroy_helper(pvt);
2164 ast_set_flag(pvt, IAX_ALREADYGONE);
2166 c = pvt->owner;
2167 if (c) {
2168 c->tech_pvt = NULL;
2169 iax2_queue_hangup(callno);
2170 pvt->owner = NULL;
2171 ast_module_unref(ast_module_info->self);
2173 return 0;
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);
2182 /* Update iseqno */
2183 f->iseqno = iaxs[f->callno]->iseqno;
2184 fh->iseqno = f->iseqno;
2185 return 0;
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;
2194 int freeme=0;
2195 int callno = f->callno;
2196 /* Make sure this call is still active */
2197 if (callno)
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) {
2204 if (f->transfer) {
2205 /* Transfer timeout */
2206 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2207 } else if (f->final) {
2208 if (f->final)
2209 iax2_destroy(callno);
2210 } else {
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, };
2216 /* Hangup the fd */
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;
2223 } else {
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);
2234 freeme++;
2235 } else {
2236 /* Update it if it needs it */
2237 update_packet(f);
2238 /* Attempt transmission */
2239 send_packet(f);
2240 f->retries++;
2241 /* Try again later after 10 times as long */
2242 f->retrytime *= 10;
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);
2250 } else {
2251 /* Make sure it gets freed */
2252 f->retries = -1;
2253 freeme++;
2255 if (callno)
2256 ast_mutex_unlock(&iaxsl[callno]);
2257 /* Do not try again */
2258 if (freeme) {
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);
2262 iaxq.count--;
2263 AST_LIST_UNLOCK(&iaxq.queue);
2264 f->retrans = -1;
2265 /* Free the IAX frame */
2266 iax2_frame_free(f);
2270 static int attempt_transmit(const void *data)
2272 #ifdef SCHED_MULTITHREADED
2273 if (schedule_action(__attempt_transmit, data))
2274 #endif
2275 __attempt_transmit(data);
2276 return 0;
2279 static int iax2_prune_realtime(int fd, int argc, char *argv[])
2281 struct iax2_peer *peer;
2283 if (argc != 4)
2284 return RESULT_SHOWUSAGE;
2285 if (!strcmp(argv[3],"all")) {
2286 reload_config();
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]);
2293 } else {
2294 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2296 peer_unref(peer);
2297 } else {
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[])
2306 if (argc != 4)
2307 return RESULT_SHOWUSAGE;
2309 test_losspct = atoi(argv[3]);
2311 return RESULT_SUCCESS;
2314 #ifdef IAXTESTS
2315 static int iax2_test_late(int fd, int argc, char *argv[])
2317 if (argc != 4)
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[])
2327 if (argc != 4)
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]);
2341 if (argc == 5)
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)
2352 int res = 0;
2353 if (peer->maxms) {
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);
2358 res = 1;
2359 } else if (peer->lastms) {
2360 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2361 res = 1;
2362 } else {
2363 ast_copy_string(status, "UNKNOWN", statuslen);
2365 } else {
2366 ast_copy_string(status, "Unmonitored", statuslen);
2367 res = -1;
2369 return res;
2372 /*! \brief Show one peer in detail */
2373 static int iax2_show_peer(int fd, int argc, char *argv[])
2375 char status[30];
2376 char cbuf[256];
2377 struct iax2_peer *peer;
2378 char codec_buf[512];
2379 int x = 0, codec = 0, load_realtime = 0;
2381 if (argc < 4)
2382 return RESULT_SHOWUSAGE;
2384 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2386 peer = find_peer(argv[3], load_realtime);
2387 if (peer) {
2388 ast_cli(fd,"\n\n");
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);
2407 if(!codec)
2408 break;
2409 ast_cli(fd, "%s", ast_getformatname(codec));
2410 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2411 ast_cli(fd, "|");
2414 if (!x)
2415 ast_cli(fd, "none");
2416 ast_cli(fd, ")\n");
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");
2422 ast_cli(fd,"\n");
2423 peer_unref(peer);
2424 } else {
2425 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2426 ast_cli(fd,"\n");
2429 return RESULT_SUCCESS;
2432 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2434 int which = 0;
2435 struct iax2_peer *peer;
2436 char *res = NULL;
2437 int wordlen = strlen(word);
2438 struct ao2_iterator i;
2440 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2441 if (pos != 3)
2442 return NULL;
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);
2448 peer_unref(peer);
2449 break;
2451 peer_unref(peer);
2454 return res;
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;
2462 if (argc != 3)
2463 return RESULT_SHOWUSAGE;
2465 AST_LIST_LOCK(&iaxq.queue);
2466 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2467 if (cur->retries < 0)
2468 dead++;
2469 if (cur->final)
2470 final++;
2471 cnt++;
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;
2487 int s;
2488 int x,y;
2489 struct timeval tv;
2490 gettimeofday(&tv, NULL);
2491 ast_mutex_lock(&dpcache_lock);
2492 dp = dpcache;
2493 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2494 while(dp) {
2495 s = dp->expiry.tv_sec - tv.tv_sec;
2496 tmp[0] = '\0';
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';
2516 else
2517 ast_copy_string(tmp, "(none)", sizeof(tmp));
2518 y=0;
2519 pc = strchr(dp->peercontext, '@');
2520 if (!pc)
2521 pc = dp->peercontext;
2522 else
2523 pc++;
2524 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2525 if (dp->waiters[x] > -1)
2526 y++;
2527 if (s > 0)
2528 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2529 else
2530 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2531 dp = dp->next;
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)
2576 int when;
2578 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2580 when = jb_next(pvt->jb) - when;
2582 AST_SCHED_DEL(sched, pvt->jbid);
2584 if(when <= 0) {
2585 /* XXX should really just empty until when > 0.. */
2586 when = 1;
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;
2597 jb_frame frame;
2598 int ret;
2599 long now;
2600 long next;
2601 struct timeval tv;
2603 /* Make sure we have a valid private structure before going on */
2604 ast_mutex_lock(&iaxsl[callno]);
2605 pvt = iaxs[callno];
2606 if (!pvt) {
2607 /* No go! */
2608 ast_mutex_unlock(&iaxsl[callno]);
2609 return;
2612 pvt->jbid = -1;
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 */
2618 tv.tv_usec += 1000;
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));
2624 switch(ret) {
2625 case JB_OK:
2626 fr = frame.data;
2627 __do_deliver(fr);
2628 /* __do_deliver() can cause the call to disappear */
2629 pvt = iaxs[callno];
2630 break;
2631 case JB_INTERP:
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 */
2648 pvt = iaxs[callno];
2651 break;
2652 case JB_DROP:
2653 iax2_frame_free(frame.data);
2654 break;
2655 case JB_NOFRAME:
2656 case JB_EMPTY:
2657 /* do nothing */
2658 break;
2659 default:
2660 /* shouldn't happen */
2661 break;
2664 if (pvt)
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))
2673 #endif
2674 __get_from_jb(data);
2675 return 0;
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)
2686 int type, len;
2687 int ret;
2688 int needfree = 0;
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));
2698 else {
2699 #if 0
2700 if (option_debug)
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");
2702 #endif
2703 fr->af.delivery = ast_tv(0,0);
2706 type = JB_TYPE_CONTROL;
2707 len = 0;
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)) ) {
2717 if (tsout)
2718 *tsout = fr->ts;
2719 __do_deliver(fr);
2720 return -1;
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) ) {
2729 jb_frame frame;
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])
2736 return -1;
2739 jb_reset(iaxs[fr->callno]->jb);
2741 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
2743 /* deliver this frame now */
2744 if (tsout)
2745 *tsout = fr->ts;
2746 __do_deliver(fr);
2747 return -1;
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) {
2755 needfree++;
2756 } else if (ret == JB_SCHED) {
2757 update_jbsched(iaxs[fr->callno]);
2759 if (tsout)
2760 *tsout = fr->ts;
2761 if (needfree) {
2762 /* Free our iax frame */
2763 iax2_frame_free(fr);
2764 return -1;
2766 return 0;
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 */
2774 fr->sentyet = 0;
2775 AST_LIST_LOCK(&iaxq.queue);
2776 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2777 iaxq.count++;
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);
2783 return 0;
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]);
2819 if (iaxs[callno])
2820 iaxs[callno]->owner = newchan;
2821 else
2822 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2823 ast_mutex_unlock(&iaxsl[callno]);
2824 return 0;
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;
2837 int dynamic=0;
2839 if (peername) {
2840 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
2841 if (!var && sin)
2842 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2843 } else if (sin) {
2844 char porta[25];
2845 sprintf(porta, "%d", ntohs(sin->sin_port));
2846 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2847 if (var) {
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);
2857 /*!\note
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).
2863 if (var && sin) {
2864 for (tmp = var; tmp; tmp = tmp->next) {
2865 if (!strcasecmp(tmp->name, "host")) {
2866 struct ast_hostent ahp;
2867 struct hostent *hp;
2868 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2869 /* No match */
2870 ast_variables_destroy(var);
2871 var = NULL;
2873 break;
2878 if (!var)
2879 return NULL;
2881 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2883 if (!peer) {
2884 ast_variables_destroy(var);
2885 return NULL;
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);
2895 break;
2897 } else if (!strcasecmp(tmp->name, "regseconds")) {
2898 ast_get_time_t(tmp->value, &regseconds, 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"))
2905 dynamic = 1;
2909 ast_variables_destroy(var);
2911 if (!peer)
2912 return NULL;
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)) {
2919 peer->expire = -1;
2920 peer_unref(peer);
2923 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
2924 if (peer->expire == -1)
2925 peer_unref(peer);
2927 ao2_link(peers, peer);
2928 if (ast_test_flag(peer, IAX_DYNAMIC))
2929 reg_source_db(peer);
2930 } else {
2931 ast_set_flag(peer, IAX_TEMPONLY);
2934 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2935 time(&nowtime);
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);
2939 if (option_debug)
2940 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2941 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2943 else {
2944 if (option_debug)
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);
2950 return peer;
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);
2960 if (!var)
2961 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2962 if (!var && sin) {
2963 char porta[6];
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);
2966 if (!var)
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);
2971 /*!\note
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).
2977 if (var) {
2978 for (tmp = var; tmp; tmp = tmp->next) {
2979 if (!strcasecmp(tmp->name, "host")) {
2980 struct ast_hostent ahp;
2981 struct hostent *hp;
2982 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2983 /* No match */
2984 ast_variables_destroy(var);
2985 var = NULL;
2987 break;
2992 if (!var)
2993 return NULL;
2995 tmp = var;
2996 while(tmp) {
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")) {
3001 return NULL;
3004 tmp = tmp->next;
3007 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3009 ast_variables_destroy(var);
3011 if (!user)
3012 return NULL;
3014 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3015 ast_set_flag(user, IAX_RTCACHEFRIENDS);
3016 ao2_link(users, user);
3017 } else {
3018 ast_set_flag(user, IAX_TEMPONLY);
3021 return user;
3024 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3026 char port[10];
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 {
3037 int capability;
3038 unsigned int flags;
3039 int maxtime;
3040 int encmethods;
3041 int found;
3042 int sockfd;
3043 int adsi;
3044 char username[80];
3045 char secret[80];
3046 char outkey[80];
3047 char timezone[80];
3048 char prefs[32];
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;
3058 struct hostent *hp;
3059 struct iax2_peer *peer;
3060 int res = -1;
3061 struct ast_codec_pref ourprefs;
3063 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3064 cai->sockfd = defaultsockfd;
3065 cai->maxtime = 0;
3066 sin->sin_family = AF_INET;
3068 if (!(peer = find_peer(peername, 1))) {
3069 cai->found = 0;
3071 hp = ast_gethostbyname(peername, &ahp);
3072 if (hp) {
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));
3078 if (c)
3079 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3080 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3081 return 0;
3082 } else {
3083 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3084 return -1;
3088 cai->found = 1;
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))
3092 goto return_unref;
3094 /* if the peer is being monitored and is currently unreachable, return failure */
3095 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3096 goto return_unref;
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 */
3106 if (c) {
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));
3120 } else {
3121 char *family;
3122 char *key = NULL;
3124 family = ast_strdupa(peer->dbsecret);
3125 key = strchr(family, '/');
3126 if (key)
3127 *key++ = '\0';
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);
3130 goto return_unref;
3134 if (peer->addr.sin_addr.s_addr) {
3135 sin->sin_addr = peer->addr.sin_addr;
3136 sin->sin_port = peer->addr.sin_port;
3137 } else {
3138 sin->sin_addr = peer->defaddr.sin_addr;
3139 sin->sin_port = peer->defaddr.sin_port;
3142 res = 0;
3144 return_unref:
3145 peer_unref(peer);
3147 return res;
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]);
3155 if (iaxs[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))
3167 #endif
3168 __auto_congest(data);
3169 return 0;
3172 static unsigned int iax2_datetime(const char *tz)
3174 time_t t;
3175 struct tm tm;
3176 unsigned int tmp;
3177 time(&t);
3178 if (!ast_strlen_zero(tz))
3179 ast_localtime(&t, &tm, tz);
3180 else
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 */
3188 return tmp;
3191 struct parsed_dial_string {
3192 char *username;
3193 char *password;
3194 char *key;
3195 char *peer;
3196 char *port;
3197 char *exten;
3198 char *context;
3199 char *options;
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
3215 * \return nothing
3217 * This function parses the string and fills the structure
3218 * with pointers to its component parts. The input string
3219 * will be modified.
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))
3232 return;
3234 pds->peer = strsep(&data, "/");
3235 pds->exten = strsep(&data, "/");
3236 pds->options = data;
3238 if (pds->exten) {
3239 data = pds->exten;
3240 pds->exten = strsep(&data, "@");
3241 pds->context = data;
3244 if (strchr(pds->peer, '@')) {
3245 data = pds->peer;
3246 pds->username = strsep(&data, "@");
3247 pds->peer = data;
3250 if (pds->username) {
3251 data = pds->username;
3252 pds->username = strsep(&data, ":");
3253 pds->password = data;
3256 data = pds->peer;
3257 pds->peer = strsep(&data, ":");
3258 pds->port = 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);
3281 return -1;
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);
3293 return -1;
3296 if (!pds.exten) {
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);
3302 return -1;
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));
3317 if (pds.port)
3318 sin.sin_port = htons(atoi(pds.port));
3320 l = c->cid.cid_num;
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);
3336 if (l) {
3337 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3338 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3339 } else {
3340 if (n)
3341 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3342 else
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);
3349 if (n)
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);
3361 if (pds.context)
3362 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3364 if (pds.username)
3365 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3367 if (cai.encmethods)
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);
3375 if (pds.username)
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);
3385 if (pds.key)
3386 ast_string_field_set(iaxs[callno], outkey, pds.key);
3387 if (pds.password)
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);
3413 return 0;
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]) {
3423 if (option_debug)
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]);
3431 return 0;
3434 /* Explicitly predestroy it */
3435 iax2_predestroy(callno);
3436 /* If we were already gone to begin with, destroy us now */
3437 if (iaxs[callno]) {
3438 if (option_debug)
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.
3447 c->tech_pvt = NULL;
3449 ast_mutex_unlock(&iaxsl[callno]);
3450 if (option_verbose > 2)
3451 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3452 return 0;
3455 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3457 struct ast_option_header *h;
3458 int res;
3460 switch (option) {
3461 case AST_OPTION_TXGAIN:
3462 case AST_OPTION_RXGAIN:
3463 /* these two cannot be sent, because they require a result */
3464 errno = ENOSYS;
3465 return -1;
3466 default:
3467 if (!(h = ast_malloc(datalen + sizeof(*h))))
3468 return -1;
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);
3476 free(h);
3477 return res;
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)
3489 int res;
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);
3504 if (res)
3505 return -1;
3506 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3507 if (res)
3508 return -1;
3509 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3510 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3511 return 0;
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;
3532 int to = -1;
3533 int res = -1;
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 */
3553 cs[0] = c0;
3554 cs[1] = c1;
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) {
3575 char buf0[255];
3576 char buf1[255];
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);
3583 if (iaxs[callno0])
3584 iaxs[callno0]->bridgecallno = 0;
3585 if (iaxs[callno1])
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)) {
3602 waittimer = tv;
3603 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3604 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3605 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3606 *fo = NULL;
3607 *rc = c0;
3608 res = AST_BRIDGE_COMPLETE;
3609 break;
3612 to = 1000;
3613 who = ast_waitfor_n(cs, 2, &to);
3614 if (timeoutms > -1) {
3615 timeoutms -= (1000 - to);
3616 if (timeoutms < 0)
3617 timeoutms = 0;
3619 if (!who) {
3620 if (!timeoutms) {
3621 res = AST_BRIDGE_RETRY;
3622 break;
3624 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3625 res = AST_BRIDGE_FAILED;
3626 break;
3628 continue;
3630 f = ast_read(who);
3631 if (!f) {
3632 *fo = NULL;
3633 *rc = who;
3634 res = AST_BRIDGE_COMPLETE;
3635 break;
3637 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3638 *fo = f;
3639 *rc = who;
3640 res = AST_BRIDGE_COMPLETE;
3641 break;
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)) {
3654 *rc = who;
3655 *fo = f;
3656 res = AST_BRIDGE_COMPLETE;
3657 /* Remove from native mode */
3658 break;
3660 /* everything else goes to the other side */
3661 ast_write(other, f);
3663 ast_frfree(f);
3664 /* Swap who gets priority */
3665 cs[2] = cs[0];
3666 cs[0] = cs[1];
3667 cs[1] = cs[2];
3669 lock_both(callno0, callno1);
3670 if(iaxs[callno0])
3671 iaxs[callno0]->bridgecallno = 0;
3672 if(iaxs[callno1])
3673 iaxs[callno1]->bridgecallno = 0;
3674 unlock_both(callno0, callno1);
3675 return res;
3678 static int iax2_answer(struct ast_channel *c)
3680 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3681 if (option_debug)
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;
3690 int res = 0;
3692 if (option_debug && iaxdebug)
3693 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3695 ast_mutex_lock(&iaxsl[callno]);
3696 pvt = iaxs[callno];
3698 if (!pvt->peercallno) {
3699 /* We don't know the remote side's call number, yet. :( */
3700 int count = 10;
3701 while (count-- && pvt && !pvt->peercallno) {
3702 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
3703 pvt = iaxs[callno];
3705 if (!pvt->peercallno) {
3706 res = -1;
3707 goto done;
3711 switch (condition) {
3712 case AST_CONTROL_HOLD:
3713 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3714 ast_moh_start(c, data, pvt->mohinterpret);
3715 goto done;
3717 break;
3718 case AST_CONTROL_UNHOLD:
3719 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3720 ast_moh_stop(c);
3721 goto done;
3725 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3727 done:
3728 ast_mutex_unlock(&iaxsl[callno]);
3730 return res;
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, '@');
3740 if (context) {
3741 *context = '\0';
3742 context++;
3744 memset(&ied, 0, sizeof(ied));
3745 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3746 if (context)
3747 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3748 if (option_debug)
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;
3756 int res = 0;
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);
3764 peer_unref(peer);
3765 break;
3767 peer_unref(peer);
3770 return res;
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);
3782 return NULL;
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]) {
3790 if (tmp) {
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]);
3796 return NULL;
3799 if (!tmp)
3800 return NULL;
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);
3812 else
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);
3823 if (i->amaflags)
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));
3827 if (i->adsi)
3828 tmp->adsicpe = i->peeradsicpe;
3829 else
3830 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3831 i->owner = tmp;
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);
3840 ast_hangup(tmp);
3841 i->owner = NULL;
3842 return NULL;
3846 ast_module_ref(ast_module_info->self);
3848 return tmp;
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 */
3854 long int ms, pred;
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)
3871 ms = pred;
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;
3877 return 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 */
3892 return ms + ts;
3895 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3897 int ms;
3898 int voice = 0;
3899 int genuine = 0;
3900 int adjust;
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
3910 if (f) {
3911 if (f->frametype == AST_FRAME_VOICE) {
3912 voice = 1;
3913 delivery = &f->delivery;
3914 } else if (f->frametype == AST_FRAME_IAX) {
3915 genuine = 1;
3916 } else if (f->frametype == AST_FRAME_CNG) {
3917 p->notsilenttx = 0;
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 */
3926 if (ts)
3927 return ts;
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);
3933 } else {
3934 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3935 if (ms < 0)
3936 ms = 0;
3937 if (voice) {
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 */
3941 /* AN EXPLANATION:
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);
3959 if (adjust < 0)
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));
3964 if (!p->nextpred) {
3965 p->nextpred = ms; /*f->samples / 8;*/
3966 if (p->nextpred <= p->lastsent)
3967 p->nextpred = p->lastsent + 3;
3969 ms = p->nextpred;
3970 } else {
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);
3987 if (diff)
3988 ms += f->samples/8 - diff;
3991 p->nextpred = ms;
3992 p->notsilenttx = 1;
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
4000 * them
4001 * We do want to make sure that frames don't go backwards though
4003 if ( (unsigned int)ms < p->lastsent )
4004 ms = p->lastsent;
4005 } else {
4006 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
4007 it's a genuine frame */
4008 if (genuine) {
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;
4018 p->lastsent = ms;
4019 if (voice)
4020 p->nextpred = p->nextpred + f->samples / 8;
4021 return ms;
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 */
4028 int ms;
4029 #ifdef IAXTESTS
4030 int jit;
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));
4039 #if 1
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));
4043 #endif
4046 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
4047 #ifdef IAXTESTS
4048 if (test_jit) {
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)))
4052 jit = -jit;
4053 ms += jit;
4056 if (test_late) {
4057 ms += test_late;
4058 test_late = 0;
4060 #endif /* IAXTESTS */
4061 return ms;
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);
4074 break;
4077 if (!tpeer) {
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;
4085 tpeer->sockfd = fd;
4086 tpeers = tpeer;
4087 #ifdef SO_NO_CHECK
4088 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
4089 #endif
4090 if (option_debug)
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);
4095 return tpeer;
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;
4102 void *tmp, *ptr;
4103 struct ast_iax2_meta_trunk_entry *met;
4104 struct ast_iax2_meta_trunk_mini *mtm;
4106 f = &fr->af;
4107 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
4108 if (tpeer) {
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);
4114 return -1;
4117 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
4118 tpeer->trunkdata = tmp;
4119 if (option_debug)
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);
4121 } else {
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);
4124 return -1;
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);
4137 } else {
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;
4150 tpeer->calls++;
4151 ast_mutex_unlock(&tpeer->lock);
4153 return 0;
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)
4164 #if 0
4165 /* Debug with "fake encryption" */
4166 int x;
4167 if (len % 16)
4168 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4169 for (x=0;x<len;x++)
4170 dst[x] = src[x] ^ 0xff;
4171 #else
4172 unsigned char lastblock[16] = { 0 };
4173 int x;
4174 while(len > 0) {
4175 aes_decrypt(src, dst, dcx);
4176 for (x=0;x<16;x++)
4177 dst[x] ^= lastblock[x];
4178 memcpy(lastblock, src, sizeof(lastblock));
4179 dst += 16;
4180 src += 16;
4181 len -= 16;
4183 #endif
4186 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
4188 #if 0
4189 /* Debug with "fake encryption" */
4190 int x;
4191 if (len % 16)
4192 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4193 for (x=0;x<len;x++)
4194 dst[x] = src[x] ^ 0xff;
4195 #else
4196 unsigned char curblock[16] = { 0 };
4197 int x;
4198 while(len > 0) {
4199 for (x=0;x<16;x++)
4200 curblock[x] ^= src[x];
4201 aes_encrypt(curblock, dst, ecx);
4202 memcpy(curblock, dst, sizeof(curblock));
4203 dst += 16;
4204 src += 16;
4205 len -= 16;
4207 #endif
4210 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4212 int padding;
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))
4220 return -1;
4221 /* Decrypt */
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))
4228 return -1;
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);
4235 } else {
4236 f->subclass = uncompress_subclass(fh->csub);
4238 } else {
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))
4243 return -1;
4244 /* Decrypt */
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))
4248 return -1;
4249 *datalen -= padding;
4250 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4252 return 0;
4255 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4257 int padding;
4258 unsigned char *workspace;
4259 workspace = alloca(*datalen + 32);
4260 if (!workspace)
4261 return -1;
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);
4278 } else {
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);
4293 return 0;
4296 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4298 int res=-1;
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);
4306 stringp = tmppw;
4307 while ((tmppw = strsep(&stringp, ";"))) {
4308 MD5Init(&md5);
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);
4314 if (!res) {
4315 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4316 break;
4319 } else
4320 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4321 return res;
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;
4332 struct {
4333 struct iax_frame fr2;
4334 unsigned char buffer[4096];
4335 } frb;
4336 struct iax_frame *fr;
4337 int res;
4338 int sendmini=0;
4339 unsigned int lastsent;
4340 unsigned int fts;
4342 frb.fr2.afdatalen = sizeof(frb.buffer);
4344 if (!pvt) {
4345 ast_log(LOG_WARNING, "No private structure for packet?\n");
4346 return -1;
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)
4358 return 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 */
4370 now = 1;
4371 /* Mark that mini-style frame is appropriate */
4372 sendmini = 1;
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)
4383 now = 1;
4384 sendmini = 1;
4385 } else {
4386 now = 0;
4387 sendmini = 0;
4389 pvt->lastvsent = fts;
4391 /* Allocate an iax_frame */
4392 if (now) {
4393 fr = &frb.fr2;
4394 } else
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));
4396 if (!fr) {
4397 ast_log(LOG_WARNING, "Out of memory\n");
4398 return -1;
4400 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4401 iax_frame_wrap(fr, f);
4403 fr->ts = fts;
4404 fr->callno = pvt->callno;
4405 fr->transfer = transfer;
4406 fr->final = final;
4407 if (!sendmini) {
4408 /* We need a full frame */
4409 if (seqno > -1)
4410 fr->oseqno = seqno;
4411 else
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;
4418 if (transfer) {
4419 fh->iseqno = 0;
4420 } else
4421 fh->iseqno = fr->iseqno;
4422 /* Keep track of the last thing we've acknowledged */
4423 if (!transfer)
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);
4428 else
4429 fh->csub = compress_subclass(fr->af.subclass);
4430 if (transfer) {
4431 fr->dcallno = pvt->transfercallno;
4432 } else
4433 fr->dcallno = pvt->peercallno;
4434 fh->dcallno = htons(fr->dcallno);
4435 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4436 fr->data = fh;
4437 fr->retries = 0;
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))
4446 fr->retries = -1;
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)) {
4453 if (iaxdebug) {
4454 if (fr->transfer)
4455 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4456 else
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);
4460 } else
4461 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4464 if (now) {
4465 res = send_packet(fr);
4466 } else
4467 res = iax2_transmit(fr);
4468 } else {
4469 if (ast_test_flag(pvt, IAX_TRUNK)) {
4470 iax2_trunk_queue(pvt, fr);
4471 res = 0;
4472 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4473 /* Video frame have no sequence number */
4474 fr->oseqno = -1;
4475 fr->iseqno = -1;
4476 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
4477 vh->zeros = 0;
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);
4481 fr->data = vh;
4482 fr->retries = -1;
4483 res = send_packet(fr);
4484 } else {
4485 /* Mini-frames have no sequence number */
4486 fr->oseqno = -1;
4487 fr->iseqno = -1;
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);
4493 fr->data = mh;
4494 fr->retries = -1;
4495 if (pvt->transferring == TRANSFER_MEDIAPASS)
4496 fr->transfer = 1;
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);
4500 } else
4501 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4503 res = send_packet(fr);
4506 return res;
4509 static int iax2_show_users(int fd, int argc, char *argv[])
4511 regex_t regexbuf;
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;
4518 char auth[90];
4519 char *pstr = "";
4520 struct ao2_iterator i;
4522 switch (argc) {
4523 case 5:
4524 if (!strcasecmp(argv[3], "like")) {
4525 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4526 return RESULT_SHOWUSAGE;
4527 havepattern = 1;
4528 } else
4529 return RESULT_SHOWUSAGE;
4530 case 3:
4531 break;
4532 default:
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(&regexbuf, user->name, 0, NULL, 0))
4541 continue;
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);
4547 } else
4548 ast_copy_string(auth, "-no secret-", sizeof(auth));
4550 if(ast_test_flag(user,IAX_CODEC_NOCAP))
4551 pstr = "REQ Only";
4552 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
4553 pstr = "Disabled";
4554 else
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);
4562 if (havepattern)
4563 regfree(&regexbuf);
4565 return RESULT_SUCCESS;
4566 #undef FORMAT
4567 #undef FORMAT2
4570 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
4572 regex_t regexbuf;
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;
4584 char name[256];
4585 int registeredonly=0;
4586 char *term = manager ? "\r\n" : "\n";
4588 switch (argc) {
4589 case 6:
4590 if (!strcasecmp(argv[3], "registered"))
4591 registeredonly = 1;
4592 else
4593 return RESULT_SHOWUSAGE;
4594 if (!strcasecmp(argv[4], "like")) {
4595 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
4596 return RESULT_SHOWUSAGE;
4597 havepattern = 1;
4598 } else
4599 return RESULT_SHOWUSAGE;
4600 break;
4601 case 5:
4602 if (!strcasecmp(argv[3], "like")) {
4603 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4604 return RESULT_SHOWUSAGE;
4605 havepattern = 1;
4606 } else
4607 return RESULT_SHOWUSAGE;
4608 break;
4609 case 4:
4610 if (!strcasecmp(argv[3], "registered"))
4611 registeredonly = 1;
4612 else
4613 return RESULT_SHOWUSAGE;
4614 break;
4615 case 3:
4616 break;
4617 default:
4618 return RESULT_SHOWUSAGE;
4622 if (s)
4623 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4624 else
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)) {
4630 char nm[20];
4631 char status[20];
4632 char srch[2000];
4633 int retstatus;
4635 if (registeredonly && !peer->addr.sin_addr.s_addr)
4636 continue;
4637 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
4638 continue;
4640 if (!ast_strlen_zero(peer->username))
4641 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
4642 else
4643 ast_copy_string(name, peer->name, sizeof(name));
4645 retstatus = peer_status(peer, status, sizeof(status));
4646 if (retstatus > 0)
4647 online_peers++;
4648 else if (!retstatus)
4649 offline_peers++;
4650 else
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);
4662 if (s)
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);
4669 else
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);
4676 total_peers++;
4679 if (s)
4680 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4681 else
4682 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4684 if (havepattern)
4685 regfree(&regexbuf);
4687 return RESULT_SUCCESS;
4688 #undef FORMAT
4689 #undef FORMAT2
4692 static int iax2_show_threads(int fd, int argc, char *argv[])
4694 struct iax2_thread *thread = NULL;
4695 time_t t;
4696 int threadcount = 0, dynamiccount = 0;
4697 char type;
4699 if (argc != 3)
4700 return RESULT_SHOWUSAGE;
4702 ast_cli(fd, "IAX2 Thread Information\n");
4703 time(&t);
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);
4710 #else
4711 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4712 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4713 #endif
4714 threadcount++;
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)
4721 type = 'D';
4722 else
4723 type = 'P';
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);
4727 #else
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);
4730 #endif
4731 threadcount++;
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);
4740 #else
4741 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4742 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4743 #endif
4744 dynamiccount++;
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;
4783 #undef FORMAT
4784 #undef FORMAT2
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" };
4791 int ret;
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" );
4798 return ret;
4799 } /* /JDG */
4801 static char *regstate2str(int regstate)
4803 switch(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:
4813 return "Rejected";
4814 case REG_STATE_TIMEOUT:
4815 return "Timeout";
4816 case REG_STATE_NOAUTH:
4817 return "No Authentication";
4818 default:
4819 return "Unknown";
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;
4829 char host[80];
4830 char perceived[80];
4831 if (argc != 3)
4832 return RESULT_SHOWUSAGE;
4833 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4834 AST_LIST_LOCK(&registrations);
4835 AST_LIST_TRAVERSE(&registrations, 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));
4839 else
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(&registrations);
4846 return RESULT_SUCCESS;
4847 #undef FORMAT
4848 #undef FORMAT2
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"
4856 int x;
4857 int numchans = 0;
4859 if (argc != 3)
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]);
4864 if (iaxs[x]) {
4865 int lag, jitter, localdelay;
4866 jb_info jbinfo;
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;
4872 } else {
4873 jitter = -1;
4874 localdelay = 0;
4876 lag = iaxs[x]->remote_rr.delay;
4877 ast_cli(fd, FORMAT,
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,
4883 lag,
4884 jitter,
4885 localdelay,
4886 ast_getformatname(iaxs[x]->voiceformat) );
4887 numchans++;
4889 ast_mutex_unlock(&iaxsl[x]);
4891 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4892 return RESULT_SUCCESS;
4893 #undef FORMAT
4894 #undef FORMAT2
4895 #undef FORMATB
4898 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
4900 int x;
4901 int numchans = 0;
4902 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
4903 ast_mutex_lock(&iaxsl[x]);
4904 if (iaxs[x]) {
4905 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
4906 char *fmt;
4907 jb_info jbinfo;
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;
4917 } else {
4918 localjitter = -1;
4919 localdelay = 0;
4920 locallost = -1;
4921 locallosspct = -1;
4922 localdropped = 0;
4923 localooo = -1;
4925 if (limit_fmt)
4926 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4927 else
4928 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4929 if (s)
4931 astman_append(s, fmt,
4932 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4933 iaxs[x]->pingtime,
4934 localjitter,
4935 localdelay,
4936 locallost,
4937 locallosspct,
4938 localdropped,
4939 localooo,
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);
4948 else
4949 ast_cli(fd, fmt,
4950 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4951 iaxs[x]->pingtime,
4952 localjitter,
4953 localdelay,
4954 locallost,
4955 locallosspct,
4956 localdropped,
4957 localooo,
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
4967 numchans++;
4969 ast_mutex_unlock(&iaxsl[x]);
4971 return numchans;
4974 static int iax2_show_netstats(int fd, int argc, char *argv[])
4976 int numchans = 0;
4977 if (argc != 3)
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;
4990 iaxdebug = 1;
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;
4999 iaxtrunkdebug = 1;
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;
5017 iaxdebug = 0;
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;
5026 iaxtrunkdebug = 0;
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);
5044 int res = -1;
5045 ast_mutex_lock(&iaxsl[callno]);
5046 if (iaxs[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))
5050 res = 0;
5051 /* Don't waste bandwidth sending null frames */
5052 else if (f->frametype == AST_FRAME_NULL)
5053 res = 0;
5054 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
5055 res = 0;
5056 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
5057 res = 0;
5058 else
5059 /* Simple, just queue for transmission */
5060 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
5061 } else {
5062 if (option_debug)
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]);
5068 return res;
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, };
5076 f.frametype = type;
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)
5092 int res;
5093 ast_mutex_lock(&iaxsl[callno]);
5094 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
5095 ast_mutex_unlock(&iaxsl[callno]);
5096 return res;
5100 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5101 * the pvt struct for the given call number may disappear during its
5102 * execution.
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])
5110 return -1;
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)
5126 while(con) {
5127 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
5128 return -1;
5129 con = con->next;
5131 return 0;
5135 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5137 /* Start pessimistic */
5138 int res = -1;
5139 int version = 2;
5140 struct iax2_user *user = NULL, *best = NULL;
5141 int bestscore = 0;
5142 int gotcapability = 0;
5143 struct ast_variable *v = NULL, *tmpvar = NULL;
5144 struct ao2_iterator i;
5146 if (!iaxs[callno])
5147 return res;
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);
5158 if (ies->dnid)
5159 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
5160 if (ies->rdnis)
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);
5164 if (ies->language)
5165 ast_string_field_set(iaxs[callno], language, ies->language);
5166 if (ies->username)
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;
5174 if (ies->format)
5175 iaxs[callno]->peerformat = ies->format;
5176 if (ies->adsicpe)
5177 iaxs[callno]->peeradsicpe = ies->adsicpe;
5178 if (ies->capability) {
5179 gotcapability = 1;
5180 iaxs[callno]->peercapability = ies->capability;
5182 if (ies->version)
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);
5191 if (!gotcapability)
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);
5196 return res;
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. */
5208 if (best)
5209 user_unref(best);
5210 best = user;
5211 break;
5212 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5213 /* No required authentication */
5214 if (user->ha) {
5215 /* There was host authentication and we passed, bonus! */
5216 if (bestscore < 4) {
5217 bestscore = 4;
5218 if (best)
5219 user_unref(best);
5220 best = user;
5221 continue;
5223 } else {
5224 /* No host access, but no secret, either, not bad */
5225 if (bestscore < 3) {
5226 bestscore = 3;
5227 if (best)
5228 user_unref(best);
5229 best = user;
5230 continue;
5233 } else {
5234 if (user->ha) {
5235 /* Authentication, but host access too, eh, it's something.. */
5236 if (bestscore < 2) {
5237 bestscore = 2;
5238 if (best)
5239 user_unref(best);
5240 best = user;
5241 continue;
5243 } else {
5244 /* Authentication and no host access... This is our baseline */
5245 if (bestscore < 1) {
5246 bestscore = 1;
5247 if (best)
5248 user_unref(best);
5249 best = user;
5250 continue;
5255 user_unref(user);
5257 user = best;
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);
5265 if (user) {
5266 /* We found our match (use the first) */
5267 /* copy vars */
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)) {
5290 if (user->contexts)
5291 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5292 else
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);
5317 if (user->amaflags)
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;
5325 char buf[80];
5326 family = ast_strdupa(user->dbsecret);
5327 key = strchr(family, '/');
5328 if (key) {
5329 *key = '\0';
5330 key++;
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);
5334 else
5335 ast_string_field_set(iaxs[callno], secret, buf);
5336 } else
5337 ast_string_field_set(iaxs[callno], secret, user->secret);
5338 res = 0;
5339 user = user_unref(user);
5341 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
5342 return res;
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);
5350 fh.ts = 0;
5351 fh.oseqno = 0;
5352 fh.iseqno = 0;
5353 fh.type = AST_FRAME_IAX;
5354 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
5355 if (iaxdebug)
5356 iax_showframe(NULL, &fh, 0, sin, 0);
5357 if (option_debug)
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;
5370 else
5371 p->encmethods = 0;
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;
5385 char challenge[10];
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);
5397 if (user) {
5398 if (user->curauthreq == user->maxauthreq)
5399 authreq_restrict = 1;
5400 else
5401 user->curauthreq++;
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);
5411 return 0;
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);
5421 if (p->encmethods)
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);
5428 if (p->encmethods)
5429 ast_set_flag(p, IAX_ENCRYPTED);
5431 return res;
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] = "";
5440 int res = -1;
5441 int x;
5442 struct iax2_user *user, tmp_user = {
5443 .name = p->username,
5446 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5447 if (user) {
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))
5457 return res;
5458 if (ies->password)
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;
5466 char *keyn;
5467 char tmpkey[256];
5468 char *stringp=NULL;
5469 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
5470 stringp=tmpkey;
5471 keyn = strsep(&stringp, ":");
5472 while(keyn) {
5473 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5474 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
5475 res = 0;
5476 break;
5477 } else if (!key)
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);
5487 stringp = tmppw;
5488 while((tmppw = strsep(&stringp, ";"))) {
5489 MD5Init(&md5);
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. */
5494 for (x=0;x<16;x++)
5495 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5496 if (!strcasecmp(requeststr, md5secret)) {
5497 res = 0;
5498 break;
5501 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
5502 if (!strcmp(secret, p->secret))
5503 res = 0;
5505 return res;
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;
5518 char *keyn;
5519 int x;
5520 int expire = 0;
5521 int res = -1;
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 */
5525 if (ies->username)
5526 ast_copy_string(peer, ies->username, sizeof(peer));
5527 if (ies->password)
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));
5533 if (ies->refresh)
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));
5538 return -1;
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));
5548 goto return_unref;
5551 if (!ast_test_flag(p, IAX_DYNAMIC)) {
5552 if (authdebug)
5553 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5554 goto return_unref;
5557 if (!ast_apply_ha(p->ha, sin)) {
5558 if (authdebug)
5559 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5560 goto return_unref;
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)) {
5569 char tmpkeys[256];
5570 char *stringp=NULL;
5571 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
5572 stringp=tmpkeys;
5573 keyn = strsep(&stringp, ":");
5574 while(keyn) {
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);
5578 break;
5579 } else if (!key)
5580 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
5581 keyn = strsep(&stringp, ":");
5583 if (!keyn) {
5584 if (authdebug)
5585 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
5586 goto return_unref;
5588 } else {
5589 if (authdebug)
5590 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
5591 goto return_unref;
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);
5599 stringp = tmppw;
5600 while((tmppw = strsep(&stringp, ";"))) {
5601 MD5Init(&md5);
5602 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
5603 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5604 MD5Final(digest, &md5);
5605 for (x=0;x<16;x++)
5606 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5607 if (!strcasecmp(requeststr, md5secret))
5608 break;
5610 if (tmppw) {
5611 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5612 } else {
5613 if (authdebug)
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);
5615 goto return_unref;
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)) {
5620 if (authdebug)
5621 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5622 goto return_unref;
5623 } else
5624 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5625 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
5626 if (authdebug)
5627 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
5628 goto return_unref;
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 */
5637 res = 0;
5639 return_unref:
5640 if (p)
5641 peer_unref(p);
5643 return res;
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)
5648 int res = -1;
5649 int x;
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));
5656 } else {
5657 char sig[256];
5658 struct ast_key *key;
5659 key = ast_key_get(keyn, AST_KEY_PRIVATE);
5660 if (!key) {
5661 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
5662 } else {
5663 if (ast_sign(key, (char*)challenge, sig)) {
5664 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
5665 res = -1;
5666 } else {
5667 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
5668 res = 0;
5673 /* Fall back */
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];
5678 char digres[128];
5679 MD5Init(&md5);
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. */
5684 for (x=0;x<16;x++)
5685 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
5686 if (ecx && dcx)
5687 build_enc_keys(digest, ecx, dcx);
5688 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
5689 res = 0;
5690 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
5691 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
5692 res = 0;
5693 } else
5694 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
5696 return res;
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 */
5707 int res = -1;
5708 int authmethods = 0;
5709 struct iax_ie_data ied;
5710 uint16_t callno = p->callno;
5712 memset(&ied, 0, sizeof(ied));
5714 if (ies->username)
5715 ast_string_field_set(p, username, ies->username);
5716 if (ies->challenge)
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);
5722 else
5723 p->encmethods = 0;
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);
5729 } else {
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);
5740 if (!res) {
5741 peer_unref(peer);
5742 break;
5745 peer_unref(peer);
5747 if (!peer) {
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])) {
5755 peer_unref(peer);
5756 return -1;
5758 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5759 peer_unref(peer);
5761 if (!peer) {
5762 ast_mutex_lock(&iaxsl[callno]);
5763 if (!(p = iaxs[callno]))
5764 return -1;
5768 if (ies->encmethods)
5769 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
5770 if (!res)
5771 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
5772 return res;
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;
5780 reg->expire = -1;
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))
5788 #endif
5789 __iax2_do_register_s(data);
5790 return 0;
5793 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5795 int newcall = 0;
5796 char newip[256];
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));
5804 if (ies->callno)
5805 newcall = ies->callno;
5806 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
5807 ast_log(LOG_WARNING, "Invalid transfer request\n");
5808 return -1;
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);
5819 return 0;
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;
5827 int x;
5828 int matchmore = 0;
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 */
5844 if (ies->refresh)
5845 expiry = ies->refresh;
5846 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
5847 matchmore = CACHE_FLAG_MATCHMORE;
5848 ast_mutex_lock(&dpcache_lock);
5849 prev = NULL;
5850 dp = pvt->dpentries;
5851 while(dp) {
5852 if (!strcmp(dp->exten, exten)) {
5853 /* Let them go */
5854 if (prev)
5855 prev->peer = dp->peer;
5856 else
5857 pvt->dpentries = dp->peer;
5858 dp->peer = NULL;
5859 dp->callno = 0;
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);
5871 prev = dp;
5872 dp = dp->peer;
5874 ast_mutex_unlock(&dpcache_lock);
5875 return 0;
5878 static int complete_transfer(int callno, struct iax_ies *ies)
5880 int peercallno = 0;
5881 struct chan_iax2_pvt *pvt = iaxs[callno];
5882 struct iax_frame *cur;
5883 jb_frame frame;
5885 if (ies->callno)
5886 peercallno = ies->callno;
5888 if (peercallno < 1) {
5889 ast_log(LOG_WARNING, "Invalid transfer request\n");
5890 return -1;
5892 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
5893 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
5894 /* Reset sequence numbers */
5895 pvt->oseqno = 0;
5896 pvt->rseqno = 0;
5897 pvt->iseqno = 0;
5898 pvt->aseqno = 0;
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);
5917 jb_reset(pvt->jb);
5918 pvt->lag = 0;
5919 pvt->last = 0;
5920 pvt->lastsent = 0;
5921 pvt->nextpred = 0;
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)
5929 cur->retries = -1;
5931 AST_LIST_UNLOCK(&iaxq.queue);
5932 return 0;
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] = "";
5941 char msgstatus[60];
5942 int refresh = 60;
5943 char ourip[256] = "<Unspecified>";
5944 struct sockaddr_in oldus;
5945 struct sockaddr_in us;
5946 int oldmsgs;
5948 memset(&us, 0, sizeof(us));
5949 if (ies->apparent_addr)
5950 bcopy(ies->apparent_addr, &us, sizeof(us));
5951 if (ies->username)
5952 ast_copy_string(peer, ies->username, sizeof(peer));
5953 if (ies->refresh)
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;
5959 if (!reg) {
5960 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
5961 return -1;
5963 memcpy(&oldus, &reg->us, sizeof(oldus));
5964 oldmsgs = reg->messages;
5965 if (inaddrcmp(&reg->addr, sin)) {
5966 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
5967 return -1;
5969 memcpy(&reg->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, &reg->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");
5986 else
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;
5994 return 0;
5997 static int iax2_register(char *value, int lineno)
5999 struct iax2_registry *reg;
6000 char copy[256];
6001 char *username, *hostname, *secret;
6002 char *porta;
6003 char *stringp=NULL;
6005 if (!value)
6006 return -1;
6007 ast_copy_string(copy, value, sizeof(copy));
6008 stringp=copy;
6009 username = strsep(&stringp, "@");
6010 hostname = strsep(&stringp, "@");
6011 if (!hostname) {
6012 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
6013 return -1;
6015 stringp=username;
6016 username = strsep(&stringp, ":");
6017 secret = strsep(&stringp, ":");
6018 stringp=hostname;
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);
6024 return -1;
6026 if (!(reg = ast_calloc(1, sizeof(*reg))))
6027 return -1;
6028 if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
6029 free(reg);
6030 return -1;
6032 ast_copy_string(reg->username, username, sizeof(reg->username));
6033 if (secret)
6034 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
6035 reg->expire = -1;
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(&registrations);
6040 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
6041 AST_LIST_UNLOCK(&registrations);
6043 return 0;
6046 static void register_peer_exten(struct iax2_peer *peer, int onoff)
6048 char multi[256];
6049 char *stringp, *ext;
6050 if (!ast_strlen_zero(regcontext)) {
6051 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
6052 stringp = multi;
6053 while((ext = strsep(&stringp, "&"))) {
6054 if (onoff) {
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");
6058 } else
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)) {
6069 peer->expire = -1;
6070 peer_unref(peer);
6074 if (peer->pokeexpire > -1) {
6075 if (!ast_sched_del(sched, peer->pokeexpire)) {
6076 peer->pokeexpire = -1;
6077 peer_unref(peer);
6081 ao2_unlink(peers, peer);
6084 static void __expire_registry(const void *data)
6086 struct iax2_peer *peer = (struct iax2_peer *) data;
6088 if (!peer)
6089 return;
6091 peer->expire = -1;
6093 if (option_debug)
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 */
6106 if (iax2_regfunk)
6107 iax2_regfunk(peer->name, 0);
6109 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
6110 unlink_peer(peer);
6112 peer_unref(peer);
6115 static int expire_registry(const void *data)
6117 #ifdef SCHED_MULTITHREADED
6118 if (schedule_action(__expire_registry, data))
6119 #endif
6120 __expire_registry(data);
6121 return 0;
6124 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
6126 static void reg_source_db(struct iax2_peer *p)
6128 char data[80];
6129 struct in_addr in;
6130 char *c, *d;
6131 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
6132 c = strchr(data, ':');
6133 if (c) {
6134 *c = '\0';
6135 c++;
6136 if (inet_aton(data, &in)) {
6137 d = strchr(c, ':');
6138 if (d) {
6139 *d = '\0';
6140 d++;
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)) {
6152 p->expire = -1;
6153 peer_unref(p);
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)
6159 peer_unref(p);
6160 if (iax2_regfunk)
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;
6181 int msgcount;
6182 char data[80];
6183 int version;
6184 const char *peer_name;
6185 int res = -1;
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);
6196 return -1;
6198 ast_mutex_lock(&iaxsl[callno]);
6199 if (!iaxs[callno])
6200 goto return_unref;
6202 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6203 if (sin->sin_addr.s_addr) {
6204 time_t nowtime;
6205 time(&nowtime);
6206 realtime_update_peer(peer_name, sin, nowtime);
6207 } else {
6208 realtime_update_peer(peer_name, sin, 0);
6211 if (inaddrcmp(&p->addr, sin)) {
6212 if (iax2_regfunk)
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]) {
6241 res = 0;
6242 goto return_unref;
6245 /* Store socket fd */
6246 p->sockfd = fd;
6247 /* Setup the expiry */
6248 if (p->expire > -1) {
6249 if (!ast_sched_del(sched, p->expire)) {
6250 p->expire = -1;
6251 peer_unref(p);
6254 /* treat an unspecified refresh interval as the minimum */
6255 if (!refresh)
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;
6265 } else {
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)
6271 peer_unref(p);
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)) {
6279 int new, old;
6280 ast_app_inboxcount(p->mailbox, &new, &old);
6281 if (new > 255)
6282 new = 255;
6283 if (old > 255)
6284 old = 255;
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);
6294 if (version)
6295 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
6297 res = 0;
6299 return_unref:
6300 peer_unref(p);
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;
6309 char challenge[10];
6310 const char *peer_name;
6311 int res = -1;
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]);
6319 if (!iaxs[callno])
6320 goto return_unref;
6321 if (!p) {
6322 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6323 goto return_unref;
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);
6336 res = 0;
6338 return_unref:
6339 peer_unref(p);
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] = "";
6351 int res;
6352 int authmethods = 0;
6353 if (ies->authmethods)
6354 authmethods = ies->authmethods;
6355 if (ies->username)
6356 ast_copy_string(peer, ies->username, sizeof(peer));
6357 if (ies->challenge)
6358 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
6359 memset(&ied, 0, sizeof(ied));
6360 reg = iaxs[callno]->reg;
6361 if (reg) {
6362 if (inaddrcmp(&reg->addr, sin)) {
6363 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6364 return -1;
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;
6369 return -1;
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] == '[') {
6374 char tmpkey[256];
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);
6378 } else
6379 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
6380 if (!res) {
6381 reg->regstate = REG_STATE_AUTHSENT;
6382 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
6383 } else
6384 return -1;
6385 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
6386 } else
6387 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
6388 return -1;
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]);
6402 if (iaxs[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]);
6420 if (iaxs[callno])
6421 iaxs[callno]->authid = -1;
6422 ast_mutex_unlock(&iaxsl[callno]);
6423 #ifdef SCHED_MULTITHREADED
6424 if (schedule_action(__auth_reject, data))
6425 #endif
6426 __auth_reject(data);
6427 return 0;
6430 static int auth_fail(int callno, int failcode)
6432 /* Schedule sending the authentication failure in one second, to prevent
6433 guessing */
6434 if (iaxs[callno]) {
6435 iaxs[callno]->authfail = failcode;
6436 if (delayreject) {
6437 AST_SCHED_DEL(sched, iaxs[callno]->authid);
6438 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
6439 } else
6440 auth_reject((void *)(long)callno);
6442 return 0;
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]);
6451 if (iaxs[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]);
6464 if (iaxs[callno]) {
6465 iaxs[callno]->autoid = -1;
6467 ast_mutex_unlock(&iaxsl[callno]);
6468 #ifdef SCHED_MULTITHREADED
6469 if (schedule_action(__auto_hangup, data))
6470 #endif
6471 __auto_hangup(data);
6472 return 0;
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)) {
6502 send_packet(f);
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);
6512 peer_unref(peer);
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))
6521 #endif
6522 __iax2_poke_peer_s(data);
6523 return 0;
6526 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
6528 int res = 0;
6529 struct iax_frame *fr;
6530 struct ast_iax2_meta_hdr *meta;
6531 struct ast_iax2_meta_trunk_hdr *mth;
6532 int calls = 0;
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 */
6541 meta->zeros = 0;
6542 meta->metacmd = IAX_META_TRUNK;
6543 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
6544 meta->cmddata = IAX_META_TRUNK_MINI;
6545 else
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;
6550 fr->retrans = -1;
6551 fr->transfer = 0;
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;
6557 #if 0
6558 if (option_debug)
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));
6560 #endif
6561 /* Reset transmit trunk side data */
6562 tpeer->trunkdatalen = 0;
6563 tpeer->calls = 0;
6565 if (res < 0)
6566 return res;
6567 return calls;
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)
6574 return 1;
6575 return 0;
6578 static int timing_read(int *id, int fd, short events, void *cbdata)
6580 char buf[1024];
6581 int res;
6582 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
6583 int processed = 0;
6584 int totalcalls = 0;
6585 #ifdef DAHDI_TIMERACK
6586 int x = 1;
6587 #endif
6588 struct timeval now;
6589 if (iaxtrunkdebug)
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");
6597 usleep(1);
6598 return -1;
6600 #endif
6601 } else {
6602 /* Read and ignore from the pseudo channel for timing */
6603 res = read(fd, buf, sizeof(buf));
6604 if (res < 1) {
6605 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
6606 return 1;
6609 /* For each peer that supports trunking... */
6610 ast_mutex_lock(&tpeerlock);
6611 tpeer = tpeers;
6612 while(tpeer) {
6613 processed++;
6614 res = 0;
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
6620 could be in use */
6621 if (prev)
6622 prev->next = tpeer->next;
6623 else
6624 tpeers = tpeer->next;
6625 drop = tpeer;
6626 } else {
6627 res = send_trunk(tpeer, &now);
6628 if (iaxtrunkdebug)
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);
6631 totalcalls += res;
6632 res = 0;
6633 ast_mutex_unlock(&tpeer->lock);
6634 prev = tpeer;
6635 tpeer = tpeer->next;
6637 ast_mutex_unlock(&tpeerlock);
6638 if (drop) {
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 */
6642 if (option_debug)
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);
6650 free(drop);
6653 if (iaxtrunkdebug)
6654 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
6655 iaxtrunkdebug =0;
6656 return 1;
6659 struct dpreq_data {
6660 int callno;
6661 char context[AST_MAX_EXTENSION];
6662 char callednum[AST_MAX_EXTENSION];
6663 char *callerid;
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;
6670 int mm;
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;
6679 } else {
6680 dpstatus = IAX_DPSTATUS_NONEXISTENT;
6682 if (ast_ignore_pattern(context, callednum))
6683 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
6684 if (mm)
6685 dpstatus |= IAX_DPSTATUS_MATCHMORE;
6686 if (!skiplock)
6687 ast_mutex_lock(&iaxsl[callno]);
6688 if (iaxs[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);
6694 if (!skiplock)
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);
6703 if (dpr->callerid)
6704 free(dpr->callerid);
6705 free(dpr);
6706 return NULL;
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))))
6716 return;
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));
6724 if (callerid)
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);
6733 struct iax_dual {
6734 struct ast_channel *chan1;
6735 struct ast_channel *chan2;
6738 static void *iax_park_thread(void *stuff)
6740 struct ast_channel *chan1, *chan2;
6741 struct iax_dual *d;
6742 struct ast_frame *f;
6743 int ext;
6744 int res;
6745 d = stuff;
6746 chan1 = d->chan1;
6747 chan2 = d->chan2;
6748 free(d);
6749 f = ast_read(chan1);
6750 if (f)
6751 ast_frfree(f);
6752 res = ast_park_call(chan1, chan2, 0, &ext);
6753 ast_hangup(chan2);
6754 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
6755 return NULL;
6758 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
6760 struct iax_dual *d;
6761 struct ast_channel *chan1m, *chan2m;
6762 pthread_t th;
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");
6787 ast_hangup(chan2m);
6788 return -1;
6790 } else {
6791 if (chan1m)
6792 ast_hangup(chan1m);
6793 if (chan2m)
6794 ast_hangup(chan2m);
6795 return -1;
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);
6803 d->chan1 = chan1m;
6804 d->chan2 = chan2m;
6805 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
6806 pthread_attr_destroy(&attr);
6807 return 0;
6809 pthread_attr_destroy(&attr);
6810 free(d);
6812 return -1;
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;
6821 char rsi[80];
6822 snprintf(rsi, sizeof(rsi), "si-%s", si);
6823 if (iax_provision_version(&ourver, rsi, 1))
6824 return 0;
6825 if (option_debug)
6826 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
6827 if (ourver != ver)
6828 iax2_provision(sin, sockfd, NULL, rsi, 1);
6829 return 0;
6832 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
6834 jb_info stats;
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);
6879 thread->buf = NULL;
6880 ast_free(pkt_buf);
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)))
6900 return;
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);
6911 break;
6914 AST_LIST_TRAVERSE_SAFE_END
6916 if (!cur_pkt_buf)
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;
6925 socklen_t len;
6926 time_t t;
6927 static time_t last_errtime = 0;
6928 struct ast_iax2_full_hdr *fh;
6930 if (!(thread = find_idle_thread())) {
6931 time(&t);
6932 if (t != last_errtime && option_debug)
6933 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
6934 last_errtime = t;
6935 usleep(1);
6936 return 1;
6939 len = sizeof(thread->iosin);
6940 thread->iofd = fd;
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));
6947 handle_error();
6948 thread->iostate = IAX_IOSTATE_IDLE;
6949 signal_condition(&thread->lock, &thread->cond);
6950 return 1;
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);
6955 return 1;
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))
6970 break;
6972 if (cur) {
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);
6979 return 1;
6980 } else {
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));
6994 #endif
6995 signal_condition(&thread->lock, &thread->cond);
6997 return 1;
7000 static int socket_process(struct iax2_thread *thread)
7002 struct sockaddr_in sin;
7003 int res;
7004 int updatehistory=1;
7005 int new = NEW_PREVENT;
7006 void *ptr;
7007 int dcallno = 0;
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;
7023 struct iax_ies ies;
7024 struct iax_ie_data ied0, ied1;
7025 int format;
7026 int fd;
7027 int exists;
7028 int minivid = 0;
7029 unsigned int ts;
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;
7044 fd = thread->iofd;
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));
7049 return 1;
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));
7054 return 1;
7057 /* This is a video frame, get call number */
7058 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
7059 minivid = 1;
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));
7065 return 1;
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));
7074 return 1;
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));
7080 ptr = mth->data;
7081 tpeer = find_tpeer(&sin, fd);
7082 if (!tpeer) {
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));
7084 return 1;
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);
7108 trunked_ts = 0;
7109 } else {
7110 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
7111 break;
7113 /* Stop if we don't have enough data */
7114 if (len > res)
7115 break;
7116 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd, 0);
7117 if (fr->callno) {
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;
7126 f.datalen = len;
7127 if (f.datalen >= 0) {
7128 if (f.datalen)
7129 f.data = ptr;
7130 if(trunked_ts) {
7131 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
7132 } else
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)) {
7136 /* Common things */
7137 f.src = "IAX2";
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);
7142 if (duped_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;
7148 #if 1
7149 if (option_debug && iaxdebug)
7150 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7151 #endif
7154 } else {
7155 ast_log(LOG_WARNING, "Datalen < 0?\n");
7157 } else {
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]);
7164 ptr += len;
7165 res -= len;
7169 return 1;
7172 #ifdef DEBUG_SUPPORT
7173 if (iaxdebug && (res >= sizeof(*fh)))
7174 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
7175 #endif
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));
7179 return 1;
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);
7188 } else {
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);
7196 return 1;
7197 } else if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_ACK && dcallno == 1) {
7198 /* Ignore */
7199 return 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)))
7205 new = NEW_ALLOW;
7206 } else {
7207 /* Don't know anything about it yet */
7208 f.frametype = AST_FRAME_NULL;
7209 f.subclass = 0;
7212 if (!fr->callno) {
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);
7234 if (fr->callno > 0)
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,
7248 fd);
7250 if (fr->callno > 0)
7251 ast_mutex_unlock(&iaxsl[fr->callno]);
7252 return 1;
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]);
7258 return 1;
7260 #ifdef DEBUG_SUPPORT
7261 else if (iaxdebug)
7262 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
7263 #endif
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);
7290 #ifdef IAXTESTS
7291 if (test_resync) {
7292 if (option_debug)
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 */
7297 #if 0
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)) ) )
7304 #endif
7305 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
7306 updatehistory = 0;
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))) {
7315 if (
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. */
7326 if (option_debug)
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))) {
7335 if (option_debug)
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);
7341 } else {
7342 /* Send a VNAK requesting retransmission */
7343 iax2_vnak(fr->callno);
7345 ast_mutex_unlock(&iaxsl[fr->callno]);
7346 return 1;
7348 } else {
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++;
7358 /* A full frame */
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]);
7362 return 1;
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))) {
7378 unsigned char x;
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)
7385 break;
7386 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
7387 /* The acknowledgement is within our window. Time to acknowledge everything
7388 that it says to */
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)) {
7398 cur->retries = -1;
7399 /* Destroy call if this is the end */
7400 if (cur->final)
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;
7416 else {
7417 /* Stop processing now */
7418 ast_mutex_unlock(&iaxsl[fr->callno]);
7419 return 1;
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]);
7430 return 1;
7433 if (f.datalen) {
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]);
7438 return 1;
7440 f.data = NULL;
7441 f.datalen = 0;
7442 } else
7443 f.data = thread->buf + sizeof(*fh);
7444 } else {
7445 if (f.frametype == AST_FRAME_IAX)
7446 f.data = NULL;
7447 else
7448 f.data = empty;
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]);
7462 return 1;
7467 if (f.frametype == AST_FRAME_VOICE) {
7468 if (f.subclass != iaxs[fr->callno]->voiceformat) {
7469 iaxs[fr->callno]->voiceformat = f.subclass;
7470 if (option_debug)
7471 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
7472 if (iaxs[fr->callno]->owner) {
7473 int orignative;
7474 retryowner:
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);
7488 } else {
7489 if (option_debug)
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]);
7492 return 1;
7497 if (f.frametype == AST_FRAME_VIDEO) {
7498 if (f.subclass != iaxs[fr->callno]->videoformat) {
7499 if (option_debug)
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:
7522 /* Do nothing */
7523 break;
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",
7529 "Channel: %s\r\n"
7530 "Uniqueid: %s\r\n",
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]);
7544 return 1;
7549 break;
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",
7555 "Channel: %s\r\n"
7556 "Uniqueid: %s\r\n",
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]);
7566 return 1;
7570 break;
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))
7578 cur->retries = -1;
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;
7586 break;
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))
7590 break;
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]);
7597 return 1;
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)) {
7602 int new_callno;
7603 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
7604 fr->callno = new_callno;
7606 /* For security, always ack immediately */
7607 if (delayreject)
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);
7612 if (authdebug)
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);
7614 break;
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]);
7630 return 1;
7632 } else
7633 exists = 0;
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]);
7642 return 1;
7644 if (authdebug)
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);
7646 } else {
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";
7652 } else {
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");
7659 } else {
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";
7669 } else {
7670 pref = iaxs[fr->callno]->prefs;
7672 } else
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);
7679 if (!format) {
7680 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7681 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7682 if (!format) {
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]);
7689 return 1;
7691 if (authdebug) {
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);
7694 else
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);
7697 } else {
7698 /* Pick one... */
7699 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7700 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7701 format = 0;
7702 } else {
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");
7709 } else {
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;
7715 } else {
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);
7726 if (!format) {
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]);
7734 return 1;
7736 if (authdebug)
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);
7739 break;
7743 if (format) {
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),
7758 VERBOSE_PREFIX_4,
7759 ast_getformatname(iaxs[fr->callno]->peerformat),
7760 VERBOSE_PREFIX_4,
7761 caller_pref_buf,
7762 VERBOSE_PREFIX_4,
7763 ast_getformatname(format),
7764 VERBOSE_PREFIX_4,
7765 host_pref_buf,
7766 VERBOSE_PREFIX_4,
7767 using_prefs);
7769 iaxs[fr->callno]->chosenformat = format;
7770 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7771 } else {
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));
7779 break;
7781 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
7782 merge_encryption(iaxs[fr->callno],ies.encmethods);
7783 else
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]);
7789 return 1;
7791 break;
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) {
7796 if (iaxcompat) {
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);
7799 } else {
7800 /* Just look it up */
7801 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
7804 break;
7805 case IAX_COMMAND_HANGUP:
7806 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7807 if (option_debug)
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);
7815 break;
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>");
7826 if (option_debug)
7827 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
7828 fr->callno);
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);
7836 break;
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]);
7849 return 1;
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);
7858 } else {
7859 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
7861 ast_mutex_lock(&iaxsl[fr->callno]);
7862 } else {
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);
7866 else
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);
7870 } else
7871 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
7873 break;
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))
7878 break;
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);
7883 break;
7885 if (ies.format) {
7886 iaxs[fr->callno]->peerformat = ies.format;
7887 } else {
7888 if (iaxs[fr->callno]->owner)
7889 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
7890 else
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]);
7902 return 1;
7904 if (authdebug)
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);
7906 } else {
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));
7913 retryowner2:
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;
7932 while(dp) {
7933 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
7934 iax2_dprequest(dp, fr->callno);
7936 dp = dp->peer;
7938 ast_mutex_unlock(&dpcache_lock);
7940 break;
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]);
7946 return 1;
7948 break;
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);
7956 break;
7957 case IAX_COMMAND_PONG:
7958 /* Calculate ping time */
7959 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
7960 /* save RR info */
7961 save_rr(fr, &ies);
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;
7983 else
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)) {
7989 peer_unref(peer);
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));
7996 else
7997 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
7998 if (peer->pokeexpire == -1)
7999 peer_unref(peer);
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);
8004 peer->callno = 0;
8005 if (option_debug)
8006 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
8008 break;
8009 case IAX_COMMAND_LAGRQ:
8010 case IAX_COMMAND_LAGRP:
8011 f.src = "LAGRQ";
8012 f.mallocd = 0;
8013 f.offset = 0;
8014 f.samples = 0;
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);
8020 } else {
8021 /* Received LAGRP in response to our LAGRQ */
8022 unsigned int ts;
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);
8030 break;
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>");
8034 break;
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]);
8047 return 1;
8049 break;
8050 case IAX_COMMAND_AUTHREP:
8051 /* For security, always ack immediately */
8052 if (delayreject)
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>");
8057 break;
8059 if (authenticate_verify(iaxs[fr->callno], &ies)) {
8060 if (authdebug)
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);
8064 break;
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);
8069 } else
8070 exists = 0;
8071 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
8072 if (authdebug)
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]);
8080 return 1;
8082 } else {
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";
8087 } else {
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");
8094 } else {
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";
8102 } else {
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);
8112 if (!format) {
8113 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8114 if (option_debug)
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;
8118 if (!format) {
8119 if (authdebug) {
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);
8122 else
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]);
8131 return 1;
8133 } else {
8134 /* Pick one... */
8135 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8136 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
8137 format = 0;
8138 } else {
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");
8146 } else {
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;
8152 } else {
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);
8161 if (!format) {
8162 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8163 if (authdebug) {
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);
8166 else
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]);
8175 return 1;
8180 if (format) {
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),
8195 VERBOSE_PREFIX_4,
8196 ast_getformatname(iaxs[fr->callno]->peerformat),
8197 VERBOSE_PREFIX_4,
8198 caller_pref_buf,
8199 VERBOSE_PREFIX_4,
8200 ast_getformatname(format),
8201 VERBOSE_PREFIX_4,
8202 host_pref_buf,
8203 VERBOSE_PREFIX_4,
8204 using_prefs);
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);
8209 } else {
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));
8217 break;
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)) {
8223 if (authdebug)
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]);
8231 return 1;
8233 } else {
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);
8243 break;
8244 case IAX_COMMAND_INVAL:
8245 iaxs[fr->callno]->error = ENOTCONN;
8246 if (option_debug)
8247 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
8248 iax2_destroy(fr->callno);
8249 if (option_debug)
8250 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
8251 break;
8252 case IAX_COMMAND_VNAK:
8253 if (option_debug)
8254 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
8255 /* Force retransmission */
8256 vnak_retransmit(fr->callno, fr->iseqno);
8257 break;
8258 case IAX_COMMAND_REGREQ:
8259 case IAX_COMMAND_REGREL:
8260 /* For security, always ack immediately */
8261 if (delayreject)
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]);
8266 return 1;
8268 /* Send delayed failure */
8269 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
8270 break;
8272 if (!iaxs[fr->callno]) {
8273 ast_mutex_unlock(&iaxsl[fr->callno]);
8274 return 1;
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]);
8284 return 1;
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]);
8292 return 1;
8295 break;
8297 registry_authrequest(fr->callno);
8298 if (!iaxs[fr->callno]) {
8299 ast_mutex_unlock(&iaxsl[fr->callno]);
8300 return 1;
8302 break;
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);
8309 break;
8310 case IAX_COMMAND_REGREJ:
8311 if (iaxs[fr->callno]->reg) {
8312 if (authdebug) {
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);
8321 break;
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]);
8331 return 1;
8334 break;
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);
8346 break;
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;
8352 else
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);
8374 } else {
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);
8399 break;
8400 case IAX_COMMAND_TXREQ:
8401 try_transfer(iaxs[fr->callno], &ies);
8402 break;
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);
8406 break;
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 */
8412 break;
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)) {
8419 cur->retries = -1;
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;
8426 break;
8427 case IAX_COMMAND_DPREP:
8428 complete_dpreply(iaxs[fr->callno], &ies);
8429 break;
8430 case IAX_COMMAND_UNSUPPORT:
8431 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
8432 break;
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);
8437 break;
8439 memset(&ied0, 0, sizeof(ied0));
8440 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
8441 if (res < 0)
8442 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8443 else if (res > 0)
8444 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8445 else
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]);
8449 return 1;
8451 break;
8452 default:
8453 if (option_debug)
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]);
8469 return 1;
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);
8478 else {
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]);
8482 return 1;
8484 f.datalen = res - sizeof(*vh);
8485 if (f.datalen)
8486 f.data = thread->buf + sizeof(*vh);
8487 else
8488 f.data = NULL;
8489 #ifdef IAXTESTS
8490 if (test_resync) {
8491 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
8492 } else
8493 #endif /* IAXTESTS */
8494 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
8495 } else {
8496 /* A mini frame */
8497 f.frametype = AST_FRAME_VOICE;
8498 if (iaxs[fr->callno]->voiceformat > 0)
8499 f.subclass = iaxs[fr->callno]->voiceformat;
8500 else {
8501 if (option_debug)
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]);
8505 return 1;
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]);
8511 return 1;
8513 if (f.datalen)
8514 f.data = thread->buf + sizeof(*mh);
8515 else
8516 f.data = NULL;
8517 #ifdef IAXTESTS
8518 if (test_resync) {
8519 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
8520 } else
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]);
8528 return 1;
8530 /* Common things */
8531 f.src = "IAX2";
8532 f.mallocd = 0;
8533 f.offset = 0;
8534 f.len = 0;
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);
8540 } else
8541 f.samples = 0;
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)*/
8547 fr->outoforder = 0;
8548 } else {
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);
8555 if (duped_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;
8560 #if 1
8561 if (option_debug && iaxdebug)
8562 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8563 #endif
8566 /* Always run again */
8567 ast_mutex_unlock(&iaxsl[fr->callno]);
8568 return 1;
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);
8577 free(thread);
8578 ast_atomic_dec_and_test(&iaxactivethreadcount);
8581 static void *iax2_process_thread(void *data)
8583 struct iax2_thread *thread = data;
8584 struct timeval tv;
8585 struct timespec ts;
8586 int put_into_idle = 0;
8588 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
8589 pthread_cleanup_push(iax2_process_thread_cleanup, data);
8590 for(;;) {
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 */
8598 if (put_into_idle)
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);
8612 break;
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);
8619 if (t) {
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);
8624 break;
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);
8635 break;
8638 } else {
8639 ast_cond_wait(&thread->cond, &thread->lock);
8642 /* Go back into our respective list */
8643 put_into_idle = 1;
8645 ast_mutex_unlock(&thread->lock);
8647 if (thread->iostate == IAX_IOSTATE_IDLE)
8648 continue;
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:
8658 thread->actions++;
8659 thread->iostate = IAX_IOSTATE_PROCESSING;
8660 socket_process(thread);
8661 handle_deferred_full_frames(thread);
8662 break;
8663 case IAX_IOSTATE_SCHEDREADY:
8664 thread->actions++;
8665 thread->iostate = IAX_IOSTATE_PROCESSING;
8666 #ifdef SCHED_MULTITHREADED
8667 thread->schedfunc(thread->scheddata);
8668 #endif
8669 break;
8671 time(&thread->checktime);
8672 thread->iostate = IAX_IOSTATE_IDLE;
8673 #ifdef DEBUG_SCHED_MULTITHREAD
8674 thread->curfunc[0]='\0';
8675 #endif
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);
8703 return NULL;
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);
8712 if (reg->dnsmgr &&
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]);
8727 reg->callno = 0;
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);
8735 return -1;
8738 if (!reg->callno) {
8739 if (option_debug)
8740 ast_log(LOG_DEBUG, "Allocate call number\n");
8741 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
8742 if (reg->callno < 1) {
8743 ast_log(LOG_WARNING, "Unable to create call for registration\n");
8744 return -1;
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;
8760 return 0;
8763 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
8765 if (pos != 3)
8766 return NULL;
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;
8776 unsigned int sig;
8777 struct sockaddr_in sin;
8778 int callno;
8779 struct create_addr_info cai;
8781 memset(&cai, 0, sizeof(cai));
8783 if (option_debug)
8784 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
8786 if (iax_provision_build(&provdata, &sig, template, force)) {
8787 if (option_debug)
8788 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
8789 return 0;
8792 if (end) {
8793 memcpy(&sin, end, sizeof(sin));
8794 cai.sockfd = sockfd;
8795 } else if (create_addr(dest, NULL, &sin, &cai))
8796 return -1;
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);
8803 if (!callno)
8804 return -1;
8806 if (iaxs[callno]) {
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]);
8816 return 1;
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";
8826 /*! iax2provision
8827 \ingroup applications
8829 static int iax2_prov_app(struct ast_channel *chan, void *data)
8831 int res;
8832 char *sdata;
8833 char *opts;
8834 int force =0;
8835 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
8836 if (ast_strlen_zero(data))
8837 data = "default";
8838 sdata = ast_strdupa(data);
8839 opts = strchr(sdata, '|');
8840 if (opts)
8841 *opts='\0';
8843 if (chan->tech != &iax2_tech) {
8844 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
8845 return -1;
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");
8849 return -1;
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),
8855 sdata, res);
8856 return res;
8860 static int iax2_prov_cmd(int fd, int argc, char *argv[])
8862 int force = 0;
8863 int res;
8864 if (argc < 4)
8865 return RESULT_SHOWUSAGE;
8866 if ((argc > 4)) {
8867 if (!strcasecmp(argv[4], "forced"))
8868 force = 1;
8869 else
8870 return RESULT_SHOWUSAGE;
8872 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
8873 if (res < 0)
8874 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
8875 else if (res < 1)
8876 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
8877 else
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;
8885 int callno;
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]);
8897 peer->callno = 0;
8898 peer->lastms = -1;
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)
8902 peer_unref(peer);
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))
8911 #endif
8912 __iax2_poke_noanswer(data);
8913 peer_unref(peer);
8914 return 0;
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);
8923 return 0;
8926 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
8928 int callno;
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 */
8932 peer->lastms = 0;
8933 peer->historicms = 0;
8934 peer->pokeexpire = -1;
8935 peer->callno = 0;
8936 return 0;
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]);
8946 if (heldcall)
8947 ast_mutex_unlock(&iaxsl[heldcall]);
8948 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
8949 if (heldcall)
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);
8953 return -1;
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;
8964 peer_unref(peer);
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));
8972 } else
8973 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
8975 if (peer->pokeexpire == -1)
8976 peer_unref(peer);
8978 /* And send the poke */
8979 ast_mutex_lock(&iaxsl[callno]);
8980 if (iaxs[callno]) {
8981 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
8983 ast_mutex_unlock(&iaxsl[callno]);
8985 return 0;
8988 static void free_context(struct iax2_context *con)
8990 struct iax2_context *conl;
8991 while(con) {
8992 conl = con;
8993 con = con->next;
8994 free(conl);
8998 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
9000 int callno;
9001 int res;
9002 int fmt, native;
9003 struct sockaddr_in sin;
9004 struct ast_channel *c;
9005 struct parsed_dial_string pds;
9006 struct create_addr_info cai;
9007 char *tmpstr;
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);
9015 return NULL;
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;
9026 return NULL;
9029 if (pds.port)
9030 sin.sin_port = htons(atoi(pds.port));
9032 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
9033 if (callno < 1) {
9034 ast_log(LOG_WARNING, "Unable to create call\n");
9035 *cause = AST_CAUSE_CONGESTION;
9036 return NULL;
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)) {
9042 int new_callno;
9043 if ((new_callno = make_trunk(callno, 1)) != -1)
9044 callno = new_callno;
9046 iaxs[callno]->maxtime = cai.maxtime;
9047 if (cai.found)
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]);
9054 if (c) {
9055 /* Choose a format we can live with */
9056 if (c->nativeformats & format)
9057 c->nativeformats &= format;
9058 else {
9059 native = c->nativeformats;
9060 fmt = format;
9061 res = ast_translator_best_choice(&fmt, &native);
9062 if (res < 0) {
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);
9065 ast_hangup(c);
9066 return NULL;
9068 c->nativeformats = native;
9070 c->readformat = ast_best_codec(c->nativeformats);
9071 c->writeformat = c->readformat;
9074 return c;
9077 static void *sched_thread(void *ignore)
9079 int count;
9080 int res;
9081 struct timeval tv;
9082 struct timespec ts;
9084 for (;;) {
9085 pthread_testcancel();
9086 ast_mutex_lock(&sched_lock);
9087 res = ast_sched_wait(sched);
9088 if ((res > 1000) || (res < 0))
9089 res = 1000;
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);
9101 return NULL;
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;
9111 if (timingfd > -1)
9112 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
9114 for(;;) {
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);
9120 count = 0;
9121 wakeup = -1;
9122 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
9123 if (f->sentyet)
9124 continue;
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])) {
9128 wakeup = 1;
9129 continue;
9132 f->sentyet++;
9134 if (iaxs[f->callno]) {
9135 send_packet(f);
9136 count++;
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);
9144 iaxq.count--;
9145 /* Free the iax frame */
9146 iax_frame_free(f);
9147 } else {
9148 /* We need reliable delivery. Schedule a retransmission */
9149 f->retries++;
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);
9163 if (res >= 0) {
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);
9168 return NULL;
9171 static int start_network_thread(void)
9173 pthread_attr_t attr;
9174 int threadcount = 0;
9175 int x;
9176 for (x = 0; x < iaxthreadcount; x++) {
9177 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
9178 if (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");
9187 free(thread);
9188 thread = NULL;
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);
9199 return 0;
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));
9209 return con;
9212 static int get_auth_methods(char *value)
9214 int methods = 0;
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;
9221 return methods;
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)
9230 int sd;
9231 int res;
9233 sd = socket(AF_INET, SOCK_DGRAM, 0);
9234 if (sd < 0) {
9235 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
9236 return -1;
9239 res = bind(sd, sa, salen);
9240 if (res < 0) {
9241 if (option_debug)
9242 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
9243 close(sd);
9244 return 1;
9247 close(sd);
9248 return 0;
9251 /*! \brief Parse the "sourceaddress" value,
9252 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9253 not found. */
9254 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
9256 struct sockaddr_in sin;
9257 int nonlocal = 1;
9258 int port = IAX_DEFAULT_PORTNO;
9259 int sockfd = defaultsockfd;
9260 char *tmp;
9261 char *addr;
9262 char *portstr;
9264 if (!(tmp = ast_strdupa(srcaddr)))
9265 return -1;
9267 addr = strsep(&tmp, ":");
9268 portstr = tmp;
9270 if (portstr) {
9271 port = atoi(portstr);
9272 if (port < 1)
9273 port = IAX_DEFAULT_PORTNO;
9276 if (!ast_get_ip(&sin, addr)) {
9277 struct ast_netsock *sock;
9278 int res;
9280 sin.sin_port = 0;
9281 sin.sin_family = AF_INET;
9282 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
9283 if (res == 0) {
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);
9288 if (sock) {
9289 sockfd = ast_netsock_sockfd(sock);
9290 nonlocal = 0;
9291 } else {
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);
9298 if (sock) {
9299 sockfd = ast_netsock_sockfd(sock);
9300 ast_netsock_unref(sock);
9301 nonlocal = 0;
9302 } else {
9303 nonlocal = 2;
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);
9315 return -1;
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);
9319 return -1;
9320 } else {
9321 if (option_debug)
9322 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
9323 return 0;
9327 static void peer_destructor(void *obj)
9329 struct iax2_peer *peer = obj;
9330 int callno = peer->callno;
9332 ast_free_ha(peer->ha);
9334 if (callno > 0) {
9335 ast_mutex_lock(&iaxsl[callno]);
9336 iax2_destroy(callno);
9337 ast_mutex_unlock(&iaxsl[callno]);
9340 register_peer_exten(peer, 0);
9342 if (peer->dnsmgr)
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;
9353 int maskfound=0;
9354 int found=0;
9355 int firstpass=1;
9356 struct iax2_peer tmp_peer = {
9357 .name = name,
9360 if (!temponly) {
9361 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
9362 if (peer && !ast_test_flag(peer, IAX_DELME))
9363 firstpass = 0;
9366 if (peer) {
9367 found++;
9368 if (firstpass) {
9369 oldha = peer->ha;
9370 peer->ha = NULL;
9372 unlink_peer(peer);
9373 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
9374 peer->expire = -1;
9375 peer->pokeexpire = -1;
9376 peer->sockfd = defaultsockfd;
9377 if (ast_string_field_init(peer, 32))
9378 peer = peer_unref(peer);
9381 if (peer) {
9382 if (firstpass) {
9383 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
9384 peer->encmethods = iax2_encryption;
9385 peer->adsi = adsi;
9386 ast_string_field_set(peer,secret,"");
9387 if (!found) {
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, "");
9404 if (!v) {
9405 v = alt;
9406 alt = NULL;
9408 while(v) {
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);
9442 } else
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);
9452 if (!found) {
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;
9462 } else {
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);
9471 if (!maskfound)
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")) {
9482 maskfound++;
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));
9493 else
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)) {
9503 char name2[80];
9504 char num2[80];
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);
9508 } else {
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")) {
9527 peer->maxms = 0;
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);
9532 peer->maxms = 0;
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); */
9550 v = v->next;
9551 if (!v) {
9552 v = alt;
9553 alt = NULL;
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;
9562 if (oldha)
9563 ast_free_ha(oldha);
9564 return peer;
9567 static void user_destructor(void *obj)
9569 struct iax2_user *user = obj;
9571 ast_free_ha(user->ha);
9572 free_context(user->contexts);
9573 if(user->vars) {
9574 ast_variables_destroy(user->vars);
9575 user->vars = NULL;
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;
9587 int format;
9588 int firstpass=1;
9589 int oldcurauthreq = 0;
9590 char *varname = NULL, *varval = NULL;
9591 struct ast_variable *tmpvar = NULL;
9592 struct iax2_user tmp_user = {
9593 .name = name,
9596 if (!temponly) {
9597 user = ao2_find(users, &tmp_user, OBJ_POINTER);
9598 if (user && !ast_test_flag(user, IAX_DELME))
9599 firstpass = 0;
9602 if (user) {
9603 if (firstpass) {
9604 oldcurauthreq = user->curauthreq;
9605 oldha = user->ha;
9606 oldcon = user->contexts;
9607 user->ha = NULL;
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);
9612 } else {
9613 user = ao2_alloc(sizeof(*user), user_destructor);
9616 if (user) {
9617 if (firstpass) {
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);
9622 goto cleanup;
9624 user->maxauthreq = maxauthreq;
9625 user->curauthreq = oldcurauthreq;
9626 user->prefs = prefs;
9627 user->capability = iax2_capability;
9628 user->encmethods = iax2_encryption;
9629 user->adsi = adsi;
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, "");
9637 if (!v) {
9638 v = alt;
9639 alt = NULL;
9641 while(v) {
9642 if (!strcasecmp(v->name, "context")) {
9643 con = build_context(v->value);
9644 if (con) {
9645 if (conl)
9646 conl->next = con;
9647 else
9648 user->contexts = con;
9649 conl = 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,'='))) {
9657 *varval = '\0';
9658 varval++;
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);
9687 } else
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);
9709 } else
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")) {
9713 char name2[80];
9714 char num2[80];
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);
9719 } else {
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);
9728 } else {
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);
9737 } else {
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);
9752 if (format < 0) {
9753 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9754 } else {
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); */
9767 v = v->next;
9768 if (!v) {
9769 v = alt;
9770 alt = NULL;
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;
9780 } else {
9781 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9784 ast_clear_flag(user, IAX_DELME);
9786 cleanup:
9787 if (oldha)
9788 ast_free_ha(oldha);
9789 if (oldcon)
9790 free_context(oldcon);
9791 return user;
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);
9800 return 0;
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);
9809 return 0;
9812 static void delete_users(void)
9814 struct iax2_registry *reg;
9816 ao2_callback(users, 0, user_delme_cb, NULL);
9818 AST_LIST_LOCK(&registrations);
9819 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
9820 ast_sched_del(sched, reg->expire);
9821 if (reg->callno) {
9822 int callno = reg->callno;
9823 ast_mutex_lock(&iaxsl[callno]);
9824 if (iaxs[callno]) {
9825 iaxs[callno]->reg = NULL;
9826 iax2_destroy(callno);
9828 ast_mutex_unlock(&iaxsl[callno]);
9830 if (reg->dnsmgr)
9831 ast_dnsmgr_release(reg->dnsmgr);
9832 free(reg);
9834 AST_LIST_UNLOCK(&registrations);
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);
9848 user_unref(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))
9861 unlink_peer(peer);
9862 peer_unref(peer);
9866 static void set_timing(void)
9868 #ifdef HAVE_DAHDI
9869 int bs = trunkfreq * 8;
9870 if (timingfd > -1) {
9871 if (
9872 #ifdef DAHDI_TIMERACK
9873 ioctl(timingfd, DAHDI_TIMERCONFIG, &bs) &&
9874 #endif
9875 ioctl(timingfd, DAHDI_SET_BLOCKSIZE, &bs))
9876 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
9878 #endif
9881 static void set_config_destroy(void)
9883 strcpy(accountcode, "");
9884 strcpy(language, "");
9885 strcpy(mohinterpret, "default");
9886 strcpy(mohsuggest, "");
9887 amaflags = 0;
9888 delayreject = 0;
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);
9893 delete_users();
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;
9902 char *cat;
9903 const char *utype;
9904 const char *tosval;
9905 int format;
9906 int portno = IAX_DEFAULT_PORTNO;
9907 int x;
9908 struct iax2_user *user;
9909 struct iax2_peer *peer;
9910 struct ast_netsock *ns;
9911 #if 0
9912 static unsigned short int last_port=0;
9913 #endif
9915 cfg = ast_config_load(config_file);
9917 if (!cfg) {
9918 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
9919 return -1;
9922 if (reload) {
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);
9933 #ifdef SO_NO_CHECK
9934 nochecksums = 0;
9935 #endif
9937 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9938 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9940 maxauthreq = 3;
9942 v = ast_variable_browse(cfg, "general");
9944 /* Seed initial tos value */
9945 tosval = ast_variable_retrieve(cfg, "general", "tos");
9946 if (tosval) {
9947 if (ast_str2tos(tosval, &tos))
9948 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9950 while(v) {
9951 if (!strcasecmp(v->name, "bindport")){
9952 if (reload)
9953 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
9954 else
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")) {
9959 if (reload) {
9960 if (atoi(v->value) != iaxthreadcount)
9961 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
9962 } else {
9963 iaxthreadcount = atoi(v->value);
9964 if (iaxthreadcount < 1) {
9965 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
9966 iaxthreadcount = 1;
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")) {
9973 if (reload) {
9974 AST_LIST_LOCK(&dynamic_list);
9975 iaxmaxthreadcount = atoi(v->value);
9976 AST_LIST_UNLOCK(&dynamic_list);
9977 } else {
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")) {
9988 #ifdef SO_NO_CHECK
9989 if (ast_true(v->value))
9990 nochecksums = 1;
9991 else
9992 nochecksums = 0;
9993 #else
9994 if (ast_true(v->value))
9995 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
9996 #endif
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")) {
10011 if (reload) {
10012 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
10013 } else {
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);
10016 } else {
10017 if (option_verbose > 1) {
10018 if (strchr(v->value, ':'))
10019 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
10020 else
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);
10041 } else
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);
10070 if(i > 0)
10071 global_rtautoclear = i;
10072 else
10073 i = 0;
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)
10078 trunkfreq = 10;
10079 } else if (!strcasecmp(v->name, "autokill")) {
10080 if (sscanf(v->value, "%d", &x) == 1) {
10081 if (x >= 0)
10082 autokill = x;
10083 else
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;
10087 } else {
10088 autokill = 0;
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;
10097 } else
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);
10123 if (format < 0) {
10124 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
10125 } else {
10126 amaflags = format;
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)
10133 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); */
10138 v = v->next;
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));
10144 } else {
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);
10151 if (reload) {
10152 ast_netsock_release(outsock);
10153 outsock = ast_netsock_list_alloc();
10154 if (!outsock) {
10155 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10156 return -1;
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");
10169 if (ucfg) {
10170 struct ast_variable *gen;
10171 int genhasiax;
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);
10179 while (cat) {
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);
10186 if (user) {
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);
10191 if (peer) {
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)) {
10199 char tmp[256];
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");
10203 if (!host)
10204 host = ast_variable_retrieve(ucfg, "general", "host");
10205 if (!username)
10206 username = ast_variable_retrieve(ucfg, "general", "username");
10207 if (!secret)
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);
10212 else
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);
10224 while(cat) {
10225 if (strcasecmp(cat, "general")) {
10226 utype = ast_variable_retrieve(cfg, cat, "type");
10227 if (utype) {
10228 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
10229 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
10230 if (user) {
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);
10237 if (peer) {
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);
10246 } else
10247 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10249 cat = ast_category_browse(cfg, cat);
10251 ast_config_destroy(cfg);
10252 set_timing();
10253 return 1;
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);
10264 peer_unref(peer);
10267 static int reload_config(void)
10269 char *config = "iax.conf";
10270 struct iax2_registry *reg;
10272 if (set_config(config, 1) > 0) {
10273 prune_peers();
10274 prune_users();
10275 AST_LIST_LOCK(&registrations);
10276 AST_LIST_TRAVERSE(&registrations, reg, entry)
10277 iax2_do_register(reg);
10278 AST_LIST_UNLOCK(&registrations);
10279 /* Qualify hosts, too */
10280 poke_all_peers();
10282 reload_firmware(0);
10283 iax_provision_reload();
10285 return 0;
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;
10301 int x;
10302 int callno;
10303 struct iax_ie_data ied;
10304 struct create_addr_info cai;
10305 struct parsed_dial_string pds;
10306 char *tmpstr;
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))
10313 return x;
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);
10329 return -1;
10332 /* Populate our address from the given */
10333 if (create_addr(pds.peer, NULL, &sin, &cai))
10334 return -1;
10336 if (option_debug)
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);
10341 if (callno < 1) {
10342 ast_log(LOG_WARNING, "Unable to create call\n");
10343 return -1;
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
10354 if (pds.exten)
10355 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10356 if (pds.username)
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 */
10361 if (pds.password)
10362 ast_string_field_set(iaxs[callno], secret, pds.password);
10363 if (pds.key)
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);
10368 return callno;
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;
10374 struct timeval tv;
10375 int x;
10376 int com[2];
10377 int timeout;
10378 int old=0;
10379 int outfd;
10380 int abort;
10381 int callno;
10382 struct ast_channel *c;
10383 struct ast_frame *f;
10384 gettimeofday(&tv, NULL);
10385 dp = dpcache;
10386 while(dp) {
10387 next = dp->next;
10388 /* Expire old caches */
10389 if (ast_tvcmp(tv, dp->expiry) > 0) {
10390 /* It's expired, let it disappear */
10391 if (prev)
10392 prev->next = dp->next;
10393 else
10394 dpcache = dp->next;
10395 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10396 /* Free memory and go again */
10397 free(dp);
10398 } else {
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);
10401 dp = next;
10402 continue;
10404 /* We found an entry that matches us! */
10405 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10406 break;
10407 prev = dp;
10408 dp = next;
10410 if (!dp) {
10411 /* No matching entry. Create a new one. */
10412 /* First, can we make a callno? */
10413 callno = cache_get_callno_locked(data);
10414 if (callno < 0) {
10415 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10416 return NULL;
10418 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10419 ast_mutex_unlock(&iaxsl[callno]);
10420 return NULL;
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;
10432 dpcache = dp;
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)
10447 break;
10449 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10450 ast_log(LOG_WARNING, "No more waiter positions available\n");
10451 return NULL;
10453 if (pipe(com)) {
10454 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10455 return NULL;
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 */
10463 if (chan)
10464 old = ast_channel_defer_dtmf(chan);
10465 abort = 0;
10466 while(timeout) {
10467 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10468 if (outfd > -1) {
10469 break;
10471 if (c) {
10472 f = ast_read(c);
10473 if (f)
10474 ast_frfree(f);
10475 else {
10476 /* Got hung up on, abort! */
10477 break;
10478 abort = 1;
10482 if (!timeout) {
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;
10487 close(com[1]);
10488 close(com[0]);
10489 if (abort) {
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 */
10492 if (!old && chan)
10493 ast_channel_undefer_dtmf(chan);
10494 return NULL;
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 */
10512 if (!old && chan)
10513 ast_channel_undefer_dtmf(chan);
10515 return dp;
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;
10522 int res = 0;
10523 #if 0
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);
10525 #endif
10526 if ((priority != 1) && (priority != 2))
10527 return 0;
10528 ast_mutex_lock(&dpcache_lock);
10529 dp = find_cache(chan, data, context, exten, priority);
10530 if (dp) {
10531 if (dp->flags & CACHE_FLAG_EXISTS)
10532 res= 1;
10534 ast_mutex_unlock(&dpcache_lock);
10535 if (!dp) {
10536 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10538 return res;
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)
10544 int res = 0;
10545 struct iax2_dpcache *dp;
10546 #if 0
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);
10548 #endif
10549 if ((priority != 1) && (priority != 2))
10550 return 0;
10551 ast_mutex_lock(&dpcache_lock);
10552 dp = find_cache(chan, data, context, exten, priority);
10553 if (dp) {
10554 if (dp->flags & CACHE_FLAG_CANEXIST)
10555 res= 1;
10557 ast_mutex_unlock(&dpcache_lock);
10558 if (!dp) {
10559 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10561 return res;
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)
10567 int res = 0;
10568 struct iax2_dpcache *dp;
10569 #if 0
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);
10571 #endif
10572 if ((priority != 1) && (priority != 2))
10573 return 0;
10574 ast_mutex_lock(&dpcache_lock);
10575 dp = find_cache(chan, data, context, exten, priority);
10576 if (dp) {
10577 if (dp->flags & CACHE_FLAG_MATCHMORE)
10578 res= 1;
10580 ast_mutex_unlock(&dpcache_lock);
10581 if (!dp) {
10582 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10584 return res;
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)
10590 char odata[256];
10591 char req[256];
10592 char *ncontext;
10593 struct iax2_dpcache *dp;
10594 struct ast_app *dial;
10595 #if 0
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);
10597 #endif
10598 if (priority == 2) {
10599 /* Indicate status, can be overridden in dialplan */
10600 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10601 if (dialstatus) {
10602 dial = pbx_findapp(dialstatus);
10603 if (dial)
10604 pbx_exec(chan, dial, "");
10606 return -1;
10607 } else if (priority != 1)
10608 return -1;
10609 ast_mutex_lock(&dpcache_lock);
10610 dp = find_cache(chan, data, context, exten, priority);
10611 if (dp) {
10612 if (dp->flags & CACHE_FLAG_EXISTS) {
10613 ast_copy_string(odata, data, sizeof(odata));
10614 ncontext = strchr(odata, '/');
10615 if (ncontext) {
10616 *ncontext = '\0';
10617 ncontext++;
10618 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10619 } else {
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);
10624 } else {
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);
10627 return -1;
10630 ast_mutex_unlock(&dpcache_lock);
10631 dial = pbx_findapp("Dial");
10632 if (dial) {
10633 return pbx_exec(chan, dial, req);
10634 } else {
10635 ast_log(LOG_WARNING, "No dial application registered\n");
10637 return -1;
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)
10651 return -1;
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);
10654 return 0;
10657 if ((colname = strchr(peername, ':'))) /*! \todo : will be removed after the 1.4 relese */
10658 *colname++ = '\0';
10659 else if ((colname = strchr(peername, '|')))
10660 *colname++ = '\0';
10661 else
10662 colname = "ip";
10664 if (!(peer = find_peer(peername, 1)))
10665 return -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, '[');
10690 *codecnum = '\0';
10691 codecnum++;
10692 if ((ptr = strchr(codecnum, ']'))) {
10693 *ptr = '\0';
10695 index = atoi(codecnum);
10696 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10697 ast_copy_string(buf, ast_getformatname(codec), len);
10698 } else {
10699 buf[0] = '\0';
10701 } else {
10702 buf[0] = '\0';
10705 peer_unref(peer);
10707 return 0;
10710 struct ast_custom_function iaxpeer_function = {
10711 .name = "IAXPEER",
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"
10726 "\n"
10727 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10728 "\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);
10745 return res;
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)))
10753 return res;
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;
10769 peer_unref(p);
10771 return res;
10774 static struct ast_switch iax2_switch =
10776 name: "IAX2",
10777 description: "IAX Remote Dialplan Switch",
10778 exists: iax2_exists,
10779 canmatch: iax2_canmatch,
10780 exec: iax2_exec,
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";
10870 #ifdef IAXTESTS
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,
10887 NULL };
10889 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10890 { "iax2", "jb", "debug", NULL },
10891 iax2_do_jb_debug, NULL,
10892 NULL };
10894 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10895 { "iax2", "no", "debug", NULL },
10896 iax2_no_debug, NULL,
10897 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,
10902 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,
10907 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",
10960 debug_usage },
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 },
10990 #ifdef IAXTESTS
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;
11008 int x;
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)
11060 usleep(10000);
11062 ast_netsock_release(netsock);
11063 ast_netsock_release(outsock);
11064 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
11065 if (iaxs[x]) {
11066 iax2_destroy(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);
11075 delete_users();
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);
11090 return 0;
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;
11106 return 0;
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";
11131 int res = 0;
11132 int x;
11133 struct iax2_registry *reg = NULL;
11135 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
11136 if (!peers)
11137 return AST_MODULE_LOAD_FAILURE;
11138 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
11139 if (!users) {
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);
11156 #ifdef HAVE_ZAPTEL
11157 #ifdef ZAPTEL_TIMERACK
11158 timingfd = open("/dev/zap/timer", O_RDWR);
11159 if (timingfd < 0)
11160 #endif
11161 timingfd = open("/dev/zap/pseudo", O_RDWR);
11162 if (timingfd < 0)
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);
11167 if (timingfd < 0)
11168 #endif
11169 timingfd = open("/dev/dahdi/pseudo", O_RDWR);
11170 if (timingfd < 0)
11171 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
11172 #endif
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");
11187 return -1;
11190 netsock = ast_netsock_list_alloc();
11191 if (!netsock) {
11192 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
11193 return -1;
11195 ast_netsock_init(netsock);
11197 outsock = ast_netsock_list_alloc();
11198 if (!outsock) {
11199 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
11200 return -1;
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");
11220 __unload_module();
11221 return -1;
11224 if (ast_register_switch(&iax2_switch))
11225 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
11227 res = start_network_thread();
11228 if (!res) {
11229 if (option_verbose > 1)
11230 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
11231 } else {
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(&registrations);
11238 AST_LIST_TRAVERSE(&registrations, reg, entry)
11239 iax2_do_register(reg);
11240 AST_LIST_UNLOCK(&registrations);
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();
11247 return res;
11250 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
11251 .load = load_module,
11252 .unload = unload_module,
11253 .reload = reload,