I thought I was going to be able to leave 1.4 alone, but that was not the case.
[asterisk-bristuff.git] / channels / chan_iax2.c
blob7c71f33ad27038e989ad5181fa45117819a79ca3
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>zaptel</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 #ifdef HAVE_ZAPTEL
63 #include <sys/ioctl.h>
64 #include <zaptel/zaptel.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
130 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
131 but keeps the division between trunked and non-trunked better. */
132 #define TRUNK_CALL_START 0x4000
134 #define DEBUG_SUPPORT
136 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
138 /* Sample over last 100 units to determine historic jitter */
139 #define GAMMA (0.01)
141 static struct ast_codec_pref prefs;
143 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
145 static char context[80] = "default";
147 static char language[MAX_LANGUAGE] = "";
148 static char regcontext[AST_MAX_CONTEXT] = "";
150 static int maxauthreq = 3;
151 static int max_retries = 4;
152 static int ping_time = 21;
153 static int lagrq_time = 10;
154 static int maxtrunkcall = TRUNK_CALL_START;
155 static int maxnontrunkcall = 1;
156 static int maxjitterbuffer=1000;
157 static int resyncthreshold=1000;
158 static int maxjitterinterps=10;
159 static int trunkfreq = 20;
160 static int authdebug = 1;
161 static int autokill = 0;
162 static int iaxcompat = 0;
164 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
166 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
168 static unsigned int tos = 0;
170 static int min_reg_expire;
171 static int max_reg_expire;
173 static int timingfd = -1; /* Timing file descriptor */
175 static struct ast_netsock_list *netsock;
176 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
177 static int defaultsockfd = -1;
179 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
181 /* Ethernet, etc */
182 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
183 /* T1, maybe ISDN */
184 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
185 ~AST_FORMAT_SLINEAR & \
186 ~AST_FORMAT_ULAW & \
187 ~AST_FORMAT_ALAW & \
188 ~AST_FORMAT_G722)
189 /* A modem */
190 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
191 ~AST_FORMAT_G726 & \
192 ~AST_FORMAT_G726_AAL2 & \
193 ~AST_FORMAT_ADPCM)
195 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
196 ~AST_FORMAT_G723_1)
199 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
200 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
201 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
203 static struct io_context *io;
204 static struct sched_context *sched;
206 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
208 static int iaxdebug = 0;
210 static int iaxtrunkdebug = 0;
212 static int test_losspct = 0;
213 #ifdef IAXTESTS
214 static int test_late = 0;
215 static int test_resync = 0;
216 static int test_jit = 0;
217 static int test_jitpct = 0;
218 #endif /* IAXTESTS */
220 static char accountcode[AST_MAX_ACCOUNT_CODE];
221 static char mohinterpret[MAX_MUSICCLASS];
222 static char mohsuggest[MAX_MUSICCLASS];
223 static int amaflags = 0;
224 static int adsi = 0;
225 static int delayreject = 0;
226 static int iax2_encryption = 0;
228 static struct ast_flags globalflags = { 0 };
230 static pthread_t netthreadid = AST_PTHREADT_NULL;
231 static pthread_t schedthreadid = AST_PTHREADT_NULL;
232 AST_MUTEX_DEFINE_STATIC(sched_lock);
233 static ast_cond_t sched_cond;
235 enum {
236 IAX_STATE_STARTED = (1 << 0),
237 IAX_STATE_AUTHENTICATED = (1 << 1),
238 IAX_STATE_TBD = (1 << 2),
239 IAX_STATE_UNCHANGED = (1 << 3),
240 } iax2_state;
242 struct iax2_context {
243 char context[AST_MAX_CONTEXT];
244 struct iax2_context *next;
247 enum {
248 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
249 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
250 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
251 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
252 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
253 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
254 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
255 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
256 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
257 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
258 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
259 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
260 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
261 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
262 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
263 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
264 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
265 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
266 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
267 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
268 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
269 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
270 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
271 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
272 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
273 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
274 response, so that we've achieved a three-way handshake with
275 them before sending voice or anything else*/
276 } iax2_flags;
278 static int global_rtautoclear = 120;
280 static int reload_config(void);
281 static int iax2_reload(int fd, int argc, char *argv[]);
284 struct iax2_user {
285 AST_DECLARE_STRING_FIELDS(
286 AST_STRING_FIELD(name);
287 AST_STRING_FIELD(secret);
288 AST_STRING_FIELD(dbsecret);
289 AST_STRING_FIELD(accountcode);
290 AST_STRING_FIELD(mohinterpret);
291 AST_STRING_FIELD(mohsuggest);
292 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
293 AST_STRING_FIELD(language);
294 AST_STRING_FIELD(cid_num);
295 AST_STRING_FIELD(cid_name);
298 int authmethods;
299 int encmethods;
300 int amaflags;
301 int adsi;
302 unsigned int flags;
303 int capability;
304 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
305 int curauthreq; /*!< Current number of outstanding AUTHREQs */
306 struct ast_codec_pref prefs;
307 struct ast_ha *ha;
308 struct iax2_context *contexts;
309 struct ast_variable *vars;
312 struct iax2_peer {
313 AST_DECLARE_STRING_FIELDS(
314 AST_STRING_FIELD(name);
315 AST_STRING_FIELD(username);
316 AST_STRING_FIELD(secret);
317 AST_STRING_FIELD(dbsecret);
318 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
320 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
321 AST_STRING_FIELD(context); /*!< For transfers only */
322 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
323 AST_STRING_FIELD(mailbox); /*!< Mailbox */
324 AST_STRING_FIELD(mohinterpret);
325 AST_STRING_FIELD(mohsuggest);
326 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
327 /* Suggested caller id if registering */
328 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
329 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
330 AST_STRING_FIELD(zonetag); /*!< Time Zone */
332 struct ast_codec_pref prefs;
333 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
334 struct sockaddr_in addr;
335 int formats;
336 int sockfd; /*!< Socket to use for transmission */
337 struct in_addr mask;
338 int adsi;
339 unsigned int flags;
341 /* Dynamic Registration fields */
342 struct sockaddr_in defaddr; /*!< Default address if there is one */
343 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
344 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
346 int expire; /*!< Schedule entry for expiry */
347 int expiry; /*!< How soon to expire */
348 int capability; /*!< Capability */
350 /* Qualification */
351 int callno; /*!< Call number of POKE request */
352 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
353 int lastms; /*!< How long last response took (in ms), or -1 for no response */
354 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
356 int pokefreqok; /*!< How often to check if the host is up */
357 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
358 int historicms; /*!< How long recent average responses took */
359 int smoothing; /*!< Sample over how many units to determine historic ms */
361 struct ast_ha *ha;
364 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
366 static struct iax2_trunk_peer {
367 ast_mutex_t lock;
368 int sockfd;
369 struct sockaddr_in addr;
370 struct timeval txtrunktime; /*!< Transmit trunktime */
371 struct timeval rxtrunktime; /*!< Receive trunktime */
372 struct timeval lasttxtime; /*!< Last transmitted trunktime */
373 struct timeval trunkact; /*!< Last trunk activity */
374 unsigned int lastsent; /*!< Last sent time */
375 /* Trunk data and length */
376 unsigned char *trunkdata;
377 unsigned int trunkdatalen;
378 unsigned int trunkdataalloc;
379 struct iax2_trunk_peer *next;
380 int trunkerror;
381 int calls;
382 } *tpeers = NULL;
384 AST_MUTEX_DEFINE_STATIC(tpeerlock);
386 struct iax_firmware {
387 struct iax_firmware *next;
388 int fd;
389 int mmaplen;
390 int dead;
391 struct ast_iax2_firmware_header *fwh;
392 unsigned char *buf;
395 enum iax_reg_state {
396 REG_STATE_UNREGISTERED = 0,
397 REG_STATE_REGSENT,
398 REG_STATE_AUTHSENT,
399 REG_STATE_REGISTERED,
400 REG_STATE_REJECTED,
401 REG_STATE_TIMEOUT,
402 REG_STATE_NOAUTH
405 enum iax_transfer_state {
406 TRANSFER_NONE = 0,
407 TRANSFER_BEGIN,
408 TRANSFER_READY,
409 TRANSFER_RELEASED,
410 TRANSFER_PASSTHROUGH,
411 TRANSFER_MBEGIN,
412 TRANSFER_MREADY,
413 TRANSFER_MRELEASED,
414 TRANSFER_MPASSTHROUGH,
415 TRANSFER_MEDIA,
416 TRANSFER_MEDIAPASS
419 struct iax2_registry {
420 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
421 char username[80];
422 char secret[80]; /*!< Password or key name in []'s */
423 char random[80];
424 int expire; /*!< Sched ID of expiration */
425 int refresh; /*!< How often to refresh */
426 enum iax_reg_state regstate;
427 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
428 int callno; /*!< Associated call number if applicable */
429 struct sockaddr_in us; /*!< Who the server thinks we are */
430 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
431 AST_LIST_ENTRY(iax2_registry) entry;
434 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
436 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
437 #define MIN_RETRY_TIME 100
438 #define MAX_RETRY_TIME 10000
440 #define MAX_JITTER_BUFFER 50
441 #define MIN_JITTER_BUFFER 10
443 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
444 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
446 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
448 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
449 #define TS_GAP_FOR_JB_RESYNC 5000
451 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
452 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
453 static int iaxdynamicthreadcount = 0;
454 static int iaxactivethreadcount = 0;
456 struct iax_rr {
457 int jitter;
458 int losspct;
459 int losscnt;
460 int packets;
461 int delay;
462 int dropped;
463 int ooo;
466 struct chan_iax2_pvt {
467 /*! Socket to send/receive on for this call */
468 int sockfd;
469 /*! Last received voice format */
470 int voiceformat;
471 /*! Last received video format */
472 int videoformat;
473 /*! Last sent voice format */
474 int svoiceformat;
475 /*! Last sent video format */
476 int svideoformat;
477 /*! What we are capable of sending */
478 int capability;
479 /*! Last received timestamp */
480 unsigned int last;
481 /*! Last sent timestamp - never send the same timestamp twice in a single call */
482 unsigned int lastsent;
483 /*! Timestamp of the last video frame sent */
484 unsigned int lastvsent;
485 /*! Next outgoing timestamp if everything is good */
486 unsigned int nextpred;
487 /*! True if the last voice we transmitted was not silence/CNG */
488 int notsilenttx;
489 /*! Ping time */
490 unsigned int pingtime;
491 /*! Max time for initial response */
492 int maxtime;
493 /*! Peer Address */
494 struct sockaddr_in addr;
495 /*! Actual used codec preferences */
496 struct ast_codec_pref prefs;
497 /*! Requested codec preferences */
498 struct ast_codec_pref rprefs;
499 /*! Our call number */
500 unsigned short callno;
501 /*! Peer callno */
502 unsigned short peercallno;
503 /*! Negotiated format, this is only used to remember what format was
504 chosen for an unauthenticated call so that the channel can get
505 created later using the right format */
506 int chosenformat;
507 /*! Peer selected format */
508 int peerformat;
509 /*! Peer capability */
510 int peercapability;
511 /*! timeval that we base our transmission on */
512 struct timeval offset;
513 /*! timeval that we base our delivery on */
514 struct timeval rxcore;
515 /*! The jitterbuffer */
516 jitterbuf *jb;
517 /*! active jb read scheduler id */
518 int jbid;
519 /*! LAG */
520 int lag;
521 /*! Error, as discovered by the manager */
522 int error;
523 /*! Owner if we have one */
524 struct ast_channel *owner;
525 /*! What's our state? */
526 struct ast_flags state;
527 /*! Expiry (optional) */
528 int expiry;
529 /*! Next outgoing sequence number */
530 unsigned char oseqno;
531 /*! Next sequence number they have not yet acknowledged */
532 unsigned char rseqno;
533 /*! Next incoming sequence number */
534 unsigned char iseqno;
535 /*! Last incoming sequence number we have acknowledged */
536 unsigned char aseqno;
538 AST_DECLARE_STRING_FIELDS(
539 /*! Peer name */
540 AST_STRING_FIELD(peer);
541 /*! Default Context */
542 AST_STRING_FIELD(context);
543 /*! Caller ID if available */
544 AST_STRING_FIELD(cid_num);
545 AST_STRING_FIELD(cid_name);
546 /*! Hidden Caller ID (i.e. ANI) if appropriate */
547 AST_STRING_FIELD(ani);
548 /*! DNID */
549 AST_STRING_FIELD(dnid);
550 /*! RDNIS */
551 AST_STRING_FIELD(rdnis);
552 /*! Requested Extension */
553 AST_STRING_FIELD(exten);
554 /*! Expected Username */
555 AST_STRING_FIELD(username);
556 /*! Expected Secret */
557 AST_STRING_FIELD(secret);
558 /*! MD5 challenge */
559 AST_STRING_FIELD(challenge);
560 /*! Public keys permitted keys for incoming authentication */
561 AST_STRING_FIELD(inkeys);
562 /*! Private key for outgoing authentication */
563 AST_STRING_FIELD(outkey);
564 /*! Preferred language */
565 AST_STRING_FIELD(language);
566 /*! Hostname/peername for naming purposes */
567 AST_STRING_FIELD(host);
569 AST_STRING_FIELD(dproot);
570 AST_STRING_FIELD(accountcode);
571 AST_STRING_FIELD(mohinterpret);
572 AST_STRING_FIELD(mohsuggest);
575 /*! permitted authentication methods */
576 int authmethods;
577 /*! permitted encryption methods */
578 int encmethods;
579 /*! Encryption AES-128 Key */
580 aes_encrypt_ctx ecx;
581 /*! Decryption AES-128 Key */
582 aes_decrypt_ctx dcx;
583 /*! 32 bytes of semi-random data */
584 unsigned char semirand[32];
585 /*! Associated registry */
586 struct iax2_registry *reg;
587 /*! Associated peer for poking */
588 struct iax2_peer *peerpoke;
589 /*! IAX_ flags */
590 unsigned int flags;
591 int adsi;
593 /*! Transferring status */
594 enum iax_transfer_state transferring;
595 /*! Transfer identifier */
596 int transferid;
597 /*! Who we are IAX transfering to */
598 struct sockaddr_in transfer;
599 /*! What's the new call number for the transfer */
600 unsigned short transfercallno;
601 /*! Transfer decrypt AES-128 Key */
602 aes_encrypt_ctx tdcx;
604 /*! Status of knowledge of peer ADSI capability */
605 int peeradsicpe;
607 /*! Who we are bridged to */
608 unsigned short bridgecallno;
610 int pingid; /*!< Transmit PING request */
611 int lagid; /*!< Retransmit lag request */
612 int autoid; /*!< Auto hangup for Dialplan requestor */
613 int authid; /*!< Authentication rejection ID */
614 int authfail; /*!< Reason to report failure */
615 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
616 int calling_ton;
617 int calling_tns;
618 int calling_pres;
619 int amaflags;
620 struct iax2_dpcache *dpentries;
621 struct ast_variable *vars;
622 /*! last received remote rr */
623 struct iax_rr remote_rr;
624 /*! Current base time: (just for stats) */
625 int min;
626 /*! Dropped frame count: (just for stats) */
627 int frames_dropped;
628 /*! received frame count: (just for stats) */
629 int frames_received;
632 static struct ast_iax2_queue {
633 AST_LIST_HEAD(, iax_frame) queue;
634 int count;
635 } iaxq;
638 * This module will get much higher performance when doing a lot of
639 * user and peer lookups if the number of buckets is increased from 1.
640 * However, to maintain old behavior for Asterisk 1.4, these are set to
641 * 1 by default. When using multiple buckets, search order through these
642 * containers is considered random, so you will not be able to depend on
643 * the order the entires are specified in iax.conf for matching order. */
644 #ifdef LOW_MEMORY
645 #define MAX_PEER_BUCKETS 1
646 /* #define MAX_PEER_BUCKETS 17 */
647 #else
648 #define MAX_PEER_BUCKETS 1
649 /* #define MAX_PEER_BUCKETS 563 */
650 #endif
651 static struct ao2_container *peers;
653 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
654 static struct ao2_container *users;
656 static struct ast_firmware_list {
657 struct iax_firmware *wares;
658 ast_mutex_t lock;
659 } waresl;
661 /*! Extension exists */
662 #define CACHE_FLAG_EXISTS (1 << 0)
663 /*! Extension is nonexistent */
664 #define CACHE_FLAG_NONEXISTENT (1 << 1)
665 /*! Extension can exist */
666 #define CACHE_FLAG_CANEXIST (1 << 2)
667 /*! Waiting to hear back response */
668 #define CACHE_FLAG_PENDING (1 << 3)
669 /*! Timed out */
670 #define CACHE_FLAG_TIMEOUT (1 << 4)
671 /*! Request transmitted */
672 #define CACHE_FLAG_TRANSMITTED (1 << 5)
673 /*! Timeout */
674 #define CACHE_FLAG_UNKNOWN (1 << 6)
675 /*! Matchmore */
676 #define CACHE_FLAG_MATCHMORE (1 << 7)
678 static struct iax2_dpcache {
679 char peercontext[AST_MAX_CONTEXT];
680 char exten[AST_MAX_EXTENSION];
681 struct timeval orig;
682 struct timeval expiry;
683 int flags;
684 unsigned short callno;
685 int waiters[256];
686 struct iax2_dpcache *next;
687 struct iax2_dpcache *peer; /*!< For linking in peers */
688 } *dpcache;
690 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
692 static void reg_source_db(struct iax2_peer *p);
693 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
695 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
697 #define IAX_IOSTATE_IDLE 0
698 #define IAX_IOSTATE_READY 1
699 #define IAX_IOSTATE_PROCESSING 2
700 #define IAX_IOSTATE_SCHEDREADY 3
702 #define IAX_TYPE_POOL 1
703 #define IAX_TYPE_DYNAMIC 2
705 struct iax2_pkt_buf {
706 AST_LIST_ENTRY(iax2_pkt_buf) entry;
707 size_t len;
708 unsigned char buf[1];
711 struct iax2_thread {
712 AST_LIST_ENTRY(iax2_thread) list;
713 int type;
714 int iostate;
715 #ifdef SCHED_MULTITHREADED
716 void (*schedfunc)(const void *);
717 const void *scheddata;
718 #endif
719 #ifdef DEBUG_SCHED_MULTITHREAD
720 char curfunc[80];
721 #endif
722 int actions;
723 pthread_t threadid;
724 int threadnum;
725 struct sockaddr_in iosin;
726 unsigned char readbuf[4096];
727 unsigned char *buf;
728 ssize_t buf_len;
729 size_t buf_size;
730 int iofd;
731 time_t checktime;
732 ast_mutex_t lock;
733 ast_cond_t cond;
734 unsigned int ready_for_signal:1;
735 /*! if this thread is processing a full frame,
736 some information about that frame will be stored
737 here, so we can avoid dispatching any more full
738 frames for that callno to other threads */
739 struct {
740 unsigned short callno;
741 struct sockaddr_in sin;
742 unsigned char type;
743 unsigned char csub;
744 } ffinfo;
745 /*! Queued up full frames for processing. If more full frames arrive for
746 * a call which this thread is already processing a full frame for, they
747 * are queued up here. */
748 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
751 /* Thread lists */
752 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
753 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
754 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
756 static void *iax2_process_thread(void *data);
758 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
760 ast_mutex_lock(lock);
761 ast_cond_signal(cond);
762 ast_mutex_unlock(lock);
765 static void iax_debug_output(const char *data)
767 if (iaxdebug)
768 ast_verbose("%s", data);
771 static void iax_error_output(const char *data)
773 ast_log(LOG_WARNING, "%s", data);
776 static void jb_error_output(const char *fmt, ...)
778 va_list args;
779 char buf[1024];
781 va_start(args, fmt);
782 vsnprintf(buf, 1024, fmt, args);
783 va_end(args);
785 ast_log(LOG_ERROR, buf);
788 static void jb_warning_output(const char *fmt, ...)
790 va_list args;
791 char buf[1024];
793 va_start(args, fmt);
794 vsnprintf(buf, 1024, fmt, args);
795 va_end(args);
797 ast_log(LOG_WARNING, buf);
800 static void jb_debug_output(const char *fmt, ...)
802 va_list args;
803 char buf[1024];
805 va_start(args, fmt);
806 vsnprintf(buf, 1024, fmt, args);
807 va_end(args);
809 ast_verbose(buf);
812 /* XXX We probably should use a mutex when working with this XXX */
813 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
814 static ast_mutex_t iaxsl[IAX_MAX_CALLS];
815 static struct timeval lastused[IAX_MAX_CALLS];
817 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
818 static int expire_registry(const void *data);
819 static int iax2_answer(struct ast_channel *c);
820 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
821 static int iax2_devicestate(void *data);
822 static int iax2_digit_begin(struct ast_channel *c, char digit);
823 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
824 static int iax2_do_register(struct iax2_registry *reg);
825 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
826 static int iax2_hangup(struct ast_channel *c);
827 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
828 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
829 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
830 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
831 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
832 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
833 static int iax2_sendtext(struct ast_channel *c, const char *text);
834 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
835 static int iax2_transfer(struct ast_channel *c, const char *dest);
836 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
837 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
838 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
839 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
840 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
841 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
842 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
843 static struct ast_frame *iax2_read(struct ast_channel *c);
844 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
845 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
846 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
847 static void prune_peers(void);
849 static const struct ast_channel_tech iax2_tech = {
850 .type = "IAX2",
851 .description = tdesc,
852 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
853 .properties = AST_CHAN_TP_WANTSJITTER,
854 .requester = iax2_request,
855 .devicestate = iax2_devicestate,
856 .send_digit_begin = iax2_digit_begin,
857 .send_digit_end = iax2_digit_end,
858 .send_text = iax2_sendtext,
859 .send_image = iax2_sendimage,
860 .send_html = iax2_sendhtml,
861 .call = iax2_call,
862 .hangup = iax2_hangup,
863 .answer = iax2_answer,
864 .read = iax2_read,
865 .write = iax2_write,
866 .write_video = iax2_write,
867 .indicate = iax2_indicate,
868 .setoption = iax2_setoption,
869 .bridge = iax2_bridge,
870 .transfer = iax2_transfer,
871 .fixup = iax2_fixup,
874 /* WARNING: insert_idle_thread should only ever be called within the
875 * context of an iax2_process_thread() thread.
877 static void insert_idle_thread(struct iax2_thread *thread)
879 if (thread->type == IAX_TYPE_DYNAMIC) {
880 AST_LIST_LOCK(&dynamic_list);
881 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
882 AST_LIST_UNLOCK(&dynamic_list);
883 } else {
884 AST_LIST_LOCK(&idle_list);
885 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
886 AST_LIST_UNLOCK(&idle_list);
889 return;
892 static struct iax2_thread *find_idle_thread(void)
894 pthread_attr_t attr;
895 struct iax2_thread *thread = NULL;
897 /* Pop the head of the list off */
898 AST_LIST_LOCK(&idle_list);
899 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
900 AST_LIST_UNLOCK(&idle_list);
902 /* If no idle thread is available from the regular list, try dynamic */
903 if (thread == NULL) {
904 AST_LIST_LOCK(&dynamic_list);
905 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
906 /* Make sure we absolutely have a thread... if not, try to make one if allowed */
907 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
908 /* We need to MAKE a thread! */
909 if ((thread = ast_calloc(1, sizeof(*thread)))) {
910 thread->threadnum = iaxdynamicthreadcount;
911 thread->type = IAX_TYPE_DYNAMIC;
912 ast_mutex_init(&thread->lock);
913 ast_cond_init(&thread->cond, NULL);
914 pthread_attr_init(&attr);
915 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
916 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
917 free(thread);
918 thread = NULL;
919 } else {
920 /* All went well and the thread is up, so increment our count */
921 iaxdynamicthreadcount++;
923 /* Wait for the thread to be ready before returning it to the caller */
924 while (!thread->ready_for_signal)
925 usleep(1);
929 AST_LIST_UNLOCK(&dynamic_list);
932 /* this thread is not processing a full frame (since it is idle),
933 so ensure that the field for the full frame call number is empty */
934 if (thread)
935 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
937 return thread;
940 #ifdef SCHED_MULTITHREADED
941 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
943 struct iax2_thread *thread = NULL;
944 static time_t lasterror;
945 static time_t t;
947 thread = find_idle_thread();
949 if (thread != NULL) {
950 thread->schedfunc = func;
951 thread->scheddata = data;
952 thread->iostate = IAX_IOSTATE_SCHEDREADY;
953 #ifdef DEBUG_SCHED_MULTITHREAD
954 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
955 #endif
956 signal_condition(&thread->lock, &thread->cond);
957 return 0;
959 time(&t);
960 if (t != lasterror && option_debug)
961 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for scheduling!\n");
962 lasterror = t;
964 return -1;
966 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
967 #endif
969 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
971 int res;
973 res = ast_sched_add(con, when, callback, data);
974 signal_condition(&sched_lock, &sched_cond);
976 return res;
979 static int send_ping(const void *data);
981 static void __send_ping(const void *data)
983 int callno = (long)data;
984 ast_mutex_lock(&iaxsl[callno]);
985 if (iaxs[callno] && iaxs[callno]->pingid != -1) {
986 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
987 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
989 ast_mutex_unlock(&iaxsl[callno]);
992 static int send_ping(const void *data)
994 #ifdef SCHED_MULTITHREADED
995 if (schedule_action(__send_ping, data))
996 #endif
997 __send_ping(data);
998 return 0;
1001 static int get_encrypt_methods(const char *s)
1003 int e;
1004 if (!strcasecmp(s, "aes128"))
1005 e = IAX_ENCRYPT_AES128;
1006 else if (ast_true(s))
1007 e = IAX_ENCRYPT_AES128;
1008 else
1009 e = 0;
1010 return e;
1013 static int send_lagrq(const void *data);
1015 static void __send_lagrq(const void *data)
1017 int callno = (long)data;
1018 /* Ping only if it's real not if it's bridged */
1019 ast_mutex_lock(&iaxsl[callno]);
1020 if (iaxs[callno] && iaxs[callno]->lagid > -1) {
1021 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1022 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1024 ast_mutex_unlock(&iaxsl[callno]);
1027 static int send_lagrq(const void *data)
1029 #ifdef SCHED_MULTITHREADED
1030 if (schedule_action(__send_lagrq, data))
1031 #endif
1032 __send_lagrq(data);
1033 return 0;
1036 static unsigned char compress_subclass(int subclass)
1038 int x;
1039 int power=-1;
1040 /* If it's 128 or smaller, just return it */
1041 if (subclass < IAX_FLAG_SC_LOG)
1042 return subclass;
1043 /* Otherwise find its power */
1044 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1045 if (subclass & (1 << x)) {
1046 if (power > -1) {
1047 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1048 return 0;
1049 } else
1050 power = x;
1053 return power | IAX_FLAG_SC_LOG;
1056 static int uncompress_subclass(unsigned char csub)
1058 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1059 if (csub & IAX_FLAG_SC_LOG) {
1060 /* special case for 'compressed' -1 */
1061 if (csub == 0xff)
1062 return -1;
1063 else
1064 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1066 else
1067 return csub;
1071 * \note The only member of the peer passed here guaranteed to be set is the name field
1073 static int peer_hash_cb(const void *obj, const int flags)
1075 const struct iax2_peer *peer = obj;
1077 return ast_str_hash(peer->name);
1081 * \note The only member of the peer passed here guaranteed to be set is the name field
1083 static int peer_cmp_cb(void *obj, void *arg, int flags)
1085 struct iax2_peer *peer = obj, *peer2 = arg;
1087 return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1091 * \note The only member of the user passed here guaranteed to be set is the name field
1093 static int user_hash_cb(const void *obj, const int flags)
1095 const struct iax2_user *user = obj;
1097 return ast_str_hash(user->name);
1101 * \note The only member of the user passed here guaranteed to be set is the name field
1103 static int user_cmp_cb(void *obj, void *arg, int flags)
1105 struct iax2_user *user = obj, *user2 = arg;
1107 return !strcasecmp(user->name, user2->name) ? CMP_MATCH : 0;
1111 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1112 * so do not call it with a pvt lock held.
1114 static struct iax2_peer *find_peer(const char *name, int realtime)
1116 struct iax2_peer *peer = NULL;
1117 struct iax2_peer tmp_peer = {
1118 .name = name,
1121 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1123 /* Now go for realtime if applicable */
1124 if(!peer && realtime)
1125 peer = realtime_peer(name, NULL);
1127 return peer;
1130 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1132 ao2_ref(peer, +1);
1133 return peer;
1136 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1138 ao2_ref(peer, -1);
1139 return NULL;
1142 static inline struct iax2_user *user_ref(struct iax2_user *user)
1144 ao2_ref(user, +1);
1145 return user;
1148 static inline struct iax2_user *user_unref(struct iax2_user *user)
1150 ao2_ref(user, -1);
1151 return NULL;
1154 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1156 struct iax2_peer *peer = NULL;
1157 int res = 0;
1158 struct ao2_iterator i;
1160 i = ao2_iterator_init(peers, 0);
1161 while ((peer = ao2_iterator_next(&i))) {
1162 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1163 (peer->addr.sin_port == sin.sin_port)) {
1164 ast_copy_string(host, peer->name, len);
1165 peer_unref(peer);
1166 res = 1;
1167 break;
1169 peer_unref(peer);
1172 if (!peer) {
1173 peer = realtime_peer(NULL, &sin);
1174 if (peer) {
1175 ast_copy_string(host, peer->name, len);
1176 peer_unref(peer);
1177 res = 1;
1181 return res;
1184 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1186 struct chan_iax2_pvt *tmp;
1187 jb_conf jbconf;
1189 if (!(tmp = ast_calloc(1, sizeof(*tmp))))
1190 return NULL;
1192 if (ast_string_field_init(tmp, 32)) {
1193 free(tmp);
1194 tmp = NULL;
1195 return NULL;
1198 tmp->prefs = prefs;
1199 tmp->callno = 0;
1200 tmp->peercallno = 0;
1201 tmp->transfercallno = 0;
1202 tmp->bridgecallno = 0;
1203 tmp->pingid = -1;
1204 tmp->lagid = -1;
1205 tmp->autoid = -1;
1206 tmp->authid = -1;
1207 tmp->initid = -1;
1209 ast_string_field_set(tmp,exten, "s");
1210 ast_string_field_set(tmp,host, host);
1212 tmp->jb = jb_new();
1213 tmp->jbid = -1;
1214 jbconf.max_jitterbuf = maxjitterbuffer;
1215 jbconf.resync_threshold = resyncthreshold;
1216 jbconf.max_contig_interp = maxjitterinterps;
1217 jb_setconf(tmp->jb,&jbconf);
1219 return tmp;
1222 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1224 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1225 if (new) {
1226 size_t afdatalen = new->afdatalen;
1227 memcpy(new, fr, sizeof(*new));
1228 iax_frame_wrap(new, &fr->af);
1229 new->afdatalen = afdatalen;
1230 new->data = NULL;
1231 new->datalen = 0;
1232 new->direction = DIRECTION_INGRESS;
1233 new->retrans = -1;
1235 return new;
1238 #define NEW_PREVENT 0
1239 #define NEW_ALLOW 1
1240 #define NEW_FORCE 2
1242 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur)
1244 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1245 (cur->addr.sin_port == sin->sin_port)) {
1246 /* This is the main host */
1247 if ((cur->peercallno == callno) ||
1248 ((dcallno == cur->callno) && !cur->peercallno)) {
1249 /* That's us. Be sure we keep track of the peer call number */
1250 return 1;
1253 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1254 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1255 /* We're transferring */
1256 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
1257 return 1;
1259 return 0;
1262 static void update_max_trunk(void)
1264 int max = TRUNK_CALL_START;
1265 int x;
1266 /* XXX Prolly don't need locks here XXX */
1267 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1268 if (iaxs[x])
1269 max = x + 1;
1271 maxtrunkcall = max;
1272 if (option_debug && iaxdebug)
1273 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
1276 static void update_max_nontrunk(void)
1278 int max = 1;
1279 int x;
1280 /* XXX Prolly don't need locks here XXX */
1281 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1282 if (iaxs[x])
1283 max = x + 1;
1285 maxnontrunkcall = max;
1286 if (option_debug && iaxdebug)
1287 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
1290 static int make_trunk(unsigned short callno, int locked)
1292 int x;
1293 int res= 0;
1294 struct timeval now;
1295 if (iaxs[callno]->oseqno) {
1296 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1297 return -1;
1299 if (callno & TRUNK_CALL_START) {
1300 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1301 return -1;
1303 gettimeofday(&now, NULL);
1304 for (x=TRUNK_CALL_START;x<IAX_MAX_CALLS - 1; x++) {
1305 ast_mutex_lock(&iaxsl[x]);
1306 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1307 iaxs[x] = iaxs[callno];
1308 iaxs[x]->callno = x;
1309 iaxs[callno] = NULL;
1310 /* Update the two timers that should have been started */
1311 AST_SCHED_DEL(sched, iaxs[x]->pingid);
1312 AST_SCHED_DEL(sched, iaxs[x]->lagid);
1313 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1314 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1315 if (locked)
1316 ast_mutex_unlock(&iaxsl[callno]);
1317 res = x;
1318 if (!locked)
1319 ast_mutex_unlock(&iaxsl[x]);
1320 break;
1322 ast_mutex_unlock(&iaxsl[x]);
1324 if (x >= IAX_MAX_CALLS - 1) {
1325 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1326 return -1;
1328 if (option_debug)
1329 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
1330 /* We move this call from a non-trunked to a trunked call */
1331 update_max_trunk();
1332 update_max_nontrunk();
1333 return res;
1337 * \note Calling this function while holding another pvt lock can cause a deadlock.
1339 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked)
1341 int res = 0;
1342 int x;
1343 struct timeval now;
1344 char host[80];
1346 if (new <= NEW_ALLOW) {
1347 /* Look for an existing connection first */
1348 for (x=1;(res < 1) && (x<maxnontrunkcall);x++) {
1349 ast_mutex_lock(&iaxsl[x]);
1350 if (iaxs[x]) {
1351 /* Look for an exact match */
1352 if (match(sin, callno, dcallno, iaxs[x])) {
1353 res = x;
1356 ast_mutex_unlock(&iaxsl[x]);
1358 for (x=TRUNK_CALL_START;(res < 1) && (x<maxtrunkcall);x++) {
1359 ast_mutex_lock(&iaxsl[x]);
1360 if (iaxs[x]) {
1361 /* Look for an exact match */
1362 if (match(sin, callno, dcallno, iaxs[x])) {
1363 res = x;
1366 ast_mutex_unlock(&iaxsl[x]);
1369 if ((res < 1) && (new >= NEW_ALLOW)) {
1370 /* It may seem odd that we look through the peer list for a name for
1371 * this *incoming* call. Well, it is weird. However, users don't
1372 * have an IP address/port number that we can match against. So,
1373 * this is just checking for a peer that has that IP/port and
1374 * assuming that we have a user of the same name. This isn't always
1375 * correct, but it will be changed if needed after authentication. */
1376 if (!iax2_getpeername(*sin, host, sizeof(host)))
1377 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1378 gettimeofday(&now, NULL);
1379 for (x=1;x<TRUNK_CALL_START;x++) {
1380 /* Find first unused call number that hasn't been used in a while */
1381 ast_mutex_lock(&iaxsl[x]);
1382 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) break;
1383 ast_mutex_unlock(&iaxsl[x]);
1385 /* We've still got lock held if we found a spot */
1386 if (x >= TRUNK_CALL_START) {
1387 ast_log(LOG_WARNING, "No more space\n");
1388 return 0;
1390 iaxs[x] = new_iax(sin, host);
1391 update_max_nontrunk();
1392 if (iaxs[x]) {
1393 if (option_debug && iaxdebug)
1394 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
1395 iaxs[x]->sockfd = sockfd;
1396 iaxs[x]->addr.sin_port = sin->sin_port;
1397 iaxs[x]->addr.sin_family = sin->sin_family;
1398 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1399 iaxs[x]->peercallno = callno;
1400 iaxs[x]->callno = x;
1401 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1402 iaxs[x]->expiry = min_reg_expire;
1403 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1404 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1405 iaxs[x]->amaflags = amaflags;
1406 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
1408 ast_string_field_set(iaxs[x], accountcode, accountcode);
1409 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1410 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1411 } else {
1412 ast_log(LOG_WARNING, "Out of resources\n");
1413 ast_mutex_unlock(&iaxsl[x]);
1414 return 0;
1416 if (!return_locked)
1417 ast_mutex_unlock(&iaxsl[x]);
1418 res = x;
1420 return res;
1423 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd) {
1425 return __find_callno(callno, dcallno, sin, new, sockfd, 0);
1428 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd) {
1430 return __find_callno(callno, dcallno, sin, new, sockfd, 1);
1433 static void iax2_frame_free(struct iax_frame *fr)
1435 AST_SCHED_DEL(sched, fr->retrans);
1436 iax_frame_free(fr);
1440 * \brief Queue a frame to a call's owning asterisk channel
1442 * \pre This function assumes that iaxsl[callno] is locked when called.
1444 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1445 * was valid before calling it, it may no longer be valid after calling it.
1446 * This function may unlock and lock the mutex associated with this callno,
1447 * meaning that another thread may grab it and destroy the call.
1449 static int iax2_queue_frame(int callno, struct ast_frame *f)
1451 for (;;) {
1452 if (iaxs[callno] && iaxs[callno]->owner) {
1453 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1454 /* Avoid deadlock by pausing and trying again */
1455 ast_mutex_unlock(&iaxsl[callno]);
1456 usleep(1);
1457 ast_mutex_lock(&iaxsl[callno]);
1458 } else {
1459 ast_queue_frame(iaxs[callno]->owner, f);
1460 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1461 break;
1463 } else
1464 break;
1466 return 0;
1470 * \brief Queue a hangup frame on the ast_channel owner
1472 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1473 * is active for the given call number.
1475 * \pre Assumes lock for callno is already held.
1477 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1478 * was valid before calling it, it may no longer be valid after calling it.
1479 * This function may unlock and lock the mutex associated with this callno,
1480 * meaning that another thread may grab it and destroy the call.
1482 static int iax2_queue_hangup(int callno)
1484 for (;;) {
1485 if (iaxs[callno] && iaxs[callno]->owner) {
1486 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1487 /* Avoid deadlock by pausing and trying again */
1488 ast_mutex_unlock(&iaxsl[callno]);
1489 usleep(1);
1490 ast_mutex_lock(&iaxsl[callno]);
1491 } else {
1492 ast_queue_hangup(iaxs[callno]->owner);
1493 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1494 break;
1496 } else
1497 break;
1499 return 0;
1503 * \brief Queue a control frame on the ast_channel owner
1505 * This function queues a control frame on the owner of the IAX2 pvt struct that
1506 * is active for the given call number.
1508 * \pre Assumes lock for callno is already held.
1510 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1511 * was valid before calling it, it may no longer be valid after calling it.
1512 * This function may unlock and lock the mutex associated with this callno,
1513 * meaning that another thread may grab it and destroy the call.
1515 static int iax2_queue_control_data(int callno,
1516 enum ast_control_frame_type control, const void *data, size_t datalen)
1518 for (;;) {
1519 if (iaxs[callno] && iaxs[callno]->owner) {
1520 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
1521 /* Avoid deadlock by pausing and trying again */
1522 ast_mutex_unlock(&iaxsl[callno]);
1523 usleep(1);
1524 ast_mutex_lock(&iaxsl[callno]);
1525 } else {
1526 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1527 ast_mutex_unlock(&iaxs[callno]->owner->lock);
1528 break;
1530 } else
1531 break;
1533 return 0;
1535 static void destroy_firmware(struct iax_firmware *cur)
1537 /* Close firmware */
1538 if (cur->fwh) {
1539 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1541 close(cur->fd);
1542 free(cur);
1545 static int try_firmware(char *s)
1547 struct stat stbuf;
1548 struct iax_firmware *cur;
1549 int ifd;
1550 int fd;
1551 int res;
1553 struct ast_iax2_firmware_header *fwh, fwh2;
1554 struct MD5Context md5;
1555 unsigned char sum[16];
1556 unsigned char buf[1024];
1557 int len, chunk;
1558 char *s2;
1559 char *last;
1560 s2 = alloca(strlen(s) + 100);
1561 if (!s2) {
1562 ast_log(LOG_WARNING, "Alloca failed!\n");
1563 return -1;
1565 last = strrchr(s, '/');
1566 if (last)
1567 last++;
1568 else
1569 last = s;
1570 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1571 res = stat(s, &stbuf);
1572 if (res < 0) {
1573 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1574 return -1;
1576 /* Make sure it's not a directory */
1577 if (S_ISDIR(stbuf.st_mode))
1578 return -1;
1579 ifd = open(s, O_RDONLY);
1580 if (ifd < 0) {
1581 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1582 return -1;
1584 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
1585 if (fd < 0) {
1586 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1587 close(ifd);
1588 return -1;
1590 /* Unlink our newly created file */
1591 unlink(s2);
1593 /* Now copy the firmware into it */
1594 len = stbuf.st_size;
1595 while(len) {
1596 chunk = len;
1597 if (chunk > sizeof(buf))
1598 chunk = sizeof(buf);
1599 res = read(ifd, buf, chunk);
1600 if (res != chunk) {
1601 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1602 close(ifd);
1603 close(fd);
1604 return -1;
1606 res = write(fd, buf, chunk);
1607 if (res != chunk) {
1608 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1609 close(ifd);
1610 close(fd);
1611 return -1;
1613 len -= chunk;
1615 close(ifd);
1616 /* Return to the beginning */
1617 lseek(fd, 0, SEEK_SET);
1618 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1619 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1620 close(fd);
1621 return -1;
1623 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
1624 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
1625 close(fd);
1626 return -1;
1628 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
1629 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
1630 close(fd);
1631 return -1;
1633 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
1634 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
1635 close(fd);
1636 return -1;
1638 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
1639 if (fwh == (void *) -1) {
1640 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
1641 close(fd);
1642 return -1;
1644 MD5Init(&md5);
1645 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
1646 MD5Final(sum, &md5);
1647 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
1648 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
1649 munmap((void*)fwh, stbuf.st_size);
1650 close(fd);
1651 return -1;
1653 cur = waresl.wares;
1654 while(cur) {
1655 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
1656 /* Found a candidate */
1657 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
1658 /* The version we have on loaded is older, load this one instead */
1659 break;
1660 /* This version is no newer than what we have. Don't worry about it.
1661 We'll consider it a proper load anyhow though */
1662 munmap((void*)fwh, stbuf.st_size);
1663 close(fd);
1664 return 0;
1666 cur = cur->next;
1668 if (!cur) {
1669 /* Allocate a new one and link it */
1670 if ((cur = ast_calloc(1, sizeof(*cur)))) {
1671 cur->fd = -1;
1672 cur->next = waresl.wares;
1673 waresl.wares = cur;
1676 if (cur) {
1677 if (cur->fwh) {
1678 munmap((void*)cur->fwh, cur->mmaplen);
1680 if (cur->fd > -1)
1681 close(cur->fd);
1682 cur->fwh = fwh;
1683 cur->fd = fd;
1684 cur->mmaplen = stbuf.st_size;
1685 cur->dead = 0;
1687 return 0;
1690 static int iax_check_version(char *dev)
1692 int res = 0;
1693 struct iax_firmware *cur;
1694 if (!ast_strlen_zero(dev)) {
1695 ast_mutex_lock(&waresl.lock);
1696 cur = waresl.wares;
1697 while(cur) {
1698 if (!strcmp(dev, (char *)cur->fwh->devname)) {
1699 res = ntohs(cur->fwh->version);
1700 break;
1702 cur = cur->next;
1704 ast_mutex_unlock(&waresl.lock);
1706 return res;
1709 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
1711 int res = -1;
1712 unsigned int bs = desc & 0xff;
1713 unsigned int start = (desc >> 8) & 0xffffff;
1714 unsigned int bytes;
1715 struct iax_firmware *cur;
1716 if (!ast_strlen_zero((char *)dev) && bs) {
1717 start *= bs;
1718 ast_mutex_lock(&waresl.lock);
1719 cur = waresl.wares;
1720 while(cur) {
1721 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
1722 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
1723 if (start < ntohl(cur->fwh->datalen)) {
1724 bytes = ntohl(cur->fwh->datalen) - start;
1725 if (bytes > bs)
1726 bytes = bs;
1727 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
1728 } else {
1729 bytes = 0;
1730 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
1732 if (bytes == bs)
1733 res = 0;
1734 else
1735 res = 1;
1736 break;
1738 cur = cur->next;
1740 ast_mutex_unlock(&waresl.lock);
1742 return res;
1746 static void reload_firmware(int unload)
1748 struct iax_firmware *cur, *curl, *curp;
1749 DIR *fwd;
1750 struct dirent *de;
1751 char dir[256];
1752 char fn[256];
1753 /* Mark all as dead */
1754 ast_mutex_lock(&waresl.lock);
1755 cur = waresl.wares;
1756 while(cur) {
1757 cur->dead = 1;
1758 cur = cur->next;
1761 /* Now that we've freed them, load the new ones */
1762 if (!unload) {
1763 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
1764 fwd = opendir(dir);
1765 if (fwd) {
1766 while((de = readdir(fwd))) {
1767 if (de->d_name[0] != '.') {
1768 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
1769 if (!try_firmware(fn)) {
1770 if (option_verbose > 1)
1771 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
1775 closedir(fwd);
1776 } else
1777 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
1780 /* Clean up leftovers */
1781 cur = waresl.wares;
1782 curp = NULL;
1783 while(cur) {
1784 curl = cur;
1785 cur = cur->next;
1786 if (curl->dead) {
1787 if (curp) {
1788 curp->next = cur;
1789 } else {
1790 waresl.wares = cur;
1792 destroy_firmware(curl);
1793 } else {
1794 curp = cur;
1797 ast_mutex_unlock(&waresl.lock);
1801 * \note This function assumes that iaxsl[callno] is locked when called.
1803 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1804 * was valid before calling it, it may no longer be valid after calling it.
1805 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
1806 * associated with this callno, meaning that another thread may grab it and destroy the call.
1808 static int __do_deliver(void *data)
1810 /* Just deliver the packet by using queueing. This is called by
1811 the IAX thread with the iaxsl lock held. */
1812 struct iax_frame *fr = data;
1813 fr->retrans = -1;
1814 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
1815 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
1816 iax2_queue_frame(fr->callno, &fr->af);
1817 /* Free our iax frame */
1818 iax2_frame_free(fr);
1819 /* And don't run again */
1820 return 0;
1823 static int handle_error(void)
1825 /* XXX Ideally we should figure out why an error occured and then abort those
1826 rather than continuing to try. Unfortunately, the published interface does
1827 not seem to work XXX */
1828 #if 0
1829 struct sockaddr_in *sin;
1830 int res;
1831 struct msghdr m;
1832 struct sock_extended_err e;
1833 m.msg_name = NULL;
1834 m.msg_namelen = 0;
1835 m.msg_iov = NULL;
1836 m.msg_control = &e;
1837 m.msg_controllen = sizeof(e);
1838 m.msg_flags = 0;
1839 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
1840 if (res < 0)
1841 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
1842 else {
1843 if (m.msg_controllen) {
1844 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
1845 if (sin)
1846 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
1847 else
1848 ast_log(LOG_WARNING, "No address detected??\n");
1849 } else {
1850 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
1853 #endif
1854 return 0;
1857 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
1859 int res;
1860 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
1861 sizeof(*sin));
1862 if (res < 0) {
1863 if (option_debug)
1864 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1865 handle_error();
1866 } else
1867 res = 0;
1868 return res;
1871 static int send_packet(struct iax_frame *f)
1873 int res;
1874 int callno = f->callno;
1876 /* Don't send if there was an error, but return error instead */
1877 if (!callno || !iaxs[callno] || iaxs[callno]->error)
1878 return -1;
1880 /* Called with iaxsl held */
1881 if (option_debug > 2 && iaxdebug)
1882 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
1883 if (f->transfer) {
1884 if (iaxdebug)
1885 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
1886 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
1887 sizeof(iaxs[callno]->transfer));
1888 } else {
1889 if (iaxdebug)
1890 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
1891 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
1892 sizeof(iaxs[callno]->addr));
1894 if (res < 0) {
1895 if (option_debug && iaxdebug)
1896 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
1897 handle_error();
1898 } else
1899 res = 0;
1900 return res;
1903 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1905 /* Decrement AUTHREQ count if needed */
1906 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1907 struct iax2_user *user;
1908 struct iax2_user tmp_user = {
1909 .name = pvt->username,
1912 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1913 if (user) {
1914 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1915 user_unref(user);
1918 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1920 /* No more pings or lagrq's */
1921 AST_SCHED_DEL(sched, pvt->pingid);
1922 AST_SCHED_DEL(sched, pvt->lagid);
1923 AST_SCHED_DEL(sched, pvt->autoid);
1924 AST_SCHED_DEL(sched, pvt->authid);
1925 AST_SCHED_DEL(sched, pvt->initid);
1926 AST_SCHED_DEL(sched, pvt->jbid);
1930 * \note Since this function calls iax2_queue_hangup(), the pvt struct
1931 * for the given call number may disappear during its execution.
1933 static int iax2_predestroy(int callno)
1935 struct ast_channel *c;
1936 struct chan_iax2_pvt *pvt = iaxs[callno];
1938 if (!pvt)
1939 return -1;
1940 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
1941 iax2_destroy_helper(pvt);
1942 ast_set_flag(pvt, IAX_ALREADYGONE);
1944 c = pvt->owner;
1945 if (c) {
1946 c->tech_pvt = NULL;
1947 iax2_queue_hangup(callno);
1948 pvt->owner = NULL;
1949 ast_module_unref(ast_module_info->self);
1951 return 0;
1954 static void iax2_destroy(int callno)
1956 struct chan_iax2_pvt *pvt;
1957 struct iax_frame *cur;
1958 struct ast_channel *owner;
1960 retry:
1961 pvt = iaxs[callno];
1962 gettimeofday(&lastused[callno], NULL);
1964 owner = pvt ? pvt->owner : NULL;
1966 if (owner) {
1967 if (ast_mutex_trylock(&owner->lock)) {
1968 ast_log(LOG_NOTICE, "Avoiding IAX destroy deadlock\n");
1969 ast_mutex_unlock(&iaxsl[callno]);
1970 usleep(1);
1971 ast_mutex_lock(&iaxsl[callno]);
1972 goto retry;
1975 if (!owner)
1976 iaxs[callno] = NULL;
1977 if (pvt) {
1978 if (!owner)
1979 pvt->owner = NULL;
1980 iax2_destroy_helper(pvt);
1982 /* Already gone */
1983 ast_set_flag(pvt, IAX_ALREADYGONE);
1985 if (owner) {
1986 /* If there's an owner, prod it to give up */
1987 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
1988 * because we already hold the owner channel lock. */
1989 ast_queue_hangup(owner);
1992 AST_LIST_LOCK(&iaxq.queue);
1993 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
1994 /* Cancel any pending transmissions */
1995 if (cur->callno == pvt->callno)
1996 cur->retries = -1;
1998 AST_LIST_UNLOCK(&iaxq.queue);
2000 if (pvt->reg)
2001 pvt->reg->callno = 0;
2002 if (!owner) {
2003 jb_frame frame;
2004 if (pvt->vars) {
2005 ast_variables_destroy(pvt->vars);
2006 pvt->vars = NULL;
2009 while (jb_getall(pvt->jb, &frame) == JB_OK)
2010 iax2_frame_free(frame.data);
2011 jb_destroy(pvt->jb);
2012 /* gotta free up the stringfields */
2013 ast_string_field_free_memory(pvt);
2014 free(pvt);
2017 if (owner) {
2018 ast_mutex_unlock(&owner->lock);
2020 if (callno & 0x4000)
2021 update_max_trunk();
2024 static int update_packet(struct iax_frame *f)
2026 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2027 struct ast_iax2_full_hdr *fh = f->data;
2028 /* Mark this as a retransmission */
2029 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2030 /* Update iseqno */
2031 f->iseqno = iaxs[f->callno]->iseqno;
2032 fh->iseqno = f->iseqno;
2033 return 0;
2036 static int attempt_transmit(const void *data);
2037 static void __attempt_transmit(const void *data)
2039 /* Attempt to transmit the frame to the remote peer...
2040 Called without iaxsl held. */
2041 struct iax_frame *f = (struct iax_frame *)data;
2042 int freeme=0;
2043 int callno = f->callno;
2044 /* Make sure this call is still active */
2045 if (callno)
2046 ast_mutex_lock(&iaxsl[callno]);
2047 if (callno && iaxs[callno]) {
2048 if ((f->retries < 0) /* Already ACK'd */ ||
2049 (f->retries >= max_retries) /* Too many attempts */) {
2050 /* Record an error if we've transmitted too many times */
2051 if (f->retries >= max_retries) {
2052 if (f->transfer) {
2053 /* Transfer timeout */
2054 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
2055 } else if (f->final) {
2056 if (f->final)
2057 iax2_destroy(callno);
2058 } else {
2059 if (iaxs[callno]->owner)
2060 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2061 iaxs[callno]->error = ETIMEDOUT;
2062 if (iaxs[callno]->owner) {
2063 struct ast_frame fr = { 0, };
2064 /* Hangup the fd */
2065 fr.frametype = AST_FRAME_CONTROL;
2066 fr.subclass = AST_CONTROL_HANGUP;
2067 iax2_queue_frame(callno, &fr); // XXX
2068 /* Remember, owner could disappear */
2069 if (iaxs[callno] && iaxs[callno]->owner)
2070 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2071 } else {
2072 if (iaxs[callno]->reg) {
2073 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2074 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2075 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2077 iax2_destroy(callno);
2082 freeme++;
2083 } else {
2084 /* Update it if it needs it */
2085 update_packet(f);
2086 /* Attempt transmission */
2087 send_packet(f);
2088 f->retries++;
2089 /* Try again later after 10 times as long */
2090 f->retrytime *= 10;
2091 if (f->retrytime > MAX_RETRY_TIME)
2092 f->retrytime = MAX_RETRY_TIME;
2093 /* Transfer messages max out at one second */
2094 if (f->transfer && (f->retrytime > 1000))
2095 f->retrytime = 1000;
2096 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2098 } else {
2099 /* Make sure it gets freed */
2100 f->retries = -1;
2101 freeme++;
2103 if (callno)
2104 ast_mutex_unlock(&iaxsl[callno]);
2105 /* Do not try again */
2106 if (freeme) {
2107 /* Don't attempt delivery, just remove it from the queue */
2108 AST_LIST_LOCK(&iaxq.queue);
2109 AST_LIST_REMOVE(&iaxq.queue, f, list);
2110 iaxq.count--;
2111 AST_LIST_UNLOCK(&iaxq.queue);
2112 f->retrans = -1;
2113 /* Free the IAX frame */
2114 iax2_frame_free(f);
2118 static int attempt_transmit(const void *data)
2120 #ifdef SCHED_MULTITHREADED
2121 if (schedule_action(__attempt_transmit, data))
2122 #endif
2123 __attempt_transmit(data);
2124 return 0;
2127 static int iax2_prune_realtime(int fd, int argc, char *argv[])
2129 struct iax2_peer *peer;
2131 if (argc != 4)
2132 return RESULT_SHOWUSAGE;
2133 if (!strcmp(argv[3],"all")) {
2134 reload_config();
2135 ast_cli(fd, "OK cache is flushed.\n");
2136 } else if ((peer = find_peer(argv[3], 0))) {
2137 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2138 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2139 expire_registry(peer_ref(peer));
2140 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
2141 } else {
2142 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
2144 peer_unref(peer);
2145 } else {
2146 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
2149 return RESULT_SUCCESS;
2152 static int iax2_test_losspct(int fd, int argc, char *argv[])
2154 if (argc != 4)
2155 return RESULT_SHOWUSAGE;
2157 test_losspct = atoi(argv[3]);
2159 return RESULT_SUCCESS;
2162 #ifdef IAXTESTS
2163 static int iax2_test_late(int fd, int argc, char *argv[])
2165 if (argc != 4)
2166 return RESULT_SHOWUSAGE;
2168 test_late = atoi(argv[3]);
2170 return RESULT_SUCCESS;
2173 static int iax2_test_resync(int fd, int argc, char *argv[])
2175 if (argc != 4)
2176 return RESULT_SHOWUSAGE;
2178 test_resync = atoi(argv[3]);
2180 return RESULT_SUCCESS;
2183 static int iax2_test_jitter(int fd, int argc, char *argv[])
2185 if (argc < 4 || argc > 5)
2186 return RESULT_SHOWUSAGE;
2188 test_jit = atoi(argv[3]);
2189 if (argc == 5)
2190 test_jitpct = atoi(argv[4]);
2192 return RESULT_SUCCESS;
2194 #endif /* IAXTESTS */
2196 /*! \brief peer_status: Report Peer status in character string */
2197 /* returns 1 if peer is online, -1 if unmonitored */
2198 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2200 int res = 0;
2201 if (peer->maxms) {
2202 if (peer->lastms < 0) {
2203 ast_copy_string(status, "UNREACHABLE", statuslen);
2204 } else if (peer->lastms > peer->maxms) {
2205 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2206 res = 1;
2207 } else if (peer->lastms) {
2208 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2209 res = 1;
2210 } else {
2211 ast_copy_string(status, "UNKNOWN", statuslen);
2213 } else {
2214 ast_copy_string(status, "Unmonitored", statuslen);
2215 res = -1;
2217 return res;
2220 /*! \brief Show one peer in detail */
2221 static int iax2_show_peer(int fd, int argc, char *argv[])
2223 char status[30];
2224 char cbuf[256];
2225 struct iax2_peer *peer;
2226 char codec_buf[512];
2227 int x = 0, codec = 0, load_realtime = 0;
2229 if (argc < 4)
2230 return RESULT_SHOWUSAGE;
2232 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
2234 peer = find_peer(argv[3], load_realtime);
2235 if (peer) {
2236 ast_cli(fd,"\n\n");
2237 ast_cli(fd, " * Name : %s\n", peer->name);
2238 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
2239 ast_cli(fd, " Context : %s\n", peer->context);
2240 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
2241 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
2242 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2243 ast_cli(fd, " Expire : %d\n", peer->expire);
2244 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
2245 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2246 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2247 ast_cli(fd, " Username : %s\n", peer->username);
2248 ast_cli(fd, " Codecs : ");
2249 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2250 ast_cli(fd, "%s\n", codec_buf);
2252 ast_cli(fd, " Codec Order : (");
2253 for(x = 0; x < 32 ; x++) {
2254 codec = ast_codec_pref_index(&peer->prefs,x);
2255 if(!codec)
2256 break;
2257 ast_cli(fd, "%s", ast_getformatname(codec));
2258 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2259 ast_cli(fd, "|");
2262 if (!x)
2263 ast_cli(fd, "none");
2264 ast_cli(fd, ")\n");
2266 ast_cli(fd, " Status : ");
2267 peer_status(peer, status, sizeof(status));
2268 ast_cli(fd, "%s\n",status);
2269 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2270 ast_cli(fd,"\n");
2271 peer_unref(peer);
2272 } else {
2273 ast_cli(fd,"Peer %s not found.\n", argv[3]);
2274 ast_cli(fd,"\n");
2277 return RESULT_SUCCESS;
2280 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
2282 int which = 0;
2283 struct iax2_peer *peer;
2284 char *res = NULL;
2285 int wordlen = strlen(word);
2286 struct ao2_iterator i;
2288 /* 0 - iax2; 1 - show; 2 - peer; 3 - <peername> */
2289 if (pos != 3)
2290 return NULL;
2292 i = ao2_iterator_init(peers, 0);
2293 while ((peer = ao2_iterator_next(&i))) {
2294 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2295 res = ast_strdup(peer->name);
2296 peer_unref(peer);
2297 break;
2299 peer_unref(peer);
2302 return res;
2305 static int iax2_show_stats(int fd, int argc, char *argv[])
2307 struct iax_frame *cur;
2308 int cnt = 0, dead=0, final=0;
2310 if (argc != 3)
2311 return RESULT_SHOWUSAGE;
2313 AST_LIST_LOCK(&iaxq.queue);
2314 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
2315 if (cur->retries < 0)
2316 dead++;
2317 if (cur->final)
2318 final++;
2319 cnt++;
2321 AST_LIST_UNLOCK(&iaxq.queue);
2323 ast_cli(fd, " IAX Statistics\n");
2324 ast_cli(fd, "---------------------\n");
2325 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2326 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2328 return RESULT_SUCCESS;
2331 static int iax2_show_cache(int fd, int argc, char *argv[])
2333 struct iax2_dpcache *dp;
2334 char tmp[1024], *pc;
2335 int s;
2336 int x,y;
2337 struct timeval tv;
2338 gettimeofday(&tv, NULL);
2339 ast_mutex_lock(&dpcache_lock);
2340 dp = dpcache;
2341 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2342 while(dp) {
2343 s = dp->expiry.tv_sec - tv.tv_sec;
2344 tmp[0] = '\0';
2345 if (dp->flags & CACHE_FLAG_EXISTS)
2346 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2347 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2348 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2349 if (dp->flags & CACHE_FLAG_CANEXIST)
2350 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2351 if (dp->flags & CACHE_FLAG_PENDING)
2352 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2353 if (dp->flags & CACHE_FLAG_TIMEOUT)
2354 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2355 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2356 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2357 if (dp->flags & CACHE_FLAG_MATCHMORE)
2358 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2359 if (dp->flags & CACHE_FLAG_UNKNOWN)
2360 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2361 /* Trim trailing pipe */
2362 if (!ast_strlen_zero(tmp))
2363 tmp[strlen(tmp) - 1] = '\0';
2364 else
2365 ast_copy_string(tmp, "(none)", sizeof(tmp));
2366 y=0;
2367 pc = strchr(dp->peercontext, '@');
2368 if (!pc)
2369 pc = dp->peercontext;
2370 else
2371 pc++;
2372 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
2373 if (dp->waiters[x] > -1)
2374 y++;
2375 if (s > 0)
2376 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2377 else
2378 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2379 dp = dp->next;
2381 ast_mutex_unlock(&dpcache_lock);
2382 return RESULT_SUCCESS;
2385 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2387 static void unwrap_timestamp(struct iax_frame *fr)
2389 int x;
2391 if ( (fr->ts & 0xFFFF0000) == (iaxs[fr->callno]->last & 0xFFFF0000) ) {
2392 x = fr->ts - iaxs[fr->callno]->last;
2393 if (x < -50000) {
2394 /* Sudden big jump backwards in timestamp:
2395 What likely happened here is that miniframe timestamp has circled but we haven't
2396 gotten the update from the main packet. We'll just pretend that we did, and
2397 update the timestamp appropriately. */
2398 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) + 0x10000) | (fr->ts & 0xFFFF);
2399 if (option_debug && iaxdebug)
2400 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
2402 if (x > 50000) {
2403 /* Sudden apparent big jump forwards in timestamp:
2404 What's likely happened is this is an old miniframe belonging to the previous
2405 top-16-bit timestamp that has turned up out of order.
2406 Adjust the timestamp appropriately. */
2407 fr->ts = ( (iaxs[fr->callno]->last & 0xFFFF0000) - 0x10000) | (fr->ts & 0xFFFF);
2408 if (option_debug && iaxdebug)
2409 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
2414 static int get_from_jb(const void *p);
2416 static void update_jbsched(struct chan_iax2_pvt *pvt)
2418 int when;
2420 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2422 when = jb_next(pvt->jb) - when;
2424 AST_SCHED_DEL(sched, pvt->jbid);
2426 if(when <= 0) {
2427 /* XXX should really just empty until when > 0.. */
2428 when = 1;
2431 pvt->jbid = iax2_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
2434 static void __get_from_jb(const void *p)
2436 int callno = PTR_TO_CALLNO(p);
2437 struct chan_iax2_pvt *pvt = NULL;
2438 struct iax_frame *fr;
2439 jb_frame frame;
2440 int ret;
2441 long now;
2442 long next;
2443 struct timeval tv;
2445 /* Make sure we have a valid private structure before going on */
2446 ast_mutex_lock(&iaxsl[callno]);
2447 pvt = iaxs[callno];
2448 if (!pvt) {
2449 /* No go! */
2450 ast_mutex_unlock(&iaxsl[callno]);
2451 return;
2454 pvt->jbid = -1;
2456 gettimeofday(&tv,NULL);
2457 /* round up a millisecond since ast_sched_runq does; */
2458 /* prevents us from spinning while waiting for our now */
2459 /* to catch up with runq's now */
2460 tv.tv_usec += 1000;
2462 now = ast_tvdiff_ms(tv, pvt->rxcore);
2464 if(now >= (next = jb_next(pvt->jb))) {
2465 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
2466 switch(ret) {
2467 case JB_OK:
2468 fr = frame.data;
2469 __do_deliver(fr);
2470 /* __do_deliver() can cause the call to disappear */
2471 pvt = iaxs[callno];
2472 break;
2473 case JB_INTERP:
2475 struct ast_frame af = { 0, };
2477 /* create an interpolation frame */
2478 af.frametype = AST_FRAME_VOICE;
2479 af.subclass = pvt->voiceformat;
2480 af.samples = frame.ms * 8;
2481 af.src = "IAX2 JB interpolation";
2482 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2483 af.offset = AST_FRIENDLY_OFFSET;
2485 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2486 * which we'd need to malloc, and then it would free it. That seems like a drag */
2487 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2488 iax2_queue_frame(callno, &af);
2489 /* iax2_queue_frame() could cause the call to disappear */
2490 pvt = iaxs[callno];
2493 break;
2494 case JB_DROP:
2495 iax2_frame_free(frame.data);
2496 break;
2497 case JB_NOFRAME:
2498 case JB_EMPTY:
2499 /* do nothing */
2500 break;
2501 default:
2502 /* shouldn't happen */
2503 break;
2506 if (pvt)
2507 update_jbsched(pvt);
2508 ast_mutex_unlock(&iaxsl[callno]);
2511 static int get_from_jb(const void *data)
2513 #ifdef SCHED_MULTITHREADED
2514 if (schedule_action(__get_from_jb, data))
2515 #endif
2516 __get_from_jb(data);
2517 return 0;
2521 * \note This function assumes fr->callno is locked
2523 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2524 * was valid before calling it, it may no longer be valid after calling it.
2526 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
2528 int type, len;
2529 int ret;
2530 int needfree = 0;
2531 struct ast_channel *owner = NULL;
2532 struct ast_channel *bridge = NULL;
2534 /* Attempt to recover wrapped timestamps */
2535 unwrap_timestamp(fr);
2537 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
2538 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
2539 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
2540 else {
2541 #if 0
2542 if (option_debug)
2543 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
2544 #endif
2545 fr->af.delivery = ast_tv(0,0);
2548 type = JB_TYPE_CONTROL;
2549 len = 0;
2551 if(fr->af.frametype == AST_FRAME_VOICE) {
2552 type = JB_TYPE_VOICE;
2553 len = ast_codec_get_samples(&fr->af) / 8;
2554 } else if(fr->af.frametype == AST_FRAME_CNG) {
2555 type = JB_TYPE_SILENCE;
2558 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
2559 if (tsout)
2560 *tsout = fr->ts;
2561 __do_deliver(fr);
2562 return -1;
2565 if ((owner = iaxs[fr->callno]->owner))
2566 bridge = ast_bridged_channel(owner);
2568 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
2569 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
2570 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
2571 jb_frame frame;
2573 /* deliver any frames in the jb */
2574 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
2575 __do_deliver(frame.data);
2576 /* __do_deliver() can make the call disappear */
2577 if (!iaxs[fr->callno])
2578 return -1;
2581 jb_reset(iaxs[fr->callno]->jb);
2583 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
2585 /* deliver this frame now */
2586 if (tsout)
2587 *tsout = fr->ts;
2588 __do_deliver(fr);
2589 return -1;
2592 /* insert into jitterbuffer */
2593 /* TODO: Perhaps we could act immediately if it's not droppable and late */
2594 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
2595 calc_rxstamp(iaxs[fr->callno],fr->ts));
2596 if (ret == JB_DROP) {
2597 needfree++;
2598 } else if (ret == JB_SCHED) {
2599 update_jbsched(iaxs[fr->callno]);
2601 if (tsout)
2602 *tsout = fr->ts;
2603 if (needfree) {
2604 /* Free our iax frame */
2605 iax2_frame_free(fr);
2606 return -1;
2608 return 0;
2611 static int iax2_transmit(struct iax_frame *fr)
2613 /* Lock the queue and place this packet at the end */
2614 /* By setting this to 0, the network thread will send it for us, and
2615 queue retransmission if necessary */
2616 fr->sentyet = 0;
2617 AST_LIST_LOCK(&iaxq.queue);
2618 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
2619 iaxq.count++;
2620 AST_LIST_UNLOCK(&iaxq.queue);
2621 /* Wake up the network and scheduler thread */
2622 if (netthreadid != AST_PTHREADT_NULL)
2623 pthread_kill(netthreadid, SIGURG);
2624 signal_condition(&sched_lock, &sched_cond);
2625 return 0;
2630 static int iax2_digit_begin(struct ast_channel *c, char digit)
2632 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
2635 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
2637 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
2640 static int iax2_sendtext(struct ast_channel *c, const char *text)
2643 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
2644 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
2647 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
2649 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
2652 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
2654 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
2657 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
2659 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
2660 ast_mutex_lock(&iaxsl[callno]);
2661 if (iaxs[callno])
2662 iaxs[callno]->owner = newchan;
2663 else
2664 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
2665 ast_mutex_unlock(&iaxsl[callno]);
2666 return 0;
2670 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
2671 * so do not call this with a pvt lock held.
2673 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
2675 struct ast_variable *var = NULL;
2676 struct ast_variable *tmp;
2677 struct iax2_peer *peer=NULL;
2678 time_t regseconds = 0, nowtime;
2679 int dynamic=0;
2681 if (peername) {
2682 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
2683 if (!var && sin)
2684 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2685 } else if (sin) {
2686 char porta[25];
2687 sprintf(porta, "%d", ntohs(sin->sin_port));
2688 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2689 if (var) {
2690 /* We'll need the peer name in order to build the structure! */
2691 for (tmp = var; tmp; tmp = tmp->next) {
2692 if (!strcasecmp(tmp->name, "name"))
2693 peername = tmp->value;
2697 if (!var && peername) { /* Last ditch effort */
2698 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
2699 /*!\note
2700 * If this one loaded something, then we need to ensure that the host
2701 * field matched. The only reason why we can't have this as a criteria
2702 * is because we only have the IP address and the host field might be
2703 * set as a name (and the reverse PTR might not match).
2705 if (var && sin) {
2706 for (tmp = var; tmp; tmp = tmp->next) {
2707 if (!strcasecmp(tmp->name, "host")) {
2708 struct ast_hostent ahp;
2709 struct hostent *hp;
2710 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2711 /* No match */
2712 ast_variables_destroy(var);
2713 var = NULL;
2715 break;
2720 if (!var)
2721 return NULL;
2723 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
2725 if (!peer) {
2726 ast_variables_destroy(var);
2727 return NULL;
2730 for (tmp = var; tmp; tmp = tmp->next) {
2731 /* Make sure it's not a user only... */
2732 if (!strcasecmp(tmp->name, "type")) {
2733 if (strcasecmp(tmp->value, "friend") &&
2734 strcasecmp(tmp->value, "peer")) {
2735 /* Whoops, we weren't supposed to exist! */
2736 peer = peer_unref(peer);
2737 break;
2739 } else if (!strcasecmp(tmp->name, "regseconds")) {
2740 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
2741 } else if (!strcasecmp(tmp->name, "ipaddr")) {
2742 inet_aton(tmp->value, &(peer->addr.sin_addr));
2743 } else if (!strcasecmp(tmp->name, "port")) {
2744 peer->addr.sin_port = htons(atoi(tmp->value));
2745 } else if (!strcasecmp(tmp->name, "host")) {
2746 if (!strcasecmp(tmp->value, "dynamic"))
2747 dynamic = 1;
2751 ast_variables_destroy(var);
2753 if (!peer)
2754 return NULL;
2756 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2757 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
2758 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
2759 if (peer->expire > -1) {
2760 if (!ast_sched_del(sched, peer->expire)) {
2761 peer->expire = -1;
2762 peer_unref(peer);
2765 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
2766 if (peer->expire == -1)
2767 peer_unref(peer);
2769 ao2_link(peers, peer);
2770 if (ast_test_flag(peer, IAX_DYNAMIC))
2771 reg_source_db(peer);
2772 } else {
2773 ast_set_flag(peer, IAX_TEMPONLY);
2776 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
2777 time(&nowtime);
2778 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
2779 memset(&peer->addr, 0, sizeof(peer->addr));
2780 realtime_update_peer(peer->name, &peer->addr, 0);
2781 if (option_debug)
2782 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
2783 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2785 else {
2786 if (option_debug)
2787 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
2788 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
2792 return peer;
2795 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
2797 struct ast_variable *var;
2798 struct ast_variable *tmp;
2799 struct iax2_user *user=NULL;
2801 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
2802 if (!var)
2803 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
2804 if (!var && sin) {
2805 char porta[6];
2806 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
2807 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2808 if (!var)
2809 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
2811 if (!var) { /* Last ditch effort */
2812 var = ast_load_realtime("iaxusers", "name", username, NULL);
2813 /*!\note
2814 * If this one loaded something, then we need to ensure that the host
2815 * field matched. The only reason why we can't have this as a criteria
2816 * is because we only have the IP address and the host field might be
2817 * set as a name (and the reverse PTR might not match).
2819 if (var) {
2820 for (tmp = var; tmp; tmp = tmp->next) {
2821 if (!strcasecmp(tmp->name, "host")) {
2822 struct ast_hostent ahp;
2823 struct hostent *hp;
2824 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
2825 /* No match */
2826 ast_variables_destroy(var);
2827 var = NULL;
2829 break;
2834 if (!var)
2835 return NULL;
2837 tmp = var;
2838 while(tmp) {
2839 /* Make sure it's not a peer only... */
2840 if (!strcasecmp(tmp->name, "type")) {
2841 if (strcasecmp(tmp->value, "friend") &&
2842 strcasecmp(tmp->value, "user")) {
2843 return NULL;
2846 tmp = tmp->next;
2849 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
2851 ast_variables_destroy(var);
2853 if (!user)
2854 return NULL;
2856 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
2857 ast_set_flag(user, IAX_RTCACHEFRIENDS);
2858 ao2_link(users, user);
2859 } else {
2860 ast_set_flag(user, IAX_TEMPONLY);
2863 return user;
2866 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
2868 char port[10];
2869 char regseconds[20];
2871 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
2872 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
2873 ast_update_realtime("iaxpeers", "name", peername,
2874 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
2875 "regseconds", regseconds, NULL);
2878 struct create_addr_info {
2879 int capability;
2880 unsigned int flags;
2881 int maxtime;
2882 int encmethods;
2883 int found;
2884 int sockfd;
2885 int adsi;
2886 char username[80];
2887 char secret[80];
2888 char outkey[80];
2889 char timezone[80];
2890 char prefs[32];
2891 char context[AST_MAX_CONTEXT];
2892 char peercontext[AST_MAX_CONTEXT];
2893 char mohinterpret[MAX_MUSICCLASS];
2894 char mohsuggest[MAX_MUSICCLASS];
2897 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
2899 struct ast_hostent ahp;
2900 struct hostent *hp;
2901 struct iax2_peer *peer;
2902 int res = -1;
2903 struct ast_codec_pref ourprefs;
2905 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
2906 cai->sockfd = defaultsockfd;
2907 cai->maxtime = 0;
2908 sin->sin_family = AF_INET;
2910 if (!(peer = find_peer(peername, 1))) {
2911 cai->found = 0;
2913 hp = ast_gethostbyname(peername, &ahp);
2914 if (hp) {
2915 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
2916 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
2917 /* use global iax prefs for unknown peer/user */
2918 /* But move the calling channel's native codec to the top of the preference list */
2919 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
2920 if (c)
2921 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
2922 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
2923 return 0;
2924 } else {
2925 ast_log(LOG_WARNING, "No such host: %s\n", peername);
2926 return -1;
2930 cai->found = 1;
2932 /* if the peer has no address (current or default), return failure */
2933 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
2934 goto return_unref;
2936 /* if the peer is being monitored and is currently unreachable, return failure */
2937 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
2938 goto return_unref;
2940 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
2941 cai->maxtime = peer->maxms;
2942 cai->capability = peer->capability;
2943 cai->encmethods = peer->encmethods;
2944 cai->sockfd = peer->sockfd;
2945 cai->adsi = peer->adsi;
2946 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
2947 /* Move the calling channel's native codec to the top of the preference list */
2948 if (c) {
2949 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
2950 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
2952 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
2953 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
2954 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
2955 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
2956 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
2957 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
2958 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
2959 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
2960 if (ast_strlen_zero(peer->dbsecret)) {
2961 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
2962 } else {
2963 char *family;
2964 char *key = NULL;
2966 family = ast_strdupa(peer->dbsecret);
2967 key = strchr(family, '/');
2968 if (key)
2969 *key++ = '\0';
2970 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
2971 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
2972 goto return_unref;
2976 if (peer->addr.sin_addr.s_addr) {
2977 sin->sin_addr = peer->addr.sin_addr;
2978 sin->sin_port = peer->addr.sin_port;
2979 } else {
2980 sin->sin_addr = peer->defaddr.sin_addr;
2981 sin->sin_port = peer->defaddr.sin_port;
2984 res = 0;
2986 return_unref:
2987 peer_unref(peer);
2989 return res;
2992 static void __auto_congest(const void *nothing)
2994 int callno = PTR_TO_CALLNO(nothing);
2995 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
2996 ast_mutex_lock(&iaxsl[callno]);
2997 if (iaxs[callno]) {
2998 iaxs[callno]->initid = -1;
2999 iax2_queue_frame(callno, &f);
3000 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3002 ast_mutex_unlock(&iaxsl[callno]);
3005 static int auto_congest(const void *data)
3007 #ifdef SCHED_MULTITHREADED
3008 if (schedule_action(__auto_congest, data))
3009 #endif
3010 __auto_congest(data);
3011 return 0;
3014 static unsigned int iax2_datetime(const char *tz)
3016 time_t t;
3017 struct tm tm;
3018 unsigned int tmp;
3019 time(&t);
3020 if (!ast_strlen_zero(tz))
3021 ast_localtime(&t, &tm, tz);
3022 else
3023 ast_localtime(&t, &tm, NULL);
3024 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3025 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3026 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3027 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3028 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3029 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3030 return tmp;
3033 struct parsed_dial_string {
3034 char *username;
3035 char *password;
3036 char *key;
3037 char *peer;
3038 char *port;
3039 char *exten;
3040 char *context;
3041 char *options;
3045 * \brief Parses an IAX dial string into its component parts.
3046 * \param data the string to be parsed
3047 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3048 * \return nothing
3050 * This function parses the string and fills the structure
3051 * with pointers to its component parts. The input string
3052 * will be modified.
3054 * \note This function supports both plaintext passwords and RSA
3055 * key names; if the password string is formatted as '[keyname]',
3056 * then the keyname will be placed into the key field, and the
3057 * password field will be set to NULL.
3059 * \note The dial string format is:
3060 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3062 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3064 if (ast_strlen_zero(data))
3065 return;
3067 pds->peer = strsep(&data, "/");
3068 pds->exten = strsep(&data, "/");
3069 pds->options = data;
3071 if (pds->exten) {
3072 data = pds->exten;
3073 pds->exten = strsep(&data, "@");
3074 pds->context = data;
3077 if (strchr(pds->peer, '@')) {
3078 data = pds->peer;
3079 pds->username = strsep(&data, "@");
3080 pds->peer = data;
3083 if (pds->username) {
3084 data = pds->username;
3085 pds->username = strsep(&data, ":");
3086 pds->password = data;
3089 data = pds->peer;
3090 pds->peer = strsep(&data, ":");
3091 pds->port = data;
3093 /* check for a key name wrapped in [] in the secret position, if found,
3094 move it to the key field instead
3096 if (pds->password && (pds->password[0] == '[')) {
3097 pds->key = ast_strip_quoted(pds->password, "[", "]");
3098 pds->password = NULL;
3102 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3104 struct sockaddr_in sin;
3105 char *l=NULL, *n=NULL, *tmpstr;
3106 struct iax_ie_data ied;
3107 char *defaultrdest = "s";
3108 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3109 struct parsed_dial_string pds;
3110 struct create_addr_info cai;
3112 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3113 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3114 return -1;
3117 memset(&cai, 0, sizeof(cai));
3118 cai.encmethods = iax2_encryption;
3120 memset(&pds, 0, sizeof(pds));
3121 tmpstr = ast_strdupa(dest);
3122 parse_dial_string(tmpstr, &pds);
3124 if (ast_strlen_zero(pds.peer)) {
3125 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3126 return -1;
3129 if (!pds.exten) {
3130 if (!ast_strlen_zero(c->exten))
3131 pds.exten = c->exten;
3132 else
3133 pds.exten = defaultrdest;
3136 if (create_addr(pds.peer, c, &sin, &cai)) {
3137 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3138 return -1;
3141 if (!pds.username && !ast_strlen_zero(cai.username))
3142 pds.username = cai.username;
3143 if (!pds.password && !ast_strlen_zero(cai.secret))
3144 pds.password = cai.secret;
3145 if (!pds.key && !ast_strlen_zero(cai.outkey))
3146 pds.key = cai.outkey;
3147 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3148 pds.context = cai.peercontext;
3150 /* Keep track of the context for outgoing calls too */
3151 ast_copy_string(c->context, cai.context, sizeof(c->context));
3153 if (pds.port)
3154 sin.sin_port = htons(atoi(pds.port));
3156 l = c->cid.cid_num;
3157 n = c->cid.cid_name;
3159 /* Now build request */
3160 memset(&ied, 0, sizeof(ied));
3162 /* On new call, first IE MUST be IAX version of caller */
3163 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3164 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3165 if (pds.options && strchr(pds.options, 'a')) {
3166 /* Request auto answer */
3167 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3170 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3172 if (l) {
3173 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3174 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3175 } else {
3176 if (n)
3177 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3178 else
3179 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3182 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3183 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3185 if (n)
3186 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3187 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3188 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3190 if (!ast_strlen_zero(c->language))
3191 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3192 if (!ast_strlen_zero(c->cid.cid_dnid))
3193 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3194 if (!ast_strlen_zero(c->cid.cid_rdnis))
3195 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3197 if (pds.context)
3198 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3200 if (pds.username)
3201 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3203 if (cai.encmethods)
3204 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3206 ast_mutex_lock(&iaxsl[callno]);
3208 if (!ast_strlen_zero(c->context))
3209 ast_string_field_set(iaxs[callno], context, c->context);
3211 if (pds.username)
3212 ast_string_field_set(iaxs[callno], username, pds.username);
3214 iaxs[callno]->encmethods = cai.encmethods;
3216 iaxs[callno]->adsi = cai.adsi;
3218 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3219 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3221 if (pds.key)
3222 ast_string_field_set(iaxs[callno], outkey, pds.key);
3223 if (pds.password)
3224 ast_string_field_set(iaxs[callno], secret, pds.password);
3226 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3227 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3228 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3229 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3231 if (iaxs[callno]->maxtime) {
3232 /* Initialize pingtime and auto-congest time */
3233 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3234 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3235 } else if (autokill) {
3236 iaxs[callno]->pingtime = autokill / 2;
3237 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3240 /* send the command using the appropriate socket for this peer */
3241 iaxs[callno]->sockfd = cai.sockfd;
3243 /* Transmit the string in a "NEW" request */
3244 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3246 ast_mutex_unlock(&iaxsl[callno]);
3247 ast_setstate(c, AST_STATE_RINGING);
3249 return 0;
3252 static int iax2_hangup(struct ast_channel *c)
3254 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3255 int alreadygone;
3256 struct iax_ie_data ied;
3257 memset(&ied, 0, sizeof(ied));
3258 ast_mutex_lock(&iaxsl[callno]);
3259 if (callno && iaxs[callno]) {
3260 if (option_debug)
3261 ast_log(LOG_DEBUG, "We're hanging up %s now...\n", c->name);
3262 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
3263 /* Send the hangup unless we have had a transmission error or are already gone */
3264 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3265 if (!iaxs[callno]->error && !alreadygone) {
3266 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3267 if (!iaxs[callno]) {
3268 ast_mutex_unlock(&iaxsl[callno]);
3269 return 0;
3272 /* Explicitly predestroy it */
3273 iax2_predestroy(callno);
3274 /* If we were already gone to begin with, destroy us now */
3275 if (alreadygone && iaxs[callno]) {
3276 if (option_debug)
3277 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
3278 iax2_destroy(callno);
3281 ast_mutex_unlock(&iaxsl[callno]);
3282 if (option_verbose > 2)
3283 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
3284 return 0;
3287 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3289 struct ast_option_header *h;
3290 int res;
3292 switch (option) {
3293 case AST_OPTION_TXGAIN:
3294 case AST_OPTION_RXGAIN:
3295 /* these two cannot be sent, because they require a result */
3296 errno = ENOSYS;
3297 return -1;
3298 default:
3299 if (!(h = ast_malloc(datalen + sizeof(*h))))
3300 return -1;
3302 h->flag = AST_OPTION_FLAG_REQUEST;
3303 h->option = htons(option);
3304 memcpy(h->data, data, datalen);
3305 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3306 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3307 datalen + sizeof(*h), -1);
3308 free(h);
3309 return res;
3313 static struct ast_frame *iax2_read(struct ast_channel *c)
3315 ast_log(LOG_NOTICE, "I should never be called!\n");
3316 return &ast_null_frame;
3319 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3321 int res;
3322 struct iax_ie_data ied0;
3323 struct iax_ie_data ied1;
3324 unsigned int transferid = (unsigned int)ast_random();
3325 memset(&ied0, 0, sizeof(ied0));
3326 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3327 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3328 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3330 memset(&ied1, 0, sizeof(ied1));
3331 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3332 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3333 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3335 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3336 if (res)
3337 return -1;
3338 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3339 if (res)
3340 return -1;
3341 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3342 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3343 return 0;
3346 static void lock_both(unsigned short callno0, unsigned short callno1)
3348 ast_mutex_lock(&iaxsl[callno0]);
3349 while (ast_mutex_trylock(&iaxsl[callno1])) {
3350 ast_mutex_unlock(&iaxsl[callno0]);
3351 usleep(10);
3352 ast_mutex_lock(&iaxsl[callno0]);
3356 static void unlock_both(unsigned short callno0, unsigned short callno1)
3358 ast_mutex_unlock(&iaxsl[callno1]);
3359 ast_mutex_unlock(&iaxsl[callno0]);
3362 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3364 struct ast_channel *cs[3];
3365 struct ast_channel *who, *other;
3366 int to = -1;
3367 int res = -1;
3368 int transferstarted=0;
3369 struct ast_frame *f;
3370 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3371 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3372 struct timeval waittimer = {0, 0}, tv;
3374 lock_both(callno0, callno1);
3375 if (!iaxs[callno0] || !iaxs[callno1]) {
3376 unlock_both(callno0, callno1);
3377 return AST_BRIDGE_FAILED;
3379 /* Put them in native bridge mode */
3380 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3381 iaxs[callno0]->bridgecallno = callno1;
3382 iaxs[callno1]->bridgecallno = callno0;
3384 unlock_both(callno0, callno1);
3386 /* If not, try to bridge until we can execute a transfer, if we can */
3387 cs[0] = c0;
3388 cs[1] = c1;
3389 for (/* ever */;;) {
3390 /* Check in case we got masqueraded into */
3391 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3392 if (option_verbose > 2)
3393 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
3394 /* Remove from native mode */
3395 if (c0->tech == &iax2_tech) {
3396 ast_mutex_lock(&iaxsl[callno0]);
3397 iaxs[callno0]->bridgecallno = 0;
3398 ast_mutex_unlock(&iaxsl[callno0]);
3400 if (c1->tech == &iax2_tech) {
3401 ast_mutex_lock(&iaxsl[callno1]);
3402 iaxs[callno1]->bridgecallno = 0;
3403 ast_mutex_unlock(&iaxsl[callno1]);
3405 return AST_BRIDGE_FAILED_NOWARN;
3407 if (c0->nativeformats != c1->nativeformats) {
3408 if (option_verbose > 2) {
3409 char buf0[255];
3410 char buf1[255];
3411 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3412 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3413 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3415 /* Remove from native mode */
3416 lock_both(callno0, callno1);
3417 if (iaxs[callno0])
3418 iaxs[callno0]->bridgecallno = 0;
3419 if (iaxs[callno1])
3420 iaxs[callno1]->bridgecallno = 0;
3421 unlock_both(callno0, callno1);
3422 return AST_BRIDGE_FAILED_NOWARN;
3424 /* check if transfered and if we really want native bridging */
3425 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
3426 /* Try the transfer */
3427 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
3428 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
3429 ast_log(LOG_WARNING, "Unable to start the transfer\n");
3430 transferstarted = 1;
3432 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
3433 /* Call has been transferred. We're no longer involved */
3434 gettimeofday(&tv, NULL);
3435 if (ast_tvzero(waittimer)) {
3436 waittimer = tv;
3437 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
3438 c0->_softhangup |= AST_SOFTHANGUP_DEV;
3439 c1->_softhangup |= AST_SOFTHANGUP_DEV;
3440 *fo = NULL;
3441 *rc = c0;
3442 res = AST_BRIDGE_COMPLETE;
3443 break;
3446 to = 1000;
3447 who = ast_waitfor_n(cs, 2, &to);
3448 if (timeoutms > -1) {
3449 timeoutms -= (1000 - to);
3450 if (timeoutms < 0)
3451 timeoutms = 0;
3453 if (!who) {
3454 if (!timeoutms) {
3455 res = AST_BRIDGE_RETRY;
3456 break;
3458 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
3459 res = AST_BRIDGE_FAILED;
3460 break;
3462 continue;
3464 f = ast_read(who);
3465 if (!f) {
3466 *fo = NULL;
3467 *rc = who;
3468 res = AST_BRIDGE_COMPLETE;
3469 break;
3471 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
3472 *fo = f;
3473 *rc = who;
3474 res = AST_BRIDGE_COMPLETE;
3475 break;
3477 other = (who == c0) ? c1 : c0; /* the 'other' channel */
3478 if ((f->frametype == AST_FRAME_VOICE) ||
3479 (f->frametype == AST_FRAME_TEXT) ||
3480 (f->frametype == AST_FRAME_VIDEO) ||
3481 (f->frametype == AST_FRAME_IMAGE) ||
3482 (f->frametype == AST_FRAME_DTMF)) {
3483 /* monitored dtmf take out of the bridge.
3484 * check if we monitor the specific source.
3486 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
3487 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
3488 *rc = who;
3489 *fo = f;
3490 res = AST_BRIDGE_COMPLETE;
3491 /* Remove from native mode */
3492 break;
3494 /* everything else goes to the other side */
3495 ast_write(other, f);
3497 ast_frfree(f);
3498 /* Swap who gets priority */
3499 cs[2] = cs[0];
3500 cs[0] = cs[1];
3501 cs[1] = cs[2];
3503 lock_both(callno0, callno1);
3504 if(iaxs[callno0])
3505 iaxs[callno0]->bridgecallno = 0;
3506 if(iaxs[callno1])
3507 iaxs[callno1]->bridgecallno = 0;
3508 unlock_both(callno0, callno1);
3509 return res;
3512 static int iax2_answer(struct ast_channel *c)
3514 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3515 if (option_debug)
3516 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
3517 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
3520 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
3522 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3523 struct chan_iax2_pvt *pvt;
3524 int res = 0;
3526 if (option_debug && iaxdebug)
3527 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
3529 ast_mutex_lock(&iaxsl[callno]);
3530 pvt = iaxs[callno];
3532 switch (condition) {
3533 case AST_CONTROL_HOLD:
3534 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3535 ast_moh_start(c, data, pvt->mohinterpret);
3536 goto done;
3538 break;
3539 case AST_CONTROL_UNHOLD:
3540 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
3541 ast_moh_stop(c);
3542 goto done;
3546 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
3548 done:
3549 ast_mutex_unlock(&iaxsl[callno]);
3551 return res;
3554 static int iax2_transfer(struct ast_channel *c, const char *dest)
3556 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3557 struct iax_ie_data ied;
3558 char tmp[256], *context;
3559 ast_copy_string(tmp, dest, sizeof(tmp));
3560 context = strchr(tmp, '@');
3561 if (context) {
3562 *context = '\0';
3563 context++;
3565 memset(&ied, 0, sizeof(ied));
3566 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
3567 if (context)
3568 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
3569 if (option_debug)
3570 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
3571 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
3574 static int iax2_getpeertrunk(struct sockaddr_in sin)
3576 struct iax2_peer *peer;
3577 int res = 0;
3578 struct ao2_iterator i;
3580 i = ao2_iterator_init(peers, 0);
3581 while ((peer = ao2_iterator_next(&i))) {
3582 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
3583 (peer->addr.sin_port == sin.sin_port)) {
3584 res = ast_test_flag(peer, IAX_TRUNK);
3585 peer_unref(peer);
3586 break;
3588 peer_unref(peer);
3591 return res;
3594 /*! \brief Create new call, interface with the PBX core */
3595 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
3597 struct ast_channel *tmp;
3598 struct chan_iax2_pvt *i;
3599 struct ast_variable *v = NULL;
3601 if (!(i = iaxs[callno])) {
3602 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
3603 return NULL;
3606 /* Don't hold call lock */
3607 ast_mutex_unlock(&iaxsl[callno]);
3608 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
3609 ast_mutex_lock(&iaxsl[callno]);
3610 if (!iaxs[callno]) {
3611 if (tmp) {
3612 ast_channel_free(tmp);
3614 ast_mutex_unlock(&iaxsl[callno]);
3615 return NULL;
3618 if (!tmp)
3619 return NULL;
3620 tmp->tech = &iax2_tech;
3621 /* We can support any format by default, until we get restricted */
3622 tmp->nativeformats = capability;
3623 tmp->readformat = ast_best_codec(capability);
3624 tmp->writeformat = ast_best_codec(capability);
3625 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
3627 /* Don't use ast_set_callerid() here because it will
3628 * generate a NewCallerID event before the NewChannel event */
3629 if (!ast_strlen_zero(i->ani))
3630 tmp->cid.cid_ani = ast_strdup(i->ani);
3631 else
3632 tmp->cid.cid_ani = ast_strdup(i->cid_num);
3633 tmp->cid.cid_dnid = ast_strdup(i->dnid);
3634 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
3635 tmp->cid.cid_pres = i->calling_pres;
3636 tmp->cid.cid_ton = i->calling_ton;
3637 tmp->cid.cid_tns = i->calling_tns;
3638 if (!ast_strlen_zero(i->language))
3639 ast_string_field_set(tmp, language, i->language);
3640 if (!ast_strlen_zero(i->accountcode))
3641 ast_string_field_set(tmp, accountcode, i->accountcode);
3642 if (i->amaflags)
3643 tmp->amaflags = i->amaflags;
3644 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
3645 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
3646 if (i->adsi)
3647 tmp->adsicpe = i->peeradsicpe;
3648 else
3649 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
3650 i->owner = tmp;
3651 i->capability = capability;
3653 for (v = i->vars ; v ; v = v->next)
3654 pbx_builtin_setvar_helper(tmp, v->name, v->value);
3656 if (state != AST_STATE_DOWN) {
3657 if (ast_pbx_start(tmp)) {
3658 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
3659 ast_hangup(tmp);
3660 i->owner = NULL;
3661 return NULL;
3665 ast_module_ref(ast_module_info->self);
3667 return tmp;
3670 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
3672 unsigned long int mssincetx; /* unsigned to handle overflows */
3673 long int ms, pred;
3675 tpeer->trunkact = *tv;
3676 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
3677 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
3678 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
3679 tpeer->txtrunktime = *tv;
3680 tpeer->lastsent = 999999;
3682 /* Update last transmit time now */
3683 tpeer->lasttxtime = *tv;
3685 /* Calculate ms offset */
3686 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
3687 /* Predict from last value */
3688 pred = tpeer->lastsent + sampms;
3689 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
3690 ms = pred;
3692 /* We never send the same timestamp twice, so fudge a little if we must */
3693 if (ms == tpeer->lastsent)
3694 ms = tpeer->lastsent + 1;
3695 tpeer->lastsent = ms;
3696 return ms;
3699 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
3701 long ms; /* NOT unsigned */
3702 if (ast_tvzero(iaxs[callno]->rxcore)) {
3703 /* Initialize rxcore time if appropriate */
3704 gettimeofday(&iaxs[callno]->rxcore, NULL);
3705 /* Round to nearest 20ms so traces look pretty */
3706 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
3708 /* Calculate difference between trunk and channel */
3709 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
3710 /* Return as the sum of trunk time and the difference between trunk and real time */
3711 return ms + ts;
3714 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
3716 int ms;
3717 int voice = 0;
3718 int genuine = 0;
3719 int adjust;
3720 struct timeval *delivery = NULL;
3723 /* What sort of frame do we have?: voice is self-explanatory
3724 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
3725 non-genuine frames are CONTROL frames [ringing etc], DTMF
3726 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
3727 the others need a timestamp slaved to the voice frames so that they go in sequence
3729 if (f) {
3730 if (f->frametype == AST_FRAME_VOICE) {
3731 voice = 1;
3732 delivery = &f->delivery;
3733 } else if (f->frametype == AST_FRAME_IAX) {
3734 genuine = 1;
3735 } else if (f->frametype == AST_FRAME_CNG) {
3736 p->notsilenttx = 0;
3739 if (ast_tvzero(p->offset)) {
3740 gettimeofday(&p->offset, NULL);
3741 /* Round to nearest 20ms for nice looking traces */
3742 p->offset.tv_usec -= p->offset.tv_usec % 20000;
3744 /* If the timestamp is specified, just send it as is */
3745 if (ts)
3746 return ts;
3747 /* If we have a time that the frame arrived, always use it to make our timestamp */
3748 if (delivery && !ast_tvzero(*delivery)) {
3749 ms = ast_tvdiff_ms(*delivery, p->offset);
3750 if (option_debug > 2 && iaxdebug)
3751 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
3752 } else {
3753 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
3754 if (ms < 0)
3755 ms = 0;
3756 if (voice) {
3757 /* On a voice frame, use predicted values if appropriate */
3758 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
3759 /* Adjust our txcore, keeping voice and non-voice synchronized */
3760 /* AN EXPLANATION:
3761 When we send voice, we usually send "calculated" timestamps worked out
3762 on the basis of the number of samples sent. When we send other frames,
3763 we usually send timestamps worked out from the real clock.
3764 The problem is that they can tend to drift out of step because the
3765 source channel's clock and our clock may not be exactly at the same rate.
3766 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
3767 for this call. Moving it adjusts timestamps for non-voice frames.
3768 We make the adjustment in the style of a moving average. Each time we
3769 adjust p->offset by 10% of the difference between our clock-derived
3770 timestamp and the predicted timestamp. That's why you see "10000"
3771 below even though IAX2 timestamps are in milliseconds.
3772 The use of a moving average avoids offset moving too radically.
3773 Generally, "adjust" roams back and forth around 0, with offset hardly
3774 changing at all. But if a consistent different starts to develop it
3775 will be eliminated over the course of 10 frames (200-300msecs)
3777 adjust = (ms - p->nextpred);
3778 if (adjust < 0)
3779 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
3780 else if (adjust > 0)
3781 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
3783 if (!p->nextpred) {
3784 p->nextpred = ms; /*f->samples / 8;*/
3785 if (p->nextpred <= p->lastsent)
3786 p->nextpred = p->lastsent + 3;
3788 ms = p->nextpred;
3789 } else {
3790 /* in this case, just use the actual
3791 * time, since we're either way off
3792 * (shouldn't happen), or we're ending a
3793 * silent period -- and seed the next
3794 * predicted time. Also, round ms to the
3795 * next multiple of frame size (so our
3796 * silent periods are multiples of
3797 * frame size too) */
3799 if (option_debug && iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
3800 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
3801 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
3803 if (f->samples >= 8) /* check to make sure we dont core dump */
3805 int diff = ms % (f->samples / 8);
3806 if (diff)
3807 ms += f->samples/8 - diff;
3810 p->nextpred = ms;
3811 p->notsilenttx = 1;
3813 } else if ( f->frametype == AST_FRAME_VIDEO ) {
3815 * IAX2 draft 03 says that timestamps MUST be in order.
3816 * It does not say anything about several frames having the same timestamp
3817 * When transporting video, we can have a frame that spans multiple iax packets
3818 * (so called slices), so it would make sense to use the same timestamp for all of
3819 * them
3820 * We do want to make sure that frames don't go backwards though
3822 if ( (unsigned int)ms < p->lastsent )
3823 ms = p->lastsent;
3824 } else {
3825 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
3826 it's a genuine frame */
3827 if (genuine) {
3828 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
3829 if (ms <= p->lastsent)
3830 ms = p->lastsent + 3;
3831 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
3832 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
3833 ms = p->lastsent + 3;
3837 p->lastsent = ms;
3838 if (voice)
3839 p->nextpred = p->nextpred + f->samples / 8;
3840 return ms;
3843 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
3845 /* Returns where in "receive time" we are. That is, how many ms
3846 since we received (or would have received) the frame with timestamp 0 */
3847 int ms;
3848 #ifdef IAXTESTS
3849 int jit;
3850 #endif /* IAXTESTS */
3851 /* Setup rxcore if necessary */
3852 if (ast_tvzero(p->rxcore)) {
3853 p->rxcore = ast_tvnow();
3854 if (option_debug && iaxdebug)
3855 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
3856 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
3857 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
3858 #if 1
3859 if (option_debug && iaxdebug)
3860 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
3861 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
3862 #endif
3865 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
3866 #ifdef IAXTESTS
3867 if (test_jit) {
3868 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
3869 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
3870 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
3871 jit = -jit;
3872 ms += jit;
3875 if (test_late) {
3876 ms += test_late;
3877 test_late = 0;
3879 #endif /* IAXTESTS */
3880 return ms;
3883 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
3885 struct iax2_trunk_peer *tpeer;
3887 /* Finds and locks trunk peer */
3888 ast_mutex_lock(&tpeerlock);
3889 for (tpeer = tpeers; tpeer; tpeer = tpeer->next) {
3890 /* We don't lock here because tpeer->addr *never* changes */
3891 if (!inaddrcmp(&tpeer->addr, sin)) {
3892 ast_mutex_lock(&tpeer->lock);
3893 break;
3896 if (!tpeer) {
3897 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
3898 ast_mutex_init(&tpeer->lock);
3899 tpeer->lastsent = 9999;
3900 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
3901 tpeer->trunkact = ast_tvnow();
3902 ast_mutex_lock(&tpeer->lock);
3903 tpeer->next = tpeers;
3904 tpeer->sockfd = fd;
3905 tpeers = tpeer;
3906 #ifdef SO_NO_CHECK
3907 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
3908 #endif
3909 if (option_debug)
3910 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3913 ast_mutex_unlock(&tpeerlock);
3914 return tpeer;
3917 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
3919 struct ast_frame *f;
3920 struct iax2_trunk_peer *tpeer;
3921 void *tmp, *ptr;
3922 struct ast_iax2_meta_trunk_entry *met;
3923 struct ast_iax2_meta_trunk_mini *mtm;
3925 f = &fr->af;
3926 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
3927 if (tpeer) {
3928 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
3929 /* Need to reallocate space */
3930 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
3931 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
3932 ast_mutex_unlock(&tpeer->lock);
3933 return -1;
3936 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
3937 tpeer->trunkdata = tmp;
3938 if (option_debug)
3939 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
3940 } else {
3941 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
3942 ast_mutex_unlock(&tpeer->lock);
3943 return -1;
3947 /* Append to meta frame */
3948 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
3949 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
3950 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
3951 mtm->len = htons(f->datalen);
3952 mtm->mini.callno = htons(pvt->callno);
3953 mtm->mini.ts = htons(0xffff & fr->ts);
3954 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
3955 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
3956 } else {
3957 met = (struct ast_iax2_meta_trunk_entry *)ptr;
3958 /* Store call number and length in meta header */
3959 met->callno = htons(pvt->callno);
3960 met->len = htons(f->datalen);
3961 /* Advance pointers/decrease length past trunk entry header */
3962 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
3963 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
3965 /* Copy actual trunk data */
3966 memcpy(ptr, f->data, f->datalen);
3967 tpeer->trunkdatalen += f->datalen;
3969 tpeer->calls++;
3970 ast_mutex_unlock(&tpeer->lock);
3972 return 0;
3975 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
3977 aes_encrypt_key128(digest, ecx);
3978 aes_decrypt_key128(digest, dcx);
3981 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
3983 #if 0
3984 /* Debug with "fake encryption" */
3985 int x;
3986 if (len % 16)
3987 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
3988 for (x=0;x<len;x++)
3989 dst[x] = src[x] ^ 0xff;
3990 #else
3991 unsigned char lastblock[16] = { 0 };
3992 int x;
3993 while(len > 0) {
3994 aes_decrypt(src, dst, dcx);
3995 for (x=0;x<16;x++)
3996 dst[x] ^= lastblock[x];
3997 memcpy(lastblock, src, sizeof(lastblock));
3998 dst += 16;
3999 src += 16;
4000 len -= 16;
4002 #endif
4005 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
4007 #if 0
4008 /* Debug with "fake encryption" */
4009 int x;
4010 if (len % 16)
4011 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4012 for (x=0;x<len;x++)
4013 dst[x] = src[x] ^ 0xff;
4014 #else
4015 unsigned char curblock[16] = { 0 };
4016 int x;
4017 while(len > 0) {
4018 for (x=0;x<16;x++)
4019 curblock[x] ^= src[x];
4020 aes_encrypt(curblock, dst, ecx);
4021 memcpy(curblock, dst, sizeof(curblock));
4022 dst += 16;
4023 src += 16;
4024 len -= 16;
4026 #endif
4029 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4031 int padding;
4032 unsigned char *workspace;
4034 workspace = alloca(*datalen);
4035 memset(f, 0, sizeof(*f));
4036 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4037 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4038 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
4039 return -1;
4040 /* Decrypt */
4041 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
4043 padding = 16 + (workspace[15] & 0xf);
4044 if (option_debug && iaxdebug)
4045 ast_log(LOG_DEBUG, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
4046 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
4047 return -1;
4049 *datalen -= padding;
4050 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4051 f->frametype = fh->type;
4052 if (f->frametype == AST_FRAME_VIDEO) {
4053 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
4054 } else {
4055 f->subclass = uncompress_subclass(fh->csub);
4057 } else {
4058 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4059 if (option_debug && iaxdebug)
4060 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
4061 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
4062 return -1;
4063 /* Decrypt */
4064 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
4065 padding = 16 + (workspace[15] & 0x0f);
4066 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
4067 return -1;
4068 *datalen -= padding;
4069 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4071 return 0;
4074 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4076 int padding;
4077 unsigned char *workspace;
4078 workspace = alloca(*datalen + 32);
4079 if (!workspace)
4080 return -1;
4081 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4082 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4083 if (option_debug && iaxdebug)
4084 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
4085 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
4086 padding = 16 + (padding & 0xf);
4087 memcpy(workspace, poo, padding);
4088 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4089 workspace[15] &= 0xf0;
4090 workspace[15] |= (padding & 0xf);
4091 if (option_debug && iaxdebug)
4092 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
4093 *datalen += padding;
4094 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
4095 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
4096 memcpy(poo, workspace + *datalen - 32, 32);
4097 } else {
4098 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4099 if (option_debug && iaxdebug)
4100 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
4101 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
4102 padding = 16 + (padding & 0xf);
4103 memcpy(workspace, poo, padding);
4104 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4105 workspace[15] &= 0xf0;
4106 workspace[15] |= (padding & 0x0f);
4107 *datalen += padding;
4108 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
4109 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
4110 memcpy(poo, workspace + *datalen - 32, 32);
4112 return 0;
4115 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4117 int res=-1;
4118 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
4119 /* Search for possible keys, given secrets */
4120 struct MD5Context md5;
4121 unsigned char digest[16];
4122 char *tmppw, *stringp;
4124 tmppw = ast_strdupa(iaxs[callno]->secret);
4125 stringp = tmppw;
4126 while ((tmppw = strsep(&stringp, ";"))) {
4127 MD5Init(&md5);
4128 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
4129 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
4130 MD5Final(digest, &md5);
4131 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
4132 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4133 if (!res) {
4134 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4135 break;
4138 } else
4139 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4140 return res;
4143 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
4145 /* Queue a packet for delivery on a given private structure. Use "ts" for
4146 timestamp, or calculate if ts is 0. Send immediately without retransmission
4147 or delayed, with retransmission */
4148 struct ast_iax2_full_hdr *fh;
4149 struct ast_iax2_mini_hdr *mh;
4150 struct ast_iax2_video_hdr *vh;
4151 struct {
4152 struct iax_frame fr2;
4153 unsigned char buffer[4096];
4154 } frb;
4155 struct iax_frame *fr;
4156 int res;
4157 int sendmini=0;
4158 unsigned int lastsent;
4159 unsigned int fts;
4161 frb.fr2.afdatalen = sizeof(frb.buffer);
4163 if (!pvt) {
4164 ast_log(LOG_WARNING, "No private structure for packet?\n");
4165 return -1;
4168 lastsent = pvt->lastsent;
4170 /* Calculate actual timestamp */
4171 fts = calc_timestamp(pvt, ts, f);
4173 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4174 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4175 * increment the "predicted timestamps" for voice, if we're predecting */
4176 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
4177 return 0;
4180 if ((ast_test_flag(pvt, IAX_TRUNK) ||
4181 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
4182 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
4183 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4184 (f->frametype == AST_FRAME_VOICE)
4185 /* is a voice frame */ &&
4186 (f->subclass == pvt->svoiceformat)
4187 /* is the same type */ ) {
4188 /* Force immediate rather than delayed transmission */
4189 now = 1;
4190 /* Mark that mini-style frame is appropriate */
4191 sendmini = 1;
4193 if ( f->frametype == AST_FRAME_VIDEO ) {
4195 * If the lower 15 bits of the timestamp roll over, or if
4196 * the video format changed then send a full frame.
4197 * Otherwise send a mini video frame
4199 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
4200 ((f->subclass & ~0x1) == pvt->svideoformat)
4202 now = 1;
4203 sendmini = 1;
4204 } else {
4205 now = 0;
4206 sendmini = 0;
4208 pvt->lastvsent = fts;
4210 /* Allocate an iax_frame */
4211 if (now) {
4212 fr = &frb.fr2;
4213 } else
4214 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
4215 if (!fr) {
4216 ast_log(LOG_WARNING, "Out of memory\n");
4217 return -1;
4219 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4220 iax_frame_wrap(fr, f);
4222 fr->ts = fts;
4223 fr->callno = pvt->callno;
4224 fr->transfer = transfer;
4225 fr->final = final;
4226 if (!sendmini) {
4227 /* We need a full frame */
4228 if (seqno > -1)
4229 fr->oseqno = seqno;
4230 else
4231 fr->oseqno = pvt->oseqno++;
4232 fr->iseqno = pvt->iseqno;
4233 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
4234 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
4235 fh->ts = htonl(fr->ts);
4236 fh->oseqno = fr->oseqno;
4237 if (transfer) {
4238 fh->iseqno = 0;
4239 } else
4240 fh->iseqno = fr->iseqno;
4241 /* Keep track of the last thing we've acknowledged */
4242 if (!transfer)
4243 pvt->aseqno = fr->iseqno;
4244 fh->type = fr->af.frametype & 0xFF;
4245 if (fr->af.frametype == AST_FRAME_VIDEO)
4246 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
4247 else
4248 fh->csub = compress_subclass(fr->af.subclass);
4249 if (transfer) {
4250 fr->dcallno = pvt->transfercallno;
4251 } else
4252 fr->dcallno = pvt->peercallno;
4253 fh->dcallno = htons(fr->dcallno);
4254 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4255 fr->data = fh;
4256 fr->retries = 0;
4257 /* Retry after 2x the ping time has passed */
4258 fr->retrytime = pvt->pingtime * 2;
4259 if (fr->retrytime < MIN_RETRY_TIME)
4260 fr->retrytime = MIN_RETRY_TIME;
4261 if (fr->retrytime > MAX_RETRY_TIME)
4262 fr->retrytime = MAX_RETRY_TIME;
4263 /* Acks' don't get retried */
4264 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
4265 fr->retries = -1;
4266 else if (f->frametype == AST_FRAME_VOICE)
4267 pvt->svoiceformat = f->subclass;
4268 else if (f->frametype == AST_FRAME_VIDEO)
4269 pvt->svideoformat = f->subclass & ~0x1;
4270 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4271 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4272 if (iaxdebug) {
4273 if (fr->transfer)
4274 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4275 else
4276 iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4278 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
4279 } else
4280 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4283 if (now) {
4284 res = send_packet(fr);
4285 } else
4286 res = iax2_transmit(fr);
4287 } else {
4288 if (ast_test_flag(pvt, IAX_TRUNK)) {
4289 iax2_trunk_queue(pvt, fr);
4290 res = 0;
4291 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4292 /* Video frame have no sequence number */
4293 fr->oseqno = -1;
4294 fr->iseqno = -1;
4295 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
4296 vh->zeros = 0;
4297 vh->callno = htons(0x8000 | fr->callno);
4298 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
4299 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
4300 fr->data = vh;
4301 fr->retries = -1;
4302 res = send_packet(fr);
4303 } else {
4304 /* Mini-frames have no sequence number */
4305 fr->oseqno = -1;
4306 fr->iseqno = -1;
4307 /* Mini frame will do */
4308 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
4309 mh->callno = htons(fr->callno);
4310 mh->ts = htons(fr->ts & 0xFFFF);
4311 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
4312 fr->data = mh;
4313 fr->retries = -1;
4314 if (pvt->transferring == TRANSFER_MEDIAPASS)
4315 fr->transfer = 1;
4316 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4317 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4318 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
4319 } else
4320 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4322 res = send_packet(fr);
4325 return res;
4328 static int iax2_show_users(int fd, int argc, char *argv[])
4330 regex_t regexbuf;
4331 int havepattern = 0;
4333 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4334 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4336 struct iax2_user *user = NULL;
4337 char auth[90];
4338 char *pstr = "";
4339 struct ao2_iterator i;
4341 switch (argc) {
4342 case 5:
4343 if (!strcasecmp(argv[3], "like")) {
4344 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4345 return RESULT_SHOWUSAGE;
4346 havepattern = 1;
4347 } else
4348 return RESULT_SHOWUSAGE;
4349 case 3:
4350 break;
4351 default:
4352 return RESULT_SHOWUSAGE;
4355 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
4356 i = ao2_iterator_init(users, 0);
4357 for (user = ao2_iterator_next(&i); user;
4358 user_unref(user), user = ao2_iterator_next(&i)) {
4359 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
4360 continue;
4362 if (!ast_strlen_zero(user->secret)) {
4363 ast_copy_string(auth,user->secret,sizeof(auth));
4364 } else if (!ast_strlen_zero(user->inkeys)) {
4365 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
4366 } else
4367 ast_copy_string(auth, "-no secret-", sizeof(auth));
4369 if(ast_test_flag(user,IAX_CODEC_NOCAP))
4370 pstr = "REQ Only";
4371 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
4372 pstr = "Disabled";
4373 else
4374 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
4376 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
4377 user->contexts ? user->contexts->context : context,
4378 user->ha ? "Yes" : "No", pstr);
4381 if (havepattern)
4382 regfree(&regexbuf);
4384 return RESULT_SUCCESS;
4385 #undef FORMAT
4386 #undef FORMAT2
4389 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
4391 regex_t regexbuf;
4392 int havepattern = 0;
4393 int total_peers = 0;
4394 int online_peers = 0;
4395 int offline_peers = 0;
4396 int unmonitored_peers = 0;
4397 struct ao2_iterator i;
4399 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
4400 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
4402 struct iax2_peer *peer = NULL;
4403 char name[256];
4404 int registeredonly=0;
4405 char *term = manager ? "\r\n" : "\n";
4407 switch (argc) {
4408 case 6:
4409 if (!strcasecmp(argv[3], "registered"))
4410 registeredonly = 1;
4411 else
4412 return RESULT_SHOWUSAGE;
4413 if (!strcasecmp(argv[4], "like")) {
4414 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
4415 return RESULT_SHOWUSAGE;
4416 havepattern = 1;
4417 } else
4418 return RESULT_SHOWUSAGE;
4419 break;
4420 case 5:
4421 if (!strcasecmp(argv[3], "like")) {
4422 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
4423 return RESULT_SHOWUSAGE;
4424 havepattern = 1;
4425 } else
4426 return RESULT_SHOWUSAGE;
4427 break;
4428 case 4:
4429 if (!strcasecmp(argv[3], "registered"))
4430 registeredonly = 1;
4431 else
4432 return RESULT_SHOWUSAGE;
4433 break;
4434 case 3:
4435 break;
4436 default:
4437 return RESULT_SHOWUSAGE;
4441 if (s)
4442 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4443 else
4444 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
4446 i = ao2_iterator_init(peers, 0);
4447 for (peer = ao2_iterator_next(&i); peer;
4448 peer_unref(peer), peer = ao2_iterator_next(&i)) {
4449 char nm[20];
4450 char status[20];
4451 char srch[2000];
4452 int retstatus;
4454 if (registeredonly && !peer->addr.sin_addr.s_addr)
4455 continue;
4456 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
4457 continue;
4459 if (!ast_strlen_zero(peer->username))
4460 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
4461 else
4462 ast_copy_string(name, peer->name, sizeof(name));
4464 retstatus = peer_status(peer, status, sizeof(status));
4465 if (retstatus > 0)
4466 online_peers++;
4467 else if (!retstatus)
4468 offline_peers++;
4469 else
4470 unmonitored_peers++;
4472 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
4474 snprintf(srch, sizeof(srch), FORMAT, name,
4475 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4476 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4478 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4479 peer->encmethods ? "(E)" : " ", status, term);
4481 if (s)
4482 astman_append(s, FORMAT, name,
4483 peer->addr.sin_addr.s_addr ? ast_inet_ntoa( peer->addr.sin_addr) : "(Unspecified)",
4484 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4486 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4487 peer->encmethods ? "(E)" : " ", status, term);
4488 else
4489 ast_cli(fd, FORMAT, name,
4490 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
4491 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
4493 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
4494 peer->encmethods ? "(E)" : " ", status, term);
4495 total_peers++;
4498 if (s)
4499 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4500 else
4501 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
4503 if (havepattern)
4504 regfree(&regexbuf);
4506 return RESULT_SUCCESS;
4507 #undef FORMAT
4508 #undef FORMAT2
4511 static int iax2_show_threads(int fd, int argc, char *argv[])
4513 struct iax2_thread *thread = NULL;
4514 time_t t;
4515 int threadcount = 0, dynamiccount = 0;
4516 char type;
4518 if (argc != 3)
4519 return RESULT_SHOWUSAGE;
4521 ast_cli(fd, "IAX2 Thread Information\n");
4522 time(&t);
4523 ast_cli(fd, "Idle Threads:\n");
4524 AST_LIST_LOCK(&idle_list);
4525 AST_LIST_TRAVERSE(&idle_list, thread, list) {
4526 #ifdef DEBUG_SCHED_MULTITHREAD
4527 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4528 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4529 #else
4530 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4531 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4532 #endif
4533 threadcount++;
4535 AST_LIST_UNLOCK(&idle_list);
4536 ast_cli(fd, "Active Threads:\n");
4537 AST_LIST_LOCK(&active_list);
4538 AST_LIST_TRAVERSE(&active_list, thread, list) {
4539 if (thread->type == IAX_TYPE_DYNAMIC)
4540 type = 'D';
4541 else
4542 type = 'P';
4543 #ifdef DEBUG_SCHED_MULTITHREAD
4544 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
4545 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4546 #else
4547 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
4548 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4549 #endif
4550 threadcount++;
4552 AST_LIST_UNLOCK(&active_list);
4553 ast_cli(fd, "Dynamic Threads:\n");
4554 AST_LIST_LOCK(&dynamic_list);
4555 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
4556 #ifdef DEBUG_SCHED_MULTITHREAD
4557 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
4558 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
4559 #else
4560 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
4561 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
4562 #endif
4563 dynamiccount++;
4565 AST_LIST_UNLOCK(&dynamic_list);
4566 ast_cli(fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
4567 return RESULT_SUCCESS;
4570 static int iax2_show_peers(int fd, int argc, char *argv[])
4572 return __iax2_show_peers(0, fd, NULL, argc, argv);
4574 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
4576 ast_cli_netstats(s, -1, 0);
4577 astman_append(s, "\r\n");
4578 return RESULT_SUCCESS;
4581 static int iax2_show_firmware(int fd, int argc, char *argv[])
4583 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
4584 #if !defined(__FreeBSD__)
4585 #define FORMAT "%-15.15s %-15d %-15d\n"
4586 #else /* __FreeBSD__ */
4587 #define FORMAT "%-15.15s %-15d %-15d\n" /* XXX 2.95 ? */
4588 #endif /* __FreeBSD__ */
4589 struct iax_firmware *cur;
4590 if ((argc != 3) && (argc != 4))
4591 return RESULT_SHOWUSAGE;
4592 ast_mutex_lock(&waresl.lock);
4594 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
4595 for (cur = waresl.wares;cur;cur = cur->next) {
4596 if ((argc == 3) || (!strcasecmp(argv[3], (char *)cur->fwh->devname)))
4597 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
4598 (int)ntohl(cur->fwh->datalen));
4600 ast_mutex_unlock(&waresl.lock);
4601 return RESULT_SUCCESS;
4602 #undef FORMAT
4603 #undef FORMAT2
4606 /* JDG: callback to display iax peers in manager */
4607 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
4609 char *a[] = { "iax2", "show", "users" };
4610 int ret;
4611 const char *id = astman_get_header(m,"ActionID");
4613 if (!ast_strlen_zero(id))
4614 astman_append(s, "ActionID: %s\r\n",id);
4615 ret = __iax2_show_peers(1, -1, s, 3, a );
4616 astman_append(s, "\r\n\r\n" );
4617 return ret;
4618 } /* /JDG */
4620 static char *regstate2str(int regstate)
4622 switch(regstate) {
4623 case REG_STATE_UNREGISTERED:
4624 return "Unregistered";
4625 case REG_STATE_REGSENT:
4626 return "Request Sent";
4627 case REG_STATE_AUTHSENT:
4628 return "Auth. Sent";
4629 case REG_STATE_REGISTERED:
4630 return "Registered";
4631 case REG_STATE_REJECTED:
4632 return "Rejected";
4633 case REG_STATE_TIMEOUT:
4634 return "Timeout";
4635 case REG_STATE_NOAUTH:
4636 return "No Authentication";
4637 default:
4638 return "Unknown";
4642 static int iax2_show_registry(int fd, int argc, char *argv[])
4644 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
4645 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
4646 struct iax2_registry *reg = NULL;
4648 char host[80];
4649 char perceived[80];
4650 if (argc != 3)
4651 return RESULT_SHOWUSAGE;
4652 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
4653 AST_LIST_LOCK(&registrations);
4654 AST_LIST_TRAVERSE(&registrations, reg, entry) {
4655 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
4656 if (reg->us.sin_addr.s_addr)
4657 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
4658 else
4659 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
4660 ast_cli(fd, FORMAT, host,
4661 (reg->dnsmgr) ? "Y" : "N",
4662 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
4664 AST_LIST_UNLOCK(&registrations);
4665 return RESULT_SUCCESS;
4666 #undef FORMAT
4667 #undef FORMAT2
4670 static int iax2_show_channels(int fd, int argc, char *argv[])
4672 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
4673 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
4674 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
4675 int x;
4676 int numchans = 0;
4678 if (argc != 3)
4679 return RESULT_SHOWUSAGE;
4680 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
4681 for (x=0;x<IAX_MAX_CALLS;x++) {
4682 ast_mutex_lock(&iaxsl[x]);
4683 if (iaxs[x]) {
4684 int lag, jitter, localdelay;
4685 jb_info jbinfo;
4687 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4688 jb_getinfo(iaxs[x]->jb, &jbinfo);
4689 jitter = jbinfo.jitter;
4690 localdelay = jbinfo.current - jbinfo.min;
4691 } else {
4692 jitter = -1;
4693 localdelay = 0;
4695 lag = iaxs[x]->remote_rr.delay;
4696 ast_cli(fd, FORMAT,
4697 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4698 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
4699 S_OR(iaxs[x]->username, "(None)"),
4700 iaxs[x]->callno, iaxs[x]->peercallno,
4701 iaxs[x]->oseqno, iaxs[x]->iseqno,
4702 lag,
4703 jitter,
4704 localdelay,
4705 ast_getformatname(iaxs[x]->voiceformat) );
4706 numchans++;
4708 ast_mutex_unlock(&iaxsl[x]);
4710 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4711 return RESULT_SUCCESS;
4712 #undef FORMAT
4713 #undef FORMAT2
4714 #undef FORMATB
4717 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
4719 int x;
4720 int numchans = 0;
4721 for (x=0;x<IAX_MAX_CALLS;x++) {
4722 ast_mutex_lock(&iaxsl[x]);
4723 if (iaxs[x]) {
4724 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
4725 char *fmt;
4726 jb_info jbinfo;
4728 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
4729 jb_getinfo(iaxs[x]->jb, &jbinfo);
4730 localjitter = jbinfo.jitter;
4731 localdelay = jbinfo.current - jbinfo.min;
4732 locallost = jbinfo.frames_lost;
4733 locallosspct = jbinfo.losspct/1000;
4734 localdropped = jbinfo.frames_dropped;
4735 localooo = jbinfo.frames_ooo;
4736 } else {
4737 localjitter = -1;
4738 localdelay = 0;
4739 locallost = -1;
4740 locallosspct = -1;
4741 localdropped = 0;
4742 localooo = -1;
4744 if (limit_fmt)
4745 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
4746 else
4747 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
4748 if (s)
4750 astman_append(s, fmt,
4751 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4752 iaxs[x]->pingtime,
4753 localjitter,
4754 localdelay,
4755 locallost,
4756 locallosspct,
4757 localdropped,
4758 localooo,
4759 iaxs[x]->frames_received/1000,
4760 iaxs[x]->remote_rr.jitter,
4761 iaxs[x]->remote_rr.delay,
4762 iaxs[x]->remote_rr.losscnt,
4763 iaxs[x]->remote_rr.losspct,
4764 iaxs[x]->remote_rr.dropped,
4765 iaxs[x]->remote_rr.ooo,
4766 iaxs[x]->remote_rr.packets/1000);
4767 else
4768 ast_cli(fd, fmt,
4769 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
4770 iaxs[x]->pingtime,
4771 localjitter,
4772 localdelay,
4773 locallost,
4774 locallosspct,
4775 localdropped,
4776 localooo,
4777 iaxs[x]->frames_received/1000,
4778 iaxs[x]->remote_rr.jitter,
4779 iaxs[x]->remote_rr.delay,
4780 iaxs[x]->remote_rr.losscnt,
4781 iaxs[x]->remote_rr.losspct,
4782 iaxs[x]->remote_rr.dropped,
4783 iaxs[x]->remote_rr.ooo,
4784 iaxs[x]->remote_rr.packets/1000
4786 numchans++;
4788 ast_mutex_unlock(&iaxsl[x]);
4790 return numchans;
4793 static int iax2_show_netstats(int fd, int argc, char *argv[])
4795 int numchans = 0;
4796 if (argc != 3)
4797 return RESULT_SHOWUSAGE;
4798 ast_cli(fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
4799 ast_cli(fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
4800 numchans = ast_cli_netstats(NULL, fd, 1);
4801 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
4802 return RESULT_SUCCESS;
4805 static int iax2_do_debug(int fd, int argc, char *argv[])
4807 if (argc < 2 || argc > 3)
4808 return RESULT_SHOWUSAGE;
4809 iaxdebug = 1;
4810 ast_cli(fd, "IAX2 Debugging Enabled\n");
4811 return RESULT_SUCCESS;
4814 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
4816 if (argc < 3 || argc > 4)
4817 return RESULT_SHOWUSAGE;
4818 iaxtrunkdebug = 1;
4819 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
4820 return RESULT_SUCCESS;
4823 static int iax2_do_jb_debug(int fd, int argc, char *argv[])
4825 if (argc < 3 || argc > 4)
4826 return RESULT_SHOWUSAGE;
4827 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
4828 ast_cli(fd, "IAX2 Jitterbuffer Debugging Enabled\n");
4829 return RESULT_SUCCESS;
4832 static int iax2_no_debug(int fd, int argc, char *argv[])
4834 if (argc < 3 || argc > 4)
4835 return RESULT_SHOWUSAGE;
4836 iaxdebug = 0;
4837 ast_cli(fd, "IAX2 Debugging Disabled\n");
4838 return RESULT_SUCCESS;
4841 static int iax2_no_trunk_debug(int fd, int argc, char *argv[])
4843 if (argc < 4 || argc > 5)
4844 return RESULT_SHOWUSAGE;
4845 iaxtrunkdebug = 0;
4846 ast_cli(fd, "IAX2 Trunk Debugging Disabled\n");
4847 return RESULT_SUCCESS;
4850 static int iax2_no_jb_debug(int fd, int argc, char *argv[])
4852 if (argc < 4 || argc > 5)
4853 return RESULT_SHOWUSAGE;
4854 jb_setoutput(jb_error_output, jb_warning_output, NULL);
4855 jb_debug_output("\n");
4856 ast_cli(fd, "IAX2 Jitterbuffer Debugging Disabled\n");
4857 return RESULT_SUCCESS;
4860 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
4862 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4863 int res = -1;
4864 ast_mutex_lock(&iaxsl[callno]);
4865 if (iaxs[callno]) {
4866 /* If there's an outstanding error, return failure now */
4867 if (!iaxs[callno]->error) {
4868 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
4869 res = 0;
4870 /* Don't waste bandwidth sending null frames */
4871 else if (f->frametype == AST_FRAME_NULL)
4872 res = 0;
4873 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
4874 res = 0;
4875 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
4876 res = 0;
4877 else
4878 /* Simple, just queue for transmission */
4879 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
4880 } else {
4881 if (option_debug)
4882 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
4885 /* If it's already gone, just return */
4886 ast_mutex_unlock(&iaxsl[callno]);
4887 return res;
4890 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
4891 int now, int transfer, int final)
4893 struct ast_frame f = { 0, };
4895 f.frametype = type;
4896 f.subclass = command;
4897 f.datalen = datalen;
4898 f.src = __FUNCTION__;
4899 f.data = (void *) data;
4901 return iax2_send(i, &f, ts, seqno, now, transfer, final);
4904 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4906 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
4909 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4911 int res;
4912 ast_mutex_lock(&iaxsl[callno]);
4913 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
4914 ast_mutex_unlock(&iaxsl[callno]);
4915 return res;
4919 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
4920 * the pvt struct for the given call number may disappear during its
4921 * execution.
4923 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4925 int call_num = i->callno;
4926 /* It is assumed that the callno has already been locked */
4927 iax2_predestroy(i->callno);
4928 if (!iaxs[call_num])
4929 return -1;
4930 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
4933 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
4935 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
4938 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
4940 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
4943 static int apply_context(struct iax2_context *con, const char *context)
4945 while(con) {
4946 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
4947 return -1;
4948 con = con->next;
4950 return 0;
4954 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
4956 /* Start pessimistic */
4957 int res = -1;
4958 int version = 2;
4959 struct iax2_user *user = NULL, *best = NULL;
4960 int bestscore = 0;
4961 int gotcapability = 0;
4962 struct ast_variable *v = NULL, *tmpvar = NULL;
4963 struct ao2_iterator i;
4965 if (!iaxs[callno])
4966 return res;
4967 if (ies->called_number)
4968 ast_string_field_set(iaxs[callno], exten, ies->called_number);
4969 if (ies->calling_number) {
4970 ast_shrink_phone_number(ies->calling_number);
4971 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
4973 if (ies->calling_name)
4974 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
4975 if (ies->calling_ani)
4976 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
4977 if (ies->dnid)
4978 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
4979 if (ies->rdnis)
4980 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
4981 if (ies->called_context)
4982 ast_string_field_set(iaxs[callno], context, ies->called_context);
4983 if (ies->language)
4984 ast_string_field_set(iaxs[callno], language, ies->language);
4985 if (ies->username)
4986 ast_string_field_set(iaxs[callno], username, ies->username);
4987 if (ies->calling_ton > -1)
4988 iaxs[callno]->calling_ton = ies->calling_ton;
4989 if (ies->calling_tns > -1)
4990 iaxs[callno]->calling_tns = ies->calling_tns;
4991 if (ies->calling_pres > -1)
4992 iaxs[callno]->calling_pres = ies->calling_pres;
4993 if (ies->format)
4994 iaxs[callno]->peerformat = ies->format;
4995 if (ies->adsicpe)
4996 iaxs[callno]->peeradsicpe = ies->adsicpe;
4997 if (ies->capability) {
4998 gotcapability = 1;
4999 iaxs[callno]->peercapability = ies->capability;
5001 if (ies->version)
5002 version = ies->version;
5004 /* Use provided preferences until told otherwise for actual preferences */
5005 if(ies->codec_prefs) {
5006 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
5007 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
5010 if (!gotcapability)
5011 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
5012 if (version > IAX_PROTO_VERSION) {
5013 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
5014 ast_inet_ntoa(sin->sin_addr), version);
5015 return res;
5017 /* Search the userlist for a compatible entry, and fill in the rest */
5018 i = ao2_iterator_init(users, 0);
5019 while ((user = ao2_iterator_next(&i))) {
5020 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
5021 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
5022 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
5023 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
5024 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
5025 if (!ast_strlen_zero(iaxs[callno]->username)) {
5026 /* Exact match, stop right now. */
5027 if (best)
5028 user_unref(best);
5029 best = user;
5030 break;
5031 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5032 /* No required authentication */
5033 if (user->ha) {
5034 /* There was host authentication and we passed, bonus! */
5035 if (bestscore < 4) {
5036 bestscore = 4;
5037 if (best)
5038 user_unref(best);
5039 best = user;
5040 continue;
5042 } else {
5043 /* No host access, but no secret, either, not bad */
5044 if (bestscore < 3) {
5045 bestscore = 3;
5046 if (best)
5047 user_unref(best);
5048 best = user;
5049 continue;
5052 } else {
5053 if (user->ha) {
5054 /* Authentication, but host access too, eh, it's something.. */
5055 if (bestscore < 2) {
5056 bestscore = 2;
5057 if (best)
5058 user_unref(best);
5059 best = user;
5060 continue;
5062 } else {
5063 /* Authentication and no host access... This is our baseline */
5064 if (bestscore < 1) {
5065 bestscore = 1;
5066 if (best)
5067 user_unref(best);
5068 best = user;
5069 continue;
5074 user_unref(user);
5076 user = best;
5077 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
5078 user = realtime_user(iaxs[callno]->username, sin);
5079 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
5080 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
5081 user = user_unref(user);
5084 if (user) {
5085 /* We found our match (use the first) */
5086 /* copy vars */
5087 for (v = user->vars ; v ; v = v->next) {
5088 if((tmpvar = ast_variable_new(v->name, v->value))) {
5089 tmpvar->next = iaxs[callno]->vars;
5090 iaxs[callno]->vars = tmpvar;
5093 /* If a max AUTHREQ restriction is in place, activate it */
5094 if (user->maxauthreq > 0)
5095 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
5096 iaxs[callno]->prefs = user->prefs;
5097 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
5098 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
5099 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
5100 iaxs[callno]->encmethods = user->encmethods;
5101 /* Store the requested username if not specified */
5102 if (ast_strlen_zero(iaxs[callno]->username))
5103 ast_string_field_set(iaxs[callno], username, user->name);
5104 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5105 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
5106 iaxs[callno]->capability = user->capability;
5107 /* And use the default context */
5108 if (ast_strlen_zero(iaxs[callno]->context)) {
5109 if (user->contexts)
5110 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5111 else
5112 ast_string_field_set(iaxs[callno], context, context);
5114 /* And any input keys */
5115 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
5116 /* And the permitted authentication methods */
5117 iaxs[callno]->authmethods = user->authmethods;
5118 iaxs[callno]->adsi = user->adsi;
5119 /* If they have callerid, override the given caller id. Always store the ANI */
5120 if (!ast_strlen_zero(iaxs[callno]->cid_num) || !ast_strlen_zero(iaxs[callno]->cid_name)) {
5121 if (ast_test_flag(user, IAX_HASCALLERID)) {
5122 iaxs[callno]->calling_tns = 0;
5123 iaxs[callno]->calling_ton = 0;
5124 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
5125 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
5126 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
5128 if (ast_strlen_zero(iaxs[callno]->ani))
5129 ast_string_field_set(iaxs[callno], ani, user->cid_num);
5130 } else {
5131 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
5133 if (!ast_strlen_zero(user->accountcode))
5134 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
5135 if (!ast_strlen_zero(user->mohinterpret))
5136 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
5137 if (!ast_strlen_zero(user->mohsuggest))
5138 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
5139 if (user->amaflags)
5140 iaxs[callno]->amaflags = user->amaflags;
5141 if (!ast_strlen_zero(user->language))
5142 ast_string_field_set(iaxs[callno], language, user->language);
5143 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
5144 /* Keep this check last */
5145 if (!ast_strlen_zero(user->dbsecret)) {
5146 char *family, *key=NULL;
5147 char buf[80];
5148 family = ast_strdupa(user->dbsecret);
5149 key = strchr(family, '/');
5150 if (key) {
5151 *key = '\0';
5152 key++;
5154 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
5155 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
5156 else
5157 ast_string_field_set(iaxs[callno], secret, buf);
5158 } else
5159 ast_string_field_set(iaxs[callno], secret, user->secret);
5160 res = 0;
5161 user = user_unref(user);
5163 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
5164 return res;
5167 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
5169 struct ast_iax2_full_hdr fh;
5170 fh.scallno = htons(src | IAX_FLAG_FULL);
5171 fh.dcallno = htons(dst);
5172 fh.ts = 0;
5173 fh.oseqno = 0;
5174 fh.iseqno = 0;
5175 fh.type = AST_FRAME_IAX;
5176 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
5177 if (iaxdebug)
5178 iax_showframe(NULL, &fh, 0, sin, 0);
5179 if (option_debug)
5180 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
5181 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
5182 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
5185 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
5187 /* Select exactly one common encryption if there are any */
5188 p->encmethods &= enc;
5189 if (p->encmethods) {
5190 if (p->encmethods & IAX_ENCRYPT_AES128)
5191 p->encmethods = IAX_ENCRYPT_AES128;
5192 else
5193 p->encmethods = 0;
5198 * \pre iaxsl[call_num] is locked
5200 * \note Since this function calls send_command_final(), the pvt struct for the given
5201 * call number may disappear while executing this function.
5203 static int authenticate_request(int call_num)
5205 struct iax_ie_data ied;
5206 int res = -1, authreq_restrict = 0;
5207 char challenge[10];
5208 struct chan_iax2_pvt *p = iaxs[call_num];
5210 memset(&ied, 0, sizeof(ied));
5212 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
5213 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5214 struct iax2_user *user, tmp_user = {
5215 .name = p->username,
5218 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5219 if (user) {
5220 if (user->curauthreq == user->maxauthreq)
5221 authreq_restrict = 1;
5222 else
5223 user->curauthreq++;
5224 user = user_unref(user);
5228 /* If the AUTHREQ limit test failed, send back an error */
5229 if (authreq_restrict) {
5230 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
5231 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
5232 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
5233 return 0;
5236 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
5237 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
5238 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
5239 ast_string_field_set(p, challenge, challenge);
5240 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
5241 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
5243 if (p->encmethods)
5244 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
5246 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
5248 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
5250 if (p->encmethods)
5251 ast_set_flag(p, IAX_ENCRYPTED);
5253 return res;
5256 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
5258 char requeststr[256];
5259 char md5secret[256] = "";
5260 char secret[256] = "";
5261 char rsasecret[256] = "";
5262 int res = -1;
5263 int x;
5264 struct iax2_user *user, tmp_user = {
5265 .name = p->username,
5268 user = ao2_find(users, &tmp_user, OBJ_POINTER);
5269 if (user) {
5270 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
5271 ast_atomic_fetchadd_int(&user->curauthreq, -1);
5272 ast_clear_flag(p, IAX_MAXAUTHREQ);
5274 ast_string_field_set(p, host, user->name);
5275 user = user_unref(user);
5278 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
5279 return res;
5280 if (ies->password)
5281 ast_copy_string(secret, ies->password, sizeof(secret));
5282 if (ies->md5_result)
5283 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5284 if (ies->rsa_result)
5285 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5286 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
5287 struct ast_key *key;
5288 char *keyn;
5289 char tmpkey[256];
5290 char *stringp=NULL;
5291 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
5292 stringp=tmpkey;
5293 keyn = strsep(&stringp, ":");
5294 while(keyn) {
5295 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5296 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
5297 res = 0;
5298 break;
5299 } else if (!key)
5300 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
5301 keyn = strsep(&stringp, ":");
5303 } else if (p->authmethods & IAX_AUTH_MD5) {
5304 struct MD5Context md5;
5305 unsigned char digest[16];
5306 char *tmppw, *stringp;
5308 tmppw = ast_strdupa(p->secret);
5309 stringp = tmppw;
5310 while((tmppw = strsep(&stringp, ";"))) {
5311 MD5Init(&md5);
5312 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
5313 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5314 MD5Final(digest, &md5);
5315 /* If they support md5, authenticate with it. */
5316 for (x=0;x<16;x++)
5317 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5318 if (!strcasecmp(requeststr, md5secret)) {
5319 res = 0;
5320 break;
5323 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
5324 if (!strcmp(secret, p->secret))
5325 res = 0;
5327 return res;
5330 /*! \brief Verify inbound registration */
5331 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5333 char requeststr[256] = "";
5334 char peer[256] = "";
5335 char md5secret[256] = "";
5336 char rsasecret[256] = "";
5337 char secret[256] = "";
5338 struct iax2_peer *p = NULL;
5339 struct ast_key *key;
5340 char *keyn;
5341 int x;
5342 int expire = 0;
5343 int res = -1;
5345 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
5346 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
5347 if (ies->username)
5348 ast_copy_string(peer, ies->username, sizeof(peer));
5349 if (ies->password)
5350 ast_copy_string(secret, ies->password, sizeof(secret));
5351 if (ies->md5_result)
5352 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
5353 if (ies->rsa_result)
5354 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
5355 if (ies->refresh)
5356 expire = ies->refresh;
5358 if (ast_strlen_zero(peer)) {
5359 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
5360 return -1;
5363 /* SLD: first call to lookup peer during registration */
5364 ast_mutex_unlock(&iaxsl[callno]);
5365 p = find_peer(peer, 1);
5366 ast_mutex_lock(&iaxsl[callno]);
5367 if (!p || !iaxs[callno]) {
5368 if (authdebug && !p)
5369 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5370 goto return_unref;
5373 if (!ast_test_flag(p, IAX_DYNAMIC)) {
5374 if (authdebug)
5375 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
5376 goto return_unref;
5379 if (!ast_apply_ha(p->ha, sin)) {
5380 if (authdebug)
5381 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5382 goto return_unref;
5384 if (!inaddrcmp(&p->addr, sin))
5385 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
5386 ast_string_field_set(iaxs[callno], secret, p->secret);
5387 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
5388 /* Check secret against what we have on file */
5389 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5390 if (!ast_strlen_zero(p->inkeys)) {
5391 char tmpkeys[256];
5392 char *stringp=NULL;
5393 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
5394 stringp=tmpkeys;
5395 keyn = strsep(&stringp, ":");
5396 while(keyn) {
5397 key = ast_key_get(keyn, AST_KEY_PUBLIC);
5398 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
5399 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5400 break;
5401 } else if (!key)
5402 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
5403 keyn = strsep(&stringp, ":");
5405 if (!keyn) {
5406 if (authdebug)
5407 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
5408 goto return_unref;
5410 } else {
5411 if (authdebug)
5412 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
5413 goto return_unref;
5415 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
5416 struct MD5Context md5;
5417 unsigned char digest[16];
5418 char *tmppw, *stringp;
5420 tmppw = ast_strdupa(p->secret);
5421 stringp = tmppw;
5422 while((tmppw = strsep(&stringp, ";"))) {
5423 MD5Init(&md5);
5424 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
5425 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
5426 MD5Final(digest, &md5);
5427 for (x=0;x<16;x++)
5428 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
5429 if (!strcasecmp(requeststr, md5secret))
5430 break;
5432 if (tmppw) {
5433 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5434 } else {
5435 if (authdebug)
5436 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
5437 goto return_unref;
5439 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
5440 /* They've provided a plain text password and we support that */
5441 if (strcmp(secret, p->secret)) {
5442 if (authdebug)
5443 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
5444 goto return_unref;
5445 } else
5446 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
5447 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
5448 if (authdebug)
5449 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
5450 goto return_unref;
5452 ast_string_field_set(iaxs[callno], peer, peer);
5453 /* Choose lowest expiry number */
5454 if (expire && (expire < iaxs[callno]->expiry))
5455 iaxs[callno]->expiry = expire;
5457 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5459 res = 0;
5461 return_unref:
5462 if (p)
5463 peer_unref(p);
5465 return res;
5468 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
5470 int res = -1;
5471 int x;
5472 if (!ast_strlen_zero(keyn)) {
5473 if (!(authmethods & IAX_AUTH_RSA)) {
5474 if (ast_strlen_zero(secret))
5475 ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
5476 } else if (ast_strlen_zero(challenge)) {
5477 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
5478 } else {
5479 char sig[256];
5480 struct ast_key *key;
5481 key = ast_key_get(keyn, AST_KEY_PRIVATE);
5482 if (!key) {
5483 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
5484 } else {
5485 if (ast_sign(key, (char*)challenge, sig)) {
5486 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
5487 res = -1;
5488 } else {
5489 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
5490 res = 0;
5495 /* Fall back */
5496 if (res && !ast_strlen_zero(secret)) {
5497 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
5498 struct MD5Context md5;
5499 unsigned char digest[16];
5500 char digres[128];
5501 MD5Init(&md5);
5502 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
5503 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
5504 MD5Final(digest, &md5);
5505 /* If they support md5, authenticate with it. */
5506 for (x=0;x<16;x++)
5507 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
5508 if (ecx && dcx)
5509 build_enc_keys(digest, ecx, dcx);
5510 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
5511 res = 0;
5512 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
5513 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
5514 res = 0;
5515 } else
5516 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
5518 return res;
5522 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
5523 * so do not call this function with a pvt lock held.
5525 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
5527 struct iax2_peer *peer = NULL;
5528 /* Start pessimistic */
5529 int res = -1;
5530 int authmethods = 0;
5531 struct iax_ie_data ied;
5532 uint16_t callno = p->callno;
5534 memset(&ied, 0, sizeof(ied));
5536 if (ies->username)
5537 ast_string_field_set(p, username, ies->username);
5538 if (ies->challenge)
5539 ast_string_field_set(p, challenge, ies->challenge);
5540 if (ies->authmethods)
5541 authmethods = ies->authmethods;
5542 if (authmethods & IAX_AUTH_MD5)
5543 merge_encryption(p, ies->encmethods);
5544 else
5545 p->encmethods = 0;
5547 /* Check for override RSA authentication first */
5548 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
5549 /* Normal password authentication */
5550 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5551 } else {
5552 struct ao2_iterator i = ao2_iterator_init(peers, 0);
5553 while ((peer = ao2_iterator_next(&i))) {
5554 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
5555 /* No peer specified at our end, or this is the peer */
5556 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
5557 /* No username specified in peer rule, or this is the right username */
5558 && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
5559 /* No specified host, or this is our host */
5561 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5562 if (!res) {
5563 peer_unref(peer);
5564 break;
5567 peer_unref(peer);
5569 if (!peer) {
5570 /* We checked our list and didn't find one. It's unlikely, but possible,
5571 that we're trying to authenticate *to* a realtime peer */
5572 const char *peer_name = ast_strdupa(p->peer);
5573 ast_mutex_unlock(&iaxsl[callno]);
5574 if ((peer = realtime_peer(peer_name, NULL))) {
5575 ast_mutex_lock(&iaxsl[callno]);
5576 if (!(p = iaxs[callno])) {
5577 peer_unref(peer);
5578 return -1;
5580 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
5581 peer_unref(peer);
5583 if (!peer) {
5584 ast_mutex_lock(&iaxsl[callno]);
5585 if (!(p = iaxs[callno]))
5586 return -1;
5590 if (ies->encmethods)
5591 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
5592 if (!res)
5593 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
5594 return res;
5597 static int iax2_do_register(struct iax2_registry *reg);
5599 static void __iax2_do_register_s(const void *data)
5601 struct iax2_registry *reg = (struct iax2_registry *)data;
5602 reg->expire = -1;
5603 iax2_do_register(reg);
5606 static int iax2_do_register_s(const void *data)
5608 #ifdef SCHED_MULTITHREADED
5609 if (schedule_action(__iax2_do_register_s, data))
5610 #endif
5611 __iax2_do_register_s(data);
5612 return 0;
5615 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5617 int newcall = 0;
5618 char newip[256];
5619 struct iax_ie_data ied;
5620 struct sockaddr_in new;
5623 memset(&ied, 0, sizeof(ied));
5624 if (ies->apparent_addr)
5625 bcopy(ies->apparent_addr, &new, sizeof(new));
5626 if (ies->callno)
5627 newcall = ies->callno;
5628 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
5629 ast_log(LOG_WARNING, "Invalid transfer request\n");
5630 return -1;
5632 pvt->transfercallno = newcall;
5633 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
5634 inet_aton(newip, &pvt->transfer.sin_addr);
5635 pvt->transfer.sin_family = AF_INET;
5636 pvt->transferring = TRANSFER_BEGIN;
5637 pvt->transferid = ies->transferid;
5638 if (ies->transferid)
5639 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
5640 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
5641 return 0;
5644 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
5646 char exten[256] = "";
5647 int status = CACHE_FLAG_UNKNOWN;
5648 int expiry = iaxdefaultdpcache;
5649 int x;
5650 int matchmore = 0;
5651 struct iax2_dpcache *dp, *prev;
5653 if (ies->called_number)
5654 ast_copy_string(exten, ies->called_number, sizeof(exten));
5656 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
5657 status = CACHE_FLAG_EXISTS;
5658 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
5659 status = CACHE_FLAG_CANEXIST;
5660 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
5661 status = CACHE_FLAG_NONEXISTENT;
5663 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
5664 /* Don't really do anything with this */
5666 if (ies->refresh)
5667 expiry = ies->refresh;
5668 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
5669 matchmore = CACHE_FLAG_MATCHMORE;
5670 ast_mutex_lock(&dpcache_lock);
5671 prev = NULL;
5672 dp = pvt->dpentries;
5673 while(dp) {
5674 if (!strcmp(dp->exten, exten)) {
5675 /* Let them go */
5676 if (prev)
5677 prev->peer = dp->peer;
5678 else
5679 pvt->dpentries = dp->peer;
5680 dp->peer = NULL;
5681 dp->callno = 0;
5682 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
5683 if (dp->flags & CACHE_FLAG_PENDING) {
5684 dp->flags &= ~CACHE_FLAG_PENDING;
5685 dp->flags |= status;
5686 dp->flags |= matchmore;
5688 /* Wake up waiters */
5689 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
5690 if (dp->waiters[x] > -1)
5691 write(dp->waiters[x], "asdf", 4);
5693 prev = dp;
5694 dp = dp->peer;
5696 ast_mutex_unlock(&dpcache_lock);
5697 return 0;
5700 static int complete_transfer(int callno, struct iax_ies *ies)
5702 int peercallno = 0;
5703 struct chan_iax2_pvt *pvt = iaxs[callno];
5704 struct iax_frame *cur;
5705 jb_frame frame;
5707 if (ies->callno)
5708 peercallno = ies->callno;
5710 if (peercallno < 1) {
5711 ast_log(LOG_WARNING, "Invalid transfer request\n");
5712 return -1;
5714 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
5715 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
5716 /* Reset sequence numbers */
5717 pvt->oseqno = 0;
5718 pvt->rseqno = 0;
5719 pvt->iseqno = 0;
5720 pvt->aseqno = 0;
5721 pvt->peercallno = peercallno;
5722 pvt->transferring = TRANSFER_NONE;
5723 pvt->svoiceformat = -1;
5724 pvt->voiceformat = 0;
5725 pvt->svideoformat = -1;
5726 pvt->videoformat = 0;
5727 pvt->transfercallno = -1;
5728 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
5729 memset(&pvt->offset, 0, sizeof(pvt->offset));
5730 /* reset jitterbuffer */
5731 while(jb_getall(pvt->jb,&frame) == JB_OK)
5732 iax2_frame_free(frame.data);
5733 jb_reset(pvt->jb);
5734 pvt->lag = 0;
5735 pvt->last = 0;
5736 pvt->lastsent = 0;
5737 pvt->nextpred = 0;
5738 pvt->pingtime = DEFAULT_RETRY_TIME;
5739 AST_LIST_LOCK(&iaxq.queue);
5740 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
5741 /* We must cancel any packets that would have been transmitted
5742 because now we're talking to someone new. It's okay, they
5743 were transmitted to someone that didn't care anyway. */
5744 if (callno == cur->callno)
5745 cur->retries = -1;
5747 AST_LIST_UNLOCK(&iaxq.queue);
5748 return 0;
5751 /*! \brief Acknowledgment received for OUR registration */
5752 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
5754 struct iax2_registry *reg;
5755 /* Start pessimistic */
5756 char peer[256] = "";
5757 char msgstatus[60];
5758 int refresh = 60;
5759 char ourip[256] = "<Unspecified>";
5760 struct sockaddr_in oldus;
5761 struct sockaddr_in us;
5762 int oldmsgs;
5764 memset(&us, 0, sizeof(us));
5765 if (ies->apparent_addr)
5766 bcopy(ies->apparent_addr, &us, sizeof(us));
5767 if (ies->username)
5768 ast_copy_string(peer, ies->username, sizeof(peer));
5769 if (ies->refresh)
5770 refresh = ies->refresh;
5771 if (ies->calling_number) {
5772 /* We don't do anything with it really, but maybe we should */
5774 reg = iaxs[callno]->reg;
5775 if (!reg) {
5776 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
5777 return -1;
5779 memcpy(&oldus, &reg->us, sizeof(oldus));
5780 oldmsgs = reg->messages;
5781 if (inaddrcmp(&reg->addr, sin)) {
5782 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
5783 return -1;
5785 memcpy(&reg->us, &us, sizeof(reg->us));
5786 if (ies->msgcount >= 0)
5787 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
5788 /* always refresh the registration at the interval requested by the server
5789 we are registering to
5791 reg->refresh = refresh;
5792 AST_SCHED_DEL(sched, reg->expire);
5793 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
5794 if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
5795 if (option_verbose > 2) {
5796 if (reg->messages > 255)
5797 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
5798 else if (reg->messages > 1)
5799 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
5800 else if (reg->messages > 0)
5801 snprintf(msgstatus, sizeof(msgstatus), " with 1 new message waiting\n");
5802 else
5803 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
5804 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
5805 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
5807 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
5809 reg->regstate = REG_STATE_REGISTERED;
5810 return 0;
5813 static int iax2_register(char *value, int lineno)
5815 struct iax2_registry *reg;
5816 char copy[256];
5817 char *username, *hostname, *secret;
5818 char *porta;
5819 char *stringp=NULL;
5821 if (!value)
5822 return -1;
5823 ast_copy_string(copy, value, sizeof(copy));
5824 stringp=copy;
5825 username = strsep(&stringp, "@");
5826 hostname = strsep(&stringp, "@");
5827 if (!hostname) {
5828 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
5829 return -1;
5831 stringp=username;
5832 username = strsep(&stringp, ":");
5833 secret = strsep(&stringp, ":");
5834 stringp=hostname;
5835 hostname = strsep(&stringp, ":");
5836 porta = strsep(&stringp, ":");
5838 if (porta && !atoi(porta)) {
5839 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
5840 return -1;
5842 if (!(reg = ast_calloc(1, sizeof(*reg))))
5843 return -1;
5844 if (ast_dnsmgr_lookup(hostname, &reg->addr.sin_addr, &reg->dnsmgr) < 0) {
5845 free(reg);
5846 return -1;
5848 ast_copy_string(reg->username, username, sizeof(reg->username));
5849 if (secret)
5850 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
5851 reg->expire = -1;
5852 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
5853 reg->addr.sin_family = AF_INET;
5854 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
5855 AST_LIST_LOCK(&registrations);
5856 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
5857 AST_LIST_UNLOCK(&registrations);
5859 return 0;
5862 static void register_peer_exten(struct iax2_peer *peer, int onoff)
5864 char multi[256];
5865 char *stringp, *ext;
5866 if (!ast_strlen_zero(regcontext)) {
5867 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
5868 stringp = multi;
5869 while((ext = strsep(&stringp, "&"))) {
5870 if (onoff) {
5871 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
5872 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
5873 "Noop", ast_strdup(peer->name), ast_free, "IAX2");
5874 } else
5875 ast_context_remove_extension(regcontext, ext, 1, NULL);
5879 static void prune_peers(void);
5881 static void unlink_peer(struct iax2_peer *peer)
5883 if (peer->expire > -1) {
5884 if (!ast_sched_del(sched, peer->expire)) {
5885 peer->expire = -1;
5886 peer_unref(peer);
5890 if (peer->pokeexpire > -1) {
5891 if (!ast_sched_del(sched, peer->pokeexpire)) {
5892 peer->pokeexpire = -1;
5893 peer_unref(peer);
5897 ao2_unlink(peers, peer);
5900 static void __expire_registry(const void *data)
5902 struct iax2_peer *peer = (struct iax2_peer *) data;
5904 if (!peer)
5905 return;
5907 peer->expire = -1;
5909 if (option_debug)
5910 ast_log(LOG_DEBUG, "Expiring registration for peer '%s'\n", peer->name);
5911 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
5912 realtime_update_peer(peer->name, &peer->addr, 0);
5913 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
5914 /* Reset the address */
5915 memset(&peer->addr, 0, sizeof(peer->addr));
5916 /* Reset expiry value */
5917 peer->expiry = min_reg_expire;
5918 if (!ast_test_flag(peer, IAX_TEMPONLY))
5919 ast_db_del("IAX/Registry", peer->name);
5920 register_peer_exten(peer, 0);
5921 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
5922 if (iax2_regfunk)
5923 iax2_regfunk(peer->name, 0);
5925 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
5926 unlink_peer(peer);
5928 peer_unref(peer);
5931 static int expire_registry(const void *data)
5933 #ifdef SCHED_MULTITHREADED
5934 if (schedule_action(__expire_registry, data))
5935 #endif
5936 __expire_registry(data);
5937 return 0;
5940 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
5942 static void reg_source_db(struct iax2_peer *p)
5944 char data[80];
5945 struct in_addr in;
5946 char *c, *d;
5947 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
5948 c = strchr(data, ':');
5949 if (c) {
5950 *c = '\0';
5951 c++;
5952 if (inet_aton(data, &in)) {
5953 d = strchr(c, ':');
5954 if (d) {
5955 *d = '\0';
5956 d++;
5957 if (option_verbose > 2)
5958 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
5959 ast_inet_ntoa(in), atoi(c), atoi(d));
5960 iax2_poke_peer(p, 0);
5961 p->expiry = atoi(d);
5962 memset(&p->addr, 0, sizeof(p->addr));
5963 p->addr.sin_family = AF_INET;
5964 p->addr.sin_addr = in;
5965 p->addr.sin_port = htons(atoi(c));
5966 if (p->expire > -1) {
5967 if (!ast_sched_del(sched, p->expire)) {
5968 p->expire = -1;
5969 peer_unref(p);
5972 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
5973 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
5974 if (p->expire == -1)
5975 peer_unref(p);
5976 if (iax2_regfunk)
5977 iax2_regfunk(p->name, 1);
5978 register_peer_exten(p, 1);
5987 * \pre iaxsl[callno] is locked
5989 * \note Since this function calls send_command_final(), the pvt struct for
5990 * the given call number may disappear while executing this function.
5992 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
5994 /* Called from IAX thread only, with proper iaxsl lock */
5995 struct iax_ie_data ied;
5996 struct iax2_peer *p;
5997 int msgcount;
5998 char data[80];
5999 int version;
6000 const char *peer_name;
6001 int res = -1;
6003 memset(&ied, 0, sizeof(ied));
6005 peer_name = ast_strdupa(iaxs[callno]->peer);
6007 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6008 ast_mutex_unlock(&iaxsl[callno]);
6009 if (!(p = find_peer(peer_name, 1))) {
6010 ast_mutex_lock(&iaxsl[callno]);
6011 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6012 return -1;
6014 ast_mutex_lock(&iaxsl[callno]);
6015 if (!iaxs[callno])
6016 goto return_unref;
6018 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6019 if (sin->sin_addr.s_addr) {
6020 time_t nowtime;
6021 time(&nowtime);
6022 realtime_update_peer(peer_name, sin, nowtime);
6023 } else {
6024 realtime_update_peer(peer_name, sin, 0);
6027 if (inaddrcmp(&p->addr, sin)) {
6028 if (iax2_regfunk)
6029 iax2_regfunk(p->name, 1);
6030 /* Stash the IP address from which they registered */
6031 memcpy(&p->addr, sin, sizeof(p->addr));
6032 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
6033 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
6034 ast_db_put("IAX/Registry", p->name, data);
6035 if (option_verbose > 2)
6036 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
6037 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
6038 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
6039 register_peer_exten(p, 1);
6040 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6041 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
6042 if (option_verbose > 2)
6043 ast_verbose(VERBOSE_PREFIX_3 "Unregistered IAX2 '%s' (%s)\n", p->name,
6044 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6045 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
6046 register_peer_exten(p, 0);
6047 ast_db_del("IAX/Registry", p->name);
6048 ast_device_state_changed("IAX2/%s", p->name); /* Activate notification */
6050 /* Update the host */
6051 /* Verify that the host is really there */
6052 iax2_poke_peer(p, callno);
6055 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6056 if (!iaxs[callno]) {
6057 res = 0;
6058 goto return_unref;
6061 /* Store socket fd */
6062 p->sockfd = fd;
6063 /* Setup the expiry */
6064 if (p->expire > -1) {
6065 if (!ast_sched_del(sched, p->expire)) {
6066 p->expire = -1;
6067 peer_unref(p);
6070 /* treat an unspecified refresh interval as the minimum */
6071 if (!refresh)
6072 refresh = min_reg_expire;
6073 if (refresh > max_reg_expire) {
6074 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6075 p->name, max_reg_expire, refresh);
6076 p->expiry = max_reg_expire;
6077 } else if (refresh < min_reg_expire) {
6078 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
6079 p->name, min_reg_expire, refresh);
6080 p->expiry = min_reg_expire;
6081 } else {
6082 p->expiry = refresh;
6084 if (p->expiry && sin->sin_addr.s_addr) {
6085 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6086 if (p->expire == -1)
6087 peer_unref(p);
6089 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
6090 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
6091 if (sin->sin_addr.s_addr) {
6092 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
6093 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
6094 if (!ast_strlen_zero(p->mailbox)) {
6095 int new, old;
6096 ast_app_inboxcount(p->mailbox, &new, &old);
6097 if (new > 255)
6098 new = 255;
6099 if (old > 255)
6100 old = 255;
6101 msgcount = (old << 8) | new;
6102 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
6104 if (ast_test_flag(p, IAX_HASCALLERID)) {
6105 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
6106 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
6109 version = iax_check_version(devtype);
6110 if (version)
6111 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
6113 res = 0;
6115 return_unref:
6116 peer_unref(p);
6118 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
6121 static int registry_authrequest(int callno)
6123 struct iax_ie_data ied;
6124 struct iax2_peer *p;
6125 char challenge[10];
6126 const char *peer_name;
6127 int res = -1;
6129 peer_name = ast_strdupa(iaxs[callno]->peer);
6131 /* SLD: third call to find_peer in registration */
6132 ast_mutex_unlock(&iaxsl[callno]);
6133 p = find_peer(peer_name, 1);
6134 ast_mutex_lock(&iaxsl[callno]);
6135 if (!iaxs[callno])
6136 goto return_unref;
6137 if (!p) {
6138 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6139 goto return_unref;
6142 memset(&ied, 0, sizeof(ied));
6143 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
6144 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
6145 /* Build the challenge */
6146 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
6147 ast_string_field_set(iaxs[callno], challenge, challenge);
6148 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
6150 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
6152 res = 0;
6154 return_unref:
6155 peer_unref(p);
6157 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
6160 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
6162 struct iax2_registry *reg;
6163 /* Start pessimistic */
6164 struct iax_ie_data ied;
6165 char peer[256] = "";
6166 char challenge[256] = "";
6167 int res;
6168 int authmethods = 0;
6169 if (ies->authmethods)
6170 authmethods = ies->authmethods;
6171 if (ies->username)
6172 ast_copy_string(peer, ies->username, sizeof(peer));
6173 if (ies->challenge)
6174 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
6175 memset(&ied, 0, sizeof(ied));
6176 reg = iaxs[callno]->reg;
6177 if (reg) {
6178 if (inaddrcmp(&reg->addr, sin)) {
6179 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6180 return -1;
6182 if (ast_strlen_zero(reg->secret)) {
6183 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
6184 reg->regstate = REG_STATE_NOAUTH;
6185 return -1;
6187 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
6188 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
6189 if (reg->secret[0] == '[') {
6190 char tmpkey[256];
6191 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
6192 tmpkey[strlen(tmpkey) - 1] = '\0';
6193 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
6194 } else
6195 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
6196 if (!res) {
6197 reg->regstate = REG_STATE_AUTHSENT;
6198 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
6199 } else
6200 return -1;
6201 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
6202 } else
6203 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
6204 return -1;
6207 static void stop_stuff(int callno)
6209 iax2_destroy_helper(iaxs[callno]);
6212 static void __auth_reject(const void *nothing)
6214 /* Called from IAX thread only, without iaxs lock */
6215 int callno = (int)(long)(nothing);
6216 struct iax_ie_data ied;
6217 ast_mutex_lock(&iaxsl[callno]);
6218 if (iaxs[callno]) {
6219 memset(&ied, 0, sizeof(ied));
6220 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
6221 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
6222 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
6223 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
6224 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
6225 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
6227 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
6229 ast_mutex_unlock(&iaxsl[callno]);
6232 static int auth_reject(const void *data)
6234 int callno = (int)(long)(data);
6235 ast_mutex_lock(&iaxsl[callno]);
6236 if (iaxs[callno])
6237 iaxs[callno]->authid = -1;
6238 ast_mutex_unlock(&iaxsl[callno]);
6239 #ifdef SCHED_MULTITHREADED
6240 if (schedule_action(__auth_reject, data))
6241 #endif
6242 __auth_reject(data);
6243 return 0;
6246 static int auth_fail(int callno, int failcode)
6248 /* Schedule sending the authentication failure in one second, to prevent
6249 guessing */
6250 if (iaxs[callno]) {
6251 iaxs[callno]->authfail = failcode;
6252 if (delayreject) {
6253 AST_SCHED_DEL(sched, iaxs[callno]->authid);
6254 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
6255 } else
6256 auth_reject((void *)(long)callno);
6258 return 0;
6261 static void __auto_hangup(const void *nothing)
6263 /* Called from IAX thread only, without iaxs lock */
6264 int callno = (int)(long)(nothing);
6265 struct iax_ie_data ied;
6266 ast_mutex_lock(&iaxsl[callno]);
6267 if (iaxs[callno]) {
6268 memset(&ied, 0, sizeof(ied));
6269 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
6270 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
6271 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
6273 ast_mutex_unlock(&iaxsl[callno]);
6276 static int auto_hangup(const void *data)
6278 int callno = (int)(long)(data);
6279 ast_mutex_lock(&iaxsl[callno]);
6280 if (iaxs[callno]) {
6281 iaxs[callno]->autoid = -1;
6283 ast_mutex_unlock(&iaxsl[callno]);
6284 #ifdef SCHED_MULTITHREADED
6285 if (schedule_action(__auto_hangup, data))
6286 #endif
6287 __auto_hangup(data);
6288 return 0;
6291 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
6293 struct iax_ie_data ied;
6294 /* Auto-hangup with 30 seconds of inactivity */
6295 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
6296 iaxs[callno]->autoid = iax2_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
6297 memset(&ied, 0, sizeof(ied));
6298 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
6299 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
6300 dp->flags |= CACHE_FLAG_TRANSMITTED;
6303 static int iax2_vnak(int callno)
6305 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
6308 static void vnak_retransmit(int callno, int last)
6310 struct iax_frame *f;
6312 AST_LIST_LOCK(&iaxq.queue);
6313 AST_LIST_TRAVERSE(&iaxq.queue, f, list) {
6314 /* Send a copy immediately */
6315 if ((f->callno == callno) && iaxs[f->callno] &&
6316 ((unsigned char ) (f->oseqno - last) < 128) &&
6317 (f->retries >= 0)) {
6318 send_packet(f);
6321 AST_LIST_UNLOCK(&iaxq.queue);
6324 static void __iax2_poke_peer_s(const void *data)
6326 struct iax2_peer *peer = (struct iax2_peer *)data;
6327 iax2_poke_peer(peer, 0);
6328 peer_unref(peer);
6331 static int iax2_poke_peer_s(const void *data)
6333 struct iax2_peer *peer = (struct iax2_peer *)data;
6334 peer->pokeexpire = -1;
6335 #ifdef SCHED_MULTITHREADED
6336 if (schedule_action(__iax2_poke_peer_s, data))
6337 #endif
6338 __iax2_poke_peer_s(data);
6339 return 0;
6342 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
6344 int res = 0;
6345 struct iax_frame *fr;
6346 struct ast_iax2_meta_hdr *meta;
6347 struct ast_iax2_meta_trunk_hdr *mth;
6348 int calls = 0;
6350 /* Point to frame */
6351 fr = (struct iax_frame *)tpeer->trunkdata;
6352 /* Point to meta data */
6353 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
6354 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
6355 if (tpeer->trunkdatalen) {
6356 /* We're actually sending a frame, so fill the meta trunk header and meta header */
6357 meta->zeros = 0;
6358 meta->metacmd = IAX_META_TRUNK;
6359 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
6360 meta->cmddata = IAX_META_TRUNK_MINI;
6361 else
6362 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
6363 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
6364 /* And the rest of the ast_iax2 header */
6365 fr->direction = DIRECTION_OUTGRESS;
6366 fr->retrans = -1;
6367 fr->transfer = 0;
6368 /* Any appropriate call will do */
6369 fr->data = fr->afdata;
6370 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
6371 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
6372 calls = tpeer->calls;
6373 #if 0
6374 if (option_debug)
6375 ast_log(LOG_DEBUG, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
6376 #endif
6377 /* Reset transmit trunk side data */
6378 tpeer->trunkdatalen = 0;
6379 tpeer->calls = 0;
6381 if (res < 0)
6382 return res;
6383 return calls;
6386 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
6388 /* Drop when trunk is about 5 seconds idle */
6389 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
6390 return 1;
6391 return 0;
6394 static int timing_read(int *id, int fd, short events, void *cbdata)
6396 char buf[1024];
6397 int res;
6398 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
6399 int processed = 0;
6400 int totalcalls = 0;
6401 #ifdef ZT_TIMERACK
6402 int x = 1;
6403 #endif
6404 struct timeval now;
6405 if (iaxtrunkdebug)
6406 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA);
6407 gettimeofday(&now, NULL);
6408 if (events & AST_IO_PRI) {
6409 #ifdef ZT_TIMERACK
6410 /* Great, this is a timing interface, just call the ioctl */
6411 if (ioctl(fd, ZT_TIMERACK, &x)) {
6412 ast_log(LOG_WARNING, "Unable to acknowledge zap timer. IAX trunking will fail!\n");
6413 usleep(1);
6414 return -1;
6416 #endif
6417 } else {
6418 /* Read and ignore from the pseudo channel for timing */
6419 res = read(fd, buf, sizeof(buf));
6420 if (res < 1) {
6421 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
6422 return 1;
6425 /* For each peer that supports trunking... */
6426 ast_mutex_lock(&tpeerlock);
6427 tpeer = tpeers;
6428 while(tpeer) {
6429 processed++;
6430 res = 0;
6431 ast_mutex_lock(&tpeer->lock);
6432 /* We can drop a single tpeer per pass. That makes all this logic
6433 substantially easier */
6434 if (!drop && iax2_trunk_expired(tpeer, &now)) {
6435 /* Take it out of the list, but don't free it yet, because it
6436 could be in use */
6437 if (prev)
6438 prev->next = tpeer->next;
6439 else
6440 tpeers = tpeer->next;
6441 drop = tpeer;
6442 } else {
6443 res = send_trunk(tpeer, &now);
6444 if (iaxtrunkdebug)
6445 ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
6447 totalcalls += res;
6448 res = 0;
6449 ast_mutex_unlock(&tpeer->lock);
6450 prev = tpeer;
6451 tpeer = tpeer->next;
6453 ast_mutex_unlock(&tpeerlock);
6454 if (drop) {
6455 ast_mutex_lock(&drop->lock);
6456 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
6457 because by the time they could get tpeerlock, we've already grabbed it */
6458 if (option_debug)
6459 ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
6460 if (drop->trunkdata) {
6461 free(drop->trunkdata);
6462 drop->trunkdata = NULL;
6464 ast_mutex_unlock(&drop->lock);
6465 ast_mutex_destroy(&drop->lock);
6466 free(drop);
6469 if (iaxtrunkdebug)
6470 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
6471 iaxtrunkdebug =0;
6472 return 1;
6475 struct dpreq_data {
6476 int callno;
6477 char context[AST_MAX_EXTENSION];
6478 char callednum[AST_MAX_EXTENSION];
6479 char *callerid;
6482 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
6484 unsigned short dpstatus = 0;
6485 struct iax_ie_data ied1;
6486 int mm;
6488 memset(&ied1, 0, sizeof(ied1));
6489 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
6490 /* Must be started */
6491 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
6492 dpstatus = IAX_DPSTATUS_EXISTS;
6493 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
6494 dpstatus = IAX_DPSTATUS_CANEXIST;
6495 } else {
6496 dpstatus = IAX_DPSTATUS_NONEXISTENT;
6498 if (ast_ignore_pattern(context, callednum))
6499 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
6500 if (mm)
6501 dpstatus |= IAX_DPSTATUS_MATCHMORE;
6502 if (!skiplock)
6503 ast_mutex_lock(&iaxsl[callno]);
6504 if (iaxs[callno]) {
6505 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
6506 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
6507 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
6508 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
6510 if (!skiplock)
6511 ast_mutex_unlock(&iaxsl[callno]);
6514 static void *dp_lookup_thread(void *data)
6516 /* Look up for dpreq */
6517 struct dpreq_data *dpr = data;
6518 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
6519 if (dpr->callerid)
6520 free(dpr->callerid);
6521 free(dpr);
6522 return NULL;
6525 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
6527 pthread_t newthread;
6528 struct dpreq_data *dpr;
6529 pthread_attr_t attr;
6531 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
6532 return;
6534 pthread_attr_init(&attr);
6535 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6537 dpr->callno = callno;
6538 ast_copy_string(dpr->context, context, sizeof(dpr->context));
6539 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
6540 if (callerid)
6541 dpr->callerid = ast_strdup(callerid);
6542 if (ast_pthread_create(&newthread, &attr, dp_lookup_thread, dpr)) {
6543 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
6546 pthread_attr_destroy(&attr);
6549 struct iax_dual {
6550 struct ast_channel *chan1;
6551 struct ast_channel *chan2;
6554 static void *iax_park_thread(void *stuff)
6556 struct ast_channel *chan1, *chan2;
6557 struct iax_dual *d;
6558 struct ast_frame *f;
6559 int ext;
6560 int res;
6561 d = stuff;
6562 chan1 = d->chan1;
6563 chan2 = d->chan2;
6564 free(d);
6565 f = ast_read(chan1);
6566 if (f)
6567 ast_frfree(f);
6568 res = ast_park_call(chan1, chan2, 0, &ext);
6569 ast_hangup(chan2);
6570 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
6571 return NULL;
6574 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
6576 struct iax_dual *d;
6577 struct ast_channel *chan1m, *chan2m;
6578 pthread_t th;
6579 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
6580 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
6581 if (chan2m && chan1m) {
6582 /* Make formats okay */
6583 chan1m->readformat = chan1->readformat;
6584 chan1m->writeformat = chan1->writeformat;
6585 ast_channel_masquerade(chan1m, chan1);
6586 /* Setup the extensions and such */
6587 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
6588 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
6589 chan1m->priority = chan1->priority;
6591 /* We make a clone of the peer channel too, so we can play
6592 back the announcement */
6593 /* Make formats okay */
6594 chan2m->readformat = chan2->readformat;
6595 chan2m->writeformat = chan2->writeformat;
6596 ast_channel_masquerade(chan2m, chan2);
6597 /* Setup the extensions and such */
6598 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
6599 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
6600 chan2m->priority = chan2->priority;
6601 if (ast_do_masquerade(chan2m)) {
6602 ast_log(LOG_WARNING, "Masquerade failed :(\n");
6603 ast_hangup(chan2m);
6604 return -1;
6606 } else {
6607 if (chan1m)
6608 ast_hangup(chan1m);
6609 if (chan2m)
6610 ast_hangup(chan2m);
6611 return -1;
6613 if ((d = ast_calloc(1, sizeof(*d)))) {
6614 pthread_attr_t attr;
6616 pthread_attr_init(&attr);
6617 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
6619 d->chan1 = chan1m;
6620 d->chan2 = chan2m;
6621 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
6622 pthread_attr_destroy(&attr);
6623 return 0;
6625 pthread_attr_destroy(&attr);
6626 free(d);
6628 return -1;
6632 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
6634 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
6636 unsigned int ourver;
6637 char rsi[80];
6638 snprintf(rsi, sizeof(rsi), "si-%s", si);
6639 if (iax_provision_version(&ourver, rsi, 1))
6640 return 0;
6641 if (option_debug)
6642 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
6643 if (ourver != ver)
6644 iax2_provision(sin, sockfd, NULL, rsi, 1);
6645 return 0;
6648 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
6650 jb_info stats;
6651 jb_getinfo(pvt->jb, &stats);
6653 memset(iep, 0, sizeof(*iep));
6655 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
6656 if(stats.frames_in == 0) stats.frames_in = 1;
6657 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
6658 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
6659 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
6660 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
6661 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
6664 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
6666 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
6667 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
6668 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
6669 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
6670 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
6671 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
6672 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
6675 static int socket_process(struct iax2_thread *thread);
6678 * \brief Handle any deferred full frames for this thread
6680 static void handle_deferred_full_frames(struct iax2_thread *thread)
6682 struct iax2_pkt_buf *pkt_buf;
6684 ast_mutex_lock(&thread->lock);
6686 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
6687 ast_mutex_unlock(&thread->lock);
6689 thread->buf = pkt_buf->buf;
6690 thread->buf_len = pkt_buf->len;
6691 thread->buf_size = pkt_buf->len + 1;
6693 socket_process(thread);
6695 thread->buf = NULL;
6696 ast_free(pkt_buf);
6698 ast_mutex_lock(&thread->lock);
6701 ast_mutex_unlock(&thread->lock);
6705 * \brief Queue the last read full frame for processing by a certain thread
6707 * If there are already any full frames queued, they are sorted
6708 * by sequence number.
6710 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
6712 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
6713 struct ast_iax2_full_hdr *fh, *cur_fh;
6715 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
6716 return;
6718 pkt_buf->len = from_here->buf_len;
6719 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
6721 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
6722 ast_mutex_lock(&to_here->lock);
6723 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
6724 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
6725 if (fh->oseqno < cur_fh->oseqno) {
6726 AST_LIST_INSERT_BEFORE_CURRENT(&to_here->full_frames, pkt_buf, entry);
6727 break;
6730 AST_LIST_TRAVERSE_SAFE_END
6732 if (!cur_pkt_buf)
6733 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
6735 ast_mutex_unlock(&to_here->lock);
6738 static int socket_read(int *id, int fd, short events, void *cbdata)
6740 struct iax2_thread *thread;
6741 socklen_t len;
6742 time_t t;
6743 static time_t last_errtime = 0;
6744 struct ast_iax2_full_hdr *fh;
6746 if (!(thread = find_idle_thread())) {
6747 time(&t);
6748 if (t != last_errtime && option_debug)
6749 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
6750 last_errtime = t;
6751 usleep(1);
6752 return 1;
6755 len = sizeof(thread->iosin);
6756 thread->iofd = fd;
6757 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
6758 thread->buf_size = sizeof(thread->readbuf);
6759 thread->buf = thread->readbuf;
6760 if (thread->buf_len < 0) {
6761 if (errno != ECONNREFUSED && errno != EAGAIN)
6762 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
6763 handle_error();
6764 thread->iostate = IAX_IOSTATE_IDLE;
6765 signal_condition(&thread->lock, &thread->cond);
6766 return 1;
6768 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
6769 thread->iostate = IAX_IOSTATE_IDLE;
6770 signal_condition(&thread->lock, &thread->cond);
6771 return 1;
6774 /* Determine if this frame is a full frame; if so, and any thread is currently
6775 processing a full frame for the same callno from this peer, then drop this
6776 frame (and the peer will retransmit it) */
6777 fh = (struct ast_iax2_full_hdr *) thread->buf;
6778 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
6779 struct iax2_thread *cur = NULL;
6780 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
6782 AST_LIST_LOCK(&active_list);
6783 AST_LIST_TRAVERSE(&active_list, cur, list) {
6784 if ((cur->ffinfo.callno == callno) &&
6785 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
6786 break;
6788 if (cur) {
6789 /* we found another thread processing a full frame for this call,
6790 so queue it up for processing later. */
6791 defer_full_frame(thread, cur);
6792 AST_LIST_UNLOCK(&active_list);
6793 thread->iostate = IAX_IOSTATE_IDLE;
6794 signal_condition(&thread->lock, &thread->cond);
6795 return 1;
6796 } else {
6797 /* this thread is going to process this frame, so mark it */
6798 thread->ffinfo.callno = callno;
6799 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
6800 thread->ffinfo.type = fh->type;
6801 thread->ffinfo.csub = fh->csub;
6803 AST_LIST_UNLOCK(&active_list);
6806 /* Mark as ready and send on its way */
6807 thread->iostate = IAX_IOSTATE_READY;
6808 #ifdef DEBUG_SCHED_MULTITHREAD
6809 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
6810 #endif
6811 signal_condition(&thread->lock, &thread->cond);
6813 return 1;
6816 static int socket_process(struct iax2_thread *thread)
6818 struct sockaddr_in sin;
6819 int res;
6820 int updatehistory=1;
6821 int new = NEW_PREVENT;
6822 void *ptr;
6823 int dcallno = 0;
6824 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
6825 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
6826 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
6827 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
6828 struct ast_iax2_meta_trunk_hdr *mth;
6829 struct ast_iax2_meta_trunk_entry *mte;
6830 struct ast_iax2_meta_trunk_mini *mtm;
6831 struct iax_frame *fr;
6832 struct iax_frame *cur;
6833 struct ast_frame f = { 0, };
6834 struct ast_channel *c;
6835 struct iax2_dpcache *dp;
6836 struct iax2_peer *peer;
6837 struct iax2_trunk_peer *tpeer;
6838 struct timeval rxtrunktime;
6839 struct iax_ies ies;
6840 struct iax_ie_data ied0, ied1;
6841 int format;
6842 int fd;
6843 int exists;
6844 int minivid = 0;
6845 unsigned int ts;
6846 char empty[32]=""; /* Safety measure */
6847 struct iax_frame *duped_fr;
6848 char host_pref_buf[128];
6849 char caller_pref_buf[128];
6850 struct ast_codec_pref pref;
6851 char *using_prefs = "mine";
6853 /* allocate an iax_frame with 4096 bytes of data buffer */
6854 fr = alloca(sizeof(*fr) + 4096);
6855 fr->callno = 0;
6856 fr->afdatalen = 4096; /* From alloca() above */
6858 /* Copy frequently used parameters to the stack */
6859 res = thread->buf_len;
6860 fd = thread->iofd;
6861 memcpy(&sin, &thread->iosin, sizeof(sin));
6863 if (res < sizeof(*mh)) {
6864 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*mh));
6865 return 1;
6867 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
6868 if (res < sizeof(*vh)) {
6869 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6870 return 1;
6873 /* This is a video frame, get call number */
6874 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd);
6875 minivid = 1;
6876 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
6877 unsigned char metatype;
6879 if (res < sizeof(*meta)) {
6880 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6881 return 1;
6884 /* This is a meta header */
6885 switch(meta->metacmd) {
6886 case IAX_META_TRUNK:
6887 if (res < (sizeof(*meta) + sizeof(*mth))) {
6888 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %zd min)\n", res,
6889 sizeof(*meta) + sizeof(*mth));
6890 return 1;
6892 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
6893 ts = ntohl(mth->ts);
6894 metatype = meta->cmddata;
6895 res -= (sizeof(*meta) + sizeof(*mth));
6896 ptr = mth->data;
6897 tpeer = find_tpeer(&sin, fd);
6898 if (!tpeer) {
6899 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6900 return 1;
6902 tpeer->trunkact = ast_tvnow();
6903 if (!ts || ast_tvzero(tpeer->rxtrunktime))
6904 tpeer->rxtrunktime = tpeer->trunkact;
6905 rxtrunktime = tpeer->rxtrunktime;
6906 ast_mutex_unlock(&tpeer->lock);
6907 while(res >= sizeof(*mte)) {
6908 /* Process channels */
6909 unsigned short callno, trunked_ts, len;
6911 if (metatype == IAX_META_TRUNK_MINI) {
6912 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
6913 ptr += sizeof(*mtm);
6914 res -= sizeof(*mtm);
6915 len = ntohs(mtm->len);
6916 callno = ntohs(mtm->mini.callno);
6917 trunked_ts = ntohs(mtm->mini.ts);
6918 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
6919 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
6920 ptr += sizeof(*mte);
6921 res -= sizeof(*mte);
6922 len = ntohs(mte->len);
6923 callno = ntohs(mte->callno);
6924 trunked_ts = 0;
6925 } else {
6926 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6927 break;
6929 /* Stop if we don't have enough data */
6930 if (len > res)
6931 break;
6932 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd);
6933 if (fr->callno) {
6934 /* If it's a valid call, deliver the contents. If not, we
6935 drop it, since we don't have a scallno to use for an INVAL */
6936 /* Process as a mini frame */
6937 memset(&f, 0, sizeof(f));
6938 f.frametype = AST_FRAME_VOICE;
6939 if (iaxs[fr->callno]) {
6940 if (iaxs[fr->callno]->voiceformat > 0) {
6941 f.subclass = iaxs[fr->callno]->voiceformat;
6942 f.datalen = len;
6943 if (f.datalen >= 0) {
6944 if (f.datalen)
6945 f.data = ptr;
6946 if(trunked_ts) {
6947 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
6948 } else
6949 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
6950 /* Don't pass any packets until we're started */
6951 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
6952 /* Common things */
6953 f.src = "IAX2";
6954 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
6955 f.samples = ast_codec_get_samples(&f);
6956 iax_frame_wrap(fr, &f);
6957 duped_fr = iaxfrdup2(fr);
6958 if (duped_fr) {
6959 schedule_delivery(duped_fr, updatehistory, 1, &fr->ts);
6961 /* It is possible for the pvt structure to go away after we call schedule_delivery */
6962 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
6963 iaxs[fr->callno]->last = fr->ts;
6964 #if 1
6965 if (option_debug && iaxdebug)
6966 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
6967 #endif
6970 } else {
6971 ast_log(LOG_WARNING, "Datalen < 0?\n");
6973 } else {
6974 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n ");
6975 iax2_vnak(fr->callno);
6978 ast_mutex_unlock(&iaxsl[fr->callno]);
6980 ptr += len;
6981 res -= len;
6985 return 1;
6988 #ifdef DEBUG_SUPPORT
6989 if (iaxdebug && (res >= sizeof(*fh)))
6990 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
6991 #endif
6992 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
6993 if (res < sizeof(*fh)) {
6994 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
6995 return 1;
6998 /* Get the destination call number */
6999 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
7000 /* Retrieve the type and subclass */
7001 f.frametype = fh->type;
7002 if (f.frametype == AST_FRAME_VIDEO) {
7003 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
7004 } else {
7005 f.subclass = uncompress_subclass(fh->csub);
7007 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
7008 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
7009 (f.subclass == IAX_COMMAND_REGREL)))
7010 new = NEW_ALLOW;
7011 } else {
7012 /* Don't know anything about it yet */
7013 f.frametype = AST_FRAME_NULL;
7014 f.subclass = 0;
7017 if (!fr->callno)
7018 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd);
7020 if (fr->callno > 0)
7021 ast_mutex_lock(&iaxsl[fr->callno]);
7023 if (!fr->callno || !iaxs[fr->callno]) {
7024 /* A call arrived for a nonexistent destination. Unless it's an "inval"
7025 frame, reply with an inval */
7026 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7027 /* We can only raw hangup control frames */
7028 if (((f.subclass != IAX_COMMAND_INVAL) &&
7029 (f.subclass != IAX_COMMAND_TXCNT) &&
7030 (f.subclass != IAX_COMMAND_TXACC) &&
7031 (f.subclass != IAX_COMMAND_FWDOWNL))||
7032 (f.frametype != AST_FRAME_IAX))
7033 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
7034 fd);
7036 if (fr->callno > 0)
7037 ast_mutex_unlock(&iaxsl[fr->callno]);
7038 return 1;
7040 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
7041 if (decrypt_frame(fr->callno, fh, &f, &res)) {
7042 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
7043 ast_mutex_unlock(&iaxsl[fr->callno]);
7044 return 1;
7046 #ifdef DEBUG_SUPPORT
7047 else if (iaxdebug)
7048 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
7049 #endif
7052 /* count this frame */
7053 iaxs[fr->callno]->frames_received++;
7055 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
7056 f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
7057 f.subclass != IAX_COMMAND_TXACC) /* for attended transfer */
7058 iaxs[fr->callno]->peercallno = (unsigned short)(ntohs(mh->callno) & ~IAX_FLAG_FULL);
7059 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
7060 if (option_debug && iaxdebug)
7061 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
7062 /* Check if it's out of order (and not an ACK or INVAL) */
7063 fr->oseqno = fh->oseqno;
7064 fr->iseqno = fh->iseqno;
7065 fr->ts = ntohl(fh->ts);
7066 #ifdef IAXTESTS
7067 if (test_resync) {
7068 if (option_debug)
7069 ast_log(LOG_DEBUG, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
7070 fr->ts += test_resync;
7072 #endif /* IAXTESTS */
7073 #if 0
7074 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
7075 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
7076 (f.subclass == IAX_COMMAND_NEW ||
7077 f.subclass == IAX_COMMAND_AUTHREQ ||
7078 f.subclass == IAX_COMMAND_ACCEPT ||
7079 f.subclass == IAX_COMMAND_REJECT)) ) )
7080 #endif
7081 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
7082 updatehistory = 0;
7083 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
7084 (iaxs[fr->callno]->iseqno ||
7085 ((f.subclass != IAX_COMMAND_TXCNT) &&
7086 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7087 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7088 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7089 (f.subclass != IAX_COMMAND_TXACC)) ||
7090 (f.frametype != AST_FRAME_IAX))) {
7091 if (
7092 ((f.subclass != IAX_COMMAND_ACK) &&
7093 (f.subclass != IAX_COMMAND_INVAL) &&
7094 (f.subclass != IAX_COMMAND_TXCNT) &&
7095 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
7096 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
7097 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
7098 (f.subclass != IAX_COMMAND_TXACC) &&
7099 (f.subclass != IAX_COMMAND_VNAK)) ||
7100 (f.frametype != AST_FRAME_IAX)) {
7101 /* If it's not an ACK packet, it's out of order. */
7102 if (option_debug)
7103 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
7104 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
7105 /* Check to see if we need to request retransmission,
7106 * and take sequence number wraparound into account */
7107 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
7108 /* If we've already seen it, ack it XXX There's a border condition here XXX */
7109 if ((f.frametype != AST_FRAME_IAX) ||
7110 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
7111 if (option_debug)
7112 ast_log(LOG_DEBUG, "Acking anyway\n");
7113 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
7114 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
7115 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7117 } else {
7118 /* Send a VNAK requesting retransmission */
7119 iax2_vnak(fr->callno);
7121 ast_mutex_unlock(&iaxsl[fr->callno]);
7122 return 1;
7124 } else {
7125 /* Increment unless it's an ACK or VNAK */
7126 if (((f.subclass != IAX_COMMAND_ACK) &&
7127 (f.subclass != IAX_COMMAND_INVAL) &&
7128 (f.subclass != IAX_COMMAND_TXCNT) &&
7129 (f.subclass != IAX_COMMAND_TXACC) &&
7130 (f.subclass != IAX_COMMAND_VNAK)) ||
7131 (f.frametype != AST_FRAME_IAX))
7132 iaxs[fr->callno]->iseqno++;
7134 /* A full frame */
7135 if (res < sizeof(*fh)) {
7136 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*fh));
7137 ast_mutex_unlock(&iaxsl[fr->callno]);
7138 return 1;
7140 /* Ensure text frames are NULL-terminated */
7141 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
7142 if (res < thread->buf_size)
7143 thread->buf[res++] = '\0';
7144 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
7145 thread->buf[res - 1] = '\0';
7147 f.datalen = res - sizeof(*fh);
7149 /* Handle implicit ACKing unless this is an INVAL, and only if this is
7150 from the real peer, not the transfer peer */
7151 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7152 ((f.subclass != IAX_COMMAND_INVAL) ||
7153 (f.frametype != AST_FRAME_IAX))) {
7154 unsigned char x;
7155 int call_to_destroy;
7156 /* XXX This code is not very efficient. Surely there is a better way which still
7157 properly handles boundary conditions? XXX */
7158 /* First we have to qualify that the ACKed value is within our window */
7159 for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
7160 if (fr->iseqno == x)
7161 break;
7162 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
7163 /* The acknowledgement is within our window. Time to acknowledge everything
7164 that it says to */
7165 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
7166 /* Ack the packet with the given timestamp */
7167 if (option_debug && iaxdebug)
7168 ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
7169 call_to_destroy = 0;
7170 AST_LIST_LOCK(&iaxq.queue);
7171 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7172 /* If it's our call, and our timestamp, mark -1 retries */
7173 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
7174 cur->retries = -1;
7175 /* Destroy call if this is the end */
7176 if (cur->final)
7177 call_to_destroy = fr->callno;
7180 AST_LIST_UNLOCK(&iaxq.queue);
7181 if (call_to_destroy) {
7182 if (iaxdebug && option_debug)
7183 ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", call_to_destroy);
7184 ast_mutex_lock(&iaxsl[call_to_destroy]);
7185 iax2_destroy(call_to_destroy);
7186 ast_mutex_unlock(&iaxsl[call_to_destroy]);
7189 /* Note how much we've received acknowledgement for */
7190 if (iaxs[fr->callno])
7191 iaxs[fr->callno]->rseqno = fr->iseqno;
7192 else {
7193 /* Stop processing now */
7194 ast_mutex_unlock(&iaxsl[fr->callno]);
7195 return 1;
7197 } else if (option_debug)
7198 ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
7200 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
7201 ((f.frametype != AST_FRAME_IAX) ||
7202 ((f.subclass != IAX_COMMAND_TXACC) &&
7203 (f.subclass != IAX_COMMAND_TXCNT)))) {
7204 /* Only messages we accept from a transfer host are TXACC and TXCNT */
7205 ast_mutex_unlock(&iaxsl[fr->callno]);
7206 return 1;
7209 if (f.datalen) {
7210 if (f.frametype == AST_FRAME_IAX) {
7211 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
7212 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
7213 ast_mutex_unlock(&iaxsl[fr->callno]);
7214 return 1;
7216 f.data = NULL;
7217 f.datalen = 0;
7218 } else
7219 f.data = thread->buf + sizeof(*fh);
7220 } else {
7221 if (f.frametype == AST_FRAME_IAX)
7222 f.data = NULL;
7223 else
7224 f.data = empty;
7225 memset(&ies, 0, sizeof(ies));
7228 /* when we receive the first full frame for a new incoming channel,
7229 it is safe to start the PBX on the channel because we have now
7230 completed a 3-way handshake with the peer */
7231 if ((f.frametype == AST_FRAME_VOICE) ||
7232 (f.frametype == AST_FRAME_VIDEO) ||
7233 (f.frametype == AST_FRAME_IAX)) {
7234 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
7235 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7236 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
7237 ast_mutex_unlock(&iaxsl[fr->callno]);
7238 return 1;
7243 if (f.frametype == AST_FRAME_VOICE) {
7244 if (f.subclass != iaxs[fr->callno]->voiceformat) {
7245 iaxs[fr->callno]->voiceformat = f.subclass;
7246 if (option_debug)
7247 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
7248 if (iaxs[fr->callno]->owner) {
7249 int orignative;
7250 retryowner:
7251 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7252 ast_mutex_unlock(&iaxsl[fr->callno]);
7253 usleep(1);
7254 ast_mutex_lock(&iaxsl[fr->callno]);
7255 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
7257 if (iaxs[fr->callno]) {
7258 if (iaxs[fr->callno]->owner) {
7259 orignative = iaxs[fr->callno]->owner->nativeformats;
7260 iaxs[fr->callno]->owner->nativeformats = f.subclass;
7261 if (iaxs[fr->callno]->owner->readformat)
7262 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7263 iaxs[fr->callno]->owner->nativeformats = orignative;
7264 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7266 } else {
7267 if (option_debug)
7268 ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
7269 ast_mutex_unlock(&iaxsl[fr->callno]);
7270 return 1;
7275 if (f.frametype == AST_FRAME_VIDEO) {
7276 if (f.subclass != iaxs[fr->callno]->videoformat) {
7277 if (option_debug)
7278 ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
7279 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
7282 if (f.frametype == AST_FRAME_IAX) {
7283 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
7284 /* Handle the IAX pseudo frame itself */
7285 if (option_debug && iaxdebug)
7286 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
7288 /* Update last ts unless the frame's timestamp originated with us. */
7289 if (iaxs[fr->callno]->last < fr->ts &&
7290 f.subclass != IAX_COMMAND_ACK &&
7291 f.subclass != IAX_COMMAND_PONG &&
7292 f.subclass != IAX_COMMAND_LAGRP) {
7293 iaxs[fr->callno]->last = fr->ts;
7294 if (option_debug && iaxdebug)
7295 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
7298 switch(f.subclass) {
7299 case IAX_COMMAND_ACK:
7300 /* Do nothing */
7301 break;
7302 case IAX_COMMAND_QUELCH:
7303 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7304 /* Generate Manager Hold event, if necessary*/
7305 if (iaxs[fr->callno]->owner) {
7306 manager_event(EVENT_FLAG_CALL, "Hold",
7307 "Channel: %s\r\n"
7308 "Uniqueid: %s\r\n",
7309 iaxs[fr->callno]->owner->name,
7310 iaxs[fr->callno]->owner->uniqueid);
7313 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
7314 if (ies.musiconhold) {
7315 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7316 const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
7317 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
7318 S_OR(mohsuggest, NULL),
7319 !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
7320 if (!iaxs[fr->callno]) {
7321 ast_mutex_unlock(&iaxsl[fr->callno]);
7322 return 1;
7327 break;
7328 case IAX_COMMAND_UNQUELCH:
7329 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7330 /* Generate Manager Unhold event, if necessary*/
7331 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
7332 manager_event(EVENT_FLAG_CALL, "Unhold",
7333 "Channel: %s\r\n"
7334 "Uniqueid: %s\r\n",
7335 iaxs[fr->callno]->owner->name,
7336 iaxs[fr->callno]->owner->uniqueid);
7339 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
7340 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
7341 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
7342 if (!iaxs[fr->callno]) {
7343 ast_mutex_unlock(&iaxsl[fr->callno]);
7344 return 1;
7348 break;
7349 case IAX_COMMAND_TXACC:
7350 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
7351 /* Ack the packet with the given timestamp */
7352 AST_LIST_LOCK(&iaxq.queue);
7353 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
7354 /* Cancel any outstanding txcnt's */
7355 if ((fr->callno == cur->callno) && (cur->transfer))
7356 cur->retries = -1;
7358 AST_LIST_UNLOCK(&iaxq.queue);
7359 memset(&ied1, 0, sizeof(ied1));
7360 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
7361 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
7362 iaxs[fr->callno]->transferring = TRANSFER_READY;
7364 break;
7365 case IAX_COMMAND_NEW:
7366 /* Ignore if it's already up */
7367 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
7368 break;
7369 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
7370 ast_mutex_unlock(&iaxsl[fr->callno]);
7371 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
7372 ast_mutex_lock(&iaxsl[fr->callno]);
7373 if (!iaxs[fr->callno]) {
7374 ast_mutex_unlock(&iaxsl[fr->callno]);
7375 return 1;
7378 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
7379 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
7380 int new_callno;
7381 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
7382 fr->callno = new_callno;
7384 /* For security, always ack immediately */
7385 if (delayreject)
7386 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7387 if (check_access(fr->callno, &sin, &ies)) {
7388 /* They're not allowed on */
7389 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7390 if (authdebug)
7391 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7392 break;
7394 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7395 const char *context, *exten, *cid_num;
7397 context = ast_strdupa(iaxs[fr->callno]->context);
7398 exten = ast_strdupa(iaxs[fr->callno]->exten);
7399 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
7401 /* This might re-enter the IAX code and need the lock */
7402 ast_mutex_unlock(&iaxsl[fr->callno]);
7403 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
7404 ast_mutex_lock(&iaxsl[fr->callno]);
7406 if (!iaxs[fr->callno]) {
7407 ast_mutex_unlock(&iaxsl[fr->callno]);
7408 return 1;
7410 } else
7411 exists = 0;
7412 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
7413 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7414 memset(&ied0, 0, sizeof(ied0));
7415 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7416 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7417 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7418 if (!iaxs[fr->callno]) {
7419 ast_mutex_unlock(&iaxsl[fr->callno]);
7420 return 1;
7422 if (authdebug)
7423 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7424 } else {
7425 /* Select an appropriate format */
7427 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7428 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7429 using_prefs = "reqonly";
7430 } else {
7431 using_prefs = "disabled";
7433 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7434 memset(&pref, 0, sizeof(pref));
7435 strcpy(caller_pref_buf, "disabled");
7436 strcpy(host_pref_buf, "disabled");
7437 } else {
7438 using_prefs = "mine";
7439 /* If the information elements are in here... use them */
7440 if (ies.codec_prefs)
7441 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7442 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7443 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
7444 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7445 pref = iaxs[fr->callno]->rprefs;
7446 using_prefs = "caller";
7447 } else {
7448 pref = iaxs[fr->callno]->prefs;
7450 } else
7451 pref = iaxs[fr->callno]->prefs;
7453 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7454 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7455 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7457 if (!format) {
7458 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7459 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7460 if (!format) {
7461 memset(&ied0, 0, sizeof(ied0));
7462 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7463 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7464 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7465 if (!iaxs[fr->callno]) {
7466 ast_mutex_unlock(&iaxsl[fr->callno]);
7467 return 1;
7469 if (authdebug) {
7470 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7471 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7472 else
7473 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7475 } else {
7476 /* Pick one... */
7477 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7478 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7479 format = 0;
7480 } else {
7481 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7482 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7483 memset(&pref, 0, sizeof(pref));
7484 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7485 strcpy(caller_pref_buf,"disabled");
7486 strcpy(host_pref_buf,"disabled");
7487 } else {
7488 using_prefs = "mine";
7489 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7490 /* Do the opposite of what we tried above. */
7491 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7492 pref = iaxs[fr->callno]->prefs;
7493 } else {
7494 pref = iaxs[fr->callno]->rprefs;
7495 using_prefs = "caller";
7497 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7499 } else /* if no codec_prefs IE do it the old way */
7500 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7504 if (!format) {
7505 memset(&ied0, 0, sizeof(ied0));
7506 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7507 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7508 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7509 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7510 if (!iaxs[fr->callno]) {
7511 ast_mutex_unlock(&iaxsl[fr->callno]);
7512 return 1;
7514 if (authdebug)
7515 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7516 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7517 break;
7521 if (format) {
7522 /* No authentication required, let them in */
7523 memset(&ied1, 0, sizeof(ied1));
7524 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7525 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7526 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7527 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7528 if (option_verbose > 2)
7529 ast_verbose(VERBOSE_PREFIX_3 "Accepting UNAUTHENTICATED call from %s:\n"
7530 "%srequested format = %s,\n"
7531 "%srequested prefs = %s,\n"
7532 "%sactual format = %s,\n"
7533 "%shost prefs = %s,\n"
7534 "%spriority = %s\n",
7535 ast_inet_ntoa(sin.sin_addr),
7536 VERBOSE_PREFIX_4,
7537 ast_getformatname(iaxs[fr->callno]->peerformat),
7538 VERBOSE_PREFIX_4,
7539 caller_pref_buf,
7540 VERBOSE_PREFIX_4,
7541 ast_getformatname(format),
7542 VERBOSE_PREFIX_4,
7543 host_pref_buf,
7544 VERBOSE_PREFIX_4,
7545 using_prefs);
7547 iaxs[fr->callno]->chosenformat = format;
7548 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
7549 } else {
7550 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7551 /* If this is a TBD call, we're ready but now what... */
7552 if (option_verbose > 2)
7553 ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
7557 break;
7559 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
7560 merge_encryption(iaxs[fr->callno],ies.encmethods);
7561 else
7562 iaxs[fr->callno]->encmethods = 0;
7563 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
7564 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
7565 if (!iaxs[fr->callno]) {
7566 ast_mutex_unlock(&iaxsl[fr->callno]);
7567 return 1;
7569 break;
7570 case IAX_COMMAND_DPREQ:
7571 /* Request status in the dialplan */
7572 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
7573 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
7574 if (iaxcompat) {
7575 /* Spawn a thread for the lookup */
7576 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
7577 } else {
7578 /* Just look it up */
7579 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
7582 break;
7583 case IAX_COMMAND_HANGUP:
7584 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
7585 if (option_debug)
7586 ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr->callno);
7587 /* Set hangup cause according to remote */
7588 if (ies.causecode && iaxs[fr->callno]->owner)
7589 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7590 /* Send ack immediately, before we destroy */
7591 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7592 iax2_destroy(fr->callno);
7593 break;
7594 case IAX_COMMAND_REJECT:
7595 /* Set hangup cause according to remote */
7596 if (ies.causecode && iaxs[fr->callno]->owner)
7597 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
7599 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7600 if (iaxs[fr->callno]->owner && authdebug)
7601 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
7602 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
7603 ies.cause ? ies.cause : "<Unknown>");
7604 if (option_debug)
7605 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
7606 fr->callno);
7608 /* Send ack immediately, before we destroy */
7609 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
7610 fr->ts, NULL, 0, fr->iseqno);
7611 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
7612 iaxs[fr->callno]->error = EPERM;
7613 iax2_destroy(fr->callno);
7614 break;
7615 case IAX_COMMAND_TRANSFER:
7617 struct ast_channel *bridged_chan;
7619 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
7620 /* Set BLINDTRANSFER channel variables */
7622 ast_mutex_unlock(&iaxsl[fr->callno]);
7623 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
7624 ast_mutex_lock(&iaxsl[fr->callno]);
7625 if (!iaxs[fr->callno]) {
7626 ast_mutex_unlock(&iaxsl[fr->callno]);
7627 return 1;
7630 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
7631 if (!strcmp(ies.called_number, ast_parking_ext())) {
7632 if (iax_park(bridged_chan, iaxs[fr->callno]->owner)) {
7633 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
7634 } else {
7635 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
7637 } else {
7638 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
7639 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
7640 ies.called_number, iaxs[fr->callno]->context);
7641 else
7642 ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
7643 ies.called_number, iaxs[fr->callno]->context);
7645 } else
7646 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
7648 break;
7650 case IAX_COMMAND_ACCEPT:
7651 /* Ignore if call is already up or needs authentication or is a TBD */
7652 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
7653 break;
7654 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
7655 /* Send ack immediately, before we destroy */
7656 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7657 iax2_destroy(fr->callno);
7658 break;
7660 if (ies.format) {
7661 iaxs[fr->callno]->peerformat = ies.format;
7662 } else {
7663 if (iaxs[fr->callno]->owner)
7664 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
7665 else
7666 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
7668 if (option_verbose > 2)
7669 ast_verbose(VERBOSE_PREFIX_3 "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
7670 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
7671 memset(&ied0, 0, sizeof(ied0));
7672 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7673 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7674 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7675 if (!iaxs[fr->callno]) {
7676 ast_mutex_unlock(&iaxsl[fr->callno]);
7677 return 1;
7679 if (authdebug)
7680 ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7681 } else {
7682 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7683 if (iaxs[fr->callno]->owner) {
7684 /* Switch us to use a compatible format */
7685 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
7686 if (option_verbose > 2)
7687 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
7688 retryowner2:
7689 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
7690 ast_mutex_unlock(&iaxsl[fr->callno]);
7691 usleep(1);
7692 ast_mutex_lock(&iaxsl[fr->callno]);
7693 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
7696 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
7697 /* Setup read/write formats properly. */
7698 if (iaxs[fr->callno]->owner->writeformat)
7699 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
7700 if (iaxs[fr->callno]->owner->readformat)
7701 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
7702 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
7706 if (iaxs[fr->callno]) {
7707 ast_mutex_lock(&dpcache_lock);
7708 dp = iaxs[fr->callno]->dpentries;
7709 while(dp) {
7710 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
7711 iax2_dprequest(dp, fr->callno);
7713 dp = dp->peer;
7715 ast_mutex_unlock(&dpcache_lock);
7717 break;
7718 case IAX_COMMAND_POKE:
7719 /* Send back a pong packet with the original timestamp */
7720 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
7721 if (!iaxs[fr->callno]) {
7722 ast_mutex_unlock(&iaxsl[fr->callno]);
7723 return 1;
7725 break;
7726 case IAX_COMMAND_PING:
7728 struct iax_ie_data pingied;
7729 construct_rr(iaxs[fr->callno], &pingied);
7730 /* Send back a pong packet with the original timestamp */
7731 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
7733 break;
7734 case IAX_COMMAND_PONG:
7735 /* Calculate ping time */
7736 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
7737 /* save RR info */
7738 save_rr(fr, &ies);
7740 if (iaxs[fr->callno]->peerpoke) {
7741 peer = iaxs[fr->callno]->peerpoke;
7742 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
7743 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
7744 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
7745 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7746 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7748 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
7749 if (iaxs[fr->callno]->pingtime > peer->maxms) {
7750 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
7751 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
7752 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
7755 peer->lastms = iaxs[fr->callno]->pingtime;
7756 if (peer->smoothing && (peer->lastms > -1))
7757 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
7758 else if (peer->smoothing && peer->lastms < 0)
7759 peer->historicms = (0 + peer->historicms) / 2;
7760 else
7761 peer->historicms = iaxs[fr->callno]->pingtime;
7763 /* Remove scheduled iax2_poke_noanswer */
7764 if (peer->pokeexpire > -1) {
7765 if (!ast_sched_del(sched, peer->pokeexpire)) {
7766 peer_unref(peer);
7767 peer->pokeexpire = -1;
7770 /* Schedule the next cycle */
7771 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
7772 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
7773 else
7774 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
7775 if (peer->pokeexpire == -1)
7776 peer_unref(peer);
7777 /* and finally send the ack */
7778 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7779 /* And wrap up the qualify call */
7780 iax2_destroy(fr->callno);
7781 peer->callno = 0;
7782 if (option_debug)
7783 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
7785 break;
7786 case IAX_COMMAND_LAGRQ:
7787 case IAX_COMMAND_LAGRP:
7788 f.src = "LAGRQ";
7789 f.mallocd = 0;
7790 f.offset = 0;
7791 f.samples = 0;
7792 iax_frame_wrap(fr, &f);
7793 if(f.subclass == IAX_COMMAND_LAGRQ) {
7794 /* Received a LAGRQ - echo back a LAGRP */
7795 fr->af.subclass = IAX_COMMAND_LAGRP;
7796 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
7797 } else {
7798 /* Received LAGRP in response to our LAGRQ */
7799 unsigned int ts;
7800 /* This is a reply we've been given, actually measure the difference */
7801 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
7802 iaxs[fr->callno]->lag = ts - fr->ts;
7803 if (option_debug && iaxdebug)
7804 ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
7805 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
7807 break;
7808 case IAX_COMMAND_AUTHREQ:
7809 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7810 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
7811 break;
7813 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
7814 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
7815 .subclass = AST_CONTROL_HANGUP,
7817 ast_log(LOG_WARNING,
7818 "I don't know how to authenticate %s to %s\n",
7819 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
7820 iax2_queue_frame(fr->callno, &hangup_fr);
7822 if (!iaxs[fr->callno]) {
7823 ast_mutex_unlock(&iaxsl[fr->callno]);
7824 return 1;
7826 break;
7827 case IAX_COMMAND_AUTHREP:
7828 /* For security, always ack immediately */
7829 if (delayreject)
7830 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
7831 /* Ignore once we've started */
7832 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
7833 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
7834 break;
7836 if (authenticate_verify(iaxs[fr->callno], &ies)) {
7837 if (authdebug)
7838 ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
7839 memset(&ied0, 0, sizeof(ied0));
7840 auth_fail(fr->callno, IAX_COMMAND_REJECT);
7841 break;
7843 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
7844 /* This might re-enter the IAX code and need the lock */
7845 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
7846 } else
7847 exists = 0;
7848 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
7849 if (authdebug)
7850 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
7851 memset(&ied0, 0, sizeof(ied0));
7852 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
7853 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
7854 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7855 if (!iaxs[fr->callno]) {
7856 ast_mutex_unlock(&iaxsl[fr->callno]);
7857 return 1;
7859 } else {
7860 /* Select an appropriate format */
7861 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7862 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7863 using_prefs = "reqonly";
7864 } else {
7865 using_prefs = "disabled";
7867 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
7868 memset(&pref, 0, sizeof(pref));
7869 strcpy(caller_pref_buf, "disabled");
7870 strcpy(host_pref_buf, "disabled");
7871 } else {
7872 using_prefs = "mine";
7873 if (ies.codec_prefs)
7874 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
7875 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7876 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7877 pref = iaxs[fr->callno]->rprefs;
7878 using_prefs = "caller";
7879 } else {
7880 pref = iaxs[fr->callno]->prefs;
7882 } else /* if no codec_prefs IE do it the old way */
7883 pref = iaxs[fr->callno]->prefs;
7885 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
7886 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
7887 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
7889 if (!format) {
7890 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7891 if (option_debug)
7892 ast_log(LOG_DEBUG, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
7893 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
7895 if (!format) {
7896 if (authdebug) {
7897 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7898 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7899 else
7900 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7902 memset(&ied0, 0, sizeof(ied0));
7903 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7904 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7905 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7906 if (!iaxs[fr->callno]) {
7907 ast_mutex_unlock(&iaxsl[fr->callno]);
7908 return 1;
7910 } else {
7911 /* Pick one... */
7912 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
7913 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
7914 format = 0;
7915 } else {
7916 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
7917 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
7918 memset(&pref, 0, sizeof(pref));
7919 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
7920 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7921 strcpy(caller_pref_buf,"disabled");
7922 strcpy(host_pref_buf,"disabled");
7923 } else {
7924 using_prefs = "mine";
7925 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
7926 /* Do the opposite of what we tried above. */
7927 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
7928 pref = iaxs[fr->callno]->prefs;
7929 } else {
7930 pref = iaxs[fr->callno]->rprefs;
7931 using_prefs = "caller";
7933 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
7934 } else /* if no codec_prefs IE do it the old way */
7935 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7938 if (!format) {
7939 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
7940 if (authdebug) {
7941 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
7942 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
7943 else
7944 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
7946 memset(&ied0, 0, sizeof(ied0));
7947 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
7948 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
7949 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
7950 if (!iaxs[fr->callno]) {
7951 ast_mutex_unlock(&iaxsl[fr->callno]);
7952 return 1;
7957 if (format) {
7958 /* Authentication received */
7959 memset(&ied1, 0, sizeof(ied1));
7960 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
7961 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
7962 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
7963 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7964 if (option_verbose > 2)
7965 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s:\n"
7966 "%srequested format = %s,\n"
7967 "%srequested prefs = %s,\n"
7968 "%sactual format = %s,\n"
7969 "%shost prefs = %s,\n"
7970 "%spriority = %s\n",
7971 ast_inet_ntoa(sin.sin_addr),
7972 VERBOSE_PREFIX_4,
7973 ast_getformatname(iaxs[fr->callno]->peerformat),
7974 VERBOSE_PREFIX_4,
7975 caller_pref_buf,
7976 VERBOSE_PREFIX_4,
7977 ast_getformatname(format),
7978 VERBOSE_PREFIX_4,
7979 host_pref_buf,
7980 VERBOSE_PREFIX_4,
7981 using_prefs);
7983 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
7984 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
7985 iax2_destroy(fr->callno);
7986 } else {
7987 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7988 /* If this is a TBD call, we're ready but now what... */
7989 if (option_verbose > 2)
7990 ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
7994 break;
7995 case IAX_COMMAND_DIAL:
7996 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
7997 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
7998 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
7999 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
8000 if (authdebug)
8001 ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
8002 memset(&ied0, 0, sizeof(ied0));
8003 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
8004 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
8005 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8006 if (!iaxs[fr->callno]) {
8007 ast_mutex_unlock(&iaxsl[fr->callno]);
8008 return 1;
8010 } else {
8011 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8012 if (option_verbose > 2)
8013 ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
8014 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8015 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
8016 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
8017 iax2_destroy(fr->callno);
8020 break;
8021 case IAX_COMMAND_INVAL:
8022 iaxs[fr->callno]->error = ENOTCONN;
8023 if (option_debug)
8024 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
8025 iax2_destroy(fr->callno);
8026 if (option_debug)
8027 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
8028 break;
8029 case IAX_COMMAND_VNAK:
8030 if (option_debug)
8031 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
8032 /* Force retransmission */
8033 vnak_retransmit(fr->callno, fr->iseqno);
8034 break;
8035 case IAX_COMMAND_REGREQ:
8036 case IAX_COMMAND_REGREL:
8037 /* For security, always ack immediately */
8038 if (delayreject)
8039 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8040 if (register_verify(fr->callno, &sin, &ies)) {
8041 if (!iaxs[fr->callno]) {
8042 ast_mutex_unlock(&iaxsl[fr->callno]);
8043 return 1;
8045 /* Send delayed failure */
8046 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
8047 break;
8049 if (!iaxs[fr->callno]) {
8050 ast_mutex_unlock(&iaxsl[fr->callno]);
8051 return 1;
8053 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
8054 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
8055 if (f.subclass == IAX_COMMAND_REGREL)
8056 memset(&sin, 0, sizeof(sin));
8057 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
8058 ast_log(LOG_WARNING, "Registry error\n");
8059 if (!iaxs[fr->callno]) {
8060 ast_mutex_unlock(&iaxsl[fr->callno]);
8061 return 1;
8063 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
8064 ast_mutex_unlock(&iaxsl[fr->callno]);
8065 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
8066 ast_mutex_lock(&iaxsl[fr->callno]);
8067 if (!iaxs[fr->callno]) {
8068 ast_mutex_unlock(&iaxsl[fr->callno]);
8069 return 1;
8072 break;
8074 registry_authrequest(fr->callno);
8075 if (!iaxs[fr->callno]) {
8076 ast_mutex_unlock(&iaxsl[fr->callno]);
8077 return 1;
8079 break;
8080 case IAX_COMMAND_REGACK:
8081 if (iax2_ack_registry(&ies, &sin, fr->callno))
8082 ast_log(LOG_WARNING, "Registration failure\n");
8083 /* Send ack immediately, before we destroy */
8084 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8085 iax2_destroy(fr->callno);
8086 break;
8087 case IAX_COMMAND_REGREJ:
8088 if (iaxs[fr->callno]->reg) {
8089 if (authdebug) {
8090 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
8091 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
8093 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
8095 /* Send ack immediately, before we destroy */
8096 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8097 iax2_destroy(fr->callno);
8098 break;
8099 case IAX_COMMAND_REGAUTH:
8100 /* Authentication request */
8101 if (registry_rerequest(&ies, fr->callno, &sin)) {
8102 memset(&ied0, 0, sizeof(ied0));
8103 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
8104 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
8105 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8106 if (!iaxs[fr->callno]) {
8107 ast_mutex_unlock(&iaxsl[fr->callno]);
8108 return 1;
8111 break;
8112 case IAX_COMMAND_TXREJ:
8113 iaxs[fr->callno]->transferring = 0;
8114 if (option_verbose > 2)
8115 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8116 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
8117 if (iaxs[fr->callno]->bridgecallno) {
8118 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
8119 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
8120 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
8123 break;
8124 case IAX_COMMAND_TXREADY:
8125 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
8126 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
8127 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
8128 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
8129 else
8130 iaxs[fr->callno]->transferring = TRANSFER_READY;
8131 if (option_verbose > 2)
8132 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8133 if (iaxs[fr->callno]->bridgecallno) {
8134 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
8135 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
8136 /* They're both ready, now release them. */
8137 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
8138 if (option_verbose > 2)
8139 ast_verbose(VERBOSE_PREFIX_3 "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8140 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8142 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
8143 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
8145 memset(&ied0, 0, sizeof(ied0));
8146 memset(&ied1, 0, sizeof(ied1));
8147 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8148 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8149 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
8150 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
8151 } else {
8152 if (option_verbose > 2)
8153 ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
8154 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
8156 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
8157 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
8158 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
8159 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8161 /* Stop doing lag & ping requests */
8162 stop_stuff(fr->callno);
8163 stop_stuff(iaxs[fr->callno]->bridgecallno);
8165 memset(&ied0, 0, sizeof(ied0));
8166 memset(&ied1, 0, sizeof(ied1));
8167 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
8168 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
8169 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
8170 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
8176 break;
8177 case IAX_COMMAND_TXREQ:
8178 try_transfer(iaxs[fr->callno], &ies);
8179 break;
8180 case IAX_COMMAND_TXCNT:
8181 if (iaxs[fr->callno]->transferring)
8182 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
8183 break;
8184 case IAX_COMMAND_TXREL:
8185 /* Send ack immediately, rather than waiting until we've changed addresses */
8186 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8187 complete_transfer(fr->callno, &ies);
8188 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
8189 break;
8190 case IAX_COMMAND_TXMEDIA:
8191 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
8192 AST_LIST_LOCK(&iaxq.queue);
8193 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
8194 /* Cancel any outstanding frames and start anew */
8195 if ((fr->callno == cur->callno) && (cur->transfer)) {
8196 cur->retries = -1;
8199 AST_LIST_UNLOCK(&iaxq.queue);
8200 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
8201 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
8203 break;
8204 case IAX_COMMAND_DPREP:
8205 complete_dpreply(iaxs[fr->callno], &ies);
8206 break;
8207 case IAX_COMMAND_UNSUPPORT:
8208 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
8209 break;
8210 case IAX_COMMAND_FWDOWNL:
8211 /* Firmware download */
8212 memset(&ied0, 0, sizeof(ied0));
8213 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
8214 if (res < 0)
8215 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8216 else if (res > 0)
8217 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8218 else
8219 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
8220 if (!iaxs[fr->callno]) {
8221 ast_mutex_unlock(&iaxsl[fr->callno]);
8222 return 1;
8224 break;
8225 default:
8226 if (option_debug)
8227 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
8228 memset(&ied0, 0, sizeof(ied0));
8229 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
8230 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
8232 /* Don't actually pass these frames along */
8233 if ((f.subclass != IAX_COMMAND_ACK) &&
8234 (f.subclass != IAX_COMMAND_TXCNT) &&
8235 (f.subclass != IAX_COMMAND_TXACC) &&
8236 (f.subclass != IAX_COMMAND_INVAL) &&
8237 (f.subclass != IAX_COMMAND_VNAK)) {
8238 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8239 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8241 ast_mutex_unlock(&iaxsl[fr->callno]);
8242 return 1;
8244 /* Unless this is an ACK or INVAL frame, ack it */
8245 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
8246 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8247 } else if (minivid) {
8248 f.frametype = AST_FRAME_VIDEO;
8249 if (iaxs[fr->callno]->videoformat > 0)
8250 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
8251 else {
8252 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n ");
8253 iax2_vnak(fr->callno);
8254 ast_mutex_unlock(&iaxsl[fr->callno]);
8255 return 1;
8257 f.datalen = res - sizeof(*vh);
8258 if (f.datalen)
8259 f.data = thread->buf + sizeof(*vh);
8260 else
8261 f.data = NULL;
8262 #ifdef IAXTESTS
8263 if (test_resync) {
8264 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
8265 } else
8266 #endif /* IAXTESTS */
8267 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
8268 } else {
8269 /* A mini frame */
8270 f.frametype = AST_FRAME_VOICE;
8271 if (iaxs[fr->callno]->voiceformat > 0)
8272 f.subclass = iaxs[fr->callno]->voiceformat;
8273 else {
8274 if (option_debug)
8275 ast_log(LOG_DEBUG, "Received mini frame before first full voice frame\n");
8276 iax2_vnak(fr->callno);
8277 ast_mutex_unlock(&iaxsl[fr->callno]);
8278 return 1;
8280 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
8281 if (f.datalen < 0) {
8282 ast_log(LOG_WARNING, "Datalen < 0?\n");
8283 ast_mutex_unlock(&iaxsl[fr->callno]);
8284 return 1;
8286 if (f.datalen)
8287 f.data = thread->buf + sizeof(*mh);
8288 else
8289 f.data = NULL;
8290 #ifdef IAXTESTS
8291 if (test_resync) {
8292 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
8293 } else
8294 #endif /* IAXTESTS */
8295 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
8296 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
8298 /* Don't pass any packets until we're started */
8299 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8300 ast_mutex_unlock(&iaxsl[fr->callno]);
8301 return 1;
8303 /* Common things */
8304 f.src = "IAX2";
8305 f.mallocd = 0;
8306 f.offset = 0;
8307 f.len = 0;
8308 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
8309 f.samples = ast_codec_get_samples(&f);
8310 /* We need to byteswap incoming slinear samples from network byte order */
8311 if (f.subclass == AST_FORMAT_SLINEAR)
8312 ast_frame_byteswap_be(&f);
8313 } else
8314 f.samples = 0;
8315 iax_frame_wrap(fr, &f);
8317 /* If this is our most recent packet, use it as our basis for timestamping */
8318 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8319 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
8320 fr->outoforder = 0;
8321 } else {
8322 if (option_debug && iaxdebug && iaxs[fr->callno])
8323 ast_log(LOG_DEBUG, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
8324 fr->outoforder = -1;
8326 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
8327 duped_fr = iaxfrdup2(fr);
8328 if (duped_fr) {
8329 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
8331 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
8332 iaxs[fr->callno]->last = fr->ts;
8333 #if 1
8334 if (option_debug && iaxdebug)
8335 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8336 #endif
8339 /* Always run again */
8340 ast_mutex_unlock(&iaxsl[fr->callno]);
8341 return 1;
8344 /* Function to clean up process thread if it is cancelled */
8345 static void iax2_process_thread_cleanup(void *data)
8347 struct iax2_thread *thread = data;
8348 ast_mutex_destroy(&thread->lock);
8349 ast_cond_destroy(&thread->cond);
8350 free(thread);
8351 ast_atomic_dec_and_test(&iaxactivethreadcount);
8354 static void *iax2_process_thread(void *data)
8356 struct iax2_thread *thread = data;
8357 struct timeval tv;
8358 struct timespec ts;
8359 int put_into_idle = 0;
8361 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
8362 pthread_cleanup_push(iax2_process_thread_cleanup, data);
8363 for(;;) {
8364 /* Wait for something to signal us to be awake */
8365 ast_mutex_lock(&thread->lock);
8367 /* Flag that we're ready to accept signals */
8368 thread->ready_for_signal = 1;
8370 /* Put into idle list if applicable */
8371 if (put_into_idle)
8372 insert_idle_thread(thread);
8374 if (thread->type == IAX_TYPE_DYNAMIC) {
8375 struct iax2_thread *t = NULL;
8376 /* Wait to be signalled or time out */
8377 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8378 ts.tv_sec = tv.tv_sec;
8379 ts.tv_nsec = tv.tv_usec * 1000;
8380 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
8381 /* This thread was never put back into the available dynamic
8382 * thread list, so just go away. */
8383 if (!put_into_idle) {
8384 ast_mutex_unlock(&thread->lock);
8385 break;
8387 AST_LIST_LOCK(&dynamic_list);
8388 /* Account for the case where this thread is acquired *right* after a timeout */
8389 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
8390 iaxdynamicthreadcount--;
8391 AST_LIST_UNLOCK(&dynamic_list);
8392 if (t) {
8393 /* This dynamic thread timed out waiting for a task and was
8394 * not acquired immediately after the timeout,
8395 * so it's time to go away. */
8396 ast_mutex_unlock(&thread->lock);
8397 break;
8399 /* Someone grabbed our thread *right* after we timed out.
8400 * Wait for them to set us up with something to do and signal
8401 * us to continue. */
8402 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
8403 ts.tv_sec = tv.tv_sec;
8404 ts.tv_nsec = tv.tv_usec * 1000;
8405 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
8407 ast_mutex_unlock(&thread->lock);
8408 break;
8411 } else {
8412 ast_cond_wait(&thread->cond, &thread->lock);
8415 /* Go back into our respective list */
8416 put_into_idle = 1;
8418 ast_mutex_unlock(&thread->lock);
8420 if (thread->iostate == IAX_IOSTATE_IDLE)
8421 continue;
8423 /* Add ourselves to the active list now */
8424 AST_LIST_LOCK(&active_list);
8425 AST_LIST_INSERT_HEAD(&active_list, thread, list);
8426 AST_LIST_UNLOCK(&active_list);
8428 /* See what we need to do */
8429 switch(thread->iostate) {
8430 case IAX_IOSTATE_READY:
8431 thread->actions++;
8432 thread->iostate = IAX_IOSTATE_PROCESSING;
8433 socket_process(thread);
8434 handle_deferred_full_frames(thread);
8435 break;
8436 case IAX_IOSTATE_SCHEDREADY:
8437 thread->actions++;
8438 thread->iostate = IAX_IOSTATE_PROCESSING;
8439 #ifdef SCHED_MULTITHREADED
8440 thread->schedfunc(thread->scheddata);
8441 #endif
8442 break;
8444 time(&thread->checktime);
8445 thread->iostate = IAX_IOSTATE_IDLE;
8446 #ifdef DEBUG_SCHED_MULTITHREAD
8447 thread->curfunc[0]='\0';
8448 #endif
8450 /* Now... remove ourselves from the active list, and return to the idle list */
8451 AST_LIST_LOCK(&active_list);
8452 AST_LIST_REMOVE(&active_list, thread, list);
8453 AST_LIST_UNLOCK(&active_list);
8455 /* Make sure another frame didn't sneak in there after we thought we were done. */
8456 handle_deferred_full_frames(thread);
8459 /*!\note For some reason, idle threads are exiting without being removed
8460 * from an idle list, which is causing memory corruption. Forcibly remove
8461 * it from the list, if it's there.
8463 AST_LIST_LOCK(&idle_list);
8464 AST_LIST_REMOVE(&idle_list, thread, list);
8465 AST_LIST_UNLOCK(&idle_list);
8467 AST_LIST_LOCK(&dynamic_list);
8468 AST_LIST_REMOVE(&dynamic_list, thread, list);
8469 AST_LIST_UNLOCK(&dynamic_list);
8471 /* I am exiting here on my own volition, I need to clean up my own data structures
8472 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
8474 pthread_cleanup_pop(1);
8476 return NULL;
8479 static int iax2_do_register(struct iax2_registry *reg)
8481 struct iax_ie_data ied;
8482 if (option_debug && iaxdebug)
8483 ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
8485 if (reg->dnsmgr &&
8486 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
8487 /* Maybe the IP has changed, force DNS refresh */
8488 ast_dnsmgr_refresh(reg->dnsmgr);
8492 * if IP has Changed, free allocated call to create a new one with new IP
8493 * call has the pointer to IP and must be updated to the new one
8495 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
8496 ast_mutex_lock(&iaxsl[reg->callno]);
8497 iax2_destroy(reg->callno);
8498 ast_mutex_unlock(&iaxsl[reg->callno]);
8499 reg->callno = 0;
8501 if (!reg->addr.sin_addr.s_addr) {
8502 if (option_debug && iaxdebug)
8503 ast_log(LOG_DEBUG, "Unable to send registration request for '%s' without IP address\n", reg->username);
8504 /* Setup the next registration attempt */
8505 AST_SCHED_DEL(sched, reg->expire);
8506 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8507 return -1;
8510 if (!reg->callno) {
8511 if (option_debug)
8512 ast_log(LOG_DEBUG, "Allocate call number\n");
8513 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd);
8514 if (reg->callno < 1) {
8515 ast_log(LOG_WARNING, "Unable to create call for registration\n");
8516 return -1;
8517 } else if (option_debug)
8518 ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
8519 iaxs[reg->callno]->reg = reg;
8520 ast_mutex_unlock(&iaxsl[reg->callno]);
8522 /* Schedule the next registration attempt */
8523 AST_SCHED_DEL(sched, reg->expire);
8524 /* Setup the next registration a little early */
8525 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
8526 /* Send the request */
8527 memset(&ied, 0, sizeof(ied));
8528 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
8529 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
8530 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
8531 reg->regstate = REG_STATE_REGSENT;
8532 return 0;
8535 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
8537 if (pos != 3)
8538 return NULL;
8539 return iax_prov_complete_template(line, word, pos, state);
8542 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
8544 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
8545 is found for template */
8546 struct iax_ie_data provdata;
8547 struct iax_ie_data ied;
8548 unsigned int sig;
8549 struct sockaddr_in sin;
8550 int callno;
8551 struct create_addr_info cai;
8553 memset(&cai, 0, sizeof(cai));
8555 if (option_debug)
8556 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
8558 if (iax_provision_build(&provdata, &sig, template, force)) {
8559 if (option_debug)
8560 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
8561 return 0;
8564 if (end) {
8565 memcpy(&sin, end, sizeof(sin));
8566 cai.sockfd = sockfd;
8567 } else if (create_addr(dest, NULL, &sin, &cai))
8568 return -1;
8570 /* Build the rest of the message */
8571 memset(&ied, 0, sizeof(ied));
8572 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
8574 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd);
8575 if (!callno)
8576 return -1;
8578 if (iaxs[callno]) {
8579 /* Schedule autodestruct in case they don't ever give us anything back */
8580 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
8581 iaxs[callno]->autoid = iax2_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
8582 ast_set_flag(iaxs[callno], IAX_PROVISION);
8583 /* Got a call number now, so go ahead and send the provisioning information */
8584 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
8586 ast_mutex_unlock(&iaxsl[callno]);
8588 return 1;
8591 static char *papp = "IAX2Provision";
8592 static char *psyn = "Provision a calling IAXy with a given template";
8593 static char *pdescrip =
8594 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
8595 "the calling entity is in fact an IAXy) with the given template or\n"
8596 "default if one is not specified. Returns -1 on error or 0 on success.\n";
8598 /*! iax2provision
8599 \ingroup applications
8601 static int iax2_prov_app(struct ast_channel *chan, void *data)
8603 int res;
8604 char *sdata;
8605 char *opts;
8606 int force =0;
8607 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
8608 if (ast_strlen_zero(data))
8609 data = "default";
8610 sdata = ast_strdupa(data);
8611 opts = strchr(sdata, '|');
8612 if (opts)
8613 *opts='\0';
8615 if (chan->tech != &iax2_tech) {
8616 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
8617 return -1;
8619 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
8620 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
8621 return -1;
8623 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
8624 if (option_verbose > 2)
8625 ast_verbose(VERBOSE_PREFIX_3 "Provisioned IAXY at '%s' with '%s'= %d\n",
8626 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
8627 sdata, res);
8628 return res;
8632 static int iax2_prov_cmd(int fd, int argc, char *argv[])
8634 int force = 0;
8635 int res;
8636 if (argc < 4)
8637 return RESULT_SHOWUSAGE;
8638 if ((argc > 4)) {
8639 if (!strcasecmp(argv[4], "forced"))
8640 force = 1;
8641 else
8642 return RESULT_SHOWUSAGE;
8644 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
8645 if (res < 0)
8646 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
8647 else if (res < 1)
8648 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
8649 else
8650 ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
8651 return RESULT_SUCCESS;
8654 static void __iax2_poke_noanswer(const void *data)
8656 struct iax2_peer *peer = (struct iax2_peer *)data;
8657 if (peer->lastms > -1) {
8658 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
8659 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
8660 ast_device_state_changed("IAX2/%s", peer->name); /* Activate notification */
8662 if (peer->callno > 0) {
8663 ast_mutex_lock(&iaxsl[peer->callno]);
8664 iax2_destroy(peer->callno);
8665 ast_mutex_unlock(&iaxsl[peer->callno]);
8667 peer->callno = 0;
8668 peer->lastms = -1;
8669 /* Try again quickly */
8670 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
8671 if (peer->pokeexpire == -1)
8672 peer_unref(peer);
8675 static int iax2_poke_noanswer(const void *data)
8677 struct iax2_peer *peer = (struct iax2_peer *)data;
8678 peer->pokeexpire = -1;
8679 #ifdef SCHED_MULTITHREADED
8680 if (schedule_action(__iax2_poke_noanswer, data))
8681 #endif
8682 __iax2_poke_noanswer(data);
8683 peer_unref(peer);
8684 return 0;
8687 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
8689 struct iax2_peer *peer = obj;
8691 iax2_poke_peer(peer, 0);
8693 return 0;
8696 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
8698 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
8699 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
8700 immediately after clearing things out */
8701 peer->lastms = 0;
8702 peer->historicms = 0;
8703 peer->pokeexpire = -1;
8704 peer->callno = 0;
8705 return 0;
8707 if (peer->callno > 0) {
8708 ast_log(LOG_NOTICE, "Still have a callno...\n");
8709 ast_mutex_lock(&iaxsl[peer->callno]);
8710 iax2_destroy(peer->callno);
8711 ast_mutex_unlock(&iaxsl[peer->callno]);
8713 if (heldcall)
8714 ast_mutex_unlock(&iaxsl[heldcall]);
8715 peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd);
8716 if (heldcall)
8717 ast_mutex_lock(&iaxsl[heldcall]);
8718 if (peer->callno < 1) {
8719 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
8720 return -1;
8723 /* Speed up retransmission times for this qualify call */
8724 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
8725 iaxs[peer->callno]->peerpoke = peer;
8727 /* Remove any pending pokeexpire task */
8728 if (peer->pokeexpire > -1) {
8729 if (!ast_sched_del(sched, peer->pokeexpire)) {
8730 peer->pokeexpire = -1;
8731 peer_unref(peer);
8735 /* Queue up a new task to handle no reply */
8736 /* If the host is already unreachable then use the unreachable interval instead */
8737 if (peer->lastms < 0) {
8738 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
8739 } else
8740 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
8742 if (peer->pokeexpire == -1)
8743 peer_unref(peer);
8745 /* And send the poke */
8746 send_command(iaxs[peer->callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
8748 return 0;
8751 static void free_context(struct iax2_context *con)
8753 struct iax2_context *conl;
8754 while(con) {
8755 conl = con;
8756 con = con->next;
8757 free(conl);
8761 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
8763 int callno;
8764 int res;
8765 int fmt, native;
8766 struct sockaddr_in sin;
8767 struct ast_channel *c;
8768 struct parsed_dial_string pds;
8769 struct create_addr_info cai;
8770 char *tmpstr;
8772 memset(&pds, 0, sizeof(pds));
8773 tmpstr = ast_strdupa(data);
8774 parse_dial_string(tmpstr, &pds);
8776 if (ast_strlen_zero(pds.peer)) {
8777 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
8778 return NULL;
8781 memset(&cai, 0, sizeof(cai));
8782 cai.capability = iax2_capability;
8784 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8786 /* Populate our address from the given */
8787 if (create_addr(pds.peer, NULL, &sin, &cai)) {
8788 *cause = AST_CAUSE_UNREGISTERED;
8789 return NULL;
8792 if (pds.port)
8793 sin.sin_port = htons(atoi(pds.port));
8795 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd);
8796 if (callno < 1) {
8797 ast_log(LOG_WARNING, "Unable to create call\n");
8798 *cause = AST_CAUSE_CONGESTION;
8799 return NULL;
8802 /* If this is a trunk, update it now */
8803 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
8804 if (ast_test_flag(&cai, IAX_TRUNK)) {
8805 int new_callno;
8806 if ((new_callno = make_trunk(callno, 1)) != -1)
8807 callno = new_callno;
8809 iaxs[callno]->maxtime = cai.maxtime;
8810 if (cai.found)
8811 ast_string_field_set(iaxs[callno], host, pds.peer);
8813 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
8815 ast_mutex_unlock(&iaxsl[callno]);
8817 if (c) {
8818 /* Choose a format we can live with */
8819 if (c->nativeformats & format)
8820 c->nativeformats &= format;
8821 else {
8822 native = c->nativeformats;
8823 fmt = format;
8824 res = ast_translator_best_choice(&fmt, &native);
8825 if (res < 0) {
8826 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
8827 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
8828 ast_hangup(c);
8829 return NULL;
8831 c->nativeformats = native;
8833 c->readformat = ast_best_codec(c->nativeformats);
8834 c->writeformat = c->readformat;
8837 return c;
8840 static void *sched_thread(void *ignore)
8842 int count;
8843 int res;
8844 struct timeval tv;
8845 struct timespec ts;
8847 for (;;) {
8848 res = ast_sched_wait(sched);
8849 if ((res > 1000) || (res < 0))
8850 res = 1000;
8851 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
8852 ts.tv_sec = tv.tv_sec;
8853 ts.tv_nsec = tv.tv_usec * 1000;
8855 pthread_testcancel();
8856 ast_mutex_lock(&sched_lock);
8857 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
8858 ast_mutex_unlock(&sched_lock);
8859 pthread_testcancel();
8861 count = ast_sched_runq(sched);
8862 if (option_debug && count >= 20)
8863 ast_log(LOG_DEBUG, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
8865 return NULL;
8868 static void *network_thread(void *ignore)
8870 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
8871 from the network, and queue them for delivery to the channels */
8872 int res, count, wakeup;
8873 struct iax_frame *f;
8875 if (timingfd > -1)
8876 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
8878 for(;;) {
8879 pthread_testcancel();
8881 /* Go through the queue, sending messages which have not yet been
8882 sent, and scheduling retransmissions if appropriate */
8883 AST_LIST_LOCK(&iaxq.queue);
8884 count = 0;
8885 wakeup = -1;
8886 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
8887 if (f->sentyet)
8888 continue;
8890 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
8891 if (ast_mutex_trylock(&iaxsl[f->callno])) {
8892 wakeup = 1;
8893 continue;
8896 f->sentyet++;
8898 if (iaxs[f->callno]) {
8899 send_packet(f);
8900 count++;
8903 ast_mutex_unlock(&iaxsl[f->callno]);
8905 if (f->retries < 0) {
8906 /* This is not supposed to be retransmitted */
8907 AST_LIST_REMOVE_CURRENT(&iaxq.queue, list);
8908 iaxq.count--;
8909 /* Free the iax frame */
8910 iax_frame_free(f);
8911 } else {
8912 /* We need reliable delivery. Schedule a retransmission */
8913 f->retries++;
8914 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
8917 AST_LIST_TRAVERSE_SAFE_END
8918 AST_LIST_UNLOCK(&iaxq.queue);
8920 pthread_testcancel();
8922 if (option_debug && count >= 20)
8923 ast_log(LOG_DEBUG, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
8925 /* Now do the IO, and run scheduled tasks */
8926 res = ast_io_wait(io, wakeup);
8927 if (res >= 0) {
8928 if (option_debug && res >= 20)
8929 ast_log(LOG_DEBUG, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
8932 return NULL;
8935 static int start_network_thread(void)
8937 pthread_attr_t attr;
8938 int threadcount = 0;
8939 int x;
8940 for (x = 0; x < iaxthreadcount; x++) {
8941 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
8942 if (thread) {
8943 thread->type = IAX_TYPE_POOL;
8944 thread->threadnum = ++threadcount;
8945 ast_mutex_init(&thread->lock);
8946 ast_cond_init(&thread->cond, NULL);
8947 pthread_attr_init(&attr);
8948 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
8949 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
8950 ast_log(LOG_WARNING, "Failed to create new thread!\n");
8951 free(thread);
8952 thread = NULL;
8954 AST_LIST_LOCK(&idle_list);
8955 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
8956 AST_LIST_UNLOCK(&idle_list);
8959 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
8960 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
8961 if (option_verbose > 1)
8962 ast_verbose(VERBOSE_PREFIX_2 "%d helper threaads started\n", threadcount);
8963 return 0;
8966 static struct iax2_context *build_context(char *context)
8968 struct iax2_context *con;
8970 if ((con = ast_calloc(1, sizeof(*con))))
8971 ast_copy_string(con->context, context, sizeof(con->context));
8973 return con;
8976 static int get_auth_methods(char *value)
8978 int methods = 0;
8979 if (strstr(value, "rsa"))
8980 methods |= IAX_AUTH_RSA;
8981 if (strstr(value, "md5"))
8982 methods |= IAX_AUTH_MD5;
8983 if (strstr(value, "plaintext"))
8984 methods |= IAX_AUTH_PLAINTEXT;
8985 return methods;
8989 /*! \brief Check if address can be used as packet source.
8990 \return 0 address available, 1 address unavailable, -1 error
8992 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
8994 int sd;
8995 int res;
8997 sd = socket(AF_INET, SOCK_DGRAM, 0);
8998 if (sd < 0) {
8999 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
9000 return -1;
9003 res = bind(sd, sa, salen);
9004 if (res < 0) {
9005 if (option_debug)
9006 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
9007 close(sd);
9008 return 1;
9011 close(sd);
9012 return 0;
9015 /*! \brief Parse the "sourceaddress" value,
9016 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
9017 not found. */
9018 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
9020 struct sockaddr_in sin;
9021 int nonlocal = 1;
9022 int port = IAX_DEFAULT_PORTNO;
9023 int sockfd = defaultsockfd;
9024 char *tmp;
9025 char *addr;
9026 char *portstr;
9028 if (!(tmp = ast_strdupa(srcaddr)))
9029 return -1;
9031 addr = strsep(&tmp, ":");
9032 portstr = tmp;
9034 if (portstr) {
9035 port = atoi(portstr);
9036 if (port < 1)
9037 port = IAX_DEFAULT_PORTNO;
9040 if (!ast_get_ip(&sin, addr)) {
9041 struct ast_netsock *sock;
9042 int res;
9044 sin.sin_port = 0;
9045 sin.sin_family = AF_INET;
9046 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
9047 if (res == 0) {
9048 /* ip address valid. */
9049 sin.sin_port = htons(port);
9050 if (!(sock = ast_netsock_find(netsock, &sin)))
9051 sock = ast_netsock_find(outsock, &sin);
9052 if (sock) {
9053 sockfd = ast_netsock_sockfd(sock);
9054 nonlocal = 0;
9055 } else {
9056 unsigned int orig_saddr = sin.sin_addr.s_addr;
9057 /* INADDR_ANY matches anyway! */
9058 sin.sin_addr.s_addr = INADDR_ANY;
9059 if (ast_netsock_find(netsock, &sin)) {
9060 sin.sin_addr.s_addr = orig_saddr;
9061 sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, socket_read, NULL);
9062 if (sock) {
9063 sockfd = ast_netsock_sockfd(sock);
9064 ast_netsock_unref(sock);
9065 nonlocal = 0;
9066 } else {
9067 nonlocal = 2;
9074 peer->sockfd = sockfd;
9076 if (nonlocal == 1) {
9077 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
9078 srcaddr, peer->name);
9079 return -1;
9080 } else if (nonlocal == 2) {
9081 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
9082 srcaddr, peer->name);
9083 return -1;
9084 } else {
9085 if (option_debug)
9086 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
9087 return 0;
9091 static void peer_destructor(void *obj)
9093 struct iax2_peer *peer = obj;
9095 ast_free_ha(peer->ha);
9097 if (peer->callno > 0) {
9098 ast_mutex_lock(&iaxsl[peer->callno]);
9099 iax2_destroy(peer->callno);
9100 ast_mutex_unlock(&iaxsl[peer->callno]);
9103 register_peer_exten(peer, 0);
9105 if (peer->dnsmgr)
9106 ast_dnsmgr_release(peer->dnsmgr);
9108 ast_string_field_free_memory(peer);
9111 /*! \brief Create peer structure based on configuration */
9112 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9114 struct iax2_peer *peer = NULL;
9115 struct ast_ha *oldha = NULL;
9116 int maskfound=0;
9117 int found=0;
9118 int firstpass=1;
9119 struct iax2_peer tmp_peer = {
9120 .name = name,
9123 if (!temponly) {
9124 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
9125 if (peer && !ast_test_flag(peer, IAX_DELME))
9126 firstpass = 0;
9129 if (peer) {
9130 found++;
9131 if (firstpass) {
9132 oldha = peer->ha;
9133 peer->ha = NULL;
9135 unlink_peer(peer);
9136 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
9137 peer->expire = -1;
9138 peer->pokeexpire = -1;
9139 peer->sockfd = defaultsockfd;
9140 if (ast_string_field_init(peer, 32))
9141 peer = peer_unref(peer);
9144 if (peer) {
9145 if (firstpass) {
9146 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
9147 peer->encmethods = iax2_encryption;
9148 peer->adsi = adsi;
9149 ast_string_field_set(peer,secret,"");
9150 if (!found) {
9151 ast_string_field_set(peer, name, name);
9152 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9153 peer->expiry = min_reg_expire;
9155 peer->prefs = prefs;
9156 peer->capability = iax2_capability;
9157 peer->smoothing = 0;
9158 peer->pokefreqok = DEFAULT_FREQ_OK;
9159 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
9160 ast_string_field_set(peer,context,"");
9161 ast_string_field_set(peer,peercontext,"");
9162 ast_clear_flag(peer, IAX_HASCALLERID);
9163 ast_string_field_set(peer, cid_name, "");
9164 ast_string_field_set(peer, cid_num, "");
9167 if (!v) {
9168 v = alt;
9169 alt = NULL;
9171 while(v) {
9172 if (!strcasecmp(v->name, "secret")) {
9173 ast_string_field_set(peer, secret, v->value);
9174 } else if (!strcasecmp(v->name, "mailbox")) {
9175 ast_string_field_set(peer, mailbox, v->value);
9176 } else if (!strcasecmp(v->name, "mohinterpret")) {
9177 ast_string_field_set(peer, mohinterpret, v->value);
9178 } else if (!strcasecmp(v->name, "mohsuggest")) {
9179 ast_string_field_set(peer, mohsuggest, v->value);
9180 } else if (!strcasecmp(v->name, "dbsecret")) {
9181 ast_string_field_set(peer, dbsecret, v->value);
9182 } else if (!strcasecmp(v->name, "trunk")) {
9183 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
9184 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
9185 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without zaptel timing\n", peer->name);
9186 ast_clear_flag(peer, IAX_TRUNK);
9188 } else if (!strcasecmp(v->name, "auth")) {
9189 peer->authmethods = get_auth_methods(v->value);
9190 } else if (!strcasecmp(v->name, "encryption")) {
9191 peer->encmethods = get_encrypt_methods(v->value);
9192 } else if (!strcasecmp(v->name, "notransfer")) {
9193 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9194 ast_clear_flag(peer, IAX_TRANSFERMEDIA);
9195 ast_set2_flag(peer, ast_true(v->value), IAX_NOTRANSFER);
9196 } else if (!strcasecmp(v->name, "transfer")) {
9197 if (!strcasecmp(v->value, "mediaonly")) {
9198 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9199 } else if (ast_true(v->value)) {
9200 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9201 } else
9202 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9203 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9204 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
9205 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9206 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
9207 } else if (!strcasecmp(v->name, "host")) {
9208 if (!strcasecmp(v->value, "dynamic")) {
9209 /* They'll register with us */
9210 ast_set_flag(peer, IAX_DYNAMIC);
9211 if (!found) {
9212 /* Initialize stuff iff we're not found, otherwise
9213 we keep going with what we had */
9214 memset(&peer->addr.sin_addr, 0, 4);
9215 if (peer->addr.sin_port) {
9216 /* If we've already got a port, make it the default rather than absolute */
9217 peer->defaddr.sin_port = peer->addr.sin_port;
9218 peer->addr.sin_port = 0;
9221 } else {
9222 /* Non-dynamic. Make sure we become that way if we're not */
9223 AST_SCHED_DEL(sched, peer->expire);
9224 ast_clear_flag(peer, IAX_DYNAMIC);
9225 if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
9226 return peer_unref(peer);
9227 if (!peer->addr.sin_port)
9228 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
9230 if (!maskfound)
9231 inet_aton("255.255.255.255", &peer->mask);
9232 } else if (!strcasecmp(v->name, "defaultip")) {
9233 if (ast_get_ip(&peer->defaddr, v->value))
9234 return peer_unref(peer);
9235 } else if (!strcasecmp(v->name, "sourceaddress")) {
9236 peer_set_srcaddr(peer, v->value);
9237 } else if (!strcasecmp(v->name, "permit") ||
9238 !strcasecmp(v->name, "deny")) {
9239 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
9240 } else if (!strcasecmp(v->name, "mask")) {
9241 maskfound++;
9242 inet_aton(v->value, &peer->mask);
9243 } else if (!strcasecmp(v->name, "context")) {
9244 ast_string_field_set(peer, context, v->value);
9245 } else if (!strcasecmp(v->name, "regexten")) {
9246 ast_string_field_set(peer, regexten, v->value);
9247 } else if (!strcasecmp(v->name, "peercontext")) {
9248 ast_string_field_set(peer, peercontext, v->value);
9249 } else if (!strcasecmp(v->name, "port")) {
9250 if (ast_test_flag(peer, IAX_DYNAMIC))
9251 peer->defaddr.sin_port = htons(atoi(v->value));
9252 else
9253 peer->addr.sin_port = htons(atoi(v->value));
9254 } else if (!strcasecmp(v->name, "username")) {
9255 ast_string_field_set(peer, username, v->value);
9256 } else if (!strcasecmp(v->name, "allow")) {
9257 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
9258 } else if (!strcasecmp(v->name, "disallow")) {
9259 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
9260 } else if (!strcasecmp(v->name, "callerid")) {
9261 if (!ast_strlen_zero(v->value)) {
9262 char name2[80];
9263 char num2[80];
9264 ast_callerid_split(v->value, name2, 80, num2, 80);
9265 ast_string_field_set(peer, cid_name, name2);
9266 ast_string_field_set(peer, cid_num, num2);
9267 ast_set_flag(peer, IAX_HASCALLERID);
9268 } else {
9269 ast_clear_flag(peer, IAX_HASCALLERID);
9270 ast_string_field_set(peer, cid_name, "");
9271 ast_string_field_set(peer, cid_num, "");
9273 } else if (!strcasecmp(v->name, "fullname")) {
9274 if (!ast_strlen_zero(v->value)) {
9275 ast_string_field_set(peer, cid_name, v->value);
9276 ast_set_flag(peer, IAX_HASCALLERID);
9277 } else {
9278 ast_string_field_set(peer, cid_name, "");
9279 if (ast_strlen_zero(peer->cid_num))
9280 ast_clear_flag(peer, IAX_HASCALLERID);
9282 } else if (!strcasecmp(v->name, "cid_number")) {
9283 if (!ast_strlen_zero(v->value)) {
9284 ast_string_field_set(peer, cid_num, v->value);
9285 ast_set_flag(peer, IAX_HASCALLERID);
9286 } else {
9287 ast_string_field_set(peer, cid_num, "");
9288 if (ast_strlen_zero(peer->cid_name))
9289 ast_clear_flag(peer, IAX_HASCALLERID);
9291 } else if (!strcasecmp(v->name, "sendani")) {
9292 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
9293 } else if (!strcasecmp(v->name, "inkeys")) {
9294 ast_string_field_set(peer, inkeys, v->value);
9295 } else if (!strcasecmp(v->name, "outkey")) {
9296 ast_string_field_set(peer, outkey, v->value);
9297 } else if (!strcasecmp(v->name, "qualify")) {
9298 if (!strcasecmp(v->value, "no")) {
9299 peer->maxms = 0;
9300 } else if (!strcasecmp(v->value, "yes")) {
9301 peer->maxms = DEFAULT_MAXMS;
9302 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
9303 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9304 peer->maxms = 0;
9306 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
9307 peer->smoothing = ast_true(v->value);
9308 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
9309 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
9310 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9312 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
9313 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
9314 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
9315 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
9316 } else if (!strcasecmp(v->name, "timezone")) {
9317 ast_string_field_set(peer, zonetag, v->value);
9318 } else if (!strcasecmp(v->name, "adsi")) {
9319 peer->adsi = ast_true(v->value);
9320 }/* else if (strcasecmp(v->name,"type")) */
9321 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9322 v = v->next;
9323 if (!v) {
9324 v = alt;
9325 alt = NULL;
9328 if (!peer->authmethods)
9329 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9330 ast_clear_flag(peer, IAX_DELME);
9331 /* Make sure these are IPv4 addresses */
9332 peer->addr.sin_family = AF_INET;
9334 if (oldha)
9335 ast_free_ha(oldha);
9336 return peer;
9339 static void user_destructor(void *obj)
9341 struct iax2_user *user = obj;
9343 ast_free_ha(user->ha);
9344 free_context(user->contexts);
9345 if(user->vars) {
9346 ast_variables_destroy(user->vars);
9347 user->vars = NULL;
9349 ast_string_field_free_memory(user);
9352 /*! \brief Create in-memory user structure from configuration */
9353 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
9355 struct iax2_user *user = NULL;
9356 struct iax2_context *con, *conl = NULL;
9357 struct ast_ha *oldha = NULL;
9358 struct iax2_context *oldcon = NULL;
9359 int format;
9360 int firstpass=1;
9361 int oldcurauthreq = 0;
9362 char *varname = NULL, *varval = NULL;
9363 struct ast_variable *tmpvar = NULL;
9364 struct iax2_user tmp_user = {
9365 .name = name,
9368 if (!temponly) {
9369 user = ao2_find(users, &tmp_user, OBJ_POINTER);
9370 if (user && !ast_test_flag(user, IAX_DELME))
9371 firstpass = 0;
9374 if (user) {
9375 if (firstpass) {
9376 oldcurauthreq = user->curauthreq;
9377 oldha = user->ha;
9378 oldcon = user->contexts;
9379 user->ha = NULL;
9380 user->contexts = NULL;
9382 /* Already in the list, remove it and it will be added back (or FREE'd) */
9383 ao2_unlink(users, user);
9384 } else {
9385 user = ao2_alloc(sizeof(*user), user_destructor);
9388 if (user) {
9389 if (firstpass) {
9390 ast_string_field_free_memory(user);
9391 memset(user, 0, sizeof(struct iax2_user));
9392 if (ast_string_field_init(user, 32)) {
9393 user = user_unref(user);
9394 goto cleanup;
9396 user->maxauthreq = maxauthreq;
9397 user->curauthreq = oldcurauthreq;
9398 user->prefs = prefs;
9399 user->capability = iax2_capability;
9400 user->encmethods = iax2_encryption;
9401 user->adsi = adsi;
9402 ast_string_field_set(user, name, name);
9403 ast_string_field_set(user, language, language);
9404 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
9405 ast_clear_flag(user, IAX_HASCALLERID);
9406 ast_string_field_set(user, cid_name, "");
9407 ast_string_field_set(user, cid_num, "");
9409 if (!v) {
9410 v = alt;
9411 alt = NULL;
9413 while(v) {
9414 if (!strcasecmp(v->name, "context")) {
9415 con = build_context(v->value);
9416 if (con) {
9417 if (conl)
9418 conl->next = con;
9419 else
9420 user->contexts = con;
9421 conl = con;
9423 } else if (!strcasecmp(v->name, "permit") ||
9424 !strcasecmp(v->name, "deny")) {
9425 user->ha = ast_append_ha(v->name, v->value, user->ha);
9426 } else if (!strcasecmp(v->name, "setvar")) {
9427 varname = ast_strdupa(v->value);
9428 if (varname && (varval = strchr(varname,'='))) {
9429 *varval = '\0';
9430 varval++;
9431 if((tmpvar = ast_variable_new(varname, varval))) {
9432 tmpvar->next = user->vars;
9433 user->vars = tmpvar;
9436 } else if (!strcasecmp(v->name, "allow")) {
9437 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
9438 } else if (!strcasecmp(v->name, "disallow")) {
9439 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
9440 } else if (!strcasecmp(v->name, "trunk")) {
9441 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
9442 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
9443 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without zaptel timing\n", user->name);
9444 ast_clear_flag(user, IAX_TRUNK);
9446 } else if (!strcasecmp(v->name, "auth")) {
9447 user->authmethods = get_auth_methods(v->value);
9448 } else if (!strcasecmp(v->name, "encryption")) {
9449 user->encmethods = get_encrypt_methods(v->value);
9450 } else if (!strcasecmp(v->name, "notransfer")) {
9451 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9452 ast_clear_flag(user, IAX_TRANSFERMEDIA);
9453 ast_set2_flag(user, ast_true(v->value), IAX_NOTRANSFER);
9454 } else if (!strcasecmp(v->name, "transfer")) {
9455 if (!strcasecmp(v->value, "mediaonly")) {
9456 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9457 } else if (ast_true(v->value)) {
9458 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9459 } else
9460 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9461 } else if (!strcasecmp(v->name, "codecpriority")) {
9462 if(!strcasecmp(v->value, "caller"))
9463 ast_set_flag(user, IAX_CODEC_USER_FIRST);
9464 else if(!strcasecmp(v->value, "disabled"))
9465 ast_set_flag(user, IAX_CODEC_NOPREFS);
9466 else if(!strcasecmp(v->value, "reqonly")) {
9467 ast_set_flag(user, IAX_CODEC_NOCAP);
9468 ast_set_flag(user, IAX_CODEC_NOPREFS);
9470 } else if (!strcasecmp(v->name, "jitterbuffer")) {
9471 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
9472 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
9473 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
9474 } else if (!strcasecmp(v->name, "dbsecret")) {
9475 ast_string_field_set(user, dbsecret, v->value);
9476 } else if (!strcasecmp(v->name, "secret")) {
9477 if (!ast_strlen_zero(user->secret)) {
9478 char *old = ast_strdupa(user->secret);
9480 ast_string_field_build(user, secret, "%s;%s", old, v->value);
9481 } else
9482 ast_string_field_set(user, secret, v->value);
9483 } else if (!strcasecmp(v->name, "callerid")) {
9484 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
9485 char name2[80];
9486 char num2[80];
9487 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
9488 ast_string_field_set(user, cid_name, name2);
9489 ast_string_field_set(user, cid_num, num2);
9490 ast_set_flag(user, IAX_HASCALLERID);
9491 } else {
9492 ast_clear_flag(user, IAX_HASCALLERID);
9493 ast_string_field_set(user, cid_name, "");
9494 ast_string_field_set(user, cid_num, "");
9496 } else if (!strcasecmp(v->name, "fullname")) {
9497 if (!ast_strlen_zero(v->value)) {
9498 ast_string_field_set(user, cid_name, v->value);
9499 ast_set_flag(user, IAX_HASCALLERID);
9500 } else {
9501 ast_string_field_set(user, cid_name, "");
9502 if (ast_strlen_zero(user->cid_num))
9503 ast_clear_flag(user, IAX_HASCALLERID);
9505 } else if (!strcasecmp(v->name, "cid_number")) {
9506 if (!ast_strlen_zero(v->value)) {
9507 ast_string_field_set(user, cid_num, v->value);
9508 ast_set_flag(user, IAX_HASCALLERID);
9509 } else {
9510 ast_string_field_set(user, cid_num, "");
9511 if (ast_strlen_zero(user->cid_name))
9512 ast_clear_flag(user, IAX_HASCALLERID);
9514 } else if (!strcasecmp(v->name, "accountcode")) {
9515 ast_string_field_set(user, accountcode, v->value);
9516 } else if (!strcasecmp(v->name, "mohinterpret")) {
9517 ast_string_field_set(user, mohinterpret, v->value);
9518 } else if (!strcasecmp(v->name, "mohsuggest")) {
9519 ast_string_field_set(user, mohsuggest, v->value);
9520 } else if (!strcasecmp(v->name, "language")) {
9521 ast_string_field_set(user, language, v->value);
9522 } else if (!strcasecmp(v->name, "amaflags")) {
9523 format = ast_cdr_amaflags2int(v->value);
9524 if (format < 0) {
9525 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9526 } else {
9527 user->amaflags = format;
9529 } else if (!strcasecmp(v->name, "inkeys")) {
9530 ast_string_field_set(user, inkeys, v->value);
9531 } else if (!strcasecmp(v->name, "maxauthreq")) {
9532 user->maxauthreq = atoi(v->value);
9533 if (user->maxauthreq < 0)
9534 user->maxauthreq = 0;
9535 } else if (!strcasecmp(v->name, "adsi")) {
9536 user->adsi = ast_true(v->value);
9537 }/* else if (strcasecmp(v->name,"type")) */
9538 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9539 v = v->next;
9540 if (!v) {
9541 v = alt;
9542 alt = NULL;
9545 if (!user->authmethods) {
9546 if (!ast_strlen_zero(user->secret)) {
9547 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9548 if (!ast_strlen_zero(user->inkeys))
9549 user->authmethods |= IAX_AUTH_RSA;
9550 } else if (!ast_strlen_zero(user->inkeys)) {
9551 user->authmethods = IAX_AUTH_RSA;
9552 } else {
9553 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
9556 ast_clear_flag(user, IAX_DELME);
9558 cleanup:
9559 if (oldha)
9560 ast_free_ha(oldha);
9561 if (oldcon)
9562 free_context(oldcon);
9563 return user;
9566 static int peer_delme_cb(void *obj, void *arg, int flags)
9568 struct iax2_peer *peer = obj;
9570 ast_set_flag(peer, IAX_DELME);
9572 return 0;
9575 static int user_delme_cb(void *obj, void *arg, int flags)
9577 struct iax2_user *user = obj;
9579 ast_set_flag(user, IAX_DELME);
9581 return 0;
9584 static void delete_users(void)
9586 struct iax2_registry *reg;
9588 ao2_callback(users, 0, user_delme_cb, NULL);
9590 AST_LIST_LOCK(&registrations);
9591 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
9592 ast_sched_del(sched, reg->expire);
9593 if (reg->callno) {
9594 ast_mutex_lock(&iaxsl[reg->callno]);
9595 if (iaxs[reg->callno]) {
9596 iaxs[reg->callno]->reg = NULL;
9597 iax2_destroy(reg->callno);
9599 ast_mutex_unlock(&iaxsl[reg->callno]);
9601 if (reg->dnsmgr)
9602 ast_dnsmgr_release(reg->dnsmgr);
9603 free(reg);
9605 AST_LIST_UNLOCK(&registrations);
9607 ao2_callback(peers, 0, peer_delme_cb, NULL);
9610 static void prune_users(void)
9612 struct iax2_user *user;
9613 struct ao2_iterator i;
9615 i = ao2_iterator_init(users, 0);
9616 while ((user = ao2_iterator_next(&i))) {
9617 if (ast_test_flag(user, IAX_DELME))
9618 ao2_unlink(users, user);
9619 user_unref(user);
9623 /* Prune peers who still are supposed to be deleted */
9624 static void prune_peers(void)
9626 struct iax2_peer *peer;
9627 struct ao2_iterator i;
9629 i = ao2_iterator_init(peers, 0);
9630 while ((peer = ao2_iterator_next(&i))) {
9631 if (ast_test_flag(peer, IAX_DELME))
9632 unlink_peer(peer);
9633 peer_unref(peer);
9637 static void set_timing(void)
9639 #ifdef HAVE_ZAPTEL
9640 int bs = trunkfreq * 8;
9641 if (timingfd > -1) {
9642 if (
9643 #ifdef ZT_TIMERACK
9644 ioctl(timingfd, ZT_TIMERCONFIG, &bs) &&
9645 #endif
9646 ioctl(timingfd, ZT_SET_BLOCKSIZE, &bs))
9647 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
9649 #endif
9652 static void set_config_destroy(void)
9654 strcpy(accountcode, "");
9655 strcpy(language, "");
9656 strcpy(mohinterpret, "default");
9657 strcpy(mohsuggest, "");
9658 amaflags = 0;
9659 delayreject = 0;
9660 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
9661 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9662 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
9663 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
9664 delete_users();
9667 /*! \brief Load configuration */
9668 static int set_config(char *config_file, int reload)
9670 struct ast_config *cfg, *ucfg;
9671 int capability=iax2_capability;
9672 struct ast_variable *v;
9673 char *cat;
9674 const char *utype;
9675 const char *tosval;
9676 int format;
9677 int portno = IAX_DEFAULT_PORTNO;
9678 int x;
9679 struct iax2_user *user;
9680 struct iax2_peer *peer;
9681 struct ast_netsock *ns;
9682 #if 0
9683 static unsigned short int last_port=0;
9684 #endif
9686 cfg = ast_config_load(config_file);
9688 if (!cfg) {
9689 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
9690 return -1;
9693 if (reload) {
9694 set_config_destroy();
9697 /* Reset global codec prefs */
9698 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
9700 /* Reset Global Flags */
9701 memset(&globalflags, 0, sizeof(globalflags));
9702 ast_set_flag(&globalflags, IAX_RTUPDATE);
9704 #ifdef SO_NO_CHECK
9705 nochecksums = 0;
9706 #endif
9708 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9709 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
9711 maxauthreq = 3;
9713 v = ast_variable_browse(cfg, "general");
9715 /* Seed initial tos value */
9716 tosval = ast_variable_retrieve(cfg, "general", "tos");
9717 if (tosval) {
9718 if (ast_str2tos(tosval, &tos))
9719 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
9721 while(v) {
9722 if (!strcasecmp(v->name, "bindport")){
9723 if (reload)
9724 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
9725 else
9726 portno = atoi(v->value);
9727 } else if (!strcasecmp(v->name, "pingtime"))
9728 ping_time = atoi(v->value);
9729 else if (!strcasecmp(v->name, "iaxthreadcount")) {
9730 if (reload) {
9731 if (atoi(v->value) != iaxthreadcount)
9732 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
9733 } else {
9734 iaxthreadcount = atoi(v->value);
9735 if (iaxthreadcount < 1) {
9736 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
9737 iaxthreadcount = 1;
9738 } else if (iaxthreadcount > 256) {
9739 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
9740 iaxthreadcount = 256;
9743 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
9744 if (reload) {
9745 AST_LIST_LOCK(&dynamic_list);
9746 iaxmaxthreadcount = atoi(v->value);
9747 AST_LIST_UNLOCK(&dynamic_list);
9748 } else {
9749 iaxmaxthreadcount = atoi(v->value);
9750 if (iaxmaxthreadcount < 0) {
9751 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
9752 iaxmaxthreadcount = 0;
9753 } else if (iaxmaxthreadcount > 256) {
9754 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
9755 iaxmaxthreadcount = 256;
9758 } else if (!strcasecmp(v->name, "nochecksums")) {
9759 #ifdef SO_NO_CHECK
9760 if (ast_true(v->value))
9761 nochecksums = 1;
9762 else
9763 nochecksums = 0;
9764 #else
9765 if (ast_true(v->value))
9766 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
9767 #endif
9769 else if (!strcasecmp(v->name, "maxjitterbuffer"))
9770 maxjitterbuffer = atoi(v->value);
9771 else if (!strcasecmp(v->name, "resyncthreshold"))
9772 resyncthreshold = atoi(v->value);
9773 else if (!strcasecmp(v->name, "maxjitterinterps"))
9774 maxjitterinterps = atoi(v->value);
9775 else if (!strcasecmp(v->name, "lagrqtime"))
9776 lagrq_time = atoi(v->value);
9777 else if (!strcasecmp(v->name, "maxregexpire"))
9778 max_reg_expire = atoi(v->value);
9779 else if (!strcasecmp(v->name, "minregexpire"))
9780 min_reg_expire = atoi(v->value);
9781 else if (!strcasecmp(v->name, "bindaddr")) {
9782 if (reload) {
9783 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
9784 } else {
9785 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, socket_read, NULL))) {
9786 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
9787 } else {
9788 if (option_verbose > 1) {
9789 if (strchr(v->value, ':'))
9790 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
9791 else
9792 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s:%d'\n", v->value, portno);
9794 if (defaultsockfd < 0)
9795 defaultsockfd = ast_netsock_sockfd(ns);
9796 ast_netsock_unref(ns);
9799 } else if (!strcasecmp(v->name, "authdebug"))
9800 authdebug = ast_true(v->value);
9801 else if (!strcasecmp(v->name, "encryption"))
9802 iax2_encryption = get_encrypt_methods(v->value);
9803 else if (!strcasecmp(v->name, "notransfer")) {
9804 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
9805 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
9806 ast_set2_flag((&globalflags), ast_true(v->value), IAX_NOTRANSFER);
9807 } else if (!strcasecmp(v->name, "transfer")) {
9808 if (!strcasecmp(v->value, "mediaonly")) {
9809 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
9810 } else if (ast_true(v->value)) {
9811 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
9812 } else
9813 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
9814 } else if (!strcasecmp(v->name, "codecpriority")) {
9815 if(!strcasecmp(v->value, "caller"))
9816 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
9817 else if(!strcasecmp(v->value, "disabled"))
9818 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9819 else if(!strcasecmp(v->value, "reqonly")) {
9820 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
9821 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
9823 } else if (!strcasecmp(v->name, "jitterbuffer"))
9824 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
9825 else if (!strcasecmp(v->name, "forcejitterbuffer"))
9826 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
9827 else if (!strcasecmp(v->name, "delayreject"))
9828 delayreject = ast_true(v->value);
9829 else if (!strcasecmp(v->name, "rtcachefriends"))
9830 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
9831 else if (!strcasecmp(v->name, "rtignoreregexpire"))
9832 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
9833 else if (!strcasecmp(v->name, "rtupdate"))
9834 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
9835 else if (!strcasecmp(v->name, "trunktimestamps"))
9836 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
9837 else if (!strcasecmp(v->name, "rtautoclear")) {
9838 int i = atoi(v->value);
9839 if(i > 0)
9840 global_rtautoclear = i;
9841 else
9842 i = 0;
9843 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
9844 } else if (!strcasecmp(v->name, "trunkfreq")) {
9845 trunkfreq = atoi(v->value);
9846 if (trunkfreq < 10)
9847 trunkfreq = 10;
9848 } else if (!strcasecmp(v->name, "autokill")) {
9849 if (sscanf(v->value, "%d", &x) == 1) {
9850 if (x >= 0)
9851 autokill = x;
9852 else
9853 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
9854 } else if (ast_true(v->value)) {
9855 autokill = DEFAULT_MAXMS;
9856 } else {
9857 autokill = 0;
9859 } else if (!strcasecmp(v->name, "bandwidth")) {
9860 if (!strcasecmp(v->value, "low")) {
9861 capability = IAX_CAPABILITY_LOWBANDWIDTH;
9862 } else if (!strcasecmp(v->value, "medium")) {
9863 capability = IAX_CAPABILITY_MEDBANDWIDTH;
9864 } else if (!strcasecmp(v->value, "high")) {
9865 capability = IAX_CAPABILITY_FULLBANDWIDTH;
9866 } else
9867 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
9868 } else if (!strcasecmp(v->name, "allow")) {
9869 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
9870 } else if (!strcasecmp(v->name, "disallow")) {
9871 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
9872 } else if (!strcasecmp(v->name, "register")) {
9873 iax2_register(v->value, v->lineno);
9874 } else if (!strcasecmp(v->name, "iaxcompat")) {
9875 iaxcompat = ast_true(v->value);
9876 } else if (!strcasecmp(v->name, "regcontext")) {
9877 ast_copy_string(regcontext, v->value, sizeof(regcontext));
9878 /* Create context if it doesn't exist already */
9879 if (!ast_context_find(regcontext))
9880 ast_context_create(NULL, regcontext, "IAX2");
9881 } else if (!strcasecmp(v->name, "tos")) {
9882 if (ast_str2tos(v->value, &tos))
9883 ast_log(LOG_WARNING, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v->lineno);
9884 } else if (!strcasecmp(v->name, "accountcode")) {
9885 ast_copy_string(accountcode, v->value, sizeof(accountcode));
9886 } else if (!strcasecmp(v->name, "mohinterpret")) {
9887 ast_copy_string(mohinterpret, v->value, sizeof(user->mohinterpret));
9888 } else if (!strcasecmp(v->name, "mohsuggest")) {
9889 ast_copy_string(mohsuggest, v->value, sizeof(user->mohsuggest));
9890 } else if (!strcasecmp(v->name, "amaflags")) {
9891 format = ast_cdr_amaflags2int(v->value);
9892 if (format < 0) {
9893 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
9894 } else {
9895 amaflags = format;
9897 } else if (!strcasecmp(v->name, "language")) {
9898 ast_copy_string(language, v->value, sizeof(language));
9899 } else if (!strcasecmp(v->name, "maxauthreq")) {
9900 maxauthreq = atoi(v->value);
9901 if (maxauthreq < 0)
9902 maxauthreq = 0;
9903 } else if (!strcasecmp(v->name, "adsi")) {
9904 adsi = ast_true(v->value);
9905 } /*else if (strcasecmp(v->name,"type")) */
9906 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
9907 v = v->next;
9910 if (defaultsockfd < 0) {
9911 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, socket_read, NULL))) {
9912 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
9913 } else {
9914 if (option_verbose > 1)
9915 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
9916 defaultsockfd = ast_netsock_sockfd(ns);
9917 ast_netsock_unref(ns);
9920 if (reload) {
9921 ast_netsock_release(outsock);
9922 outsock = ast_netsock_list_alloc();
9923 if (!outsock) {
9924 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
9925 return -1;
9927 ast_netsock_init(outsock);
9930 if (min_reg_expire > max_reg_expire) {
9931 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
9932 min_reg_expire, max_reg_expire, max_reg_expire);
9933 min_reg_expire = max_reg_expire;
9935 iax2_capability = capability;
9937 ucfg = ast_config_load("users.conf");
9938 if (ucfg) {
9939 struct ast_variable *gen;
9940 int genhasiax;
9941 int genregisteriax;
9942 const char *hasiax, *registeriax;
9944 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
9945 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
9946 gen = ast_variable_browse(ucfg, "general");
9947 cat = ast_category_browse(ucfg, NULL);
9948 while (cat) {
9949 if (strcasecmp(cat, "general")) {
9950 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
9951 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
9952 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
9953 /* Start with general parameters, then specific parameters, user and peer */
9954 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
9955 if (user) {
9956 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
9957 user = user_unref(user);
9959 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
9960 if (peer) {
9961 if (ast_test_flag(peer, IAX_DYNAMIC))
9962 reg_source_db(peer);
9963 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
9964 peer = peer_unref(peer);
9967 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
9968 char tmp[256];
9969 const char *host = ast_variable_retrieve(ucfg, cat, "host");
9970 const char *username = ast_variable_retrieve(ucfg, cat, "username");
9971 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
9972 if (!host)
9973 host = ast_variable_retrieve(ucfg, "general", "host");
9974 if (!username)
9975 username = ast_variable_retrieve(ucfg, "general", "username");
9976 if (!secret)
9977 secret = ast_variable_retrieve(ucfg, "general", "secret");
9978 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
9979 if (!ast_strlen_zero(secret))
9980 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
9981 else
9982 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
9983 iax2_register(tmp, 0);
9987 cat = ast_category_browse(ucfg, cat);
9989 ast_config_destroy(ucfg);
9992 cat = ast_category_browse(cfg, NULL);
9993 while(cat) {
9994 if (strcasecmp(cat, "general")) {
9995 utype = ast_variable_retrieve(cfg, cat, "type");
9996 if (utype) {
9997 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
9998 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
9999 if (user) {
10000 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10001 user = user_unref(user);
10004 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
10005 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
10006 if (peer) {
10007 if (ast_test_flag(peer, IAX_DYNAMIC))
10008 reg_source_db(peer);
10009 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10010 peer = peer_unref(peer);
10012 } else if (strcasecmp(utype, "user")) {
10013 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
10015 } else
10016 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10018 cat = ast_category_browse(cfg, cat);
10020 ast_config_destroy(cfg);
10021 set_timing();
10022 return 1;
10025 static void poke_all_peers(void)
10027 struct ao2_iterator i;
10028 struct iax2_peer *peer;
10030 i = ao2_iterator_init(peers, 0);
10031 while ((peer = ao2_iterator_next(&i))) {
10032 iax2_poke_peer(peer, 0);
10033 peer_unref(peer);
10036 static int reload_config(void)
10038 char *config = "iax.conf";
10039 struct iax2_registry *reg;
10041 if (set_config(config, 1) > 0) {
10042 prune_peers();
10043 prune_users();
10044 AST_LIST_LOCK(&registrations);
10045 AST_LIST_TRAVERSE(&registrations, reg, entry)
10046 iax2_do_register(reg);
10047 AST_LIST_UNLOCK(&registrations);
10048 /* Qualify hosts, too */
10049 poke_all_peers();
10051 reload_firmware(0);
10052 iax_provision_reload();
10054 return 0;
10057 static int iax2_reload(int fd, int argc, char *argv[])
10059 return reload_config();
10062 static int reload(void)
10064 return reload_config();
10067 static int cache_get_callno_locked(const char *data)
10069 struct sockaddr_in sin;
10070 int x;
10071 int callno;
10072 struct iax_ie_data ied;
10073 struct create_addr_info cai;
10074 struct parsed_dial_string pds;
10075 char *tmpstr;
10077 for (x=0; x<IAX_MAX_CALLS; x++) {
10078 /* Look for an *exact match* call. Once a call is negotiated, it can only
10079 look up entries for a single context */
10080 if (!ast_mutex_trylock(&iaxsl[x])) {
10081 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
10082 return x;
10083 ast_mutex_unlock(&iaxsl[x]);
10087 /* No match found, we need to create a new one */
10089 memset(&cai, 0, sizeof(cai));
10090 memset(&ied, 0, sizeof(ied));
10091 memset(&pds, 0, sizeof(pds));
10093 tmpstr = ast_strdupa(data);
10094 parse_dial_string(tmpstr, &pds);
10096 if (ast_strlen_zero(pds.peer)) {
10097 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
10098 return -1;
10101 /* Populate our address from the given */
10102 if (create_addr(pds.peer, NULL, &sin, &cai))
10103 return -1;
10105 if (option_debug)
10106 ast_log(LOG_DEBUG, "peer: %s, username: %s, password: %s, context: %s\n",
10107 pds.peer, pds.username, pds.password, pds.context);
10109 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd);
10110 if (callno < 1) {
10111 ast_log(LOG_WARNING, "Unable to create call\n");
10112 return -1;
10115 ast_string_field_set(iaxs[callno], dproot, data);
10116 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
10118 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
10119 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
10120 /* the string format is slightly different from a standard dial string,
10121 because the context appears in the 'exten' position
10123 if (pds.exten)
10124 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10125 if (pds.username)
10126 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
10127 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
10128 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
10129 /* Keep password handy */
10130 if (pds.password)
10131 ast_string_field_set(iaxs[callno], secret, pds.password);
10132 if (pds.key)
10133 ast_string_field_set(iaxs[callno], outkey, pds.key);
10134 /* Start the call going */
10135 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
10137 return callno;
10140 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
10142 struct iax2_dpcache *dp, *prev = NULL, *next;
10143 struct timeval tv;
10144 int x;
10145 int com[2];
10146 int timeout;
10147 int old=0;
10148 int outfd;
10149 int abort;
10150 int callno;
10151 struct ast_channel *c;
10152 struct ast_frame *f;
10153 gettimeofday(&tv, NULL);
10154 dp = dpcache;
10155 while(dp) {
10156 next = dp->next;
10157 /* Expire old caches */
10158 if (ast_tvcmp(tv, dp->expiry) > 0) {
10159 /* It's expired, let it disappear */
10160 if (prev)
10161 prev->next = dp->next;
10162 else
10163 dpcache = dp->next;
10164 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10165 /* Free memory and go again */
10166 free(dp);
10167 } else {
10168 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = %p callno = %d)\n", dp->flags, dp->peer, dp->callno);
10170 dp = next;
10171 continue;
10173 /* We found an entry that matches us! */
10174 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10175 break;
10176 prev = dp;
10177 dp = next;
10179 if (!dp) {
10180 /* No matching entry. Create a new one. */
10181 /* First, can we make a callno? */
10182 callno = cache_get_callno_locked(data);
10183 if (callno < 0) {
10184 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10185 return NULL;
10187 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10188 ast_mutex_unlock(&iaxsl[callno]);
10189 return NULL;
10191 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
10192 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
10193 gettimeofday(&dp->expiry, NULL);
10194 dp->orig = dp->expiry;
10195 /* Expires in 30 mins by default */
10196 dp->expiry.tv_sec += iaxdefaultdpcache;
10197 dp->next = dpcache;
10198 dp->flags = CACHE_FLAG_PENDING;
10199 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10200 dp->waiters[x] = -1;
10201 dpcache = dp;
10202 dp->peer = iaxs[callno]->dpentries;
10203 iaxs[callno]->dpentries = dp;
10204 /* Send the request if we're already up */
10205 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
10206 iax2_dprequest(dp, callno);
10207 ast_mutex_unlock(&iaxsl[callno]);
10209 /* By here we must have a dp */
10210 if (dp->flags & CACHE_FLAG_PENDING) {
10211 /* Okay, here it starts to get nasty. We need a pipe now to wait
10212 for a reply to come back so long as it's pending */
10213 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
10214 /* Find an empty slot */
10215 if (dp->waiters[x] < 0)
10216 break;
10218 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10219 ast_log(LOG_WARNING, "No more waiter positions available\n");
10220 return NULL;
10222 if (pipe(com)) {
10223 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10224 return NULL;
10226 dp->waiters[x] = com[1];
10227 /* Okay, now we wait */
10228 timeout = iaxdefaulttimeout * 1000;
10229 /* Temporarily unlock */
10230 ast_mutex_unlock(&dpcache_lock);
10231 /* Defer any dtmf */
10232 if (chan)
10233 old = ast_channel_defer_dtmf(chan);
10234 abort = 0;
10235 while(timeout) {
10236 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10237 if (outfd > -1) {
10238 break;
10240 if (c) {
10241 f = ast_read(c);
10242 if (f)
10243 ast_frfree(f);
10244 else {
10245 /* Got hung up on, abort! */
10246 break;
10247 abort = 1;
10251 if (!timeout) {
10252 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
10254 ast_mutex_lock(&dpcache_lock);
10255 dp->waiters[x] = -1;
10256 close(com[1]);
10257 close(com[0]);
10258 if (abort) {
10259 /* Don't interpret anything, just abort. Not sure what th epoint
10260 of undeferring dtmf on a hung up channel is but hey whatever */
10261 if (!old && chan)
10262 ast_channel_undefer_dtmf(chan);
10263 return NULL;
10265 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
10266 /* Now to do non-independent analysis the results of our wait */
10267 if (dp->flags & CACHE_FLAG_PENDING) {
10268 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
10269 pending. Don't let it take as long to timeout. */
10270 dp->flags &= ~CACHE_FLAG_PENDING;
10271 dp->flags |= CACHE_FLAG_TIMEOUT;
10272 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
10273 systems without leaving it unavailable once the server comes back online */
10274 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
10275 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10276 if (dp->waiters[x] > -1)
10277 write(dp->waiters[x], "asdf", 4);
10280 /* Our caller will obtain the rest */
10281 if (!old && chan)
10282 ast_channel_undefer_dtmf(chan);
10284 return dp;
10287 /*! \brief Part of the IAX2 switch interface */
10288 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10290 struct iax2_dpcache *dp;
10291 int res = 0;
10292 #if 0
10293 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10294 #endif
10295 if ((priority != 1) && (priority != 2))
10296 return 0;
10297 ast_mutex_lock(&dpcache_lock);
10298 dp = find_cache(chan, data, context, exten, priority);
10299 if (dp) {
10300 if (dp->flags & CACHE_FLAG_EXISTS)
10301 res= 1;
10303 ast_mutex_unlock(&dpcache_lock);
10304 if (!dp) {
10305 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10307 return res;
10310 /*! \brief part of the IAX2 dial plan switch interface */
10311 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10313 int res = 0;
10314 struct iax2_dpcache *dp;
10315 #if 0
10316 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10317 #endif
10318 if ((priority != 1) && (priority != 2))
10319 return 0;
10320 ast_mutex_lock(&dpcache_lock);
10321 dp = find_cache(chan, data, context, exten, priority);
10322 if (dp) {
10323 if (dp->flags & CACHE_FLAG_CANEXIST)
10324 res= 1;
10326 ast_mutex_unlock(&dpcache_lock);
10327 if (!dp) {
10328 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10330 return res;
10333 /*! \brief Part of the IAX2 Switch interface */
10334 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10336 int res = 0;
10337 struct iax2_dpcache *dp;
10338 #if 0
10339 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10340 #endif
10341 if ((priority != 1) && (priority != 2))
10342 return 0;
10343 ast_mutex_lock(&dpcache_lock);
10344 dp = find_cache(chan, data, context, exten, priority);
10345 if (dp) {
10346 if (dp->flags & CACHE_FLAG_MATCHMORE)
10347 res= 1;
10349 ast_mutex_unlock(&dpcache_lock);
10350 if (!dp) {
10351 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10353 return res;
10356 /*! \brief Execute IAX2 dialplan switch */
10357 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10359 char odata[256];
10360 char req[256];
10361 char *ncontext;
10362 struct iax2_dpcache *dp;
10363 struct ast_app *dial;
10364 #if 0
10365 ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
10366 #endif
10367 if (priority == 2) {
10368 /* Indicate status, can be overridden in dialplan */
10369 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10370 if (dialstatus) {
10371 dial = pbx_findapp(dialstatus);
10372 if (dial)
10373 pbx_exec(chan, dial, "");
10375 return -1;
10376 } else if (priority != 1)
10377 return -1;
10378 ast_mutex_lock(&dpcache_lock);
10379 dp = find_cache(chan, data, context, exten, priority);
10380 if (dp) {
10381 if (dp->flags & CACHE_FLAG_EXISTS) {
10382 ast_copy_string(odata, data, sizeof(odata));
10383 ncontext = strchr(odata, '/');
10384 if (ncontext) {
10385 *ncontext = '\0';
10386 ncontext++;
10387 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10388 } else {
10389 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
10391 if (option_verbose > 2)
10392 ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
10393 } else {
10394 ast_mutex_unlock(&dpcache_lock);
10395 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
10396 return -1;
10399 ast_mutex_unlock(&dpcache_lock);
10400 dial = pbx_findapp("Dial");
10401 if (dial) {
10402 return pbx_exec(chan, dial, req);
10403 } else {
10404 ast_log(LOG_WARNING, "No dial application registered\n");
10406 return -1;
10409 static int function_iaxpeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10411 struct iax2_peer *peer;
10412 char *peername, *colname;
10414 peername = ast_strdupa(data);
10416 /* if our channel, return the IP address of the endpoint of current channel */
10417 if (!strcmp(peername,"CURRENTCHANNEL")) {
10418 unsigned short callno;
10419 if (chan->tech != &iax2_tech)
10420 return -1;
10421 callno = PTR_TO_CALLNO(chan->tech_pvt);
10422 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
10423 return 0;
10426 if ((colname = strchr(peername, ':'))) /*! \todo : will be removed after the 1.4 relese */
10427 *colname++ = '\0';
10428 else if ((colname = strchr(peername, '|')))
10429 *colname++ = '\0';
10430 else
10431 colname = "ip";
10433 if (!(peer = find_peer(peername, 1)))
10434 return -1;
10436 if (!strcasecmp(colname, "ip")) {
10437 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10438 } else if (!strcasecmp(colname, "status")) {
10439 peer_status(peer, buf, len);
10440 } else if (!strcasecmp(colname, "mailbox")) {
10441 ast_copy_string(buf, peer->mailbox, len);
10442 } else if (!strcasecmp(colname, "context")) {
10443 ast_copy_string(buf, peer->context, len);
10444 } else if (!strcasecmp(colname, "expire")) {
10445 snprintf(buf, len, "%d", peer->expire);
10446 } else if (!strcasecmp(colname, "dynamic")) {
10447 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
10448 } else if (!strcasecmp(colname, "callerid_name")) {
10449 ast_copy_string(buf, peer->cid_name, len);
10450 } else if (!strcasecmp(colname, "callerid_num")) {
10451 ast_copy_string(buf, peer->cid_num, len);
10452 } else if (!strcasecmp(colname, "codecs")) {
10453 ast_getformatname_multiple(buf, len -1, peer->capability);
10454 } else if (!strncasecmp(colname, "codec[", 6)) {
10455 char *codecnum, *ptr;
10456 int index = 0, codec = 0;
10458 codecnum = strchr(colname, '[');
10459 *codecnum = '\0';
10460 codecnum++;
10461 if ((ptr = strchr(codecnum, ']'))) {
10462 *ptr = '\0';
10464 index = atoi(codecnum);
10465 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10466 ast_copy_string(buf, ast_getformatname(codec), len);
10470 peer_unref(peer);
10472 return 0;
10475 struct ast_custom_function iaxpeer_function = {
10476 .name = "IAXPEER",
10477 .synopsis = "Gets IAX peer information",
10478 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10479 .read = function_iaxpeer,
10480 .desc = "If peername specified, valid items are:\n"
10481 "- ip (default) The IP address.\n"
10482 "- status The peer's status (if qualify=yes)\n"
10483 "- mailbox The configured mailbox.\n"
10484 "- context The configured context.\n"
10485 "- expire The epoch time of the next expire.\n"
10486 "- dynamic Is it dynamic? (yes/no).\n"
10487 "- callerid_name The configured Caller ID name.\n"
10488 "- callerid_num The configured Caller ID number.\n"
10489 "- codecs The configured codecs.\n"
10490 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10491 "\n"
10492 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10493 "\n"
10497 /*! \brief Part of the device state notification system ---*/
10498 static int iax2_devicestate(void *data)
10500 struct parsed_dial_string pds;
10501 char *tmp = ast_strdupa(data);
10502 struct iax2_peer *p;
10503 int res = AST_DEVICE_INVALID;
10505 memset(&pds, 0, sizeof(pds));
10506 parse_dial_string(tmp, &pds);
10508 if (ast_strlen_zero(pds.peer)) {
10509 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10510 return res;
10513 if (option_debug > 2)
10514 ast_log(LOG_DEBUG, "Checking device state for device %s\n", pds.peer);
10516 /* SLD: FIXME: second call to find_peer during registration */
10517 if (!(p = find_peer(pds.peer, 1)))
10518 return res;
10520 res = AST_DEVICE_UNAVAILABLE;
10521 if (option_debug > 2)
10522 ast_log(LOG_DEBUG, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10523 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
10525 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
10526 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
10527 /* Peer is registered, or have default IP address
10528 and a valid registration */
10529 if (p->historicms == 0 || p->historicms <= p->maxms)
10530 /* let the core figure out whether it is in use or not */
10531 res = AST_DEVICE_UNKNOWN;
10534 peer_unref(p);
10536 return res;
10539 static struct ast_switch iax2_switch =
10541 name: "IAX2",
10542 description: "IAX Remote Dialplan Switch",
10543 exists: iax2_exists,
10544 canmatch: iax2_canmatch,
10545 exec: iax2_exec,
10546 matchmore: iax2_matchmore,
10549 static char show_stats_usage[] =
10550 "Usage: iax2 show stats\n"
10551 " Display statistics on IAX channel driver.\n";
10553 static char show_cache_usage[] =
10554 "Usage: iax2 show cache\n"
10555 " Display currently cached IAX Dialplan results.\n";
10557 static char show_peer_usage[] =
10558 "Usage: iax2 show peer <name>\n"
10559 " Display details on specific IAX peer\n";
10561 static char prune_realtime_usage[] =
10562 "Usage: iax2 prune realtime [<peername>|all]\n"
10563 " Prunes object(s) from the cache\n";
10565 static char iax2_reload_usage[] =
10566 "Usage: iax2 reload\n"
10567 " Reloads IAX configuration from iax.conf\n";
10569 static char show_prov_usage[] =
10570 "Usage: iax2 provision <host> <template> [forced]\n"
10571 " Provisions the given peer or IP address using a template\n"
10572 " matching either 'template' or '*' if the template is not\n"
10573 " found. If 'forced' is specified, even empty provisioning\n"
10574 " fields will be provisioned as empty fields.\n";
10576 static char show_users_usage[] =
10577 "Usage: iax2 show users [like <pattern>]\n"
10578 " Lists all known IAX2 users.\n"
10579 " Optional regular expression pattern is used to filter the user list.\n";
10581 static char show_channels_usage[] =
10582 "Usage: iax2 show channels\n"
10583 " Lists all currently active IAX channels.\n";
10585 static char show_netstats_usage[] =
10586 "Usage: iax2 show netstats\n"
10587 " Lists network status for all currently active IAX channels.\n";
10589 static char show_threads_usage[] =
10590 "Usage: iax2 show threads\n"
10591 " Lists status of IAX helper threads\n";
10593 static char show_peers_usage[] =
10594 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10595 " Lists all known IAX2 peers.\n"
10596 " Optional 'registered' argument lists only peers with known addresses.\n"
10597 " Optional regular expression pattern is used to filter the peer list.\n";
10599 static char show_firmware_usage[] =
10600 "Usage: iax2 show firmware\n"
10601 " Lists all known IAX firmware images.\n";
10603 static char show_reg_usage[] =
10604 "Usage: iax2 show registry\n"
10605 " Lists all registration requests and status.\n";
10607 static char debug_usage[] =
10608 "Usage: iax2 set debug\n"
10609 " Enables dumping of IAX packets for debugging purposes\n";
10611 static char no_debug_usage[] =
10612 "Usage: iax2 set debug off\n"
10613 " Disables dumping of IAX packets for debugging purposes\n";
10615 static char debug_trunk_usage[] =
10616 "Usage: iax2 set debug trunk\n"
10617 " Requests current status of IAX trunking\n";
10619 static char no_debug_trunk_usage[] =
10620 "Usage: iax2 set debug trunk off\n"
10621 " Requests current status of IAX trunking\n";
10623 static char debug_jb_usage[] =
10624 "Usage: iax2 set debug jb\n"
10625 " Enables jitterbuffer debugging information\n";
10627 static char no_debug_jb_usage[] =
10628 "Usage: iax2 set debug jb off\n"
10629 " Disables jitterbuffer debugging information\n";
10631 static char iax2_test_losspct_usage[] =
10632 "Usage: iax2 test losspct <percentage>\n"
10633 " For testing, throws away <percentage> percent of incoming packets\n";
10635 #ifdef IAXTESTS
10636 static char iax2_test_late_usage[] =
10637 "Usage: iax2 test late <ms>\n"
10638 " For testing, count the next frame as <ms> ms late\n";
10640 static char iax2_test_resync_usage[] =
10641 "Usage: iax2 test resync <ms>\n"
10642 " For testing, adjust all future frames by <ms> ms\n";
10644 static char iax2_test_jitter_usage[] =
10645 "Usage: iax2 test jitter <ms> <pct>\n"
10646 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10647 #endif /* IAXTESTS */
10649 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated = {
10650 { "iax2", "trunk", "debug", NULL },
10651 iax2_do_trunk_debug, NULL,
10652 NULL };
10654 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10655 { "iax2", "jb", "debug", NULL },
10656 iax2_do_jb_debug, NULL,
10657 NULL };
10659 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10660 { "iax2", "no", "debug", NULL },
10661 iax2_no_debug, NULL,
10662 NULL };
10664 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated = {
10665 { "iax2", "no", "trunk", "debug", NULL },
10666 iax2_no_trunk_debug, NULL,
10667 NULL };
10669 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated = {
10670 { "iax2", "no", "jb", "debug", NULL },
10671 iax2_no_jb_debug, NULL,
10672 NULL };
10674 static struct ast_cli_entry cli_iax2[] = {
10675 { { "iax2", "show", "cache", NULL },
10676 iax2_show_cache, "Display IAX cached dialplan",
10677 show_cache_usage, NULL, },
10679 { { "iax2", "show", "channels", NULL },
10680 iax2_show_channels, "List active IAX channels",
10681 show_channels_usage, NULL, },
10683 { { "iax2", "show", "firmware", NULL },
10684 iax2_show_firmware, "List available IAX firmwares",
10685 show_firmware_usage, NULL, },
10687 { { "iax2", "show", "netstats", NULL },
10688 iax2_show_netstats, "List active IAX channel netstats",
10689 show_netstats_usage, NULL, },
10691 { { "iax2", "show", "peers", NULL },
10692 iax2_show_peers, "List defined IAX peers",
10693 show_peers_usage, NULL, },
10695 { { "iax2", "show", "registry", NULL },
10696 iax2_show_registry, "Display IAX registration status",
10697 show_reg_usage, NULL, },
10699 { { "iax2", "show", "stats", NULL },
10700 iax2_show_stats, "Display IAX statistics",
10701 show_stats_usage, NULL, },
10703 { { "iax2", "show", "threads", NULL },
10704 iax2_show_threads, "Display IAX helper thread info",
10705 show_threads_usage, NULL, },
10707 { { "iax2", "show", "users", NULL },
10708 iax2_show_users, "List defined IAX users",
10709 show_users_usage, NULL, },
10711 { { "iax2", "prune", "realtime", NULL },
10712 iax2_prune_realtime, "Prune a cached realtime lookup",
10713 prune_realtime_usage, complete_iax2_show_peer },
10715 { { "iax2", "reload", NULL },
10716 iax2_reload, "Reload IAX configuration",
10717 iax2_reload_usage },
10719 { { "iax2", "show", "peer", NULL },
10720 iax2_show_peer, "Show details on specific IAX peer",
10721 show_peer_usage, complete_iax2_show_peer },
10723 { { "iax2", "set", "debug", NULL },
10724 iax2_do_debug, "Enable IAX debugging",
10725 debug_usage },
10727 { { "iax2", "set", "debug", "trunk", NULL },
10728 iax2_do_trunk_debug, "Enable IAX trunk debugging",
10729 debug_trunk_usage, NULL, &cli_iax2_trunk_debug_deprecated },
10731 { { "iax2", "set", "debug", "jb", NULL },
10732 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
10733 debug_jb_usage, NULL, &cli_iax2_jb_debug_deprecated },
10735 { { "iax2", "set", "debug", "off", NULL },
10736 iax2_no_debug, "Disable IAX debugging",
10737 no_debug_usage, NULL, &cli_iax2_no_debug_deprecated },
10739 { { "iax2", "set", "debug", "trunk", "off", NULL },
10740 iax2_no_trunk_debug, "Disable IAX trunk debugging",
10741 no_debug_trunk_usage, NULL, &cli_iax2_no_trunk_debug_deprecated },
10743 { { "iax2", "set", "debug", "jb", "off", NULL },
10744 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
10745 no_debug_jb_usage, NULL, &cli_iax2_no_jb_debug_deprecated },
10747 { { "iax2", "test", "losspct", NULL },
10748 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
10749 iax2_test_losspct_usage },
10751 { { "iax2", "provision", NULL },
10752 iax2_prov_cmd, "Provision an IAX device",
10753 show_prov_usage, iax2_prov_complete_template_3rd },
10755 #ifdef IAXTESTS
10756 { { "iax2", "test", "late", NULL },
10757 iax2_test_late, "Test the receipt of a late frame",
10758 iax2_test_late_usage },
10760 { { "iax2", "test", "resync", NULL },
10761 iax2_test_resync, "Test a resync in received timestamps",
10762 iax2_test_resync_usage },
10764 { { "iax2", "test", "jitter", NULL },
10765 iax2_test_jitter, "Simulates jitter for testing",
10766 iax2_test_jitter_usage },
10767 #endif /* IAXTESTS */
10770 static int __unload_module(void)
10772 struct iax2_thread *thread = NULL;
10773 int x;
10775 /* Make sure threads do not hold shared resources when they are canceled */
10777 /* Grab the sched lock resource to keep it away from threads about to die */
10778 /* Cancel the network thread, close the net socket */
10779 if (netthreadid != AST_PTHREADT_NULL) {
10780 AST_LIST_LOCK(&iaxq.queue);
10781 ast_mutex_lock(&sched_lock);
10782 pthread_cancel(netthreadid);
10783 ast_cond_signal(&sched_cond);
10784 ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
10785 AST_LIST_UNLOCK(&iaxq.queue);
10786 pthread_join(netthreadid, NULL);
10788 if (schedthreadid != AST_PTHREADT_NULL) {
10789 ast_mutex_lock(&sched_lock);
10790 pthread_cancel(schedthreadid);
10791 ast_cond_signal(&sched_cond);
10792 ast_mutex_unlock(&sched_lock);
10793 pthread_join(schedthreadid, NULL);
10796 /* Call for all threads to halt */
10797 AST_LIST_LOCK(&idle_list);
10798 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list, thread, list) {
10799 AST_LIST_REMOVE_CURRENT(&idle_list, list);
10800 pthread_cancel(thread->threadid);
10802 AST_LIST_TRAVERSE_SAFE_END
10803 AST_LIST_UNLOCK(&idle_list);
10805 AST_LIST_LOCK(&active_list);
10806 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list, thread, list) {
10807 AST_LIST_REMOVE_CURRENT(&active_list, list);
10808 pthread_cancel(thread->threadid);
10810 AST_LIST_TRAVERSE_SAFE_END
10811 AST_LIST_UNLOCK(&active_list);
10813 AST_LIST_LOCK(&dynamic_list);
10814 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list, thread, list) {
10815 AST_LIST_REMOVE_CURRENT(&dynamic_list, list);
10816 pthread_cancel(thread->threadid);
10818 AST_LIST_TRAVERSE_SAFE_END
10819 AST_LIST_UNLOCK(&dynamic_list);
10821 AST_LIST_HEAD_DESTROY(&iaxq.queue);
10823 /* Wait for threads to exit */
10824 while(0 < iaxactivethreadcount)
10825 usleep(10000);
10827 ast_netsock_release(netsock);
10828 ast_netsock_release(outsock);
10829 for (x=0;x<IAX_MAX_CALLS;x++)
10830 if (iaxs[x])
10831 iax2_destroy(x);
10832 ast_manager_unregister( "IAXpeers" );
10833 ast_manager_unregister( "IAXnetstats" );
10834 ast_unregister_application(papp);
10835 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10836 ast_unregister_switch(&iax2_switch);
10837 ast_channel_unregister(&iax2_tech);
10838 delete_users();
10839 iax_provision_unload();
10840 sched_context_destroy(sched);
10841 reload_firmware(1);
10843 ast_mutex_destroy(&waresl.lock);
10845 for (x = 0; x < IAX_MAX_CALLS; x++)
10846 ast_mutex_destroy(&iaxsl[x]);
10848 ao2_ref(peers, -1);
10849 ao2_ref(users, -1);
10851 return 0;
10854 static int unload_module(void)
10856 ast_custom_function_unregister(&iaxpeer_function);
10857 return __unload_module();
10860 static int peer_set_sock_cb(void *obj, void *arg, int flags)
10862 struct iax2_peer *peer = obj;
10864 if (peer->sockfd < 0)
10865 peer->sockfd = defaultsockfd;
10867 return 0;
10870 /*! \brief Load IAX2 module, load configuraiton ---*/
10871 static int load_module(void)
10873 char *config = "iax.conf";
10874 int res = 0;
10875 int x;
10876 struct iax2_registry *reg = NULL;
10878 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
10879 if (!peers)
10880 return AST_MODULE_LOAD_FAILURE;
10881 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
10882 if (!users) {
10883 ao2_ref(peers, -1);
10884 return AST_MODULE_LOAD_FAILURE;
10887 ast_custom_function_register(&iaxpeer_function);
10889 iax_set_output(iax_debug_output);
10890 iax_set_error(iax_error_output);
10891 jb_setoutput(jb_error_output, jb_warning_output, NULL);
10893 #ifdef HAVE_ZAPTEL
10894 #ifdef ZT_TIMERACK
10895 timingfd = open("/dev/zap/timer", O_RDWR);
10896 if (timingfd < 0)
10897 #endif
10898 timingfd = open("/dev/zap/pseudo", O_RDWR);
10899 if (timingfd < 0)
10900 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
10901 #endif
10903 memset(iaxs, 0, sizeof(iaxs));
10905 for (x=0;x<IAX_MAX_CALLS;x++)
10906 ast_mutex_init(&iaxsl[x]);
10908 ast_cond_init(&sched_cond, NULL);
10910 io = io_context_create();
10911 sched = sched_context_create();
10913 if (!io || !sched) {
10914 ast_log(LOG_ERROR, "Out of memory\n");
10915 return -1;
10918 netsock = ast_netsock_list_alloc();
10919 if (!netsock) {
10920 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
10921 return -1;
10923 ast_netsock_init(netsock);
10925 outsock = ast_netsock_list_alloc();
10926 if (!outsock) {
10927 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10928 return -1;
10930 ast_netsock_init(outsock);
10932 ast_mutex_init(&waresl.lock);
10934 AST_LIST_HEAD_INIT(&iaxq.queue);
10936 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
10938 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
10940 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
10941 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats, "Show IAX Netstats" );
10943 if(set_config(config, 0) == -1)
10944 return AST_MODULE_LOAD_DECLINE;
10946 if (ast_channel_register(&iax2_tech)) {
10947 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
10948 __unload_module();
10949 return -1;
10952 if (ast_register_switch(&iax2_switch))
10953 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
10955 res = start_network_thread();
10956 if (!res) {
10957 if (option_verbose > 1)
10958 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
10959 } else {
10960 ast_log(LOG_ERROR, "Unable to start network thread\n");
10961 ast_netsock_release(netsock);
10962 ast_netsock_release(outsock);
10965 AST_LIST_LOCK(&registrations);
10966 AST_LIST_TRAVERSE(&registrations, reg, entry)
10967 iax2_do_register(reg);
10968 AST_LIST_UNLOCK(&registrations);
10970 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
10971 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
10973 reload_firmware(0);
10974 iax_provision_reload();
10975 return res;
10978 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
10979 .load = load_module,
10980 .unload = unload_module,
10981 .reload = reload,