Merged revisions 140053 via svnmerge from
[asterisk-bristuff.git] / channels / chan_iax2.c
blobeb7383db396a917022578d6f47b15e4b45dd710a
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
30 * \todo Implement musicclass settings for IAX2 devices
33 /*** MODULEINFO
34 <use>crypto</use>
35 ***/
37 #include "asterisk.h"
39 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41 #include <sys/mman.h>
42 #include <dirent.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
45 #include <arpa/inet.h>
46 #include <netinet/in_systm.h>
47 #include <netinet/ip.h>
48 #include <sys/time.h>
49 #include <sys/signal.h>
50 #include <signal.h>
51 #include <strings.h>
52 #include <netdb.h>
53 #include <fcntl.h>
54 #include <sys/stat.h>
55 #include <regex.h>
57 #include "asterisk/paths.h" /* need ast_config_AST_DATA_DIR for firmware */
59 #include "asterisk/lock.h"
60 #include "asterisk/frame.h"
61 #include "asterisk/channel.h"
62 #include "asterisk/module.h"
63 #include "asterisk/pbx.h"
64 #include "asterisk/sched.h"
65 #include "asterisk/io.h"
66 #include "asterisk/config.h"
67 #include "asterisk/cli.h"
68 #include "asterisk/translate.h"
69 #include "asterisk/md5.h"
70 #include "asterisk/cdr.h"
71 #include "asterisk/crypto.h"
72 #include "asterisk/acl.h"
73 #include "asterisk/manager.h"
74 #include "asterisk/callerid.h"
75 #include "asterisk/app.h"
76 #include "asterisk/astdb.h"
77 #include "asterisk/musiconhold.h"
78 #include "asterisk/features.h"
79 #include "asterisk/utils.h"
80 #include "asterisk/causes.h"
81 #include "asterisk/localtime.h"
82 #include "asterisk/aes.h"
83 #include "asterisk/dnsmgr.h"
84 #include "asterisk/devicestate.h"
85 #include "asterisk/netsock.h"
86 #include "asterisk/stringfields.h"
87 #include "asterisk/linkedlists.h"
88 #include "asterisk/event.h"
89 #include "asterisk/astobj2.h"
90 #include "asterisk/timing.h"
92 #include "iax2.h"
93 #include "iax2-parser.h"
94 #include "iax2-provision.h"
95 #include "jitterbuf.h"
97 /* Define SCHED_MULTITHREADED to run the scheduler in a special
98 multithreaded mode. */
99 #define SCHED_MULTITHREADED
101 /* Define DEBUG_SCHED_MULTITHREADED to keep track of where each
102 thread is actually doing. */
103 #define DEBUG_SCHED_MULTITHREAD
106 #ifdef SO_NO_CHECK
107 static int nochecksums = 0;
108 #endif
110 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
111 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
113 #define DEFAULT_THREAD_COUNT 10
114 #define DEFAULT_MAX_THREAD_COUNT 100
115 #define DEFAULT_RETRY_TIME 1000
116 #define MEMORY_SIZE 100
117 #define DEFAULT_DROP 3
119 #define DEBUG_SUPPORT
121 #define MIN_REUSE_TIME 60 /* Don't reuse a call number within 60 seconds */
123 /* Sample over last 100 units to determine historic jitter */
124 #define GAMMA (0.01)
126 static struct ast_codec_pref prefs;
128 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
131 /*! \brief Maximum transmission unit for the UDP packet in the trunk not to be
132 fragmented. This is based on 1516 - ethernet - ip - udp - iax minus one g711 frame = 1240 */
133 #define MAX_TRUNK_MTU 1240
135 static int global_max_trunk_mtu; /*!< Maximum MTU, 0 if not used */
136 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ; /*!< Trunk MTU statistics */
138 #define DEFAULT_CONTEXT "default"
140 static char default_parkinglot[AST_MAX_CONTEXT];
142 static char language[MAX_LANGUAGE] = "";
143 static char regcontext[AST_MAX_CONTEXT] = "";
145 static int maxauthreq = 3;
146 static int max_retries = 4;
147 static int ping_time = 21;
148 static int lagrq_time = 10;
149 static int maxjitterbuffer=1000;
150 static int resyncthreshold=1000;
151 static int maxjitterinterps=10;
152 static int jittertargetextra = 40; /* number of milliseconds the new jitter buffer adds on to its size */
154 #define MAX_TRUNKDATA 640 * 200 /*!< 40ms, uncompressed linear * 200 channels */
156 static int trunkfreq = 20;
157 static int trunkmaxsize = MAX_TRUNKDATA;
159 static int authdebug = 1;
160 static int autokill = 0;
161 static int iaxcompat = 0;
163 static int iaxdefaultdpcache=10 * 60; /* Cache dialplan entries for 10 minutes by default */
165 static int iaxdefaulttimeout = 5; /* Default to wait no more than 5 seconds for a reply to come back */
167 static struct {
168 unsigned int tos;
169 unsigned int cos;
170 } qos = { 0, 0 };
172 static int min_reg_expire;
173 static int max_reg_expire;
175 static int srvlookup = 0;
177 static int timingfd = -1; /* Timing file descriptor */
179 static struct ast_netsock_list *netsock;
180 static struct ast_netsock_list *outsock; /*!< used if sourceaddress specified and bindaddr == INADDR_ANY */
181 static int defaultsockfd = -1;
183 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
185 /* Ethernet, etc */
186 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
187 /* T1, maybe ISDN */
188 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
189 ~AST_FORMAT_SLINEAR & \
190 ~AST_FORMAT_ULAW & \
191 ~AST_FORMAT_ALAW & \
192 ~AST_FORMAT_G722)
193 /* A modem */
194 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
195 ~AST_FORMAT_G726 & \
196 ~AST_FORMAT_G726_AAL2 & \
197 ~AST_FORMAT_ADPCM)
199 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
200 ~AST_FORMAT_G723_1)
203 #define DEFAULT_MAXMS 2000 /* Must be faster than 2 seconds by default */
204 #define DEFAULT_FREQ_OK 60 * 1000 /* How often to check for the host to be up */
205 #define DEFAULT_FREQ_NOTOK 10 * 1000 /* How often to check, if the host is down... */
207 /* if a pvt has encryption setup done and is running on the call */
208 #define IAX_CALLENCRYPTED(pvt) \
209 (ast_test_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(pvt, IAX_KEYPOPULATED))
211 #define IAX_DEBUGDIGEST(msg, key) do { \
212 int idx; \
213 char digest[33] = ""; \
215 if (!iaxdebug) \
216 break; \
218 for (idx = 0; idx < 16; idx++) \
219 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
221 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
222 } while(0)
224 static struct io_context *io;
225 static struct sched_context *sched;
227 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
229 static int iaxdebug = 0;
231 static int iaxtrunkdebug = 0;
233 static int test_losspct = 0;
234 #ifdef IAXTESTS
235 static int test_late = 0;
236 static int test_resync = 0;
237 static int test_jit = 0;
238 static int test_jitpct = 0;
239 #endif /* IAXTESTS */
241 static char accountcode[AST_MAX_ACCOUNT_CODE];
242 static char mohinterpret[MAX_MUSICCLASS];
243 static char mohsuggest[MAX_MUSICCLASS];
244 static int amaflags = 0;
245 static int adsi = 0;
246 static int delayreject = 0;
247 static int iax2_encryption = 0;
249 static struct ast_flags globalflags = { 0 };
251 static pthread_t netthreadid = AST_PTHREADT_NULL;
252 static pthread_t schedthreadid = AST_PTHREADT_NULL;
253 AST_MUTEX_DEFINE_STATIC(sched_lock);
254 static ast_cond_t sched_cond;
256 enum iax2_state {
257 IAX_STATE_STARTED = (1 << 0),
258 IAX_STATE_AUTHENTICATED = (1 << 1),
259 IAX_STATE_TBD = (1 << 2),
260 IAX_STATE_UNCHANGED = (1 << 3),
263 struct iax2_context {
264 char context[AST_MAX_CONTEXT];
265 struct iax2_context *next;
268 enum iax2_flags {
269 IAX_HASCALLERID = (1 << 0), /*!< CallerID has been specified */
270 IAX_DELME = (1 << 1), /*!< Needs to be deleted */
271 IAX_TEMPONLY = (1 << 2), /*!< Temporary (realtime) */
272 IAX_TRUNK = (1 << 3), /*!< Treat as a trunk */
273 IAX_NOTRANSFER = (1 << 4), /*!< Don't native bridge */
274 IAX_USEJITTERBUF = (1 << 5), /*!< Use jitter buffer */
275 IAX_DYNAMIC = (1 << 6), /*!< dynamic peer */
276 IAX_SENDANI = (1 << 7), /*!< Send ANI along with CallerID */
277 /* (1 << 8) is currently unused due to the deprecation of an old option. Go ahead, take it! */
278 IAX_ALREADYGONE = (1 << 9), /*!< Already disconnected */
279 IAX_PROVISION = (1 << 10), /*!< This is a provisioning request */
280 IAX_QUELCH = (1 << 11), /*!< Whether or not we quelch audio */
281 IAX_ENCRYPTED = (1 << 12), /*!< Whether we should assume encrypted tx/rx */
282 IAX_KEYPOPULATED = (1 << 13), /*!< Whether we have a key populated */
283 IAX_CODEC_USER_FIRST = (1 << 14), /*!< are we willing to let the other guy choose the codec? */
284 IAX_CODEC_NOPREFS = (1 << 15), /*!< Force old behaviour by turning off prefs */
285 IAX_CODEC_NOCAP = (1 << 16), /*!< only consider requested format and ignore capabilities*/
286 IAX_RTCACHEFRIENDS = (1 << 17), /*!< let realtime stay till your reload */
287 IAX_RTUPDATE = (1 << 18), /*!< Send a realtime update */
288 IAX_RTAUTOCLEAR = (1 << 19), /*!< erase me on expire */
289 IAX_FORCEJITTERBUF = (1 << 20), /*!< Force jitterbuffer, even when bridged to a channel that can take jitter */
290 IAX_RTIGNOREREGEXPIRE = (1 << 21), /*!< When using realtime, ignore registration expiration */
291 IAX_TRUNKTIMESTAMPS = (1 << 22), /*!< Send trunk timestamps */
292 IAX_TRANSFERMEDIA = (1 << 23), /*!< When doing IAX2 transfers, transfer media only */
293 IAX_MAXAUTHREQ = (1 << 24), /*!< Maximum outstanding AUTHREQ restriction is in place */
294 IAX_DELAYPBXSTART = (1 << 25), /*!< Don't start a PBX on the channel until the peer sends us a
295 response, so that we've achieved a three-way handshake with
296 them before sending voice or anything else*/
297 IAX_ALLOWFWDOWNLOAD = (1 << 26), /*!< Allow the FWDOWNL command? */
298 IAX_NOKEYROTATE = (1 << 27), /*!< Disable key rotation with encryption */
301 static int global_rtautoclear = 120;
303 static int reload_config(void);
305 struct iax2_user {
306 AST_DECLARE_STRING_FIELDS(
307 AST_STRING_FIELD(name);
308 AST_STRING_FIELD(secret);
309 AST_STRING_FIELD(dbsecret);
310 AST_STRING_FIELD(accountcode);
311 AST_STRING_FIELD(mohinterpret);
312 AST_STRING_FIELD(mohsuggest);
313 AST_STRING_FIELD(inkeys); /*!< Key(s) this user can use to authenticate to us */
314 AST_STRING_FIELD(language);
315 AST_STRING_FIELD(cid_num);
316 AST_STRING_FIELD(cid_name);
317 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
320 int authmethods;
321 int encmethods;
322 int amaflags;
323 int adsi;
324 unsigned int flags;
325 int capability;
326 int maxauthreq; /*!< Maximum allowed outstanding AUTHREQs */
327 int curauthreq; /*!< Current number of outstanding AUTHREQs */
328 struct ast_codec_pref prefs;
329 struct ast_ha *ha;
330 struct iax2_context *contexts;
331 struct ast_variable *vars;
334 struct iax2_peer {
335 AST_DECLARE_STRING_FIELDS(
336 AST_STRING_FIELD(name);
337 AST_STRING_FIELD(username);
338 AST_STRING_FIELD(secret);
339 AST_STRING_FIELD(dbsecret);
340 AST_STRING_FIELD(outkey); /*!< What key we use to talk to this peer */
342 AST_STRING_FIELD(regexten); /*!< Extension to register (if regcontext is used) */
343 AST_STRING_FIELD(context); /*!< For transfers only */
344 AST_STRING_FIELD(peercontext); /*!< Context to pass to peer */
345 AST_STRING_FIELD(mailbox); /*!< Mailbox */
346 AST_STRING_FIELD(mohinterpret);
347 AST_STRING_FIELD(mohsuggest);
348 AST_STRING_FIELD(inkeys); /*!< Key(s) this peer can use to authenticate to us */
349 /* Suggested caller id if registering */
350 AST_STRING_FIELD(cid_num); /*!< Default context (for transfer really) */
351 AST_STRING_FIELD(cid_name); /*!< Default context (for transfer really) */
352 AST_STRING_FIELD(zonetag); /*!< Time Zone */
353 AST_STRING_FIELD(parkinglot); /*!< Default parkinglot for device */
355 struct ast_codec_pref prefs;
356 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
357 struct sockaddr_in addr;
358 int formats;
359 int sockfd; /*!< Socket to use for transmission */
360 struct in_addr mask;
361 int adsi;
362 unsigned int flags;
364 /* Dynamic Registration fields */
365 struct sockaddr_in defaddr; /*!< Default address if there is one */
366 int authmethods; /*!< Authentication methods (IAX_AUTH_*) */
367 int encmethods; /*!< Encryption methods (IAX_ENCRYPT_*) */
369 int expire; /*!< Schedule entry for expiry */
370 int expiry; /*!< How soon to expire */
371 int capability; /*!< Capability */
373 /* Qualification */
374 int callno; /*!< Call number of POKE request */
375 int pokeexpire; /*!< Scheduled qualification-related task (ie iax2_poke_peer_s or iax2_poke_noanswer) */
376 int lastms; /*!< How long last response took (in ms), or -1 for no response */
377 int maxms; /*!< Max ms we will accept for the host to be up, 0 to not monitor */
379 int pokefreqok; /*!< How often to check if the host is up */
380 int pokefreqnotok; /*!< How often to check when the host has been determined to be down */
381 int historicms; /*!< How long recent average responses took */
382 int smoothing; /*!< Sample over how many units to determine historic ms */
384 struct ast_event_sub *mwi_event_sub;
386 struct ast_ha *ha;
389 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
391 struct iax2_trunk_peer {
392 ast_mutex_t lock;
393 int sockfd;
394 struct sockaddr_in addr;
395 struct timeval txtrunktime; /*!< Transmit trunktime */
396 struct timeval rxtrunktime; /*!< Receive trunktime */
397 struct timeval lasttxtime; /*!< Last transmitted trunktime */
398 struct timeval trunkact; /*!< Last trunk activity */
399 unsigned int lastsent; /*!< Last sent time */
400 /* Trunk data and length */
401 unsigned char *trunkdata;
402 unsigned int trunkdatalen;
403 unsigned int trunkdataalloc;
404 int trunkmaxmtu;
405 int trunkerror;
406 int calls;
407 AST_LIST_ENTRY(iax2_trunk_peer) list;
410 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
412 struct iax_firmware {
413 AST_LIST_ENTRY(iax_firmware) list;
414 int fd;
415 int mmaplen;
416 int dead;
417 struct ast_iax2_firmware_header *fwh;
418 unsigned char *buf;
421 enum iax_reg_state {
422 REG_STATE_UNREGISTERED = 0,
423 REG_STATE_REGSENT,
424 REG_STATE_AUTHSENT,
425 REG_STATE_REGISTERED,
426 REG_STATE_REJECTED,
427 REG_STATE_TIMEOUT,
428 REG_STATE_NOAUTH
431 enum iax_transfer_state {
432 TRANSFER_NONE = 0,
433 TRANSFER_BEGIN,
434 TRANSFER_READY,
435 TRANSFER_RELEASED,
436 TRANSFER_MBEGIN,
437 TRANSFER_MREADY,
438 TRANSFER_MRELEASED
441 struct iax2_registry {
442 struct sockaddr_in addr; /*!< Who we connect to for registration purposes */
443 char username[80];
444 char secret[80]; /*!< Password or key name in []'s */
445 int expire; /*!< Sched ID of expiration */
446 int refresh; /*!< How often to refresh */
447 enum iax_reg_state regstate;
448 int messages; /*!< Message count, low 8 bits = new, high 8 bits = old */
449 int callno; /*!< Associated call number if applicable */
450 struct sockaddr_in us; /*!< Who the server thinks we are */
451 struct ast_dnsmgr_entry *dnsmgr; /*!< DNS refresh manager */
452 AST_LIST_ENTRY(iax2_registry) entry;
455 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
457 /* Don't retry more frequently than every 10 ms, or less frequently than every 5 seconds */
458 #define MIN_RETRY_TIME 100
459 #define MAX_RETRY_TIME 10000
461 #define MAX_JITTER_BUFFER 50
462 #define MIN_JITTER_BUFFER 10
464 #define DEFAULT_TRUNKDATA 640 * 10 /*!< 40ms, uncompressed linear * 10 channels */
466 #define MAX_TIMESTAMP_SKEW 160 /*!< maximum difference between actual and predicted ts for sending */
468 /* If consecutive voice frame timestamps jump by more than this many milliseconds, then jitter buffer will resync */
469 #define TS_GAP_FOR_JB_RESYNC 5000
471 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
472 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
473 static int iaxdynamicthreadcount = 0;
474 static int iaxdynamicthreadnum = 0;
475 static int iaxactivethreadcount = 0;
477 struct iax_rr {
478 int jitter;
479 int losspct;
480 int losscnt;
481 int packets;
482 int delay;
483 int dropped;
484 int ooo;
487 struct iax2_pvt_ref;
489 struct chan_iax2_pvt {
490 /*! Socket to send/receive on for this call */
491 int sockfd;
492 /*! Last received voice format */
493 int voiceformat;
494 /*! Last received video format */
495 int videoformat;
496 /*! Last sent voice format */
497 int svoiceformat;
498 /*! Last sent video format */
499 int svideoformat;
500 /*! What we are capable of sending */
501 int capability;
502 /*! Last received timestamp */
503 unsigned int last;
504 /*! Last sent timestamp - never send the same timestamp twice in a single call */
505 unsigned int lastsent;
506 /*! Timestamp of the last video frame sent */
507 unsigned int lastvsent;
508 /*! Next outgoing timestamp if everything is good */
509 unsigned int nextpred;
510 /*! True if the last voice we transmitted was not silence/CNG */
511 unsigned int notsilenttx:1;
512 /*! Ping time */
513 unsigned int pingtime;
514 /*! Max time for initial response */
515 int maxtime;
516 /*! Peer Address */
517 struct sockaddr_in addr;
518 /*! Actual used codec preferences */
519 struct ast_codec_pref prefs;
520 /*! Requested codec preferences */
521 struct ast_codec_pref rprefs;
522 /*! Our call number */
523 unsigned short callno;
524 /*! Peer callno */
525 unsigned short peercallno;
526 /*! Negotiated format, this is only used to remember what format was
527 chosen for an unauthenticated call so that the channel can get
528 created later using the right format */
529 int chosenformat;
530 /*! Peer selected format */
531 int peerformat;
532 /*! Peer capability */
533 int peercapability;
534 /*! timeval that we base our transmission on */
535 struct timeval offset;
536 /*! timeval that we base our delivery on */
537 struct timeval rxcore;
538 /*! The jitterbuffer */
539 jitterbuf *jb;
540 /*! active jb read scheduler id */
541 int jbid;
542 /*! LAG */
543 int lag;
544 /*! Error, as discovered by the manager */
545 int error;
546 /*! Owner if we have one */
547 struct ast_channel *owner;
548 /*! What's our state? */
549 struct ast_flags state;
550 /*! Expiry (optional) */
551 int expiry;
552 /*! Next outgoing sequence number */
553 unsigned char oseqno;
554 /*! Next sequence number they have not yet acknowledged */
555 unsigned char rseqno;
556 /*! Next incoming sequence number */
557 unsigned char iseqno;
558 /*! Last incoming sequence number we have acknowledged */
559 unsigned char aseqno;
561 AST_DECLARE_STRING_FIELDS(
562 /*! Peer name */
563 AST_STRING_FIELD(peer);
564 /*! Default Context */
565 AST_STRING_FIELD(context);
566 /*! Caller ID if available */
567 AST_STRING_FIELD(cid_num);
568 AST_STRING_FIELD(cid_name);
569 /*! Hidden Caller ID (i.e. ANI) if appropriate */
570 AST_STRING_FIELD(ani);
571 /*! DNID */
572 AST_STRING_FIELD(dnid);
573 /*! RDNIS */
574 AST_STRING_FIELD(rdnis);
575 /*! Requested Extension */
576 AST_STRING_FIELD(exten);
577 /*! Expected Username */
578 AST_STRING_FIELD(username);
579 /*! Expected Secret */
580 AST_STRING_FIELD(secret);
581 /*! MD5 challenge */
582 AST_STRING_FIELD(challenge);
583 /*! Public keys permitted keys for incoming authentication */
584 AST_STRING_FIELD(inkeys);
585 /*! Private key for outgoing authentication */
586 AST_STRING_FIELD(outkey);
587 /*! Preferred language */
588 AST_STRING_FIELD(language);
589 /*! Hostname/peername for naming purposes */
590 AST_STRING_FIELD(host);
592 AST_STRING_FIELD(dproot);
593 AST_STRING_FIELD(accountcode);
594 AST_STRING_FIELD(mohinterpret);
595 AST_STRING_FIELD(mohsuggest);
596 /*! received OSP token */
597 AST_STRING_FIELD(osptoken);
598 /*! Default parkinglot */
599 AST_STRING_FIELD(parkinglot);
602 /*! permitted authentication methods */
603 int authmethods;
604 /*! permitted encryption methods */
605 int encmethods;
606 /*! Encryption AES-128 Key */
607 ast_aes_encrypt_key ecx;
608 /*! Decryption AES-128 Key */
609 ast_aes_decrypt_key dcx;
610 /*! scheduler id associated with iax_key_rotate
611 * for encrypted calls*/
612 int keyrotateid;
613 /*! 32 bytes of semi-random data */
614 unsigned char semirand[32];
615 /*! Associated registry */
616 struct iax2_registry *reg;
617 /*! Associated peer for poking */
618 struct iax2_peer *peerpoke;
619 /*! IAX_ flags */
620 unsigned int flags;
621 int adsi;
623 /*! Transferring status */
624 enum iax_transfer_state transferring;
625 /*! Transfer identifier */
626 int transferid;
627 /*! Who we are IAX transferring to */
628 struct sockaddr_in transfer;
629 /*! What's the new call number for the transfer */
630 unsigned short transfercallno;
631 /*! Transfer encrypt AES-128 Key */
632 ast_aes_encrypt_key tdcx;
634 /*! If transfer has been attempted */
635 unsigned int triedtransfer:1;
636 /*! Whether media is released */
637 unsigned int mediareleased:1;
638 /*! If media released, the peer to send media to */
639 struct sockaddr_in media;
641 /*! Status of knowledge of peer ADSI capability */
642 int peeradsicpe;
644 /*! Who we are bridged to */
645 unsigned short bridgecallno;
647 int pingid; /*!< Transmit PING request */
648 int lagid; /*!< Retransmit lag request */
649 int autoid; /*!< Auto hangup for Dialplan requestor */
650 int authid; /*!< Authentication rejection ID */
651 int authfail; /*!< Reason to report failure */
652 int initid; /*!< Initial peer auto-congest ID (based on qualified peers) */
653 int calling_ton;
654 int calling_tns;
655 int calling_pres;
656 int amaflags;
657 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
658 struct ast_variable *vars;
659 /*! last received remote rr */
660 struct iax_rr remote_rr;
661 /*! Current base time: (just for stats) */
662 int min;
663 /*! Dropped frame count: (just for stats) */
664 int frames_dropped;
665 /*! received frame count: (just for stats) */
666 int frames_received;
670 * \brief a list of frames that may need to be retransmitted
672 * \note The contents of this list do not need to be explicitly destroyed
673 * on module unload. This is because all active calls are destroyed, and
674 * all frames in this queue will get destroyed as a part of that process.
676 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
679 * This module will get much higher performance when doing a lot of
680 * user and peer lookups if the number of buckets is increased from 1.
681 * However, to maintain old behavior for Asterisk 1.4, these are set to
682 * 1 by default. When using multiple buckets, search order through these
683 * containers is considered random, so you will not be able to depend on
684 * the order the entires are specified in iax.conf for matching order. */
685 #ifdef LOW_MEMORY
686 #define MAX_PEER_BUCKETS 17
687 #else
688 #define MAX_PEER_BUCKETS 563
689 #endif
690 static struct ao2_container *peers;
692 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
693 static struct ao2_container *users;
695 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
697 enum {
698 /*! Extension exists */
699 CACHE_FLAG_EXISTS = (1 << 0),
700 /*! Extension is nonexistent */
701 CACHE_FLAG_NONEXISTENT = (1 << 1),
702 /*! Extension can exist */
703 CACHE_FLAG_CANEXIST = (1 << 2),
704 /*! Waiting to hear back response */
705 CACHE_FLAG_PENDING = (1 << 3),
706 /*! Timed out */
707 CACHE_FLAG_TIMEOUT = (1 << 4),
708 /*! Request transmitted */
709 CACHE_FLAG_TRANSMITTED = (1 << 5),
710 /*! Timeout */
711 CACHE_FLAG_UNKNOWN = (1 << 6),
712 /*! Matchmore */
713 CACHE_FLAG_MATCHMORE = (1 << 7),
716 struct iax2_dpcache {
717 char peercontext[AST_MAX_CONTEXT];
718 char exten[AST_MAX_EXTENSION];
719 struct timeval orig;
720 struct timeval expiry;
721 int flags;
722 unsigned short callno;
723 int waiters[256];
724 AST_LIST_ENTRY(iax2_dpcache) cache_list;
725 AST_LIST_ENTRY(iax2_dpcache) peer_list;
728 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
730 static void reg_source_db(struct iax2_peer *p);
731 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
733 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
734 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state);
735 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
737 enum iax2_thread_iostate {
738 IAX_IOSTATE_IDLE,
739 IAX_IOSTATE_READY,
740 IAX_IOSTATE_PROCESSING,
741 IAX_IOSTATE_SCHEDREADY,
744 enum iax2_thread_type {
745 IAX_THREAD_TYPE_POOL,
746 IAX_THREAD_TYPE_DYNAMIC,
749 struct iax2_pkt_buf {
750 AST_LIST_ENTRY(iax2_pkt_buf) entry;
751 size_t len;
752 unsigned char buf[1];
755 struct iax2_thread {
756 AST_LIST_ENTRY(iax2_thread) list;
757 enum iax2_thread_type type;
758 enum iax2_thread_iostate iostate;
759 #ifdef SCHED_MULTITHREADED
760 void (*schedfunc)(const void *);
761 const void *scheddata;
762 #endif
763 #ifdef DEBUG_SCHED_MULTITHREAD
764 char curfunc[80];
765 #endif
766 int actions;
767 pthread_t threadid;
768 int threadnum;
769 struct sockaddr_in iosin;
770 unsigned char readbuf[4096];
771 unsigned char *buf;
772 ssize_t buf_len;
773 size_t buf_size;
774 int iofd;
775 time_t checktime;
776 ast_mutex_t lock;
777 ast_cond_t cond;
778 unsigned int ready_for_signal:1;
779 /*! if this thread is processing a full frame,
780 some information about that frame will be stored
781 here, so we can avoid dispatching any more full
782 frames for that callno to other threads */
783 struct {
784 unsigned short callno;
785 struct sockaddr_in sin;
786 unsigned char type;
787 unsigned char csub;
788 } ffinfo;
789 /*! Queued up full frames for processing. If more full frames arrive for
790 * a call which this thread is already processing a full frame for, they
791 * are queued up here. */
792 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
795 /* Thread lists */
796 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
797 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
798 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
800 static void *iax2_process_thread(void *data);
802 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
804 ast_mutex_lock(lock);
805 ast_cond_signal(cond);
806 ast_mutex_unlock(lock);
810 * \brief an array of iax2 pvt structures
812 * The container for active chan_iax2_pvt structures is implemented as an
813 * array for extremely quick direct access to the correct pvt structure
814 * based on the local call number. The local call number is used as the
815 * index into the array where the associated pvt structure is stored.
817 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
820 * \brief Another container of iax2_pvt structures
822 * Active IAX2 pvt structs are also stored in this container, if they are a part
823 * of an active call where we know the remote side's call number. The reason
824 * for this is that incoming media frames do not contain our call number. So,
825 * instead of having to iterate the entire iaxs array, we use this container to
826 * look up calls where the remote side is using a given call number.
828 static struct ao2_container *iax_peercallno_pvts;
831 * \brief chan_iax2_pvt structure locks
833 * These locks are used when accessing a pvt structure in the iaxs array.
834 * The index used here is the same as used in the iaxs array. It is the
835 * local call number for the associated pvt struct.
837 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
840 * \brief The last time a call number was used
842 * It is important to know the last time that a call number was used locally so
843 * that it is not used again too soon. The reason for this is the same as the
844 * reason that the TCP protocol state machine requires a "TIME WAIT" state.
846 * For example, say that a call is up. Then, the remote side sends a HANGUP,
847 * which we respond to with an ACK. However, there is no way to know whether
848 * the ACK made it there successfully. If it were to get lost, the remote
849 * side may retransmit the HANGUP. If in the meantime, this call number has
850 * been reused locally, given the right set of circumstances, this retransmitted
851 * HANGUP could potentially improperly hang up the new session. So, to avoid
852 * this potential issue, we must wait a specified timeout period before reusing
853 * a local call number.
855 * The specified time that we must wait before reusing a local call number is
856 * defined as MIN_REUSE_TIME, with a default of 60 seconds.
858 static struct timeval lastused[ARRAY_LEN(iaxs)];
860 /* Flag to use with trunk calls, keeping these calls high up. It halves our effective use
861 but keeps the division between trunked and non-trunked better. */
862 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
864 /* Debug routines... */
865 static struct sockaddr_in debugaddr;
867 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
869 if (iaxdebug ||
870 (sin && debugaddr.sin_addr.s_addr &&
871 (!ntohs(debugaddr.sin_port) ||
872 debugaddr.sin_port == sin->sin_port) &&
873 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
874 if (iaxdebug) {
875 iax_showframe(f, fhi, rx, sin, datalen);
876 } else {
877 iaxdebug = 1;
878 iax_showframe(f, fhi, rx, sin, datalen);
879 iaxdebug = 0;
884 static void iax_debug_output(const char *data)
886 if (iaxdebug)
887 ast_verbose("%s", data);
890 static void iax_error_output(const char *data)
892 ast_log(LOG_WARNING, "%s", data);
895 static void __attribute__((format (printf, 1, 2))) jb_error_output(const char *fmt, ...)
897 va_list args;
898 char buf[1024];
900 va_start(args, fmt);
901 vsnprintf(buf, sizeof(buf), fmt, args);
902 va_end(args);
904 ast_log(LOG_ERROR, "%s", buf);
907 static void __attribute__((format (printf, 1, 2))) jb_warning_output(const char *fmt, ...)
909 va_list args;
910 char buf[1024];
912 va_start(args, fmt);
913 vsnprintf(buf, sizeof(buf), fmt, args);
914 va_end(args);
916 ast_log(LOG_WARNING, "%s", buf);
919 static void __attribute__((format (printf, 1, 2))) jb_debug_output(const char *fmt, ...)
921 va_list args;
922 char buf[1024];
924 va_start(args, fmt);
925 vsnprintf(buf, sizeof(buf), fmt, args);
926 va_end(args);
928 ast_verbose("%s", buf);
931 static int maxtrunkcall = TRUNK_CALL_START;
932 static int maxnontrunkcall = 1;
934 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
935 static int expire_registry(const void *data);
936 static int iax2_answer(struct ast_channel *c);
937 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
938 static int iax2_devicestate(void *data);
939 static int iax2_digit_begin(struct ast_channel *c, char digit);
940 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
941 static int iax2_do_register(struct iax2_registry *reg);
942 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
943 static int iax2_hangup(struct ast_channel *c);
944 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
945 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
946 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
947 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final, int media);
948 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
949 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
950 static int iax2_sendtext(struct ast_channel *c, const char *text);
951 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
952 static int iax2_transfer(struct ast_channel *c, const char *dest);
953 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
954 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
955 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
956 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
957 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
958 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
959 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
960 static int send_command_media(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
961 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
962 static struct ast_frame *iax2_read(struct ast_channel *c);
963 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
964 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
965 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
966 static void prune_peers(void);
967 static void *iax2_dup_variable_datastore(void *);
968 static void iax2_free_variable_datastore(void *);
970 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
971 static int acf_channel_write(struct ast_channel *chan, const char *function, char *data, const char *value);
973 static const struct ast_channel_tech iax2_tech = {
974 .type = "IAX2",
975 .description = tdesc,
976 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
977 .properties = AST_CHAN_TP_WANTSJITTER,
978 .requester = iax2_request,
979 .devicestate = iax2_devicestate,
980 .send_digit_begin = iax2_digit_begin,
981 .send_digit_end = iax2_digit_end,
982 .send_text = iax2_sendtext,
983 .send_image = iax2_sendimage,
984 .send_html = iax2_sendhtml,
985 .call = iax2_call,
986 .hangup = iax2_hangup,
987 .answer = iax2_answer,
988 .read = iax2_read,
989 .write = iax2_write,
990 .write_video = iax2_write,
991 .indicate = iax2_indicate,
992 .setoption = iax2_setoption,
993 .bridge = iax2_bridge,
994 .transfer = iax2_transfer,
995 .fixup = iax2_fixup,
996 .func_channel_read = acf_channel_read,
997 .func_channel_write = acf_channel_write,
1000 static void mwi_event_cb(const struct ast_event *event, void *userdata)
1002 /* The MWI subscriptions exist just so the core knows we care about those
1003 * mailboxes. However, we just grab the events out of the cache when it
1004 * is time to send MWI, since it is only sent with a REGACK. */
1007 /*! \brief Send manager event at call setup to link between Asterisk channel name
1008 and IAX2 call identifiers */
1009 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
1011 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
1012 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
1013 pvt->owner ? pvt->owner->name : "",
1014 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
1018 static struct ast_datastore_info iax2_variable_datastore_info = {
1019 .type = "IAX2_VARIABLE",
1020 .duplicate = iax2_dup_variable_datastore,
1021 .destroy = iax2_free_variable_datastore,
1024 static void *iax2_dup_variable_datastore(void *old)
1026 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
1027 struct ast_var_t *oldvar, *newvar;
1029 newlist = ast_calloc(sizeof(*newlist), 1);
1030 if (!newlist) {
1031 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
1032 return NULL;
1035 AST_LIST_HEAD_INIT(newlist);
1036 AST_LIST_LOCK(oldlist);
1037 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
1038 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
1039 if (newvar)
1040 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
1041 else
1042 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
1044 AST_LIST_UNLOCK(oldlist);
1045 return newlist;
1048 static void iax2_free_variable_datastore(void *old)
1050 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
1051 struct ast_var_t *oldvar;
1053 AST_LIST_LOCK(oldlist);
1054 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
1055 ast_free(oldvar);
1057 AST_LIST_UNLOCK(oldlist);
1058 AST_LIST_HEAD_DESTROY(oldlist);
1059 ast_free(oldlist);
1063 /* WARNING: insert_idle_thread should only ever be called within the
1064 * context of an iax2_process_thread() thread.
1066 static void insert_idle_thread(struct iax2_thread *thread)
1068 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
1069 AST_LIST_LOCK(&dynamic_list);
1070 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
1071 AST_LIST_UNLOCK(&dynamic_list);
1072 } else {
1073 AST_LIST_LOCK(&idle_list);
1074 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
1075 AST_LIST_UNLOCK(&idle_list);
1078 return;
1081 static struct iax2_thread *find_idle_thread(void)
1083 struct iax2_thread *thread = NULL;
1085 /* Pop the head of the idle list off */
1086 AST_LIST_LOCK(&idle_list);
1087 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
1088 AST_LIST_UNLOCK(&idle_list);
1090 /* If we popped a thread off the idle list, just return it */
1091 if (thread) {
1092 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1093 return thread;
1096 /* Pop the head of the dynamic list off */
1097 AST_LIST_LOCK(&dynamic_list);
1098 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
1099 AST_LIST_UNLOCK(&dynamic_list);
1101 /* If we popped a thread off the dynamic list, just return it */
1102 if (thread) {
1103 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1104 return thread;
1107 /* If we can't create a new dynamic thread for any reason, return no thread at all */
1108 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
1109 return NULL;
1111 /* Set default values */
1112 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
1113 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
1114 thread->type = IAX_THREAD_TYPE_DYNAMIC;
1116 /* Initialize lock and condition */
1117 ast_mutex_init(&thread->lock);
1118 ast_cond_init(&thread->cond, NULL);
1120 /* Create thread and send it on it's way */
1121 if (ast_pthread_create_detached_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
1122 ast_cond_destroy(&thread->cond);
1123 ast_mutex_destroy(&thread->lock);
1124 ast_free(thread);
1125 return NULL;
1128 /* this thread is not processing a full frame (since it is idle),
1129 so ensure that the field for the full frame call number is empty */
1130 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
1132 /* Wait for the thread to be ready before returning it to the caller */
1133 while (!thread->ready_for_signal)
1134 usleep(1);
1136 return thread;
1139 #ifdef SCHED_MULTITHREADED
1140 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
1142 struct iax2_thread *thread = NULL;
1143 static time_t lasterror;
1144 static time_t t;
1146 thread = find_idle_thread();
1148 if (thread != NULL) {
1149 thread->schedfunc = func;
1150 thread->scheddata = data;
1151 thread->iostate = IAX_IOSTATE_SCHEDREADY;
1152 #ifdef DEBUG_SCHED_MULTITHREAD
1153 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
1154 #endif
1155 signal_condition(&thread->lock, &thread->cond);
1156 return 0;
1158 time(&t);
1159 if (t != lasterror)
1160 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
1161 lasterror = t;
1163 return -1;
1165 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
1166 #endif
1168 static int iax2_sched_replace(int id, struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1170 AST_SCHED_REPLACE(id, con, when, callback, data);
1171 signal_condition(&sched_lock, &sched_cond);
1173 return id;
1176 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
1178 int res;
1180 res = ast_sched_add(con, when, callback, data);
1181 signal_condition(&sched_lock, &sched_cond);
1183 return res;
1186 static int send_ping(const void *data);
1188 static void __send_ping(const void *data)
1190 int callno = (long) data;
1192 ast_mutex_lock(&iaxsl[callno]);
1194 if (iaxs[callno]) {
1195 if (iaxs[callno]->peercallno) {
1196 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
1197 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
1198 } else {
1199 /* I am the schedule, so I'm allowed to do this */
1200 iaxs[callno]->pingid = -1;
1202 } else if (option_debug > 0) {
1203 ast_log(LOG_DEBUG, "I was supposed to send a PING with callno %d, but no such call exists (and I cannot remove pingid, either).\n", callno);
1206 ast_mutex_unlock(&iaxsl[callno]);
1209 static int send_ping(const void *data)
1211 #ifdef SCHED_MULTITHREADED
1212 if (schedule_action(__send_ping, data))
1213 #endif
1214 __send_ping(data);
1216 return 0;
1219 static int get_encrypt_methods(const char *s)
1221 int e;
1222 if (!strcasecmp(s, "aes128"))
1223 e = IAX_ENCRYPT_AES128;
1224 else if (ast_true(s))
1225 e = IAX_ENCRYPT_AES128;
1226 else
1227 e = 0;
1228 return e;
1231 static int send_lagrq(const void *data);
1233 static void __send_lagrq(const void *data)
1235 int callno = (long) data;
1237 ast_mutex_lock(&iaxsl[callno]);
1239 if (iaxs[callno]) {
1240 if (iaxs[callno]->peercallno) {
1241 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
1242 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
1243 } else {
1244 /* I am the schedule, so I'm allowed to do this */
1245 iaxs[callno]->lagid = -1;
1247 } else {
1248 ast_log(LOG_WARNING, "I was supposed to send a LAGRQ with callno %d, but no such call exists (and I cannot remove lagid, either).\n", callno);
1251 ast_mutex_unlock(&iaxsl[callno]);
1254 static int send_lagrq(const void *data)
1256 #ifdef SCHED_MULTITHREADED
1257 if (schedule_action(__send_lagrq, data))
1258 #endif
1259 __send_lagrq(data);
1261 return 0;
1264 static unsigned char compress_subclass(int subclass)
1266 int x;
1267 int power=-1;
1268 /* If it's 128 or smaller, just return it */
1269 if (subclass < IAX_FLAG_SC_LOG)
1270 return subclass;
1271 /* Otherwise find its power */
1272 for (x = 0; x < IAX_MAX_SHIFT; x++) {
1273 if (subclass & (1 << x)) {
1274 if (power > -1) {
1275 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
1276 return 0;
1277 } else
1278 power = x;
1281 return power | IAX_FLAG_SC_LOG;
1284 static int uncompress_subclass(unsigned char csub)
1286 /* If the SC_LOG flag is set, return 2^csub otherwise csub */
1287 if (csub & IAX_FLAG_SC_LOG) {
1288 /* special case for 'compressed' -1 */
1289 if (csub == 0xff)
1290 return -1;
1291 else
1292 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
1294 else
1295 return csub;
1299 * \note The only member of the peer passed here guaranteed to be set is the name field
1301 static int peer_hash_cb(const void *obj, const int flags)
1303 const struct iax2_peer *peer = obj;
1305 return ast_str_hash(peer->name);
1309 * \note The only member of the peer passed here guaranteed to be set is the name field
1311 static int peer_cmp_cb(void *obj, void *arg, int flags)
1313 struct iax2_peer *peer = obj, *peer2 = arg;
1315 return !strcmp(peer->name, peer2->name) ? CMP_MATCH : 0;
1319 * \note The only member of the user passed here guaranteed to be set is the name field
1321 static int user_hash_cb(const void *obj, const int flags)
1323 const struct iax2_user *user = obj;
1325 return ast_str_hash(user->name);
1329 * \note The only member of the user passed here guaranteed to be set is the name field
1331 static int user_cmp_cb(void *obj, void *arg, int flags)
1333 struct iax2_user *user = obj, *user2 = arg;
1335 return !strcmp(user->name, user2->name) ? CMP_MATCH : 0;
1339 * \note This funtion calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
1340 * so do not call it with a pvt lock held.
1342 static struct iax2_peer *find_peer(const char *name, int realtime)
1344 struct iax2_peer *peer = NULL;
1345 struct iax2_peer tmp_peer = {
1346 .name = name,
1349 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
1351 /* Now go for realtime if applicable */
1352 if(!peer && realtime)
1353 peer = realtime_peer(name, NULL);
1355 return peer;
1358 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
1360 ao2_ref(peer, +1);
1361 return peer;
1364 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
1366 ao2_ref(peer, -1);
1367 return NULL;
1370 static inline struct iax2_user *user_ref(struct iax2_user *user)
1372 ao2_ref(user, +1);
1373 return user;
1376 static inline struct iax2_user *user_unref(struct iax2_user *user)
1378 ao2_ref(user, -1);
1379 return NULL;
1382 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
1384 struct iax2_peer *peer = NULL;
1385 int res = 0;
1386 struct ao2_iterator i;
1388 i = ao2_iterator_init(peers, 0);
1389 while ((peer = ao2_iterator_next(&i))) {
1390 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
1391 (peer->addr.sin_port == sin.sin_port)) {
1392 ast_copy_string(host, peer->name, len);
1393 peer_unref(peer);
1394 res = 1;
1395 break;
1397 peer_unref(peer);
1400 if (!peer) {
1401 peer = realtime_peer(NULL, &sin);
1402 if (peer) {
1403 ast_copy_string(host, peer->name, len);
1404 peer_unref(peer);
1405 res = 1;
1409 return res;
1412 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
1414 /* Decrement AUTHREQ count if needed */
1415 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
1416 struct iax2_user *user;
1417 struct iax2_user tmp_user = {
1418 .name = pvt->username,
1421 user = ao2_find(users, &tmp_user, OBJ_POINTER);
1422 if (user) {
1423 ast_atomic_fetchadd_int(&user->curauthreq, -1);
1424 user_unref(user);
1427 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
1429 /* No more pings or lagrq's */
1430 AST_SCHED_DEL(sched, pvt->pingid);
1431 AST_SCHED_DEL(sched, pvt->lagid);
1432 AST_SCHED_DEL(sched, pvt->autoid);
1433 AST_SCHED_DEL(sched, pvt->authid);
1434 AST_SCHED_DEL(sched, pvt->initid);
1435 AST_SCHED_DEL(sched, pvt->jbid);
1436 AST_SCHED_DEL(sched, pvt->keyrotateid);
1439 static void iax2_frame_free(struct iax_frame *fr)
1441 AST_SCHED_DEL(sched, fr->retrans);
1442 iax_frame_free(fr);
1445 static void pvt_destructor(void *obj)
1447 struct chan_iax2_pvt *pvt = obj;
1448 struct iax_frame *cur = NULL;
1450 iax2_destroy_helper(pvt);
1452 /* Already gone */
1453 ast_set_flag(pvt, IAX_ALREADYGONE);
1455 AST_LIST_LOCK(&frame_queue);
1456 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
1457 /* Cancel any pending transmissions */
1458 if (cur->callno == pvt->callno) {
1459 cur->retries = -1;
1462 AST_LIST_UNLOCK(&frame_queue);
1464 if (pvt->reg) {
1465 pvt->reg->callno = 0;
1468 if (!pvt->owner) {
1469 jb_frame frame;
1470 if (pvt->vars) {
1471 ast_variables_destroy(pvt->vars);
1472 pvt->vars = NULL;
1475 while (jb_getall(pvt->jb, &frame) == JB_OK) {
1476 iax2_frame_free(frame.data);
1479 jb_destroy(pvt->jb);
1480 ast_string_field_free_memory(pvt);
1484 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
1486 struct chan_iax2_pvt *tmp;
1487 jb_conf jbconf;
1489 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
1490 return NULL;
1493 if (ast_string_field_init(tmp, 32)) {
1494 ao2_ref(tmp, -1);
1495 tmp = NULL;
1496 return NULL;
1499 tmp->prefs = prefs;
1500 tmp->pingid = -1;
1501 tmp->lagid = -1;
1502 tmp->autoid = -1;
1503 tmp->authid = -1;
1504 tmp->initid = -1;
1505 tmp->keyrotateid = -1;
1507 ast_string_field_set(tmp,exten, "s");
1508 ast_string_field_set(tmp,host, host);
1510 tmp->jb = jb_new();
1511 tmp->jbid = -1;
1512 jbconf.max_jitterbuf = maxjitterbuffer;
1513 jbconf.resync_threshold = resyncthreshold;
1514 jbconf.max_contig_interp = maxjitterinterps;
1515 jbconf.target_extra = jittertargetextra;
1516 jb_setconf(tmp->jb,&jbconf);
1518 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
1520 return tmp;
1523 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
1525 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
1526 if (new) {
1527 size_t afdatalen = new->afdatalen;
1528 memcpy(new, fr, sizeof(*new));
1529 iax_frame_wrap(new, &fr->af);
1530 new->afdatalen = afdatalen;
1531 new->data = NULL;
1532 new->datalen = 0;
1533 new->direction = DIRECTION_INGRESS;
1534 new->retrans = -1;
1536 return new;
1539 #define NEW_PREVENT 0
1540 #define NEW_ALLOW 1
1541 #define NEW_FORCE 2
1543 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
1545 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1546 (cur->addr.sin_port == sin->sin_port)) {
1547 /* This is the main host */
1548 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
1549 (check_dcallno ? dcallno == cur->callno : 1) ) {
1550 /* That's us. Be sure we keep track of the peer call number */
1551 return 1;
1554 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
1555 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
1556 /* We're transferring */
1557 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_NONE && cur->transfercallno == callno))
1558 return 1;
1560 return 0;
1563 static void update_max_trunk(void)
1565 int max = TRUNK_CALL_START;
1566 int x;
1568 /* XXX Prolly don't need locks here XXX */
1569 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1570 if (iaxs[x]) {
1571 max = x + 1;
1575 maxtrunkcall = max;
1576 if (iaxdebug)
1577 ast_debug(1, "New max trunk callno is %d\n", max);
1580 static void update_max_nontrunk(void)
1582 int max = 1;
1583 int x;
1584 /* XXX Prolly don't need locks here XXX */
1585 for (x=1;x<TRUNK_CALL_START - 1; x++) {
1586 if (iaxs[x])
1587 max = x + 1;
1589 maxnontrunkcall = max;
1590 if (iaxdebug)
1591 ast_debug(1, "New max nontrunk callno is %d\n", max);
1594 static int make_trunk(unsigned short callno, int locked)
1596 int x;
1597 int res= 0;
1598 struct timeval now = ast_tvnow();
1599 if (iaxs[callno]->oseqno) {
1600 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
1601 return -1;
1603 if (callno & TRUNK_CALL_START) {
1604 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
1605 return -1;
1607 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
1608 ast_mutex_lock(&iaxsl[x]);
1609 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1611 * \note We delete these before switching the slot, because if
1612 * they fire in the meantime, they will generate a warning.
1614 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
1615 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
1616 iaxs[x] = iaxs[callno];
1617 iaxs[x]->callno = x;
1618 iaxs[callno] = NULL;
1619 /* Update the two timers that should have been started */
1620 iaxs[x]->pingid = iax2_sched_add(sched,
1621 ping_time * 1000, send_ping, (void *)(long)x);
1622 iaxs[x]->lagid = iax2_sched_add(sched,
1623 lagrq_time * 1000, send_lagrq, (void *)(long)x);
1624 if (locked)
1625 ast_mutex_unlock(&iaxsl[callno]);
1626 res = x;
1627 if (!locked)
1628 ast_mutex_unlock(&iaxsl[x]);
1629 break;
1631 ast_mutex_unlock(&iaxsl[x]);
1633 if (x >= ARRAY_LEN(iaxs) - 1) {
1634 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
1635 return -1;
1637 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
1638 /* We move this call from a non-trunked to a trunked call */
1639 update_max_trunk();
1640 update_max_nontrunk();
1641 return res;
1644 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
1646 if (!pvt->peercallno) {
1647 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1648 return;
1651 ao2_link(iax_peercallno_pvts, pvt);
1654 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
1656 if (!pvt->peercallno) {
1657 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
1658 return;
1661 ao2_unlink(iax_peercallno_pvts, pvt);
1665 * \note Calling this function while holding another pvt lock can cause a deadlock.
1667 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
1669 int res = 0;
1670 int x;
1671 struct timeval now;
1672 char host[80];
1674 if (new <= NEW_ALLOW) {
1675 if (callno) {
1676 struct chan_iax2_pvt *pvt;
1677 struct chan_iax2_pvt tmp_pvt = {
1678 .callno = dcallno,
1679 .peercallno = callno,
1680 /* hack!! */
1681 .frames_received = check_dcallno,
1684 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
1686 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
1687 if (return_locked) {
1688 ast_mutex_lock(&iaxsl[pvt->callno]);
1690 res = pvt->callno;
1691 ao2_ref(pvt, -1);
1692 pvt = NULL;
1693 return res;
1697 /* This will occur on the first response to a message that we initiated,
1698 * such as a PING. */
1699 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
1700 iaxs[dcallno]->peercallno = callno;
1701 res = dcallno;
1702 store_by_peercallno(iaxs[dcallno]);
1703 return res;
1706 #ifdef IAX_OLD_FIND
1707 /* If we get here, we SHOULD NOT find a call structure for this
1708 callno; if we do, it means that there is a call structure that
1709 has a peer callno but did NOT get entered into the hash table,
1710 which is bad.
1712 If we find a call structure using this old, slow method, output a log
1713 message so we'll know about it. After a few months of leaving this in
1714 place, if we don't hear about people seeing these messages, we can
1715 remove this code for good.
1718 for (x = 1; !res && x < maxnontrunkcall; x++) {
1719 ast_mutex_lock(&iaxsl[x]);
1720 if (iaxs[x]) {
1721 /* Look for an exact match */
1722 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1723 res = x;
1726 if (!res || !return_locked)
1727 ast_mutex_unlock(&iaxsl[x]);
1729 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
1730 ast_mutex_lock(&iaxsl[x]);
1731 if (iaxs[x]) {
1732 /* Look for an exact match */
1733 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
1734 res = x;
1737 if (!res || !return_locked)
1738 ast_mutex_unlock(&iaxsl[x]);
1740 #endif
1742 if (!res && (new >= NEW_ALLOW)) {
1743 int start, found = 0;
1745 /* It may seem odd that we look through the peer list for a name for
1746 * this *incoming* call. Well, it is weird. However, users don't
1747 * have an IP address/port number that we can match against. So,
1748 * this is just checking for a peer that has that IP/port and
1749 * assuming that we have a user of the same name. This isn't always
1750 * correct, but it will be changed if needed after authentication. */
1751 if (!iax2_getpeername(*sin, host, sizeof(host)))
1752 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
1754 now = ast_tvnow();
1755 start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
1756 for (x = start; 1; x++) {
1757 if (x == TRUNK_CALL_START) {
1758 x = 1;
1759 continue;
1762 /* Find first unused call number that hasn't been used in a while */
1763 ast_mutex_lock(&iaxsl[x]);
1764 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
1765 found = 1;
1766 break;
1768 ast_mutex_unlock(&iaxsl[x]);
1770 if (x == start - 1) {
1771 break;
1774 /* We've still got lock held if we found a spot */
1775 if (x == start - 1 && !found) {
1776 ast_log(LOG_WARNING, "No more space\n");
1777 return 0;
1779 iaxs[x] = new_iax(sin, host);
1780 update_max_nontrunk();
1781 if (iaxs[x]) {
1782 if (iaxdebug)
1783 ast_debug(1, "Creating new call structure %d\n", x);
1784 iaxs[x]->sockfd = sockfd;
1785 iaxs[x]->addr.sin_port = sin->sin_port;
1786 iaxs[x]->addr.sin_family = sin->sin_family;
1787 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
1788 iaxs[x]->peercallno = callno;
1789 iaxs[x]->callno = x;
1790 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
1791 iaxs[x]->expiry = min_reg_expire;
1792 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
1793 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
1794 iaxs[x]->amaflags = amaflags;
1795 ast_copy_flags(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_NOKEYROTATE);
1797 ast_string_field_set(iaxs[x], accountcode, accountcode);
1798 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
1799 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
1800 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
1802 if (iaxs[x]->peercallno) {
1803 store_by_peercallno(iaxs[x]);
1805 } else {
1806 ast_log(LOG_WARNING, "Out of resources\n");
1807 ast_mutex_unlock(&iaxsl[x]);
1808 return 0;
1810 if (!return_locked)
1811 ast_mutex_unlock(&iaxsl[x]);
1812 res = x;
1814 return res;
1817 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1819 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
1822 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
1824 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
1828 * \brief Queue a frame to a call's owning asterisk channel
1830 * \pre This function assumes that iaxsl[callno] is locked when called.
1832 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1833 * was valid before calling it, it may no longer be valid after calling it.
1834 * This function may unlock and lock the mutex associated with this callno,
1835 * meaning that another thread may grab it and destroy the call.
1837 static int iax2_queue_frame(int callno, struct ast_frame *f)
1839 for (;;) {
1840 if (iaxs[callno] && iaxs[callno]->owner) {
1841 if (ast_channel_trylock(iaxs[callno]->owner)) {
1842 /* Avoid deadlock by pausing and trying again */
1843 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1844 } else {
1845 ast_queue_frame(iaxs[callno]->owner, f);
1846 ast_channel_unlock(iaxs[callno]->owner);
1847 break;
1849 } else
1850 break;
1852 return 0;
1856 * \brief Queue a hangup frame on the ast_channel owner
1858 * This function queues a hangup frame on the owner of the IAX2 pvt struct that
1859 * is active for the given call number.
1861 * \pre Assumes lock for callno is already held.
1863 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1864 * was valid before calling it, it may no longer be valid after calling it.
1865 * This function may unlock and lock the mutex associated with this callno,
1866 * meaning that another thread may grab it and destroy the call.
1868 static int iax2_queue_hangup(int callno)
1870 for (;;) {
1871 if (iaxs[callno] && iaxs[callno]->owner) {
1872 if (ast_channel_trylock(iaxs[callno]->owner)) {
1873 /* Avoid deadlock by pausing and trying again */
1874 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1875 } else {
1876 ast_queue_hangup(iaxs[callno]->owner);
1877 ast_channel_unlock(iaxs[callno]->owner);
1878 break;
1880 } else
1881 break;
1883 return 0;
1887 * \brief Queue a control frame on the ast_channel owner
1889 * This function queues a control frame on the owner of the IAX2 pvt struct that
1890 * is active for the given call number.
1892 * \pre Assumes lock for callno is already held.
1894 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
1895 * was valid before calling it, it may no longer be valid after calling it.
1896 * This function may unlock and lock the mutex associated with this callno,
1897 * meaning that another thread may grab it and destroy the call.
1899 static int iax2_queue_control_data(int callno,
1900 enum ast_control_frame_type control, const void *data, size_t datalen)
1902 for (;;) {
1903 if (iaxs[callno] && iaxs[callno]->owner) {
1904 if (ast_channel_trylock(iaxs[callno]->owner)) {
1905 /* Avoid deadlock by pausing and trying again */
1906 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
1907 } else {
1908 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
1909 ast_channel_unlock(iaxs[callno]->owner);
1910 break;
1912 } else
1913 break;
1915 return 0;
1917 static void destroy_firmware(struct iax_firmware *cur)
1919 /* Close firmware */
1920 if (cur->fwh) {
1921 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
1923 close(cur->fd);
1924 ast_free(cur);
1927 static int try_firmware(char *s)
1929 struct stat stbuf;
1930 struct iax_firmware *cur = NULL;
1931 int ifd, fd, res, len, chunk;
1932 struct ast_iax2_firmware_header *fwh, fwh2;
1933 struct MD5Context md5;
1934 unsigned char sum[16], buf[1024];
1935 char *s2, *last;
1937 if (!(s2 = alloca(strlen(s) + 100))) {
1938 ast_log(LOG_WARNING, "Alloca failed!\n");
1939 return -1;
1942 last = strrchr(s, '/');
1943 if (last)
1944 last++;
1945 else
1946 last = s;
1948 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
1950 if ((res = stat(s, &stbuf) < 0)) {
1951 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
1952 return -1;
1955 /* Make sure it's not a directory */
1956 if (S_ISDIR(stbuf.st_mode))
1957 return -1;
1958 ifd = open(s, O_RDONLY);
1959 if (ifd < 0) {
1960 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
1961 return -1;
1963 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
1964 if (fd < 0) {
1965 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
1966 close(ifd);
1967 return -1;
1969 /* Unlink our newly created file */
1970 unlink(s2);
1972 /* Now copy the firmware into it */
1973 len = stbuf.st_size;
1974 while(len) {
1975 chunk = len;
1976 if (chunk > sizeof(buf))
1977 chunk = sizeof(buf);
1978 res = read(ifd, buf, chunk);
1979 if (res != chunk) {
1980 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1981 close(ifd);
1982 close(fd);
1983 return -1;
1985 res = write(fd, buf, chunk);
1986 if (res != chunk) {
1987 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
1988 close(ifd);
1989 close(fd);
1990 return -1;
1992 len -= chunk;
1994 close(ifd);
1995 /* Return to the beginning */
1996 lseek(fd, 0, SEEK_SET);
1997 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
1998 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
1999 close(fd);
2000 return -1;
2002 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
2003 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
2004 close(fd);
2005 return -1;
2007 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
2008 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
2009 close(fd);
2010 return -1;
2012 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
2013 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
2014 close(fd);
2015 return -1;
2017 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
2018 if (fwh == (void *) -1) {
2019 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
2020 close(fd);
2021 return -1;
2023 MD5Init(&md5);
2024 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
2025 MD5Final(sum, &md5);
2026 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
2027 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
2028 munmap((void*)fwh, stbuf.st_size);
2029 close(fd);
2030 return -1;
2033 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2034 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
2035 /* Found a candidate */
2036 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
2037 /* The version we have on loaded is older, load this one instead */
2038 break;
2039 /* This version is no newer than what we have. Don't worry about it.
2040 We'll consider it a proper load anyhow though */
2041 munmap((void*)fwh, stbuf.st_size);
2042 close(fd);
2043 return 0;
2047 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
2048 cur->fd = -1;
2049 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
2052 if (cur) {
2053 if (cur->fwh)
2054 munmap((void*)cur->fwh, cur->mmaplen);
2055 if (cur->fd > -1)
2056 close(cur->fd);
2057 cur->fwh = fwh;
2058 cur->fd = fd;
2059 cur->mmaplen = stbuf.st_size;
2060 cur->dead = 0;
2063 return 0;
2066 static int iax_check_version(char *dev)
2068 int res = 0;
2069 struct iax_firmware *cur = NULL;
2071 if (ast_strlen_zero(dev))
2072 return 0;
2074 AST_LIST_LOCK(&firmwares);
2075 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2076 if (!strcmp(dev, (char *)cur->fwh->devname)) {
2077 res = ntohs(cur->fwh->version);
2078 break;
2081 AST_LIST_UNLOCK(&firmwares);
2083 return res;
2086 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
2088 int res = -1;
2089 unsigned int bs = desc & 0xff;
2090 unsigned int start = (desc >> 8) & 0xffffff;
2091 unsigned int bytes;
2092 struct iax_firmware *cur;
2094 if (ast_strlen_zero((char *)dev) || !bs)
2095 return -1;
2097 start *= bs;
2099 AST_LIST_LOCK(&firmwares);
2100 AST_LIST_TRAVERSE(&firmwares, cur, list) {
2101 if (strcmp((char *)dev, (char *)cur->fwh->devname))
2102 continue;
2103 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
2104 if (start < ntohl(cur->fwh->datalen)) {
2105 bytes = ntohl(cur->fwh->datalen) - start;
2106 if (bytes > bs)
2107 bytes = bs;
2108 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
2109 } else {
2110 bytes = 0;
2111 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
2113 if (bytes == bs)
2114 res = 0;
2115 else
2116 res = 1;
2117 break;
2119 AST_LIST_UNLOCK(&firmwares);
2121 return res;
2125 static void reload_firmware(int unload)
2127 struct iax_firmware *cur = NULL;
2128 DIR *fwd;
2129 struct dirent *de;
2130 char dir[256], fn[256];
2132 AST_LIST_LOCK(&firmwares);
2134 /* Mark all as dead */
2135 AST_LIST_TRAVERSE(&firmwares, cur, list)
2136 cur->dead = 1;
2138 /* Now that we have marked them dead... load new ones */
2139 if (!unload) {
2140 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
2141 fwd = opendir(dir);
2142 if (fwd) {
2143 while((de = readdir(fwd))) {
2144 if (de->d_name[0] != '.') {
2145 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
2146 if (!try_firmware(fn)) {
2147 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
2151 closedir(fwd);
2152 } else
2153 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
2156 /* Clean up leftovers */
2157 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
2158 if (!cur->dead)
2159 continue;
2160 AST_LIST_REMOVE_CURRENT(list);
2161 destroy_firmware(cur);
2163 AST_LIST_TRAVERSE_SAFE_END;
2165 AST_LIST_UNLOCK(&firmwares);
2169 * \note This function assumes that iaxsl[callno] is locked when called.
2171 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
2172 * was valid before calling it, it may no longer be valid after calling it.
2173 * This function calls iax2_queue_frame(), which may unlock and lock the mutex
2174 * associated with this callno, meaning that another thread may grab it and destroy the call.
2176 static int __do_deliver(void *data)
2178 /* Just deliver the packet by using queueing. This is called by
2179 the IAX thread with the iaxsl lock held. */
2180 struct iax_frame *fr = data;
2181 fr->retrans = -1;
2182 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
2183 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
2184 iax2_queue_frame(fr->callno, &fr->af);
2185 /* Free our iax frame */
2186 iax2_frame_free(fr);
2187 /* And don't run again */
2188 return 0;
2191 static int handle_error(void)
2193 /* XXX Ideally we should figure out why an error occurred and then abort those
2194 rather than continuing to try. Unfortunately, the published interface does
2195 not seem to work XXX */
2196 #if 0
2197 struct sockaddr_in *sin;
2198 int res;
2199 struct msghdr m;
2200 struct sock_extended_err e;
2201 m.msg_name = NULL;
2202 m.msg_namelen = 0;
2203 m.msg_iov = NULL;
2204 m.msg_control = &e;
2205 m.msg_controllen = sizeof(e);
2206 m.msg_flags = 0;
2207 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
2208 if (res < 0)
2209 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
2210 else {
2211 if (m.msg_controllen) {
2212 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
2213 if (sin)
2214 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
2215 else
2216 ast_log(LOG_WARNING, "No address detected??\n");
2217 } else {
2218 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
2221 #endif
2222 return 0;
2225 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
2227 int res;
2228 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
2229 sizeof(*sin));
2230 if (res < 0) {
2231 ast_debug(1, "Received error: %s\n", strerror(errno));
2232 handle_error();
2233 } else
2234 res = 0;
2235 return res;
2238 static int send_packet(struct iax_frame *f)
2240 int res;
2241 int callno = f->callno;
2242 struct sockaddr_in *addr;
2244 /* Don't send if there was an error, but return error instead */
2245 if (!callno || !iaxs[callno] || iaxs[callno]->error)
2246 return -1;
2248 /* Called with iaxsl held */
2249 if (iaxdebug)
2250 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
2252 if (f->media) {
2253 addr = &iaxs[callno]->media;
2254 } else if (f->transfer) {
2255 addr = &iaxs[callno]->transfer;
2256 } else {
2257 addr = &iaxs[callno]->addr;
2260 iax_outputframe(f, NULL, 0, addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
2262 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)addr,
2263 sizeof(iaxs[callno]->media));
2265 if (res < 0) {
2266 if (iaxdebug)
2267 ast_debug(1, "Received error: %s\n", strerror(errno));
2268 handle_error();
2269 } else
2270 res = 0;
2272 return res;
2276 * \note Since this function calls iax2_queue_hangup(), the pvt struct
2277 * for the given call number may disappear during its execution.
2279 static int iax2_predestroy(int callno)
2281 struct ast_channel *c = NULL;
2282 struct chan_iax2_pvt *pvt = iaxs[callno];
2284 if (!pvt)
2285 return -1;
2287 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
2288 iax2_destroy_helper(pvt);
2289 ast_set_flag(pvt, IAX_ALREADYGONE);
2292 if ((c = pvt->owner)) {
2293 c->tech_pvt = NULL;
2294 iax2_queue_hangup(callno);
2295 pvt->owner = NULL;
2296 ast_module_unref(ast_module_info->self);
2299 return 0;
2302 static void iax2_destroy(int callno)
2304 struct chan_iax2_pvt *pvt = NULL;
2305 struct ast_channel *owner = NULL;
2307 retry:
2308 pvt = iaxs[callno];
2309 lastused[callno] = ast_tvnow();
2311 owner = pvt ? pvt->owner : NULL;
2313 if (owner) {
2314 if (ast_channel_trylock(owner)) {
2315 ast_debug(3, "Avoiding IAX destroy deadlock\n");
2316 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
2317 goto retry;
2321 if (!owner) {
2322 iaxs[callno] = NULL;
2325 if (pvt) {
2326 if (!owner) {
2327 pvt->owner = NULL;
2328 } else {
2329 /* If there's an owner, prod it to give up */
2330 /* It is ok to use ast_queue_hangup() here instead of iax2_queue_hangup()
2331 * because we already hold the owner channel lock. */
2332 ast_queue_hangup(owner);
2335 if (pvt->peercallno) {
2336 remove_by_peercallno(pvt);
2339 if (!owner) {
2340 ao2_ref(pvt, -1);
2341 pvt = NULL;
2345 if (owner) {
2346 ast_channel_unlock(owner);
2349 if (callno & 0x4000) {
2350 update_max_trunk();
2354 static int update_packet(struct iax_frame *f)
2356 /* Called with iaxsl lock held, and iaxs[callno] non-NULL */
2357 struct ast_iax2_full_hdr *fh = f->data;
2358 /* Mark this as a retransmission */
2359 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
2360 /* Update iseqno */
2361 f->iseqno = iaxs[f->callno]->iseqno;
2362 fh->iseqno = f->iseqno;
2363 return 0;
2366 static int attempt_transmit(const void *data);
2367 static void __attempt_transmit(const void *data)
2369 /* Attempt to transmit the frame to the remote peer...
2370 Called without iaxsl held. */
2371 struct iax_frame *f = (struct iax_frame *)data;
2372 int freeme = 0;
2373 int callno = f->callno;
2374 /* Make sure this call is still active */
2375 if (callno)
2376 ast_mutex_lock(&iaxsl[callno]);
2377 if (callno && iaxs[callno]) {
2378 if ((f->retries < 0) /* Already ACK'd */ ||
2379 (f->retries >= max_retries) /* Too many attempts */) {
2380 /* Record an error if we've transmitted too many times */
2381 if (f->retries >= max_retries) {
2382 if (f->transfer) {
2383 /* Transfer timeout */
2384 struct iax_ie_data ied;
2385 memset(&ied, 0, sizeof(ied));
2386 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, iaxs[callno]->transferid);
2387 if (iaxs[callno]->mediareleased) {
2388 send_command_media(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos);
2389 } else {
2390 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied.buf, ied.pos, -1);
2392 } else if (f->final) {
2393 if (f->final)
2394 iax2_destroy(callno);
2395 } else {
2396 if (iaxs[callno]->owner)
2397 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
2398 iaxs[callno]->error = ETIMEDOUT;
2399 if (iaxs[callno]->owner) {
2400 struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
2401 /* Hangup the fd */
2402 iax2_queue_frame(callno, &fr); /* XXX */
2403 /* Remember, owner could disappear */
2404 if (iaxs[callno] && iaxs[callno]->owner)
2405 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
2406 } else {
2407 if (iaxs[callno]->reg) {
2408 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
2409 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
2410 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
2412 iax2_destroy(callno);
2417 freeme = 1;
2418 } else {
2419 /* Update it if it needs it */
2420 update_packet(f);
2421 /* Attempt transmission */
2422 send_packet(f);
2423 f->retries++;
2424 /* Try again later after 10 times as long */
2425 f->retrytime *= 10;
2426 if (f->retrytime > MAX_RETRY_TIME)
2427 f->retrytime = MAX_RETRY_TIME;
2428 /* Transfer messages max out at one second */
2429 if (f->transfer && (f->retrytime > 1000))
2430 f->retrytime = 1000;
2431 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
2433 } else {
2434 /* Make sure it gets freed */
2435 f->retries = -1;
2436 freeme = 1;
2438 if (callno)
2439 ast_mutex_unlock(&iaxsl[callno]);
2440 /* Do not try again */
2441 if (freeme) {
2442 /* Don't attempt delivery, just remove it from the queue */
2443 AST_LIST_LOCK(&frame_queue);
2444 AST_LIST_REMOVE(&frame_queue, f, list);
2445 AST_LIST_UNLOCK(&frame_queue);
2446 f->retrans = -1;
2447 /* Free the IAX frame */
2448 iax2_frame_free(f);
2452 static int attempt_transmit(const void *data)
2454 #ifdef SCHED_MULTITHREADED
2455 if (schedule_action(__attempt_transmit, data))
2456 #endif
2457 __attempt_transmit(data);
2458 return 0;
2461 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2463 struct iax2_peer *peer;
2465 switch (cmd) {
2466 case CLI_INIT:
2467 e->command = "iax2 prune realtime";
2468 e->usage =
2469 "Usage: iax2 prune realtime [<peername>|all]\n"
2470 " Prunes object(s) from the cache\n";
2471 return NULL;
2472 case CLI_GENERATE:
2473 if (a->pos == 3)
2474 return complete_iax2_peers(a->line, a->word, a->pos, a->n);
2475 return NULL;
2478 if (a->argc != 4)
2479 return CLI_SHOWUSAGE;
2480 if (!strcmp(a->argv[3], "all")) {
2481 reload_config();
2482 ast_cli(a->fd, "Cache flushed successfully.\n");
2483 } else if ((peer = find_peer(a->argv[3], 0))) {
2484 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
2485 ast_set_flag(peer, IAX_RTAUTOCLEAR);
2486 expire_registry(peer_ref(peer));
2487 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
2488 } else {
2489 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
2491 peer_unref(peer);
2492 } else {
2493 ast_cli(a->fd, "Peer %s was not found in the cache.\n", a->argv[3]);
2496 return CLI_SUCCESS;
2499 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2501 switch (cmd) {
2502 case CLI_INIT:
2503 e->command = "iax2 test losspct";
2504 e->usage =
2505 "Usage: iax2 test losspct <percentage>\n"
2506 " For testing, throws away <percentage> percent of incoming packets\n";
2507 return NULL;
2508 case CLI_GENERATE:
2509 return NULL;
2511 if (a->argc != 4)
2512 return CLI_SHOWUSAGE;
2514 test_losspct = atoi(a->argv[3]);
2516 return CLI_SUCCESS;
2519 #ifdef IAXTESTS
2520 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2522 switch (cmd) {
2523 case CLI_INIT:
2524 e->command = "iax2 test late";
2525 e->usage =
2526 "Usage: iax2 test late <ms>\n"
2527 " For testing, count the next frame as <ms> ms late\n";
2528 return NULL;
2529 case CLI_GENERATE:
2530 return NULL;
2533 if (a->argc != 4)
2534 return CLI_SHOWUSAGE;
2536 test_late = atoi(a->argv[3]);
2538 return CLI_SUCCESS;
2541 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2543 switch (cmd) {
2544 case CLI_INIT:
2545 e->command = "iax2 test resync";
2546 e->usage =
2547 "Usage: iax2 test resync <ms>\n"
2548 " For testing, adjust all future frames by <ms> ms\n";
2549 return NULL;
2550 case CLI_GENERATE:
2551 return NULL;
2554 if (a->argc != 4)
2555 return CLI_SHOWUSAGE;
2557 test_resync = atoi(a->argv[3]);
2559 return CLI_SUCCESS;
2562 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2564 switch (cmd) {
2565 case CLI_INIT:
2566 e->command = "iax2 test jitter";
2567 e->usage =
2568 "Usage: iax2 test jitter <ms> <pct>\n"
2569 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
2570 " percentage of packets. If <pct> is not specified, adds\n"
2571 " jitter to all packets.\n";
2572 return NULL;
2573 case CLI_GENERATE:
2574 return NULL;
2577 if (a->argc < 4 || a->argc > 5)
2578 return CLI_SHOWUSAGE;
2580 test_jit = atoi(a->argv[3]);
2581 if (a->argc == 5)
2582 test_jitpct = atoi(a->argv[4]);
2584 return CLI_SUCCESS;
2586 #endif /* IAXTESTS */
2588 /*! \brief peer_status: Report Peer status in character string */
2589 /* returns 1 if peer is online, -1 if unmonitored */
2590 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
2592 int res = 0;
2593 if (peer->maxms) {
2594 if (peer->lastms < 0) {
2595 ast_copy_string(status, "UNREACHABLE", statuslen);
2596 } else if (peer->lastms > peer->maxms) {
2597 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
2598 res = 1;
2599 } else if (peer->lastms) {
2600 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
2601 res = 1;
2602 } else {
2603 ast_copy_string(status, "UNKNOWN", statuslen);
2605 } else {
2606 ast_copy_string(status, "Unmonitored", statuslen);
2607 res = -1;
2609 return res;
2612 /*! \brief Show one peer in detail */
2613 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2615 char status[30];
2616 char cbuf[256];
2617 struct iax2_peer *peer;
2618 char codec_buf[512];
2619 int x = 0, codec = 0, load_realtime = 0;
2621 switch (cmd) {
2622 case CLI_INIT:
2623 e->command = "iax2 show peer";
2624 e->usage =
2625 "Usage: iax2 show peer <name>\n"
2626 " Display details on specific IAX peer\n";
2627 return NULL;
2628 case CLI_GENERATE:
2629 if (a->pos == 3)
2630 return complete_iax2_peers(a->line, a->word, a->pos, a->n);
2631 return NULL;
2634 if (a->argc < 4)
2635 return CLI_SHOWUSAGE;
2637 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
2639 peer = find_peer(a->argv[3], load_realtime);
2640 if (peer) {
2641 ast_cli(a->fd, "\n\n");
2642 ast_cli(a->fd, " * Name : %s\n", peer->name);
2643 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
2644 ast_cli(a->fd, " Context : %s\n", peer->context);
2645 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
2646 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
2647 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
2648 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
2649 ast_cli(a->fd, " Expire : %d\n", peer->expire);
2650 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
2651 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
2652 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
2653 ast_cli(a->fd, " Username : %s\n", peer->username);
2654 ast_cli(a->fd, " Codecs : ");
2655 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
2656 ast_cli(a->fd, "%s\n", codec_buf);
2658 ast_cli(a->fd, " Codec Order : (");
2659 for(x = 0; x < 32 ; x++) {
2660 codec = ast_codec_pref_index(&peer->prefs,x);
2661 if(!codec)
2662 break;
2663 ast_cli(a->fd, "%s", ast_getformatname(codec));
2664 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
2665 ast_cli(a->fd, "|");
2668 if (!x)
2669 ast_cli(a->fd, "none");
2670 ast_cli(a->fd, ")\n");
2672 ast_cli(a->fd, " Status : ");
2673 peer_status(peer, status, sizeof(status));
2674 ast_cli(a->fd, "%s\n",status);
2675 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
2676 ast_cli(a->fd, "\n");
2677 peer_unref(peer);
2678 } else {
2679 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
2680 ast_cli(a->fd, "\n");
2683 return CLI_SUCCESS;
2686 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state)
2688 int which = 0;
2689 struct iax2_peer *peer;
2690 char *res = NULL;
2691 int wordlen = strlen(word);
2692 struct ao2_iterator i;
2694 i = ao2_iterator_init(peers, 0);
2695 while ((peer = ao2_iterator_next(&i))) {
2696 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
2697 res = ast_strdup(peer->name);
2698 peer_unref(peer);
2699 break;
2701 peer_unref(peer);
2704 return res;
2707 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2709 struct iax_frame *cur;
2710 int cnt = 0, dead = 0, final = 0;
2712 switch (cmd) {
2713 case CLI_INIT:
2714 e->command = "iax2 show stats";
2715 e->usage =
2716 "Usage: iax2 show stats\n"
2717 " Display statistics on IAX channel driver.\n";
2718 return NULL;
2719 case CLI_GENERATE:
2720 return NULL;
2723 if (a->argc != 3)
2724 return CLI_SHOWUSAGE;
2726 AST_LIST_LOCK(&frame_queue);
2727 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
2728 if (cur->retries < 0)
2729 dead++;
2730 if (cur->final)
2731 final++;
2732 cnt++;
2734 AST_LIST_UNLOCK(&frame_queue);
2736 ast_cli(a->fd, " IAX Statistics\n");
2737 ast_cli(a->fd, "---------------------\n");
2738 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
2739 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
2740 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
2741 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
2743 trunk_timed = trunk_untimed = 0;
2744 if (trunk_maxmtu > trunk_nmaxmtu)
2745 trunk_nmaxmtu = trunk_maxmtu;
2747 return CLI_SUCCESS;
2750 /*! \brief Set trunk MTU from CLI */
2751 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2753 int mtuv;
2755 switch (cmd) {
2756 case CLI_INIT:
2757 e->command = "iax2 set mtu";
2758 e->usage =
2759 "Usage: iax2 set mtu <value>\n"
2760 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
2761 " zero to disable. Disabling means that the operating system\n"
2762 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
2763 " packet exceeds the UDP payload size. This is substantially\n"
2764 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
2765 " greater for G.711 samples.\n";
2766 return NULL;
2767 case CLI_GENERATE:
2768 return NULL;
2771 if (a->argc != 4)
2772 return CLI_SHOWUSAGE;
2773 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
2774 mtuv = MAX_TRUNK_MTU;
2775 else
2776 mtuv = atoi(a->argv[3]);
2778 if (mtuv == 0) {
2779 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
2780 global_max_trunk_mtu = 0;
2781 return CLI_SUCCESS;
2783 if (mtuv < 172 || mtuv > 4000) {
2784 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
2785 return CLI_SHOWUSAGE;
2787 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
2788 global_max_trunk_mtu = mtuv;
2789 return CLI_SUCCESS;
2792 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2794 struct iax2_dpcache *dp = NULL;
2795 char tmp[1024], *pc = NULL;
2796 int s, x, y;
2797 struct timeval now = ast_tvnow();
2799 switch (cmd) {
2800 case CLI_INIT:
2801 e->command = "iax2 show cache";
2802 e->usage =
2803 "Usage: iax2 show cache\n"
2804 " Display currently cached IAX Dialplan results.\n";
2805 return NULL;
2806 case CLI_GENERATE:
2807 return NULL;
2810 AST_LIST_LOCK(&dpcache);
2812 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
2814 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
2815 s = dp->expiry.tv_sec - now.tv_sec;
2816 tmp[0] = '\0';
2817 if (dp->flags & CACHE_FLAG_EXISTS)
2818 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
2819 if (dp->flags & CACHE_FLAG_NONEXISTENT)
2820 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
2821 if (dp->flags & CACHE_FLAG_CANEXIST)
2822 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
2823 if (dp->flags & CACHE_FLAG_PENDING)
2824 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
2825 if (dp->flags & CACHE_FLAG_TIMEOUT)
2826 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
2827 if (dp->flags & CACHE_FLAG_TRANSMITTED)
2828 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
2829 if (dp->flags & CACHE_FLAG_MATCHMORE)
2830 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
2831 if (dp->flags & CACHE_FLAG_UNKNOWN)
2832 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
2833 /* Trim trailing pipe */
2834 if (!ast_strlen_zero(tmp)) {
2835 tmp[strlen(tmp) - 1] = '\0';
2836 } else {
2837 ast_copy_string(tmp, "(none)", sizeof(tmp));
2839 y = 0;
2840 pc = strchr(dp->peercontext, '@');
2841 if (!pc) {
2842 pc = dp->peercontext;
2843 } else {
2844 pc++;
2846 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
2847 if (dp->waiters[x] > -1)
2848 y++;
2850 if (s > 0) {
2851 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
2852 } else {
2853 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
2857 AST_LIST_LOCK(&dpcache);
2859 return CLI_SUCCESS;
2862 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
2864 static void unwrap_timestamp(struct iax_frame *fr)
2866 /* Video mini frames only encode the lower 15 bits of the session
2867 * timestamp, but other frame types (e.g. audio) encode 16 bits. */
2868 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
2869 const int lower_mask = (1 << ts_shift) - 1;
2870 const int upper_mask = ~lower_mask;
2871 const int last_upper = iaxs[fr->callno]->last & upper_mask;
2873 if ( (fr->ts & upper_mask) == last_upper ) {
2874 const int x = fr->ts - iaxs[fr->callno]->last;
2875 const int threshold = (ts_shift == 15) ? 25000 : 50000;
2877 if (x < -threshold) {
2878 /* Sudden big jump backwards in timestamp:
2879 What likely happened here is that miniframe timestamp has circled but we haven't
2880 gotten the update from the main packet. We'll just pretend that we did, and
2881 update the timestamp appropriately. */
2882 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
2883 if (iaxdebug)
2884 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
2885 } else if (x > threshold) {
2886 /* Sudden apparent big jump forwards in timestamp:
2887 What's likely happened is this is an old miniframe belonging to the previous
2888 top 15 or 16-bit timestamp that has turned up out of order.
2889 Adjust the timestamp appropriately. */
2890 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
2891 if (iaxdebug)
2892 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
2897 static int get_from_jb(const void *p);
2899 static void update_jbsched(struct chan_iax2_pvt *pvt)
2901 int when;
2903 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
2905 when = jb_next(pvt->jb) - when;
2907 if (when <= 0) {
2908 /* XXX should really just empty until when > 0.. */
2909 when = 1;
2912 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
2913 CALLNO_TO_PTR(pvt->callno));
2916 static void __get_from_jb(const void *p)
2918 int callno = PTR_TO_CALLNO(p);
2919 struct chan_iax2_pvt *pvt = NULL;
2920 struct iax_frame *fr;
2921 jb_frame frame;
2922 int ret;
2923 long ms;
2924 long next;
2925 struct timeval now = ast_tvnow();
2927 /* Make sure we have a valid private structure before going on */
2928 ast_mutex_lock(&iaxsl[callno]);
2929 pvt = iaxs[callno];
2930 if (!pvt) {
2931 /* No go! */
2932 ast_mutex_unlock(&iaxsl[callno]);
2933 return;
2936 pvt->jbid = -1;
2938 /* round up a millisecond since ast_sched_runq does; */
2939 /* prevents us from spinning while waiting for our now */
2940 /* to catch up with runq's now */
2941 now.tv_usec += 1000;
2943 ms = ast_tvdiff_ms(now, pvt->rxcore);
2945 if(ms >= (next = jb_next(pvt->jb))) {
2946 ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
2947 switch(ret) {
2948 case JB_OK:
2949 fr = frame.data;
2950 __do_deliver(fr);
2951 /* __do_deliver() can cause the call to disappear */
2952 pvt = iaxs[callno];
2953 break;
2954 case JB_INTERP:
2956 struct ast_frame af = { 0, };
2958 /* create an interpolation frame */
2959 af.frametype = AST_FRAME_VOICE;
2960 af.subclass = pvt->voiceformat;
2961 af.samples = frame.ms * 8;
2962 af.src = "IAX2 JB interpolation";
2963 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
2964 af.offset = AST_FRIENDLY_OFFSET;
2966 /* queue the frame: For consistency, we would call __do_deliver here, but __do_deliver wants an iax_frame,
2967 * which we'd need to malloc, and then it would free it. That seems like a drag */
2968 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
2969 iax2_queue_frame(callno, &af);
2970 /* iax2_queue_frame() could cause the call to disappear */
2971 pvt = iaxs[callno];
2974 break;
2975 case JB_DROP:
2976 iax2_frame_free(frame.data);
2977 break;
2978 case JB_NOFRAME:
2979 case JB_EMPTY:
2980 /* do nothing */
2981 break;
2982 default:
2983 /* shouldn't happen */
2984 break;
2987 if (pvt)
2988 update_jbsched(pvt);
2989 ast_mutex_unlock(&iaxsl[callno]);
2992 static int get_from_jb(const void *data)
2994 #ifdef SCHED_MULTITHREADED
2995 if (schedule_action(__get_from_jb, data))
2996 #endif
2997 __get_from_jb(data);
2998 return 0;
3002 * \note This function assumes fr->callno is locked
3004 * \note IMPORTANT NOTE!!! Any time this function is used, even if iaxs[callno]
3005 * was valid before calling it, it may no longer be valid after calling it.
3007 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
3009 int type, len;
3010 int ret;
3011 int needfree = 0;
3012 struct ast_channel *owner = NULL;
3013 struct ast_channel *bridge = NULL;
3015 /* Attempt to recover wrapped timestamps */
3016 unwrap_timestamp(fr);
3018 /* delivery time is sender's sent timestamp converted back into absolute time according to our clock */
3019 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
3020 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
3021 else {
3022 #if 0
3023 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
3024 #endif
3025 fr->af.delivery = ast_tv(0,0);
3028 type = JB_TYPE_CONTROL;
3029 len = 0;
3031 if(fr->af.frametype == AST_FRAME_VOICE) {
3032 type = JB_TYPE_VOICE;
3033 len = ast_codec_get_samples(&fr->af) / 8;
3034 } else if(fr->af.frametype == AST_FRAME_CNG) {
3035 type = JB_TYPE_SILENCE;
3038 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
3039 if (tsout)
3040 *tsout = fr->ts;
3041 __do_deliver(fr);
3042 return -1;
3045 if ((owner = iaxs[fr->callno]->owner))
3046 bridge = ast_bridged_channel(owner);
3048 /* if the user hasn't requested we force the use of the jitterbuffer, and we're bridged to
3049 * a channel that can accept jitter, then flush and suspend the jb, and send this frame straight through */
3050 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
3051 jb_frame frame;
3053 /* deliver any frames in the jb */
3054 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
3055 __do_deliver(frame.data);
3056 /* __do_deliver() can make the call disappear */
3057 if (!iaxs[fr->callno])
3058 return -1;
3061 jb_reset(iaxs[fr->callno]->jb);
3063 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
3065 /* deliver this frame now */
3066 if (tsout)
3067 *tsout = fr->ts;
3068 __do_deliver(fr);
3069 return -1;
3072 /* insert into jitterbuffer */
3073 /* TODO: Perhaps we could act immediately if it's not droppable and late */
3074 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
3075 calc_rxstamp(iaxs[fr->callno],fr->ts));
3076 if (ret == JB_DROP) {
3077 needfree++;
3078 } else if (ret == JB_SCHED) {
3079 update_jbsched(iaxs[fr->callno]);
3081 if (tsout)
3082 *tsout = fr->ts;
3083 if (needfree) {
3084 /* Free our iax frame */
3085 iax2_frame_free(fr);
3086 return -1;
3088 return 0;
3091 static int iax2_transmit(struct iax_frame *fr)
3093 /* Lock the queue and place this packet at the end */
3094 /* By setting this to 0, the network thread will send it for us, and
3095 queue retransmission if necessary */
3096 fr->sentyet = 0;
3097 AST_LIST_LOCK(&frame_queue);
3098 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
3099 AST_LIST_UNLOCK(&frame_queue);
3100 /* Wake up the network and scheduler thread */
3101 if (netthreadid != AST_PTHREADT_NULL)
3102 pthread_kill(netthreadid, SIGURG);
3103 signal_condition(&sched_lock, &sched_cond);
3104 return 0;
3109 static int iax2_digit_begin(struct ast_channel *c, char digit)
3111 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
3114 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
3116 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
3119 static int iax2_sendtext(struct ast_channel *c, const char *text)
3122 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
3123 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
3126 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
3128 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data.ptr, img->datalen, -1);
3131 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
3133 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
3136 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
3138 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
3139 ast_mutex_lock(&iaxsl[callno]);
3140 if (iaxs[callno])
3141 iaxs[callno]->owner = newchan;
3142 else
3143 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
3144 ast_mutex_unlock(&iaxsl[callno]);
3145 return 0;
3149 * \note This function calls reg_source_db -> iax2_poke_peer -> find_callno,
3150 * so do not call this with a pvt lock held.
3152 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
3154 struct ast_variable *var = NULL;
3155 struct ast_variable *tmp;
3156 struct iax2_peer *peer=NULL;
3157 time_t regseconds = 0, nowtime;
3158 int dynamic=0;
3160 if (peername) {
3161 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
3162 if (!var && sin)
3163 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
3164 } else if (sin) {
3165 char porta[25];
3166 sprintf(porta, "%d", ntohs(sin->sin_port));
3167 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
3168 if (var) {
3169 /* We'll need the peer name in order to build the structure! */
3170 for (tmp = var; tmp; tmp = tmp->next) {
3171 if (!strcasecmp(tmp->name, "name"))
3172 peername = tmp->value;
3176 if (!var && peername) { /* Last ditch effort */
3177 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
3178 /*!\note
3179 * If this one loaded something, then we need to ensure that the host
3180 * field matched. The only reason why we can't have this as a criteria
3181 * is because we only have the IP address and the host field might be
3182 * set as a name (and the reverse PTR might not match).
3184 if (var && sin) {
3185 for (tmp = var; tmp; tmp = tmp->next) {
3186 if (!strcasecmp(tmp->name, "host")) {
3187 struct ast_hostent ahp;
3188 struct hostent *hp;
3189 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3190 /* No match */
3191 ast_variables_destroy(var);
3192 var = NULL;
3194 break;
3199 if (!var)
3200 return NULL;
3202 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
3204 if (!peer) {
3205 ast_variables_destroy(var);
3206 return NULL;
3209 for (tmp = var; tmp; tmp = tmp->next) {
3210 /* Make sure it's not a user only... */
3211 if (!strcasecmp(tmp->name, "type")) {
3212 if (strcasecmp(tmp->value, "friend") &&
3213 strcasecmp(tmp->value, "peer")) {
3214 /* Whoops, we weren't supposed to exist! */
3215 peer = peer_unref(peer);
3216 break;
3218 } else if (!strcasecmp(tmp->name, "regseconds")) {
3219 ast_get_time_t(tmp->value, &regseconds, 0, NULL);
3220 } else if (!strcasecmp(tmp->name, "ipaddr")) {
3221 inet_aton(tmp->value, &(peer->addr.sin_addr));
3222 } else if (!strcasecmp(tmp->name, "port")) {
3223 peer->addr.sin_port = htons(atoi(tmp->value));
3224 } else if (!strcasecmp(tmp->name, "host")) {
3225 if (!strcasecmp(tmp->value, "dynamic"))
3226 dynamic = 1;
3230 ast_variables_destroy(var);
3232 if (!peer)
3233 return NULL;
3235 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3236 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
3237 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
3238 if (peer->expire > -1) {
3239 if (!ast_sched_del(sched, peer->expire)) {
3240 peer->expire = -1;
3241 peer_unref(peer);
3244 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
3245 if (peer->expire == -1)
3246 peer_unref(peer);
3248 ao2_link(peers, peer);
3249 if (ast_test_flag(peer, IAX_DYNAMIC))
3250 reg_source_db(peer);
3251 } else {
3252 ast_set_flag(peer, IAX_TEMPONLY);
3255 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
3256 time(&nowtime);
3257 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
3258 memset(&peer->addr, 0, sizeof(peer->addr));
3259 realtime_update_peer(peer->name, &peer->addr, 0);
3260 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
3261 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3263 else {
3264 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
3265 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
3269 return peer;
3272 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
3274 struct ast_variable *var;
3275 struct ast_variable *tmp;
3276 struct iax2_user *user=NULL;
3278 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
3279 if (!var)
3280 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
3281 if (!var && sin) {
3282 char porta[6];
3283 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
3284 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
3285 if (!var)
3286 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
3288 if (!var) { /* Last ditch effort */
3289 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
3290 /*!\note
3291 * If this one loaded something, then we need to ensure that the host
3292 * field matched. The only reason why we can't have this as a criteria
3293 * is because we only have the IP address and the host field might be
3294 * set as a name (and the reverse PTR might not match).
3296 if (var) {
3297 for (tmp = var; tmp; tmp = tmp->next) {
3298 if (!strcasecmp(tmp->name, "host")) {
3299 struct ast_hostent ahp;
3300 struct hostent *hp;
3301 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
3302 /* No match */
3303 ast_variables_destroy(var);
3304 var = NULL;
3306 break;
3311 if (!var)
3312 return NULL;
3314 tmp = var;
3315 while(tmp) {
3316 /* Make sure it's not a peer only... */
3317 if (!strcasecmp(tmp->name, "type")) {
3318 if (strcasecmp(tmp->value, "friend") &&
3319 strcasecmp(tmp->value, "user")) {
3320 return NULL;
3323 tmp = tmp->next;
3326 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
3328 ast_variables_destroy(var);
3330 if (!user)
3331 return NULL;
3333 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
3334 ast_set_flag(user, IAX_RTCACHEFRIENDS);
3335 ao2_link(users, user);
3336 } else {
3337 ast_set_flag(user, IAX_TEMPONLY);
3340 return user;
3343 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
3345 char port[10];
3346 char regseconds[20];
3348 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
3349 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
3350 ast_update_realtime("iaxpeers", "name", peername,
3351 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
3352 "regseconds", regseconds, SENTINEL);
3355 struct create_addr_info {
3356 int capability;
3357 unsigned int flags;
3358 int maxtime;
3359 int encmethods;
3360 int found;
3361 int sockfd;
3362 int adsi;
3363 char username[80];
3364 char secret[80];
3365 char outkey[80];
3366 char timezone[80];
3367 char prefs[32];
3368 char context[AST_MAX_CONTEXT];
3369 char peercontext[AST_MAX_CONTEXT];
3370 char mohinterpret[MAX_MUSICCLASS];
3371 char mohsuggest[MAX_MUSICCLASS];
3374 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
3376 struct iax2_peer *peer;
3377 int res = -1;
3378 struct ast_codec_pref ourprefs;
3380 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
3381 cai->sockfd = defaultsockfd;
3382 cai->maxtime = 0;
3383 sin->sin_family = AF_INET;
3385 if (!(peer = find_peer(peername, 1))) {
3386 cai->found = 0;
3387 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
3388 ast_log(LOG_WARNING, "No such host: %s\n", peername);
3389 return -1;
3391 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
3392 /* use global iax prefs for unknown peer/user */
3393 /* But move the calling channel's native codec to the top of the preference list */
3394 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
3395 if (c)
3396 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3397 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3398 return 0;
3401 cai->found = 1;
3403 /* if the peer has no address (current or default), return failure */
3404 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
3405 goto return_unref;
3407 /* if the peer is being monitored and is currently unreachable, return failure */
3408 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
3409 goto return_unref;
3411 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_NOKEYROTATE);
3412 cai->maxtime = peer->maxms;
3413 cai->capability = peer->capability;
3414 cai->encmethods = peer->encmethods;
3415 cai->sockfd = peer->sockfd;
3416 cai->adsi = peer->adsi;
3417 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
3418 /* Move the calling channel's native codec to the top of the preference list */
3419 if (c) {
3420 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
3421 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
3423 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
3424 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
3425 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
3426 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
3427 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
3428 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
3429 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
3430 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
3431 if (ast_strlen_zero(peer->dbsecret)) {
3432 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
3433 } else {
3434 char *family;
3435 char *key = NULL;
3437 family = ast_strdupa(peer->dbsecret);
3438 key = strchr(family, '/');
3439 if (key)
3440 *key++ = '\0';
3441 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
3442 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
3443 goto return_unref;
3447 if (peer->addr.sin_addr.s_addr) {
3448 sin->sin_addr = peer->addr.sin_addr;
3449 sin->sin_port = peer->addr.sin_port;
3450 } else {
3451 sin->sin_addr = peer->defaddr.sin_addr;
3452 sin->sin_port = peer->defaddr.sin_port;
3455 res = 0;
3457 return_unref:
3458 peer_unref(peer);
3460 return res;
3463 static void __auto_congest(const void *nothing)
3465 int callno = PTR_TO_CALLNO(nothing);
3466 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
3467 ast_mutex_lock(&iaxsl[callno]);
3468 if (iaxs[callno]) {
3469 iaxs[callno]->initid = -1;
3470 iax2_queue_frame(callno, &f);
3471 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
3473 ast_mutex_unlock(&iaxsl[callno]);
3476 static int auto_congest(const void *data)
3478 #ifdef SCHED_MULTITHREADED
3479 if (schedule_action(__auto_congest, data))
3480 #endif
3481 __auto_congest(data);
3482 return 0;
3485 static unsigned int iax2_datetime(const char *tz)
3487 struct timeval t = ast_tvnow();
3488 struct ast_tm tm;
3489 unsigned int tmp;
3490 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
3491 tmp = (tm.tm_sec >> 1) & 0x1f; /* 5 bits of seconds */
3492 tmp |= (tm.tm_min & 0x3f) << 5; /* 6 bits of minutes */
3493 tmp |= (tm.tm_hour & 0x1f) << 11; /* 5 bits of hours */
3494 tmp |= (tm.tm_mday & 0x1f) << 16; /* 5 bits of day of month */
3495 tmp |= ((tm.tm_mon + 1) & 0xf) << 21; /* 4 bits of month */
3496 tmp |= ((tm.tm_year - 100) & 0x7f) << 25; /* 7 bits of year */
3497 return tmp;
3500 struct parsed_dial_string {
3501 char *username;
3502 char *password;
3503 char *key;
3504 char *peer;
3505 char *port;
3506 char *exten;
3507 char *context;
3508 char *options;
3511 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int command, int ts, unsigned char seqno)
3513 struct ast_iax2_full_hdr f = { .scallno = htons(0x8000 | callno), .dcallno = htons(dcallno),
3514 .ts = htonl(ts), .iseqno = seqno, .oseqno = seqno, .type = AST_FRAME_IAX,
3515 .csub = compress_subclass(command) };
3517 return sendto(defaultsockfd, &f, sizeof(f), 0, (struct sockaddr *)sin, sizeof(*sin));
3521 * \brief Parses an IAX dial string into its component parts.
3522 * \param data the string to be parsed
3523 * \param pds pointer to a \c struct \c parsed_dial_string to be filled in
3524 * \return nothing
3526 * This function parses the string and fills the structure
3527 * with pointers to its component parts. The input string
3528 * will be modified.
3530 * \note This function supports both plaintext passwords and RSA
3531 * key names; if the password string is formatted as '[keyname]',
3532 * then the keyname will be placed into the key field, and the
3533 * password field will be set to NULL.
3535 * \note The dial string format is:
3536 * [username[:password]@]peer[:port][/exten[@@context]][/options]
3538 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
3540 if (ast_strlen_zero(data))
3541 return;
3543 pds->peer = strsep(&data, "/");
3544 pds->exten = strsep(&data, "/");
3545 pds->options = data;
3547 if (pds->exten) {
3548 data = pds->exten;
3549 pds->exten = strsep(&data, "@");
3550 pds->context = data;
3553 if (strchr(pds->peer, '@')) {
3554 data = pds->peer;
3555 pds->username = strsep(&data, "@");
3556 pds->peer = data;
3559 if (pds->username) {
3560 data = pds->username;
3561 pds->username = strsep(&data, ":");
3562 pds->password = data;
3565 data = pds->peer;
3566 pds->peer = strsep(&data, ":");
3567 pds->port = data;
3569 /* check for a key name wrapped in [] in the secret position, if found,
3570 move it to the key field instead
3572 if (pds->password && (pds->password[0] == '[')) {
3573 pds->key = ast_strip_quoted(pds->password, "[", "]");
3574 pds->password = NULL;
3578 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
3580 struct sockaddr_in sin;
3581 char *l=NULL, *n=NULL, *tmpstr;
3582 struct iax_ie_data ied;
3583 char *defaultrdest = "s";
3584 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3585 struct parsed_dial_string pds;
3586 struct create_addr_info cai;
3587 struct ast_var_t *var;
3588 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
3589 const char* osp_token_ptr;
3590 unsigned int osp_token_length;
3591 unsigned char osp_block_index;
3592 unsigned int osp_block_length;
3593 unsigned char osp_buffer[256];
3595 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
3596 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
3597 return -1;
3600 memset(&cai, 0, sizeof(cai));
3601 cai.encmethods = iax2_encryption;
3603 memset(&pds, 0, sizeof(pds));
3604 tmpstr = ast_strdupa(dest);
3605 parse_dial_string(tmpstr, &pds);
3607 if (ast_strlen_zero(pds.peer)) {
3608 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
3609 return -1;
3612 if (!pds.exten) {
3613 pds.exten = defaultrdest;
3616 if (create_addr(pds.peer, c, &sin, &cai)) {
3617 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
3618 return -1;
3621 if (!pds.username && !ast_strlen_zero(cai.username))
3622 pds.username = cai.username;
3623 if (!pds.password && !ast_strlen_zero(cai.secret))
3624 pds.password = cai.secret;
3625 if (!pds.key && !ast_strlen_zero(cai.outkey))
3626 pds.key = cai.outkey;
3627 if (!pds.context && !ast_strlen_zero(cai.peercontext))
3628 pds.context = cai.peercontext;
3630 /* Keep track of the context for outgoing calls too */
3631 ast_copy_string(c->context, cai.context, sizeof(c->context));
3633 if (pds.port)
3634 sin.sin_port = htons(atoi(pds.port));
3636 l = c->cid.cid_num;
3637 n = c->cid.cid_name;
3639 /* Now build request */
3640 memset(&ied, 0, sizeof(ied));
3642 /* On new call, first IE MUST be IAX version of caller */
3643 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
3644 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
3645 if (pds.options && strchr(pds.options, 'a')) {
3646 /* Request auto answer */
3647 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
3650 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
3652 if (l) {
3653 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
3654 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3655 } else {
3656 if (n)
3657 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
3658 else
3659 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
3662 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
3663 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
3665 if (n)
3666 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
3667 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
3668 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
3670 if (!ast_strlen_zero(c->language))
3671 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
3672 if (!ast_strlen_zero(c->cid.cid_dnid))
3673 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
3674 if (!ast_strlen_zero(c->cid.cid_rdnis))
3675 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
3677 if (pds.context)
3678 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
3680 if (pds.username)
3681 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
3683 if (cai.encmethods)
3684 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
3686 ast_mutex_lock(&iaxsl[callno]);
3688 if (!ast_strlen_zero(c->context))
3689 ast_string_field_set(iaxs[callno], context, c->context);
3691 if (pds.username)
3692 ast_string_field_set(iaxs[callno], username, pds.username);
3694 iaxs[callno]->encmethods = cai.encmethods;
3696 iaxs[callno]->adsi = cai.adsi;
3698 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
3699 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
3701 if (pds.key)
3702 ast_string_field_set(iaxs[callno], outkey, pds.key);
3703 if (pds.password)
3704 ast_string_field_set(iaxs[callno], secret, pds.password);
3706 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
3707 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
3708 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
3709 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
3711 if (iaxs[callno]->maxtime) {
3712 /* Initialize pingtime and auto-congest time */
3713 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
3714 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
3715 } else if (autokill) {
3716 iaxs[callno]->pingtime = autokill / 2;
3717 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
3720 /* Check if there is an OSP token set by IAXCHANINFO function */
3721 osp_token_ptr = iaxs[callno]->osptoken;
3722 if (!ast_strlen_zero(osp_token_ptr)) {
3723 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
3724 osp_block_index = 0;
3725 while (osp_token_length > 0) {
3726 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
3727 osp_buffer[0] = osp_block_index;
3728 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
3729 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
3730 osp_block_index++;
3731 osp_token_ptr += osp_block_length;
3732 osp_token_length -= osp_block_length;
3734 } else
3735 ast_log(LOG_WARNING, "OSP token is too long\n");
3736 } else if (iaxdebug)
3737 ast_debug(1, "OSP token is undefined\n");
3739 /* send the command using the appropriate socket for this peer */
3740 iaxs[callno]->sockfd = cai.sockfd;
3742 /* Add remote vars */
3743 if (variablestore) {
3744 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
3745 AST_LIST_LOCK(variablelist);
3746 AST_LIST_TRAVERSE(variablelist, var, entries) {
3747 char tmp[256];
3748 int i;
3749 /* Automatically divide the value up into sized chunks */
3750 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
3751 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
3752 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
3755 AST_LIST_UNLOCK(variablelist);
3758 /* Transmit the string in a "NEW" request */
3759 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
3761 ast_mutex_unlock(&iaxsl[callno]);
3762 ast_setstate(c, AST_STATE_RINGING);
3764 return 0;
3767 static int iax2_hangup(struct ast_channel *c)
3769 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
3770 struct iax_ie_data ied;
3771 memset(&ied, 0, sizeof(ied));
3772 ast_mutex_lock(&iaxsl[callno]);
3773 if (callno && iaxs[callno]) {
3774 ast_debug(1, "We're hanging up %s now...\n", c->name);
3775 /* Send the hangup unless we have had a transmission error or are already gone */
3776 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
3777 if (!iaxs[callno]->error && !ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
3778 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
3779 if (!iaxs[callno]) {
3780 ast_mutex_unlock(&iaxsl[callno]);
3781 return 0;
3784 /* Explicitly predestroy it */
3785 iax2_predestroy(callno);
3786 /* If we were already gone to begin with, destroy us now */
3787 if (iaxs[callno]) {
3788 ast_debug(1, "Really destroying %s now...\n", c->name);
3789 iax2_destroy(callno);
3791 } else if (c->tech_pvt) {
3792 /* If this call no longer exists, but the channel still
3793 * references it we need to set the channel's tech_pvt to null
3794 * to avoid ast_channel_free() trying to free it.
3796 c->tech_pvt = NULL;
3798 ast_mutex_unlock(&iaxsl[callno]);
3799 ast_verb(3, "Hungup '%s'\n", c->name);
3800 return 0;
3803 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
3805 struct ast_option_header *h;
3806 int res;
3808 switch (option) {
3809 case AST_OPTION_TXGAIN:
3810 case AST_OPTION_RXGAIN:
3811 /* these two cannot be sent, because they require a result */
3812 errno = ENOSYS;
3813 return -1;
3814 default:
3815 if (!(h = ast_malloc(datalen + sizeof(*h))))
3816 return -1;
3818 h->flag = AST_OPTION_FLAG_REQUEST;
3819 h->option = htons(option);
3820 memcpy(h->data, data, datalen);
3821 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
3822 AST_CONTROL_OPTION, 0, (unsigned char *) h,
3823 datalen + sizeof(*h), -1);
3824 ast_free(h);
3825 return res;
3829 static struct ast_frame *iax2_read(struct ast_channel *c)
3831 ast_log(LOG_NOTICE, "I should never be called!\n");
3832 return &ast_null_frame;
3835 static int iax2_key_rotate(const void *vpvt)
3837 int res = 0;
3838 struct chan_iax2_pvt *pvt = (void *) vpvt;
3839 struct MD5Context md5;
3840 char key[17] = "";
3841 struct iax_ie_data ied = {
3842 .pos = 0,
3845 ast_mutex_lock(&iaxsl[pvt->callno]);
3847 pvt->keyrotateid =
3848 ast_sched_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
3850 snprintf(key, sizeof(key), "%lX", ast_random());
3852 MD5Init(&md5);
3853 MD5Update(&md5, (unsigned char *) key, strlen(key));
3854 MD5Final((unsigned char *) key, &md5);
3856 IAX_DEBUGDIGEST("Sending", key);
3858 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
3860 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
3862 ast_aes_encrypt_key((unsigned char *) key, &pvt->ecx);
3864 ast_mutex_unlock(&iaxsl[pvt->callno]);
3866 return res;
3869 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
3871 int res;
3872 struct iax_ie_data ied0;
3873 struct iax_ie_data ied1;
3874 unsigned int transferid = (unsigned int)ast_random();
3876 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
3877 ast_debug(1, "transfers are not supported for encrypted calls at this time");
3878 ast_set_flag(iaxs[callno0], IAX_NOTRANSFER);
3879 ast_set_flag(iaxs[callno1], IAX_NOTRANSFER);
3880 return 0;
3883 memset(&ied0, 0, sizeof(ied0));
3884 iaxs[callno0]->transferid = transferid;
3885 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
3886 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
3887 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
3889 memset(&ied1, 0, sizeof(ied1));
3890 iaxs[callno1]->transferid = transferid;
3891 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
3892 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
3893 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
3895 if (iaxs[callno0]->mediareleased) {
3896 res = send_command_media(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos);
3897 } else {
3898 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
3901 if (res)
3902 return -1;
3904 if (iaxs[callno1]->mediareleased)
3905 res = send_command_media(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos);
3906 else
3907 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
3909 if (res)
3910 return -1;
3911 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3912 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
3913 iaxs[callno0]->triedtransfer = 1;
3914 iaxs[callno1]->triedtransfer = 1;
3916 return 0;
3919 static void lock_both(unsigned short callno0, unsigned short callno1)
3921 ast_mutex_lock(&iaxsl[callno0]);
3922 while (ast_mutex_trylock(&iaxsl[callno1])) {
3923 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
3927 static void unlock_both(unsigned short callno0, unsigned short callno1)
3929 ast_mutex_unlock(&iaxsl[callno1]);
3930 ast_mutex_unlock(&iaxsl[callno0]);
3933 static enum ast_bridge_result iax2_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms)
3935 struct ast_channel *cs[3];
3936 struct ast_channel *who, *other;
3937 int to = -1;
3938 int res = -1;
3939 struct ast_frame *f;
3940 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
3941 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
3942 struct timeval waittimer = {0, 0};
3944 /* We currently do not support native bridging if a timeoutms value has been provided */
3945 if (timeoutms > 0) {
3946 return AST_BRIDGE_FAILED;
3949 timeoutms = 0;
3951 lock_both(callno0, callno1);
3952 if (!iaxs[callno0] || !iaxs[callno1]) {
3953 unlock_both(callno0, callno1);
3954 return AST_BRIDGE_FAILED;
3956 /* Put them in native bridge mode */
3957 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
3958 iaxs[callno0]->bridgecallno = callno1;
3959 iaxs[callno1]->bridgecallno = callno0;
3961 unlock_both(callno0, callno1);
3963 /* If not, try to bridge until we can execute a transfer, if we can */
3964 cs[0] = c0;
3965 cs[1] = c1;
3966 for (/* ever */;;) {
3967 /* Check in case we got masqueraded into */
3968 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
3969 ast_verb(3, "Can't masquerade, we're different...\n");
3970 /* Remove from native mode */
3971 if (c0->tech == &iax2_tech) {
3972 ast_mutex_lock(&iaxsl[callno0]);
3973 iaxs[callno0]->bridgecallno = 0;
3974 ast_mutex_unlock(&iaxsl[callno0]);
3976 if (c1->tech == &iax2_tech) {
3977 ast_mutex_lock(&iaxsl[callno1]);
3978 iaxs[callno1]->bridgecallno = 0;
3979 ast_mutex_unlock(&iaxsl[callno1]);
3981 return AST_BRIDGE_FAILED_NOWARN;
3983 if (c0->nativeformats != c1->nativeformats) {
3984 char buf0[255];
3985 char buf1[255];
3986 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
3987 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
3988 ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
3989 /* Remove from native mode */
3990 lock_both(callno0, callno1);
3991 if (iaxs[callno0])
3992 iaxs[callno0]->bridgecallno = 0;
3993 if (iaxs[callno1])
3994 iaxs[callno1]->bridgecallno = 0;
3995 unlock_both(callno0, callno1);
3996 return AST_BRIDGE_FAILED_NOWARN;
3998 /* check if if we really want native bridging */
3999 if (!ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
4000 if (!iaxs[callno0]->triedtransfer && !iaxs[callno1]->triedtransfer &&
4001 (iaxs[callno0]->transferring == TRANSFER_NONE) &&
4002 (iaxs[callno1]->transferring == TRANSFER_NONE)) {
4003 /* Try the transfer */
4004 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
4005 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA))) {
4006 ast_log(LOG_WARNING, "Unable to start the transfer\n");
4010 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
4011 /* Call has been transferred. We're no longer involved */
4012 struct timeval now = ast_tvnow();
4013 if (ast_tvzero(waittimer)) {
4014 waittimer = now;
4015 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
4016 c0->_softhangup |= AST_SOFTHANGUP_DEV;
4017 c1->_softhangup |= AST_SOFTHANGUP_DEV;
4018 *fo = NULL;
4019 *rc = c0;
4020 res = AST_BRIDGE_COMPLETE;
4021 break;
4024 to = 1000;
4025 who = ast_waitfor_n(cs, 2, &to);
4026 if (timeoutms > -1) {
4027 timeoutms -= (1000 - to);
4028 if (timeoutms < 0)
4029 timeoutms = 0;
4031 if (!who) {
4032 if (!timeoutms) {
4033 res = AST_BRIDGE_RETRY;
4034 break;
4036 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
4037 res = AST_BRIDGE_FAILED;
4038 break;
4040 continue;
4042 f = ast_read(who);
4043 if (!f) {
4044 *fo = NULL;
4045 *rc = who;
4046 res = AST_BRIDGE_COMPLETE;
4047 break;
4049 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
4050 *fo = f;
4051 *rc = who;
4052 res = AST_BRIDGE_COMPLETE;
4053 break;
4055 other = (who == c0) ? c1 : c0; /* the 'other' channel */
4056 if ((f->frametype == AST_FRAME_VOICE) ||
4057 (f->frametype == AST_FRAME_TEXT) ||
4058 (f->frametype == AST_FRAME_VIDEO) ||
4059 (f->frametype == AST_FRAME_IMAGE) ||
4060 (f->frametype == AST_FRAME_DTMF)) {
4061 /* monitored dtmf take out of the bridge.
4062 * check if we monitor the specific source.
4064 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
4065 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
4066 *rc = who;
4067 *fo = f;
4068 res = AST_BRIDGE_COMPLETE;
4069 /* Remove from native mode */
4070 break;
4072 /* everything else goes to the other side */
4073 ast_write(other, f);
4075 ast_frfree(f);
4076 /* Swap who gets priority */
4077 cs[2] = cs[0];
4078 cs[0] = cs[1];
4079 cs[1] = cs[2];
4081 lock_both(callno0, callno1);
4082 if(iaxs[callno0])
4083 iaxs[callno0]->bridgecallno = 0;
4084 if(iaxs[callno1])
4085 iaxs[callno1]->bridgecallno = 0;
4086 unlock_both(callno0, callno1);
4087 return res;
4090 static int iax2_answer(struct ast_channel *c)
4092 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4093 ast_debug(1, "Answering IAX2 call\n");
4094 ast_mutex_lock(&iaxsl[callno]);
4095 if (iaxs[callno])
4096 iax2_ami_channelupdate(iaxs[callno]);
4097 ast_mutex_unlock(&iaxsl[callno]);
4098 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
4101 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
4103 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4104 struct chan_iax2_pvt *pvt;
4105 int res = 0;
4107 if (iaxdebug)
4108 ast_debug(1, "Indicating condition %d\n", condition);
4110 ast_mutex_lock(&iaxsl[callno]);
4111 pvt = iaxs[callno];
4113 if (!pvt->peercallno) {
4114 /* We don't know the remote side's call number, yet. :( */
4115 int count = 10;
4116 while (count-- && pvt && !pvt->peercallno) {
4117 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
4118 pvt = iaxs[callno];
4120 if (!pvt->peercallno) {
4121 res = -1;
4122 goto done;
4126 switch (condition) {
4127 case AST_CONTROL_HOLD:
4128 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
4129 ast_moh_start(c, data, pvt->mohinterpret);
4130 goto done;
4132 break;
4133 case AST_CONTROL_UNHOLD:
4134 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
4135 ast_moh_stop(c);
4136 goto done;
4140 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
4142 done:
4143 ast_mutex_unlock(&iaxsl[callno]);
4145 return res;
4148 static int iax2_transfer(struct ast_channel *c, const char *dest)
4150 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
4151 struct iax_ie_data ied = { "", };
4152 char tmp[256], *context;
4153 ast_copy_string(tmp, dest, sizeof(tmp));
4154 context = strchr(tmp, '@');
4155 if (context) {
4156 *context = '\0';
4157 context++;
4159 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
4160 if (context)
4161 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
4162 ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
4163 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
4166 static int iax2_getpeertrunk(struct sockaddr_in sin)
4168 struct iax2_peer *peer;
4169 int res = 0;
4170 struct ao2_iterator i;
4172 i = ao2_iterator_init(peers, 0);
4173 while ((peer = ao2_iterator_next(&i))) {
4174 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
4175 (peer->addr.sin_port == sin.sin_port)) {
4176 res = ast_test_flag(peer, IAX_TRUNK);
4177 peer_unref(peer);
4178 break;
4180 peer_unref(peer);
4183 return res;
4186 /*! \brief Create new call, interface with the PBX core */
4187 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
4189 struct ast_channel *tmp;
4190 struct chan_iax2_pvt *i;
4191 struct ast_variable *v = NULL;
4193 if (!(i = iaxs[callno])) {
4194 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
4195 return NULL;
4198 /* Don't hold call lock */
4199 ast_mutex_unlock(&iaxsl[callno]);
4200 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
4201 ast_mutex_lock(&iaxsl[callno]);
4202 if (i != iaxs[callno]) {
4203 if (tmp) {
4204 /* unlock and relock iaxsl[callno] to preserve locking order */
4205 ast_mutex_unlock(&iaxsl[callno]);
4206 ast_channel_free(tmp);
4207 ast_mutex_lock(&iaxsl[callno]);
4209 return NULL;
4211 iax2_ami_channelupdate(i);
4212 if (!tmp)
4213 return NULL;
4214 tmp->tech = &iax2_tech;
4215 /* We can support any format by default, until we get restricted */
4216 tmp->nativeformats = capability;
4217 tmp->readformat = ast_best_codec(capability);
4218 tmp->writeformat = ast_best_codec(capability);
4219 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
4221 if (!ast_strlen_zero(i->parkinglot))
4222 ast_string_field_set(tmp, parkinglot, i->parkinglot);
4223 /* Don't use ast_set_callerid() here because it will
4224 * generate a NewCallerID event before the NewChannel event */
4225 if (!ast_strlen_zero(i->ani))
4226 tmp->cid.cid_ani = ast_strdup(i->ani);
4227 else
4228 tmp->cid.cid_ani = ast_strdup(i->cid_num);
4229 tmp->cid.cid_dnid = ast_strdup(i->dnid);
4230 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
4231 tmp->cid.cid_pres = i->calling_pres;
4232 tmp->cid.cid_ton = i->calling_ton;
4233 tmp->cid.cid_tns = i->calling_tns;
4234 if (!ast_strlen_zero(i->language))
4235 ast_string_field_set(tmp, language, i->language);
4236 if (!ast_strlen_zero(i->accountcode))
4237 ast_string_field_set(tmp, accountcode, i->accountcode);
4238 if (i->amaflags)
4239 tmp->amaflags = i->amaflags;
4240 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
4241 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
4242 if (i->adsi)
4243 tmp->adsicpe = i->peeradsicpe;
4244 else
4245 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
4246 i->owner = tmp;
4247 i->capability = capability;
4249 /* Set inherited variables */
4250 if (i->vars) {
4251 for (v = i->vars ; v ; v = v->next)
4252 pbx_builtin_setvar_helper(tmp, v->name, v->value);
4255 if (state != AST_STATE_DOWN) {
4256 if (ast_pbx_start(tmp)) {
4257 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
4258 ast_hangup(tmp);
4259 i->owner = NULL;
4260 return NULL;
4264 ast_module_ref(ast_module_info->self);
4265 return tmp;
4268 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
4270 unsigned long int mssincetx; /* unsigned to handle overflows */
4271 long int ms, pred;
4273 tpeer->trunkact = *now;
4274 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
4275 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
4276 /* If it's been at least 5 seconds since the last time we transmitted on this trunk, reset our timers */
4277 tpeer->txtrunktime = *now;
4278 tpeer->lastsent = 999999;
4280 /* Update last transmit time now */
4281 tpeer->lasttxtime = *now;
4283 /* Calculate ms offset */
4284 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
4285 /* Predict from last value */
4286 pred = tpeer->lastsent + sampms;
4287 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
4288 ms = pred;
4290 /* We never send the same timestamp twice, so fudge a little if we must */
4291 if (ms == tpeer->lastsent)
4292 ms = tpeer->lastsent + 1;
4293 tpeer->lastsent = ms;
4294 return ms;
4297 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
4299 long ms; /* NOT unsigned */
4300 if (ast_tvzero(iaxs[callno]->rxcore)) {
4301 /* Initialize rxcore time if appropriate */
4302 iaxs[callno]->rxcore = ast_tvnow();
4303 /* Round to nearest 20ms so traces look pretty */
4304 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
4306 /* Calculate difference between trunk and channel */
4307 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
4308 /* Return as the sum of trunk time and the difference between trunk and real time */
4309 return ms + ts;
4312 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
4314 int ms;
4315 int voice = 0;
4316 int genuine = 0;
4317 int adjust;
4318 struct timeval *delivery = NULL;
4321 /* What sort of frame do we have?: voice is self-explanatory
4322 "genuine" means an IAX frame - things like LAGRQ/RP, PING/PONG, ACK
4323 non-genuine frames are CONTROL frames [ringing etc], DTMF
4324 The "genuine" distinction is needed because genuine frames must get a clock-based timestamp,
4325 the others need a timestamp slaved to the voice frames so that they go in sequence
4327 if (f) {
4328 if (f->frametype == AST_FRAME_VOICE) {
4329 voice = 1;
4330 delivery = &f->delivery;
4331 } else if (f->frametype == AST_FRAME_IAX) {
4332 genuine = 1;
4333 } else if (f->frametype == AST_FRAME_CNG) {
4334 p->notsilenttx = 0;
4337 if (ast_tvzero(p->offset)) {
4338 p->offset = ast_tvnow();
4339 /* Round to nearest 20ms for nice looking traces */
4340 p->offset.tv_usec -= p->offset.tv_usec % 20000;
4342 /* If the timestamp is specified, just send it as is */
4343 if (ts)
4344 return ts;
4345 /* If we have a time that the frame arrived, always use it to make our timestamp */
4346 if (delivery && !ast_tvzero(*delivery)) {
4347 ms = ast_tvdiff_ms(*delivery, p->offset);
4348 if (iaxdebug)
4349 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
4350 } else {
4351 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
4352 if (ms < 0)
4353 ms = 0;
4354 if (voice) {
4355 /* On a voice frame, use predicted values if appropriate */
4356 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
4357 /* Adjust our txcore, keeping voice and non-voice synchronized */
4358 /* AN EXPLANATION:
4359 When we send voice, we usually send "calculated" timestamps worked out
4360 on the basis of the number of samples sent. When we send other frames,
4361 we usually send timestamps worked out from the real clock.
4362 The problem is that they can tend to drift out of step because the
4363 source channel's clock and our clock may not be exactly at the same rate.
4364 We fix this by continuously "tweaking" p->offset. p->offset is "time zero"
4365 for this call. Moving it adjusts timestamps for non-voice frames.
4366 We make the adjustment in the style of a moving average. Each time we
4367 adjust p->offset by 10% of the difference between our clock-derived
4368 timestamp and the predicted timestamp. That's why you see "10000"
4369 below even though IAX2 timestamps are in milliseconds.
4370 The use of a moving average avoids offset moving too radically.
4371 Generally, "adjust" roams back and forth around 0, with offset hardly
4372 changing at all. But if a consistent different starts to develop it
4373 will be eliminated over the course of 10 frames (200-300msecs)
4375 adjust = (ms - p->nextpred);
4376 if (adjust < 0)
4377 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
4378 else if (adjust > 0)
4379 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
4381 if (!p->nextpred) {
4382 p->nextpred = ms; /*f->samples / 8;*/
4383 if (p->nextpred <= p->lastsent)
4384 p->nextpred = p->lastsent + 3;
4386 ms = p->nextpred;
4387 } else {
4388 /* in this case, just use the actual
4389 * time, since we're either way off
4390 * (shouldn't happen), or we're ending a
4391 * silent period -- and seed the next
4392 * predicted time. Also, round ms to the
4393 * next multiple of frame size (so our
4394 * silent periods are multiples of
4395 * frame size too) */
4397 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
4398 ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
4399 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
4401 if (f->samples >= 8) /* check to make sure we dont core dump */
4403 int diff = ms % (f->samples / 8);
4404 if (diff)
4405 ms += f->samples/8 - diff;
4408 p->nextpred = ms;
4409 p->notsilenttx = 1;
4411 } else if ( f->frametype == AST_FRAME_VIDEO ) {
4413 * IAX2 draft 03 says that timestamps MUST be in order.
4414 * It does not say anything about several frames having the same timestamp
4415 * When transporting video, we can have a frame that spans multiple iax packets
4416 * (so called slices), so it would make sense to use the same timestamp for all of
4417 * them
4418 * We do want to make sure that frames don't go backwards though
4420 if ( (unsigned int)ms < p->lastsent )
4421 ms = p->lastsent;
4422 } else {
4423 /* On a dataframe, use last value + 3 (to accomodate jitter buffer shrinking) if appropriate unless
4424 it's a genuine frame */
4425 if (genuine) {
4426 /* genuine (IAX LAGRQ etc) must keep their clock-based stamps */
4427 if (ms <= p->lastsent)
4428 ms = p->lastsent + 3;
4429 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
4430 /* non-genuine frames (!?) (DTMF, CONTROL) should be pulled into the predicted stream stamps */
4431 ms = p->lastsent + 3;
4435 p->lastsent = ms;
4436 if (voice)
4437 p->nextpred = p->nextpred + f->samples / 8;
4438 return ms;
4441 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
4443 /* Returns where in "receive time" we are. That is, how many ms
4444 since we received (or would have received) the frame with timestamp 0 */
4445 int ms;
4446 #ifdef IAXTESTS
4447 int jit;
4448 #endif /* IAXTESTS */
4449 /* Setup rxcore if necessary */
4450 if (ast_tvzero(p->rxcore)) {
4451 p->rxcore = ast_tvnow();
4452 if (iaxdebug)
4453 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
4454 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
4455 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
4456 #if 1
4457 if (iaxdebug)
4458 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
4459 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
4460 #endif
4463 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
4464 #ifdef IAXTESTS
4465 if (test_jit) {
4466 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
4467 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
4468 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
4469 jit = -jit;
4470 ms += jit;
4473 if (test_late) {
4474 ms += test_late;
4475 test_late = 0;
4477 #endif /* IAXTESTS */
4478 return ms;
4481 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
4483 struct iax2_trunk_peer *tpeer = NULL;
4485 /* Finds and locks trunk peer */
4486 AST_LIST_LOCK(&tpeers);
4488 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
4489 if (!inaddrcmp(&tpeer->addr, sin)) {
4490 ast_mutex_lock(&tpeer->lock);
4491 break;
4495 if (!tpeer) {
4496 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
4497 ast_mutex_init(&tpeer->lock);
4498 tpeer->lastsent = 9999;
4499 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
4500 tpeer->trunkact = ast_tvnow();
4501 ast_mutex_lock(&tpeer->lock);
4502 tpeer->sockfd = fd;
4503 #ifdef SO_NO_CHECK
4504 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
4505 #endif
4506 ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
4507 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
4511 AST_LIST_UNLOCK(&tpeers);
4513 return tpeer;
4516 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
4518 struct ast_frame *f;
4519 struct iax2_trunk_peer *tpeer;
4520 void *tmp, *ptr;
4521 struct timeval now;
4522 int res;
4523 struct ast_iax2_meta_trunk_entry *met;
4524 struct ast_iax2_meta_trunk_mini *mtm;
4526 f = &fr->af;
4527 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
4528 if (tpeer) {
4529 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
4530 /* Need to reallocate space */
4531 if (tpeer->trunkdataalloc < trunkmaxsize) {
4532 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
4533 ast_mutex_unlock(&tpeer->lock);
4534 return -1;
4537 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
4538 tpeer->trunkdata = tmp;
4539 ast_debug(1, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
4540 } else {
4541 ast_log(LOG_WARNING, "Maximum trunk data space exceeded to %s:%d\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
4542 ast_mutex_unlock(&tpeer->lock);
4543 return -1;
4547 /* Append to meta frame */
4548 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
4549 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
4550 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
4551 mtm->len = htons(f->datalen);
4552 mtm->mini.callno = htons(pvt->callno);
4553 mtm->mini.ts = htons(0xffff & fr->ts);
4554 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
4555 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
4556 } else {
4557 met = (struct ast_iax2_meta_trunk_entry *)ptr;
4558 /* Store call number and length in meta header */
4559 met->callno = htons(pvt->callno);
4560 met->len = htons(f->datalen);
4561 /* Advance pointers/decrease length past trunk entry header */
4562 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
4563 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
4565 /* Copy actual trunk data */
4566 memcpy(ptr, f->data.ptr, f->datalen);
4567 tpeer->trunkdatalen += f->datalen;
4569 tpeer->calls++;
4571 /* track the largest mtu we actually have sent */
4572 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
4573 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
4575 /* if we have enough for a full MTU, ship it now without waiting */
4576 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
4577 now = ast_tvnow();
4578 res = send_trunk(tpeer, &now);
4579 trunk_untimed ++;
4582 ast_mutex_unlock(&tpeer->lock);
4584 return 0;
4587 static void build_enc_keys(const unsigned char *digest, ast_aes_encrypt_key *ecx, ast_aes_decrypt_key *dcx)
4589 ast_aes_encrypt_key(digest, ecx);
4590 ast_aes_decrypt_key(digest, dcx);
4593 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
4595 #if 0
4596 /* Debug with "fake encryption" */
4597 int x;
4598 if (len % 16)
4599 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4600 for (x=0;x<len;x++)
4601 dst[x] = src[x] ^ 0xff;
4602 #else
4603 unsigned char lastblock[16] = { 0 };
4604 int x;
4605 while(len > 0) {
4606 ast_aes_decrypt(src, dst, dcx);
4607 for (x=0;x<16;x++)
4608 dst[x] ^= lastblock[x];
4609 memcpy(lastblock, src, sizeof(lastblock));
4610 dst += 16;
4611 src += 16;
4612 len -= 16;
4614 #endif
4617 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
4619 #if 0
4620 /* Debug with "fake encryption" */
4621 int x;
4622 if (len % 16)
4623 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
4624 for (x=0;x<len;x++)
4625 dst[x] = src[x] ^ 0xff;
4626 #else
4627 unsigned char curblock[16] = { 0 };
4628 int x;
4629 while(len > 0) {
4630 for (x=0;x<16;x++)
4631 curblock[x] ^= src[x];
4632 ast_aes_encrypt(curblock, dst, ecx);
4633 memcpy(curblock, dst, sizeof(curblock));
4634 dst += 16;
4635 src += 16;
4636 len -= 16;
4638 #endif
4641 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4643 int padding;
4644 unsigned char *workspace;
4646 workspace = alloca(*datalen);
4647 memset(f, 0, sizeof(*f));
4648 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4649 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4650 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
4651 return -1;
4652 /* Decrypt */
4653 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
4655 padding = 16 + (workspace[15] & 0xf);
4656 if (iaxdebug)
4657 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
4658 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
4659 return -1;
4661 *datalen -= padding;
4662 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4663 f->frametype = fh->type;
4664 if (f->frametype == AST_FRAME_VIDEO) {
4665 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
4666 } else {
4667 f->subclass = uncompress_subclass(fh->csub);
4669 } else {
4670 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4671 if (iaxdebug)
4672 ast_debug(1, "Decoding mini with length %d\n", *datalen);
4673 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
4674 return -1;
4675 /* Decrypt */
4676 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
4677 padding = 16 + (workspace[15] & 0x0f);
4678 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
4679 return -1;
4680 *datalen -= padding;
4681 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4683 return 0;
4686 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
4688 int padding;
4689 unsigned char *workspace;
4690 workspace = alloca(*datalen + 32);
4691 if (!workspace)
4692 return -1;
4693 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
4694 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
4695 if (iaxdebug)
4696 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
4697 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
4698 padding = 16 + (padding & 0xf);
4699 memcpy(workspace, poo, padding);
4700 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
4701 workspace[15] &= 0xf0;
4702 workspace[15] |= (padding & 0xf);
4703 if (iaxdebug)
4704 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
4705 *datalen += padding;
4706 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
4707 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
4708 memcpy(poo, workspace + *datalen - 32, 32);
4709 } else {
4710 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
4711 if (iaxdebug)
4712 ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
4713 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
4714 padding = 16 + (padding & 0xf);
4715 memcpy(workspace, poo, padding);
4716 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
4717 workspace[15] &= 0xf0;
4718 workspace[15] |= (padding & 0x0f);
4719 *datalen += padding;
4720 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
4721 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
4722 memcpy(poo, workspace + *datalen - 32, 32);
4724 return 0;
4727 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
4729 int res=-1;
4730 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
4731 /* Search for possible keys, given secrets */
4732 struct MD5Context md5;
4733 unsigned char digest[16];
4734 char *tmppw, *stringp;
4736 tmppw = ast_strdupa(iaxs[callno]->secret);
4737 stringp = tmppw;
4738 while ((tmppw = strsep(&stringp, ";"))) {
4739 MD5Init(&md5);
4740 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
4741 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
4742 MD5Final(digest, &md5);
4743 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
4744 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4745 if (!res) {
4746 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
4747 break;
4750 } else
4751 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
4752 return res;
4755 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final, int media)
4757 /* Queue a packet for delivery on a given private structure. Use "ts" for
4758 timestamp, or calculate if ts is 0. Send immediately without retransmission
4759 or delayed, with retransmission */
4760 struct ast_iax2_full_hdr *fh;
4761 struct ast_iax2_mini_hdr *mh;
4762 struct ast_iax2_video_hdr *vh;
4763 struct {
4764 struct iax_frame fr2;
4765 unsigned char buffer[4096];
4766 } frb;
4767 struct iax_frame *fr;
4768 int res;
4769 int sendmini=0;
4770 unsigned int lastsent;
4771 unsigned int fts;
4773 frb.fr2.afdatalen = sizeof(frb.buffer);
4775 if (!pvt) {
4776 ast_log(LOG_WARNING, "No private structure for packet?\n");
4777 return -1;
4780 lastsent = pvt->lastsent;
4782 /* Calculate actual timestamp */
4783 fts = calc_timestamp(pvt, ts, f);
4785 /* Bail here if this is an "interp" frame; we don't want or need to send these placeholders out
4786 * (the endpoint should detect the lost packet itself). But, we want to do this here, so that we
4787 * increment the "predicted timestamps" for voice, if we're predicting */
4788 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
4789 return 0;
4790 #if 0
4791 ast_log(LOG_NOTICE,
4792 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
4793 *("=!" + (f->frametype == AST_FRAME_VOICE)),
4794 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
4795 pvt->keyrotateid != -1 ? "" : "no "
4797 #endif
4799 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
4800 if (ast_test_flag(pvt, IAX_NOKEYROTATE)) {
4801 pvt->keyrotateid = -2;
4802 } else {
4803 iax2_key_rotate(pvt);
4807 if ((ast_test_flag(pvt, IAX_TRUNK) ||
4808 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
4809 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
4810 /* High two bytes are the same on timestamp, or sending on a trunk */ &&
4811 (f->frametype == AST_FRAME_VOICE)
4812 /* is a voice frame */ &&
4813 (f->subclass == pvt->svoiceformat)
4814 /* is the same type */ ) {
4815 /* Force immediate rather than delayed transmission */
4816 now = 1;
4817 /* Mark that mini-style frame is appropriate */
4818 sendmini = 1;
4820 if ( f->frametype == AST_FRAME_VIDEO ) {
4822 * If the lower 15 bits of the timestamp roll over, or if
4823 * the video format changed then send a full frame.
4824 * Otherwise send a mini video frame
4826 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
4827 ((f->subclass & ~0x1) == pvt->svideoformat)
4829 now = 1;
4830 sendmini = 1;
4831 } else {
4832 now = 0;
4833 sendmini = 0;
4835 pvt->lastvsent = fts;
4837 /* Allocate an iax_frame */
4838 if (now) {
4839 fr = &frb.fr2;
4840 } else
4841 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
4842 if (!fr) {
4843 ast_log(LOG_WARNING, "Out of memory\n");
4844 return -1;
4846 /* Copy our prospective frame into our immediate or retransmitted wrapper */
4847 iax_frame_wrap(fr, f);
4849 fr->ts = fts;
4850 fr->callno = pvt->callno;
4851 fr->transfer = transfer;
4852 fr->media = media;
4853 fr->final = final;
4854 if (!sendmini) {
4855 /* We need a full frame */
4856 if (seqno > -1)
4857 fr->oseqno = seqno;
4858 else
4859 fr->oseqno = pvt->oseqno++;
4860 fr->iseqno = pvt->iseqno;
4861 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
4862 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
4863 fh->ts = htonl(fr->ts);
4864 fh->oseqno = fr->oseqno;
4865 if (transfer || media) {
4866 fh->iseqno = 0;
4867 } else
4868 fh->iseqno = fr->iseqno;
4869 /* Keep track of the last thing we've acknowledged */
4870 if (!transfer || media)
4871 pvt->aseqno = fr->iseqno;
4872 fh->type = fr->af.frametype & 0xFF;
4873 if (fr->af.frametype == AST_FRAME_VIDEO)
4874 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
4875 else
4876 fh->csub = compress_subclass(fr->af.subclass);
4877 if (transfer) {
4878 fr->dcallno = pvt->transfercallno;
4879 } else
4880 fr->dcallno = pvt->peercallno;
4881 fh->dcallno = htons(fr->dcallno);
4882 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
4883 fr->data = fh;
4884 fr->retries = 0;
4885 /* Retry after 2x the ping time has passed */
4886 fr->retrytime = pvt->pingtime * 2;
4887 if (fr->retrytime < MIN_RETRY_TIME)
4888 fr->retrytime = MIN_RETRY_TIME;
4889 if (fr->retrytime > MAX_RETRY_TIME)
4890 fr->retrytime = MAX_RETRY_TIME;
4891 /* Acks' don't get retried */
4892 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
4893 fr->retries = -1;
4894 else if (f->frametype == AST_FRAME_VOICE)
4895 pvt->svoiceformat = f->subclass;
4896 else if (f->frametype == AST_FRAME_VIDEO)
4897 pvt->svideoformat = f->subclass & ~0x1;
4898 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4899 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4900 if (fr->transfer)
4901 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4902 else if (fr->media)
4903 iax_outputframe(fr, NULL, 2, &pvt->media, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4904 else
4905 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
4906 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
4907 } else
4908 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4911 if (now) {
4912 res = send_packet(fr);
4913 } else
4914 res = iax2_transmit(fr);
4915 } else {
4916 if (ast_test_flag(pvt, IAX_TRUNK)) {
4917 iax2_trunk_queue(pvt, fr);
4918 res = 0;
4919 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
4920 /* Video frame have no sequence number */
4921 fr->oseqno = -1;
4922 fr->iseqno = -1;
4923 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
4924 vh->zeros = 0;
4925 vh->callno = htons(0x8000 | fr->callno);
4926 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
4927 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
4928 fr->data = vh;
4929 fr->retries = -1;
4930 if (pvt->mediareleased) {
4931 fr->media = 1;
4933 res = send_packet(fr);
4934 } else {
4935 /* Mini-frames have no sequence number */
4936 fr->oseqno = -1;
4937 fr->iseqno = -1;
4938 /* Mini frame will do */
4939 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
4940 mh->callno = htons(fr->callno);
4941 mh->ts = htons(fr->ts & 0xFFFF);
4942 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
4943 fr->data = mh;
4944 fr->retries = -1;
4945 if (pvt->mediareleased) {
4946 fr->media = 1;
4948 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
4949 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
4950 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
4951 } else
4952 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
4954 res = send_packet(fr);
4957 return res;
4960 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4962 regex_t regexbuf;
4963 int havepattern = 0;
4965 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
4966 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
4968 struct iax2_user *user = NULL;
4969 char auth[90];
4970 char *pstr = "";
4971 struct ao2_iterator i;
4973 switch (cmd) {
4974 case CLI_INIT:
4975 e->command = "iax2 show users [like]";
4976 e->usage =
4977 "Usage: iax2 show users [like <pattern>]\n"
4978 " Lists all known IAX2 users.\n"
4979 " Optional regular expression pattern is used to filter the user list.\n";
4980 return NULL;
4981 case CLI_GENERATE:
4982 return NULL;
4985 switch (a->argc) {
4986 case 5:
4987 if (!strcasecmp(a->argv[3], "like")) {
4988 if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
4989 return CLI_SHOWUSAGE;
4990 havepattern = 1;
4991 } else
4992 return CLI_SHOWUSAGE;
4993 case 3:
4994 break;
4995 default:
4996 return CLI_SHOWUSAGE;
4999 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
5000 i = ao2_iterator_init(users, 0);
5001 for (user = ao2_iterator_next(&i); user;
5002 user_unref(user), user = ao2_iterator_next(&i)) {
5003 if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0))
5004 continue;
5006 if (!ast_strlen_zero(user->secret)) {
5007 ast_copy_string(auth,user->secret, sizeof(auth));
5008 } else if (!ast_strlen_zero(user->inkeys)) {
5009 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
5010 } else
5011 ast_copy_string(auth, "-no secret-", sizeof(auth));
5013 if(ast_test_flag(user,IAX_CODEC_NOCAP))
5014 pstr = "REQ Only";
5015 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
5016 pstr = "Disabled";
5017 else
5018 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
5020 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
5021 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
5022 user->ha ? "Yes" : "No", pstr);
5025 if (havepattern)
5026 regfree(&regexbuf);
5028 return CLI_SUCCESS;
5029 #undef FORMAT
5030 #undef FORMAT2
5033 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
5035 regex_t regexbuf;
5036 int havepattern = 0;
5037 int total_peers = 0;
5038 int online_peers = 0;
5039 int offline_peers = 0;
5040 int unmonitored_peers = 0;
5041 struct ao2_iterator i;
5043 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
5044 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
5046 struct iax2_peer *peer = NULL;
5047 char name[256];
5048 int registeredonly=0;
5049 char *term = manager ? "\r\n" : "\n";
5050 char idtext[256] = "";
5051 switch (argc) {
5052 case 6:
5053 if (!strcasecmp(argv[3], "registered"))
5054 registeredonly = 1;
5055 else
5056 return RESULT_SHOWUSAGE;
5057 if (!strcasecmp(argv[4], "like")) {
5058 if (regcomp(&regexbuf, argv[5], REG_EXTENDED | REG_NOSUB))
5059 return RESULT_SHOWUSAGE;
5060 havepattern = 1;
5061 } else
5062 return RESULT_SHOWUSAGE;
5063 break;
5064 case 5:
5065 if (!strcasecmp(argv[3], "like")) {
5066 if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
5067 return RESULT_SHOWUSAGE;
5068 havepattern = 1;
5069 } else
5070 return RESULT_SHOWUSAGE;
5071 break;
5072 case 4:
5073 if (!strcasecmp(argv[3], "registered"))
5074 registeredonly = 1;
5075 else
5076 return RESULT_SHOWUSAGE;
5077 break;
5078 case 3:
5079 break;
5080 default:
5081 return RESULT_SHOWUSAGE;
5085 if (!s)
5086 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
5088 i = ao2_iterator_init(peers, 0);
5089 for (peer = ao2_iterator_next(&i); peer;
5090 peer_unref(peer), peer = ao2_iterator_next(&i)) {
5091 char nm[20];
5092 char status[20];
5093 char srch[2000];
5094 int retstatus;
5096 if (registeredonly && !peer->addr.sin_addr.s_addr)
5097 continue;
5098 if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0))
5099 continue;
5101 if (!ast_strlen_zero(peer->username))
5102 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
5103 else
5104 ast_copy_string(name, peer->name, sizeof(name));
5106 retstatus = peer_status(peer, status, sizeof(status));
5107 if (retstatus > 0)
5108 online_peers++;
5109 else if (!retstatus)
5110 offline_peers++;
5111 else
5112 unmonitored_peers++;
5114 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
5116 snprintf(srch, sizeof(srch), FORMAT, name,
5117 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
5118 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
5120 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
5121 peer->encmethods ? "(E)" : " ", status, term);
5123 if (s)
5124 astman_append(s,
5125 "Event: PeerEntry\r\n%s"
5126 "Channeltype: IAX2\r\n"
5127 "ChanObjectType: peer\r\n"
5128 "ObjectName: %s\r\n"
5129 "IPaddress: %s\r\n"
5130 "IPport: %d\r\n"
5131 "Dynamic: %s\r\n"
5132 "Status: %s\r\n\r\n",
5133 idtext,
5134 name,
5135 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
5136 ntohs(peer->addr.sin_port),
5137 ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no",
5138 status);
5140 else
5141 ast_cli(fd, FORMAT, name,
5142 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
5143 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
5145 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
5146 peer->encmethods ? "(E)" : " ", status, term);
5147 total_peers++;
5150 if (!s)
5151 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
5153 if (havepattern)
5154 regfree(&regexbuf);
5156 return RESULT_SUCCESS;
5157 #undef FORMAT
5158 #undef FORMAT2
5161 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5163 struct iax2_thread *thread = NULL;
5164 time_t t;
5165 int threadcount = 0, dynamiccount = 0;
5166 char type;
5168 switch (cmd) {
5169 case CLI_INIT:
5170 e->command = "iax2 show threads";
5171 e->usage =
5172 "Usage: iax2 show threads\n"
5173 " Lists status of IAX helper threads\n";
5174 return NULL;
5175 case CLI_GENERATE:
5176 return NULL;
5178 if (a->argc != 3)
5179 return CLI_SHOWUSAGE;
5181 ast_cli(a->fd, "IAX2 Thread Information\n");
5182 time(&t);
5183 ast_cli(a->fd, "Idle Threads:\n");
5184 AST_LIST_LOCK(&idle_list);
5185 AST_LIST_TRAVERSE(&idle_list, thread, list) {
5186 #ifdef DEBUG_SCHED_MULTITHREAD
5187 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
5188 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
5189 #else
5190 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
5191 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
5192 #endif
5193 threadcount++;
5195 AST_LIST_UNLOCK(&idle_list);
5196 ast_cli(a->fd, "Active Threads:\n");
5197 AST_LIST_LOCK(&active_list);
5198 AST_LIST_TRAVERSE(&active_list, thread, list) {
5199 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
5200 type = 'D';
5201 else
5202 type = 'P';
5203 #ifdef DEBUG_SCHED_MULTITHREAD
5204 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
5205 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
5206 #else
5207 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
5208 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
5209 #endif
5210 threadcount++;
5212 AST_LIST_UNLOCK(&active_list);
5213 ast_cli(a->fd, "Dynamic Threads:\n");
5214 AST_LIST_LOCK(&dynamic_list);
5215 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
5216 #ifdef DEBUG_SCHED_MULTITHREAD
5217 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
5218 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
5219 #else
5220 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
5221 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
5222 #endif
5223 dynamiccount++;
5225 AST_LIST_UNLOCK(&dynamic_list);
5226 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
5227 return CLI_SUCCESS;
5230 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5232 struct iax2_peer *p;
5234 switch (cmd) {
5235 case CLI_INIT:
5236 e->command = "iax2 unregister";
5237 e->usage =
5238 "Usage: iax2 unregister <peername>\n"
5239 " Unregister (force expiration) an IAX2 peer from the registry.\n";
5240 return NULL;
5241 case CLI_GENERATE:
5242 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
5245 if (a->argc != 3)
5246 return CLI_SHOWUSAGE;
5248 p = find_peer(a->argv[2], 1);
5249 if (p) {
5250 if (p->expire > 0) {
5251 struct iax2_peer tmp_peer = {
5252 .name = a->argv[2],
5254 struct iax2_peer *peer;
5256 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
5257 if (peer) {
5258 expire_registry(peer_ref(peer)); /* will release its own reference when done */
5259 peer_unref(peer); /* ref from ao2_find() */
5260 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
5261 } else {
5262 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
5264 } else {
5265 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
5267 } else {
5268 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
5270 return CLI_SUCCESS;
5273 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
5275 int which = 0;
5276 struct iax2_peer *p = NULL;
5277 char *res = NULL;
5278 int wordlen = strlen(word);
5280 /* 0 - iax2; 1 - unregister; 2 - <peername> */
5281 if (pos == 2) {
5282 struct ao2_iterator i = ao2_iterator_init(peers, 0);
5283 while ((p = ao2_iterator_next(&i))) {
5284 if (!strncasecmp(p->name, word, wordlen) &&
5285 ++which > state && p->expire > 0) {
5286 res = ast_strdup(p->name);
5287 peer_unref(p);
5288 break;
5290 peer_unref(p);
5294 return res;
5297 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5299 switch (cmd) {
5300 case CLI_INIT:
5301 e->command = "iax2 show peers";
5302 e->usage =
5303 "Usage: iax2 show peers [registered] [like <pattern>]\n"
5304 " Lists all known IAX2 peers.\n"
5305 " Optional 'registered' argument lists only peers with known addresses.\n"
5306 " Optional regular expression pattern is used to filter the peer list.\n";
5307 return NULL;
5308 case CLI_GENERATE:
5309 return NULL;
5312 switch (__iax2_show_peers(0, a->fd, NULL, a->argc, a->argv)) {
5313 case RESULT_SHOWUSAGE:
5314 return CLI_SHOWUSAGE;
5315 case RESULT_FAILURE:
5316 return CLI_FAILURE;
5317 default:
5318 return CLI_SUCCESS;
5322 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
5324 ast_cli_netstats(s, -1, 0);
5325 astman_append(s, "\r\n");
5326 return RESULT_SUCCESS;
5329 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5331 struct iax_firmware *cur = NULL;
5333 switch (cmd) {
5334 case CLI_INIT:
5335 e->command = "iax2 show firmware";
5336 e->usage =
5337 "Usage: iax2 show firmware\n"
5338 " Lists all known IAX firmware images.\n";
5339 return NULL;
5340 case CLI_GENERATE:
5341 return NULL;
5344 if (a->argc != 3 && a->argc != 4)
5345 return CLI_SHOWUSAGE;
5347 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
5348 AST_LIST_LOCK(&firmwares);
5349 AST_LIST_TRAVERSE(&firmwares, cur, list) {
5350 if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
5351 ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
5352 ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
5355 AST_LIST_UNLOCK(&firmwares);
5357 return CLI_SUCCESS;
5360 /*! \brief callback to display iax peers in manager */
5361 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
5363 char *a[] = { "iax2", "show", "users" };
5364 const char *id = astman_get_header(m,"ActionID");
5365 char idtext[256] = "";
5367 if (!ast_strlen_zero(id))
5368 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
5369 astman_send_ack(s, m, "Peer status list will follow");
5370 return __iax2_show_peers(1, -1, s, 3, a );
5373 /*! \brief callback to display iax peers in manager format */
5374 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
5376 struct iax2_peer *peer = NULL;
5377 int peer_count = 0;
5378 char nm[20];
5379 char status[20];
5380 const char *id = astman_get_header(m,"ActionID");
5381 char idtext[256] = "";
5382 struct ao2_iterator i;
5384 if (!ast_strlen_zero(id))
5385 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
5387 astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
5390 i = ao2_iterator_init(peers, 0);
5391 for (peer = ao2_iterator_next(&i); peer; peer_unref(peer), peer = ao2_iterator_next(&i)) {
5393 astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
5394 if (!ast_strlen_zero(peer->username)) {
5395 astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
5396 } else {
5397 astman_append(s, "ObjectName: %s\r\n", peer->name);
5399 astman_append(s, "ChanObjectType: peer\r\n");
5400 astman_append(s, "IPaddress: %s\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-");
5401 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
5402 astman_append(s, "Mask: %s\r\n", nm);
5403 astman_append(s, "Port: %d\r\n", ntohs(peer->addr.sin_port));
5404 astman_append(s, "Dynamic: %s\r\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
5405 peer_status(peer, status, sizeof(status));
5406 astman_append(s, "Status: %s\r\n\r\n", status);
5407 peer_count++;
5410 astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
5411 return RESULT_SUCCESS;
5415 static char *regstate2str(int regstate)
5417 switch(regstate) {
5418 case REG_STATE_UNREGISTERED:
5419 return "Unregistered";
5420 case REG_STATE_REGSENT:
5421 return "Request Sent";
5422 case REG_STATE_AUTHSENT:
5423 return "Auth. Sent";
5424 case REG_STATE_REGISTERED:
5425 return "Registered";
5426 case REG_STATE_REJECTED:
5427 return "Rejected";
5428 case REG_STATE_TIMEOUT:
5429 return "Timeout";
5430 case REG_STATE_NOAUTH:
5431 return "No Authentication";
5432 default:
5433 return "Unknown";
5437 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5439 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
5440 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
5441 struct iax2_registry *reg = NULL;
5442 char host[80];
5443 char perceived[80];
5444 int counter = 0;
5446 switch (cmd) {
5447 case CLI_INIT:
5448 e->command = "iax2 show registry";
5449 e->usage =
5450 "Usage: iax2 show registry\n"
5451 " Lists all registration requests and status.\n";
5452 return NULL;
5453 case CLI_GENERATE:
5454 return NULL;
5456 if (a->argc != 3)
5457 return CLI_SHOWUSAGE;
5458 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
5459 AST_LIST_LOCK(&registrations);
5460 AST_LIST_TRAVERSE(&registrations, reg, entry) {
5461 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
5462 if (reg->us.sin_addr.s_addr)
5463 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
5464 else
5465 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
5466 ast_cli(a->fd, FORMAT, host,
5467 (reg->dnsmgr) ? "Y" : "N",
5468 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
5469 counter++;
5471 AST_LIST_UNLOCK(&registrations);
5472 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
5473 return CLI_SUCCESS;
5474 #undef FORMAT
5475 #undef FORMAT2
5478 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5480 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
5481 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s\n"
5482 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
5483 int x;
5484 int numchans = 0;
5486 switch (cmd) {
5487 case CLI_INIT:
5488 e->command = "iax2 show channels";
5489 e->usage =
5490 "Usage: iax2 show channels\n"
5491 " Lists all currently active IAX channels.\n";
5492 return NULL;
5493 case CLI_GENERATE:
5494 return NULL;
5497 if (a->argc != 3)
5498 return CLI_SHOWUSAGE;
5499 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
5500 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
5501 ast_mutex_lock(&iaxsl[x]);
5502 if (iaxs[x]) {
5503 int lag, jitter, localdelay;
5504 jb_info jbinfo;
5506 if (ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
5507 jb_getinfo(iaxs[x]->jb, &jbinfo);
5508 jitter = jbinfo.jitter;
5509 localdelay = jbinfo.current - jbinfo.min;
5510 } else {
5511 jitter = -1;
5512 localdelay = 0;
5514 lag = iaxs[x]->remote_rr.delay;
5515 ast_cli(a->fd, FORMAT,
5516 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
5517 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
5518 S_OR(iaxs[x]->username, "(None)"),
5519 iaxs[x]->callno, iaxs[x]->peercallno,
5520 iaxs[x]->oseqno, iaxs[x]->iseqno,
5521 lag,
5522 jitter,
5523 localdelay,
5524 ast_getformatname(iaxs[x]->voiceformat) );
5525 numchans++;
5527 ast_mutex_unlock(&iaxsl[x]);
5529 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
5530 return CLI_SUCCESS;
5531 #undef FORMAT
5532 #undef FORMAT2
5533 #undef FORMATB
5536 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
5538 int x;
5539 int numchans = 0;
5540 #define ACN_FORMAT1 "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n"
5541 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n"
5542 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
5543 ast_mutex_lock(&iaxsl[x]);
5544 if (iaxs[x]) {
5545 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
5546 jb_info jbinfo;
5548 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
5549 jb_getinfo(iaxs[x]->jb, &jbinfo);
5550 localjitter = jbinfo.jitter;
5551 localdelay = jbinfo.current - jbinfo.min;
5552 locallost = jbinfo.frames_lost;
5553 locallosspct = jbinfo.losspct/1000;
5554 localdropped = jbinfo.frames_dropped;
5555 localooo = jbinfo.frames_ooo;
5556 } else {
5557 localjitter = -1;
5558 localdelay = 0;
5559 locallost = -1;
5560 locallosspct = -1;
5561 localdropped = 0;
5562 localooo = -1;
5564 if (s)
5566 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
5567 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
5568 iaxs[x]->pingtime,
5569 localjitter,
5570 localdelay,
5571 locallost,
5572 locallosspct,
5573 localdropped,
5574 localooo,
5575 iaxs[x]->frames_received/1000,
5576 iaxs[x]->remote_rr.jitter,
5577 iaxs[x]->remote_rr.delay,
5578 iaxs[x]->remote_rr.losscnt,
5579 iaxs[x]->remote_rr.losspct,
5580 iaxs[x]->remote_rr.dropped,
5581 iaxs[x]->remote_rr.ooo,
5582 iaxs[x]->remote_rr.packets/1000);
5583 else
5584 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
5585 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
5586 iaxs[x]->pingtime,
5587 localjitter,
5588 localdelay,
5589 locallost,
5590 locallosspct,
5591 localdropped,
5592 localooo,
5593 iaxs[x]->frames_received/1000,
5594 iaxs[x]->remote_rr.jitter,
5595 iaxs[x]->remote_rr.delay,
5596 iaxs[x]->remote_rr.losscnt,
5597 iaxs[x]->remote_rr.losspct,
5598 iaxs[x]->remote_rr.dropped,
5599 iaxs[x]->remote_rr.ooo,
5600 iaxs[x]->remote_rr.packets/1000
5602 numchans++;
5604 ast_mutex_unlock(&iaxsl[x]);
5607 return numchans;
5610 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5612 int numchans = 0;
5614 switch (cmd) {
5615 case CLI_INIT:
5616 e->command = "iax2 show netstats";
5617 e->usage =
5618 "Usage: iax2 show netstats\n"
5619 " Lists network status for all currently active IAX channels.\n";
5620 return NULL;
5621 case CLI_GENERATE:
5622 return NULL;
5624 if (a->argc != 3)
5625 return CLI_SHOWUSAGE;
5626 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
5627 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
5628 numchans = ast_cli_netstats(NULL, a->fd, 1);
5629 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
5630 return CLI_SUCCESS;
5635 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5637 switch (cmd) {
5638 case CLI_INIT:
5639 e->command = "iax2 set debug {on|off|peer}";
5640 e->usage =
5641 "Usage: iax2 set debug {on|off|peer peername}\n"
5642 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
5643 return NULL;
5644 case CLI_GENERATE:
5645 if (a->pos == 4)
5646 return complete_iax2_peers(a->line, a->word, a->pos, a->n);
5647 return NULL;
5650 if (a->argc < e->args || a->argc > e->args + 1)
5651 return CLI_SHOWUSAGE;
5653 if (!strcasecmp(a->argv[3], "peer")) {
5654 struct iax2_peer *peer;
5656 if (a->argc != e->args + 1)
5657 return CLI_SHOWUSAGE;
5659 peer = find_peer(a->argv[4], 1);
5661 if (!peer) {
5662 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
5663 return CLI_FAILURE;
5666 debugaddr.sin_addr = peer->addr.sin_addr;
5667 debugaddr.sin_port = peer->addr.sin_port;
5669 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
5670 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
5672 ao2_ref(peer, -1);
5673 } else if (!strncasecmp(a->argv[3], "on", 2)) {
5674 iaxdebug = 1;
5675 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
5676 } else {
5677 iaxdebug = 0;
5678 memset(&debugaddr, 0, sizeof(debugaddr));
5679 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
5681 return CLI_SUCCESS;
5684 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5686 switch (cmd) {
5687 case CLI_INIT:
5688 e->command = "iax2 set debug trunk {on|off}";
5689 e->usage =
5690 "Usage: iax2 set debug trunk {on|off}\n"
5691 " Enables/Disables debugging of IAX trunking\n";
5692 return NULL;
5693 case CLI_GENERATE:
5694 return NULL;
5697 if (a->argc != e->args)
5698 return CLI_SHOWUSAGE;
5700 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
5701 iaxtrunkdebug = 1;
5702 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
5703 } else {
5704 iaxtrunkdebug = 0;
5705 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
5707 return CLI_SUCCESS;
5710 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
5712 switch (cmd) {
5713 case CLI_INIT:
5714 e->command = "iax2 set debug jb {on|off}";
5715 e->usage =
5716 "Usage: iax2 set debug jb {on|off}\n"
5717 " Enables/Disables jitterbuffer debugging information\n";
5718 return NULL;
5719 case CLI_GENERATE:
5720 return NULL;
5723 if (a->argc != e->args)
5724 return CLI_SHOWUSAGE;
5726 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
5727 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
5728 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
5729 } else {
5730 jb_setoutput(jb_error_output, jb_warning_output, NULL);
5731 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
5733 return CLI_SUCCESS;
5736 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
5738 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
5739 int res = -1;
5740 ast_mutex_lock(&iaxsl[callno]);
5741 if (iaxs[callno]) {
5742 /* If there's an outstanding error, return failure now */
5743 if (!iaxs[callno]->error) {
5744 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
5745 res = 0;
5746 /* Don't waste bandwidth sending null frames */
5747 else if (f->frametype == AST_FRAME_NULL)
5748 res = 0;
5749 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
5750 res = 0;
5751 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
5752 res = 0;
5753 else
5754 /* Simple, just queue for transmission */
5755 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0, 0);
5756 } else {
5757 ast_debug(1, "Write error: %s\n", strerror(errno));
5760 /* If it's already gone, just return */
5761 ast_mutex_unlock(&iaxsl[callno]);
5762 return res;
5765 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
5766 int now, int transfer, int final, int media)
5768 struct ast_frame f = { 0, };
5770 f.frametype = type;
5771 f.subclass = command;
5772 f.datalen = datalen;
5773 f.src = __FUNCTION__;
5774 f.data.ptr = (void *) data;
5776 return iax2_send(i, &f, ts, seqno, now, transfer, final, media);
5779 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5781 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0, 0);
5784 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5786 int res;
5787 ast_mutex_lock(&iaxsl[callno]);
5788 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
5789 ast_mutex_unlock(&iaxsl[callno]);
5790 return res;
5794 * \note Since this function calls iax2_predestroy() -> iax2_queue_hangup(),
5795 * the pvt struct for the given call number may disappear during its
5796 * execution.
5798 static int send_command_final(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5800 int call_num = i->callno;
5801 /* It is assumed that the callno has already been locked */
5802 iax2_predestroy(i->callno);
5803 if (!iaxs[call_num])
5804 return -1;
5805 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1, 0);
5808 static int send_command_immediate(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
5810 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0, 0);
5813 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
5815 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0, 0);
5818 static int send_command_media(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
5820 return __send_command(i, type, command, ts, data, datalen, 0, 0, 0, 0, 1);
5823 static int apply_context(struct iax2_context *con, const char *context)
5825 while(con) {
5826 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
5827 return -1;
5828 con = con->next;
5830 return 0;
5834 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
5836 /* Start pessimistic */
5837 int res = -1;
5838 int version = 2;
5839 struct iax2_user *user = NULL, *best = NULL;
5840 int bestscore = 0;
5841 int gotcapability = 0;
5842 struct ast_variable *v = NULL, *tmpvar = NULL;
5843 struct ao2_iterator i;
5845 if (!iaxs[callno])
5846 return res;
5847 if (ies->called_number)
5848 ast_string_field_set(iaxs[callno], exten, ies->called_number);
5849 if (ies->calling_number) {
5850 ast_shrink_phone_number(ies->calling_number);
5851 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
5853 if (ies->calling_name)
5854 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
5855 if (ies->calling_ani)
5856 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
5857 if (ies->dnid)
5858 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
5859 if (ies->rdnis)
5860 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
5861 if (ies->called_context)
5862 ast_string_field_set(iaxs[callno], context, ies->called_context);
5863 if (ies->language)
5864 ast_string_field_set(iaxs[callno], language, ies->language);
5865 if (ies->username)
5866 ast_string_field_set(iaxs[callno], username, ies->username);
5867 if (ies->calling_ton > -1)
5868 iaxs[callno]->calling_ton = ies->calling_ton;
5869 if (ies->calling_tns > -1)
5870 iaxs[callno]->calling_tns = ies->calling_tns;
5871 if (ies->calling_pres > -1)
5872 iaxs[callno]->calling_pres = ies->calling_pres;
5873 if (ies->format)
5874 iaxs[callno]->peerformat = ies->format;
5875 if (ies->adsicpe)
5876 iaxs[callno]->peeradsicpe = ies->adsicpe;
5877 if (ies->capability) {
5878 gotcapability = 1;
5879 iaxs[callno]->peercapability = ies->capability;
5881 if (ies->version)
5882 version = ies->version;
5884 /* Use provided preferences until told otherwise for actual preferences */
5885 if(ies->codec_prefs) {
5886 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
5887 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
5890 if (!gotcapability)
5891 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
5892 if (version > IAX_PROTO_VERSION) {
5893 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
5894 ast_inet_ntoa(sin->sin_addr), version);
5895 return res;
5897 /* Search the userlist for a compatible entry, and fill in the rest */
5898 i = ao2_iterator_init(users, 0);
5899 while ((user = ao2_iterator_next(&i))) {
5900 if ((ast_strlen_zero(iaxs[callno]->username) || /* No username specified */
5901 !strcmp(iaxs[callno]->username, user->name)) /* Or this username specified */
5902 && ast_apply_ha(user->ha, sin) /* Access is permitted from this IP */
5903 && (ast_strlen_zero(iaxs[callno]->context) || /* No context specified */
5904 apply_context(user->contexts, iaxs[callno]->context))) { /* Context is permitted */
5905 if (!ast_strlen_zero(iaxs[callno]->username)) {
5906 /* Exact match, stop right now. */
5907 if (best)
5908 user_unref(best);
5909 best = user;
5910 break;
5911 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
5912 /* No required authentication */
5913 if (user->ha) {
5914 /* There was host authentication and we passed, bonus! */
5915 if (bestscore < 4) {
5916 bestscore = 4;
5917 if (best)
5918 user_unref(best);
5919 best = user;
5920 continue;
5922 } else {
5923 /* No host access, but no secret, either, not bad */
5924 if (bestscore < 3) {
5925 bestscore = 3;
5926 if (best)
5927 user_unref(best);
5928 best = user;
5929 continue;
5932 } else {
5933 if (user->ha) {
5934 /* Authentication, but host access too, eh, it's something.. */
5935 if (bestscore < 2) {
5936 bestscore = 2;
5937 if (best)
5938 user_unref(best);
5939 best = user;
5940 continue;
5942 } else {
5943 /* Authentication and no host access... This is our baseline */
5944 if (bestscore < 1) {
5945 bestscore = 1;
5946 if (best)
5947 user_unref(best);
5948 best = user;
5949 continue;
5954 user_unref(user);
5956 user = best;
5957 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
5958 user = realtime_user(iaxs[callno]->username, sin);
5959 if (user && !ast_strlen_zero(iaxs[callno]->context) && /* No context specified */
5960 !apply_context(user->contexts, iaxs[callno]->context)) { /* Context is permitted */
5961 user = user_unref(user);
5964 if (user) {
5965 /* We found our match (use the first) */
5966 /* copy vars */
5967 for (v = user->vars ; v ; v = v->next) {
5968 if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
5969 tmpvar->next = iaxs[callno]->vars;
5970 iaxs[callno]->vars = tmpvar;
5973 /* If a max AUTHREQ restriction is in place, activate it */
5974 if (user->maxauthreq > 0)
5975 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
5976 iaxs[callno]->prefs = user->prefs;
5977 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
5978 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
5979 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
5980 ast_copy_flags(iaxs[callno], user, IAX_NOKEYROTATE);
5981 iaxs[callno]->encmethods = user->encmethods;
5982 /* Store the requested username if not specified */
5983 if (ast_strlen_zero(iaxs[callno]->username))
5984 ast_string_field_set(iaxs[callno], username, user->name);
5985 /* Store whether this is a trunked call, too, of course, and move if appropriate */
5986 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
5987 iaxs[callno]->capability = user->capability;
5988 /* And use the default context */
5989 if (ast_strlen_zero(iaxs[callno]->context)) {
5990 if (user->contexts)
5991 ast_string_field_set(iaxs[callno], context, user->contexts->context);
5992 else
5993 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
5995 /* And any input keys */
5996 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
5997 /* And the permitted authentication methods */
5998 iaxs[callno]->authmethods = user->authmethods;
5999 iaxs[callno]->adsi = user->adsi;
6000 /* If the user has callerid, override the remote caller id. */
6001 if (ast_test_flag(user, IAX_HASCALLERID)) {
6002 iaxs[callno]->calling_tns = 0;
6003 iaxs[callno]->calling_ton = 0;
6004 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
6005 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
6006 ast_string_field_set(iaxs[callno], ani, user->cid_num);
6007 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
6008 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
6009 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
6010 } /* else user is allowed to set their own CID settings */
6011 if (!ast_strlen_zero(user->accountcode))
6012 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
6013 if (!ast_strlen_zero(user->mohinterpret))
6014 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
6015 if (!ast_strlen_zero(user->mohsuggest))
6016 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
6017 if (!ast_strlen_zero(user->parkinglot))
6018 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
6019 if (user->amaflags)
6020 iaxs[callno]->amaflags = user->amaflags;
6021 if (!ast_strlen_zero(user->language))
6022 ast_string_field_set(iaxs[callno], language, user->language);
6023 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
6024 /* Keep this check last */
6025 if (!ast_strlen_zero(user->dbsecret)) {
6026 char *family, *key=NULL;
6027 char buf[80];
6028 family = ast_strdupa(user->dbsecret);
6029 key = strchr(family, '/');
6030 if (key) {
6031 *key = '\0';
6032 key++;
6034 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
6035 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
6036 else
6037 ast_string_field_set(iaxs[callno], secret, buf);
6038 } else
6039 ast_string_field_set(iaxs[callno], secret, user->secret);
6040 res = 0;
6041 user = user_unref(user);
6043 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
6044 return res;
6047 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
6049 struct ast_iax2_full_hdr fh;
6050 fh.scallno = htons(src | IAX_FLAG_FULL);
6051 fh.dcallno = htons(dst);
6052 fh.ts = 0;
6053 fh.oseqno = 0;
6054 fh.iseqno = 0;
6055 fh.type = AST_FRAME_IAX;
6056 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
6057 iax_outputframe(NULL, &fh, 0, sin, 0);
6058 #if 0
6059 if (option_debug)
6060 #endif
6061 ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
6062 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
6063 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
6066 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
6068 /* Select exactly one common encryption if there are any */
6069 p->encmethods &= enc;
6070 if (p->encmethods) {
6071 if (p->encmethods & IAX_ENCRYPT_AES128)
6072 p->encmethods = IAX_ENCRYPT_AES128;
6073 else
6074 p->encmethods = 0;
6079 * \pre iaxsl[call_num] is locked
6081 * \note Since this function calls send_command_final(), the pvt struct for the given
6082 * call number may disappear while executing this function.
6084 static int authenticate_request(int call_num)
6086 struct iax_ie_data ied;
6087 int res = -1, authreq_restrict = 0;
6088 char challenge[10];
6089 struct chan_iax2_pvt *p = iaxs[call_num];
6091 memset(&ied, 0, sizeof(ied));
6093 /* If an AUTHREQ restriction is in place, make sure we can send an AUTHREQ back */
6094 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
6095 struct iax2_user *user, tmp_user = {
6096 .name = p->username,
6099 user = ao2_find(users, &tmp_user, OBJ_POINTER);
6100 if (user) {
6101 if (user->curauthreq == user->maxauthreq)
6102 authreq_restrict = 1;
6103 else
6104 user->curauthreq++;
6105 user = user_unref(user);
6109 /* If the AUTHREQ limit test failed, send back an error */
6110 if (authreq_restrict) {
6111 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
6112 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
6113 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
6114 return 0;
6117 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
6118 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
6119 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
6120 ast_string_field_set(p, challenge, challenge);
6121 /* snprintf(p->challenge, sizeof(p->challenge), "%d", (int)ast_random()); */
6122 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
6124 if (p->encmethods)
6125 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
6127 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
6129 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
6131 if (p->encmethods)
6132 ast_set_flag(p, IAX_ENCRYPTED);
6134 return res;
6137 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
6139 char requeststr[256];
6140 char md5secret[256] = "";
6141 char secret[256] = "";
6142 char rsasecret[256] = "";
6143 int res = -1;
6144 int x;
6145 struct iax2_user *user, tmp_user = {
6146 .name = p->username,
6149 user = ao2_find(users, &tmp_user, OBJ_POINTER);
6150 if (user) {
6151 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
6152 ast_atomic_fetchadd_int(&user->curauthreq, -1);
6153 ast_clear_flag(p, IAX_MAXAUTHREQ);
6155 ast_string_field_set(p, host, user->name);
6156 user = user_unref(user);
6159 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
6160 return res;
6161 if (ies->password)
6162 ast_copy_string(secret, ies->password, sizeof(secret));
6163 if (ies->md5_result)
6164 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
6165 if (ies->rsa_result)
6166 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
6167 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
6168 struct ast_key *key;
6169 char *keyn;
6170 char tmpkey[256];
6171 char *stringp=NULL;
6172 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
6173 stringp=tmpkey;
6174 keyn = strsep(&stringp, ":");
6175 while(keyn) {
6176 key = ast_key_get(keyn, AST_KEY_PUBLIC);
6177 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
6178 res = 0;
6179 break;
6180 } else if (!key)
6181 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
6182 keyn = strsep(&stringp, ":");
6184 } else if (p->authmethods & IAX_AUTH_MD5) {
6185 struct MD5Context md5;
6186 unsigned char digest[16];
6187 char *tmppw, *stringp;
6189 tmppw = ast_strdupa(p->secret);
6190 stringp = tmppw;
6191 while((tmppw = strsep(&stringp, ";"))) {
6192 MD5Init(&md5);
6193 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
6194 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6195 MD5Final(digest, &md5);
6196 /* If they support md5, authenticate with it. */
6197 for (x=0;x<16;x++)
6198 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
6199 if (!strcasecmp(requeststr, md5secret)) {
6200 res = 0;
6201 break;
6204 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
6205 if (!strcmp(secret, p->secret))
6206 res = 0;
6208 return res;
6211 /*! \brief Verify inbound registration */
6212 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
6214 char requeststr[256] = "";
6215 char peer[256] = "";
6216 char md5secret[256] = "";
6217 char rsasecret[256] = "";
6218 char secret[256] = "";
6219 struct iax2_peer *p = NULL;
6220 struct ast_key *key;
6221 char *keyn;
6222 int x;
6223 int expire = 0;
6224 int res = -1;
6226 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
6227 /* iaxs[callno]->peer[0] = '\0'; not necc. any more-- stringfield is pre-inited to null string */
6228 if (ies->username)
6229 ast_copy_string(peer, ies->username, sizeof(peer));
6230 if (ies->password)
6231 ast_copy_string(secret, ies->password, sizeof(secret));
6232 if (ies->md5_result)
6233 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
6234 if (ies->rsa_result)
6235 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
6236 if (ies->refresh)
6237 expire = ies->refresh;
6239 if (ast_strlen_zero(peer)) {
6240 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
6241 return -1;
6244 /* SLD: first call to lookup peer during registration */
6245 ast_mutex_unlock(&iaxsl[callno]);
6246 p = find_peer(peer, 1);
6247 ast_mutex_lock(&iaxsl[callno]);
6248 if (!p || !iaxs[callno]) {
6249 if (authdebug && !p)
6250 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
6251 goto return_unref;
6254 if (!ast_test_flag(p, IAX_DYNAMIC)) {
6255 if (authdebug)
6256 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
6257 goto return_unref;
6260 if (!ast_apply_ha(p->ha, sin)) {
6261 if (authdebug)
6262 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
6263 goto return_unref;
6265 if (!inaddrcmp(&p->addr, sin))
6266 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
6267 ast_string_field_set(iaxs[callno], secret, p->secret);
6268 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
6269 /* Check secret against what we have on file */
6270 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
6271 if (!ast_strlen_zero(p->inkeys)) {
6272 char tmpkeys[256];
6273 char *stringp=NULL;
6274 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
6275 stringp=tmpkeys;
6276 keyn = strsep(&stringp, ":");
6277 while(keyn) {
6278 key = ast_key_get(keyn, AST_KEY_PUBLIC);
6279 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
6280 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
6281 break;
6282 } else if (!key)
6283 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
6284 keyn = strsep(&stringp, ":");
6286 if (!keyn) {
6287 if (authdebug)
6288 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
6289 goto return_unref;
6291 } else {
6292 if (authdebug)
6293 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
6294 goto return_unref;
6296 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
6297 struct MD5Context md5;
6298 unsigned char digest[16];
6299 char *tmppw, *stringp;
6301 tmppw = ast_strdupa(p->secret);
6302 stringp = tmppw;
6303 while((tmppw = strsep(&stringp, ";"))) {
6304 MD5Init(&md5);
6305 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
6306 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
6307 MD5Final(digest, &md5);
6308 for (x=0;x<16;x++)
6309 sprintf(requeststr + (x << 1), "%2.2x", digest[x]); /* safe */
6310 if (!strcasecmp(requeststr, md5secret))
6311 break;
6313 if (tmppw) {
6314 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
6315 } else {
6316 if (authdebug)
6317 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
6318 goto return_unref;
6320 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
6321 /* They've provided a plain text password and we support that */
6322 if (strcmp(secret, p->secret)) {
6323 if (authdebug)
6324 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
6325 goto return_unref;
6326 } else
6327 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
6328 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
6329 if (authdebug)
6330 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
6331 goto return_unref;
6333 ast_string_field_set(iaxs[callno], peer, peer);
6334 /* Choose lowest expiry number */
6335 if (expire && (expire < iaxs[callno]->expiry))
6336 iaxs[callno]->expiry = expire;
6338 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
6340 res = 0;
6342 return_unref:
6343 if (p)
6344 peer_unref(p);
6346 return res;
6349 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, ast_aes_encrypt_key *ecx, ast_aes_decrypt_key *dcx)
6351 int res = -1;
6352 int x;
6353 if (!ast_strlen_zero(keyn)) {
6354 if (!(authmethods & IAX_AUTH_RSA)) {
6355 if (ast_strlen_zero(secret))
6356 ast_log(LOG_NOTICE, "Asked to authenticate to %s with an RSA key, but they don't allow RSA authentication\n", ast_inet_ntoa(sin->sin_addr));
6357 } else if (ast_strlen_zero(challenge)) {
6358 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
6359 } else {
6360 char sig[256];
6361 struct ast_key *key;
6362 key = ast_key_get(keyn, AST_KEY_PRIVATE);
6363 if (!key) {
6364 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
6365 } else {
6366 if (ast_sign(key, (char*)challenge, sig)) {
6367 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
6368 res = -1;
6369 } else {
6370 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
6371 res = 0;
6376 /* Fall back */
6377 if (res && !ast_strlen_zero(secret)) {
6378 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
6379 struct MD5Context md5;
6380 unsigned char digest[16];
6381 char digres[128];
6382 MD5Init(&md5);
6383 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
6384 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
6385 MD5Final(digest, &md5);
6386 /* If they support md5, authenticate with it. */
6387 for (x=0;x<16;x++)
6388 sprintf(digres + (x << 1), "%2.2x", digest[x]); /* safe */
6389 if (ecx && dcx)
6390 build_enc_keys(digest, ecx, dcx);
6391 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
6392 res = 0;
6393 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
6394 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
6395 res = 0;
6396 } else
6397 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
6399 return res;
6403 * \note This function calls realtime_peer -> reg_source_db -> iax2_poke_peer -> find_callno,
6404 * so do not call this function with a pvt lock held.
6406 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
6408 struct iax2_peer *peer = NULL;
6409 /* Start pessimistic */
6410 int res = -1;
6411 int authmethods = 0;
6412 struct iax_ie_data ied;
6413 uint16_t callno = p->callno;
6415 memset(&ied, 0, sizeof(ied));
6417 if (ies->username)
6418 ast_string_field_set(p, username, ies->username);
6419 if (ies->challenge)
6420 ast_string_field_set(p, challenge, ies->challenge);
6421 if (ies->authmethods)
6422 authmethods = ies->authmethods;
6423 if (authmethods & IAX_AUTH_MD5)
6424 merge_encryption(p, ies->encmethods);
6425 else
6426 p->encmethods = 0;
6428 /* Check for override RSA authentication first */
6429 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
6430 /* Normal password authentication */
6431 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
6432 } else {
6433 struct ao2_iterator i = ao2_iterator_init(peers, 0);
6434 while ((peer = ao2_iterator_next(&i))) {
6435 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
6436 /* No peer specified at our end, or this is the peer */
6437 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
6438 /* No username specified in peer rule, or this is the right username */
6439 && (!peer->addr.sin_addr.s_addr || ((sin->sin_addr.s_addr & peer->mask.s_addr) == (peer->addr.sin_addr.s_addr & peer->mask.s_addr)))
6440 /* No specified host, or this is our host */
6442 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
6443 if (!res) {
6444 peer_unref(peer);
6445 break;
6448 peer_unref(peer);
6450 if (!peer) {
6451 /* We checked our list and didn't find one. It's unlikely, but possible,
6452 that we're trying to authenticate *to* a realtime peer */
6453 const char *peer_name = ast_strdupa(p->peer);
6454 ast_mutex_unlock(&iaxsl[callno]);
6455 if ((peer = realtime_peer(peer_name, NULL))) {
6456 ast_mutex_lock(&iaxsl[callno]);
6457 if (!(p = iaxs[callno])) {
6458 peer_unref(peer);
6459 return -1;
6461 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
6462 peer_unref(peer);
6464 if (!peer) {
6465 ast_mutex_lock(&iaxsl[callno]);
6466 if (!(p = iaxs[callno]))
6467 return -1;
6471 if (ies->encmethods)
6472 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
6473 if (!res) {
6474 struct ast_datastore *variablestore;
6475 struct ast_variable *var, *prev = NULL;
6476 AST_LIST_HEAD(, ast_var_t) *varlist;
6477 varlist = ast_calloc(1, sizeof(*varlist));
6478 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
6479 if (variablestore && varlist && p->owner) {
6480 variablestore->data = varlist;
6481 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
6482 AST_LIST_HEAD_INIT(varlist);
6483 for (var = ies->vars; var; var = var->next) {
6484 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
6485 if (prev)
6486 ast_free(prev);
6487 prev = var;
6488 if (!newvar) {
6489 /* Don't abort list traversal, as this would leave ies->vars in an inconsistent state. */
6490 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6491 } else {
6492 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
6495 if (prev)
6496 ast_free(prev);
6497 ies->vars = NULL;
6498 ast_channel_datastore_add(p->owner, variablestore);
6499 } else {
6500 if (p->owner)
6501 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
6502 if (variablestore)
6503 ast_datastore_free(variablestore);
6504 if (varlist)
6505 ast_free(varlist);
6509 if (!res)
6510 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
6511 return res;
6514 static int iax2_do_register(struct iax2_registry *reg);
6516 static void __iax2_do_register_s(const void *data)
6518 struct iax2_registry *reg = (struct iax2_registry *)data;
6519 reg->expire = -1;
6520 iax2_do_register(reg);
6523 static int iax2_do_register_s(const void *data)
6525 #ifdef SCHED_MULTITHREADED
6526 if (schedule_action(__iax2_do_register_s, data))
6527 #endif
6528 __iax2_do_register_s(data);
6529 return 0;
6532 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
6534 int newcall = 0;
6535 char newip[256];
6536 struct iax_ie_data ied;
6537 struct sockaddr_in new;
6540 memset(&ied, 0, sizeof(ied));
6541 if (ies->apparent_addr)
6542 bcopy(ies->apparent_addr, &new, sizeof(new));
6543 if (ies->callno)
6544 newcall = ies->callno;
6545 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
6546 ast_log(LOG_WARNING, "Invalid transfer request\n");
6547 return -1;
6549 pvt->transfercallno = newcall;
6550 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
6551 inet_aton(newip, &pvt->transfer.sin_addr);
6552 pvt->transfer.sin_family = AF_INET;
6553 pvt->transferring = TRANSFER_BEGIN;
6554 pvt->transferid = ies->transferid;
6555 if (ies->transferid)
6556 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
6557 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
6558 return 0;
6561 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
6563 char exten[256] = "";
6564 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
6565 struct iax2_dpcache *dp = NULL;
6567 if (ies->called_number)
6568 ast_copy_string(exten, ies->called_number, sizeof(exten));
6570 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
6571 status = CACHE_FLAG_EXISTS;
6572 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
6573 status = CACHE_FLAG_CANEXIST;
6574 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
6575 status = CACHE_FLAG_NONEXISTENT;
6577 if (ies->refresh)
6578 expiry = ies->refresh;
6579 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
6580 matchmore = CACHE_FLAG_MATCHMORE;
6582 AST_LIST_LOCK(&dpcache);
6583 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
6584 if (strcmp(dp->exten, exten))
6585 continue;
6586 AST_LIST_REMOVE_CURRENT(peer_list);
6587 dp->callno = 0;
6588 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
6589 if (dp->flags & CACHE_FLAG_PENDING) {
6590 dp->flags &= ~CACHE_FLAG_PENDING;
6591 dp->flags |= status;
6592 dp->flags |= matchmore;
6594 /* Wake up waiters */
6595 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
6596 if (dp->waiters[x] > -1)
6597 write(dp->waiters[x], "asdf", 4);
6600 AST_LIST_TRAVERSE_SAFE_END;
6601 AST_LIST_UNLOCK(&dpcache);
6603 return 0;
6606 static int complete_transfer(int callno, struct iax_ies *ies)
6608 int peercallno = 0;
6609 struct chan_iax2_pvt *pvt = iaxs[callno];
6610 struct iax_frame *cur;
6611 jb_frame frame;
6613 if (ies->callno)
6614 peercallno = ies->callno;
6616 if (peercallno < 1) {
6617 ast_log(LOG_WARNING, "Invalid transfer request\n");
6618 return -1;
6620 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
6621 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
6622 pvt->mediareleased = 0;
6623 memset(&pvt->media, 0, sizeof(pvt->media));
6624 /* Reset sequence numbers */
6625 pvt->oseqno = 0;
6626 pvt->rseqno = 0;
6627 pvt->iseqno = 0;
6628 pvt->aseqno = 0;
6630 if (pvt->peercallno) {
6631 remove_by_peercallno(pvt);
6633 pvt->peercallno = peercallno;
6634 store_by_peercallno(pvt);
6636 pvt->transferring = TRANSFER_NONE;
6637 pvt->svoiceformat = -1;
6638 pvt->voiceformat = 0;
6639 pvt->svideoformat = -1;
6640 pvt->videoformat = 0;
6641 pvt->transfercallno = -1;
6642 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
6643 memset(&pvt->offset, 0, sizeof(pvt->offset));
6644 /* reset jitterbuffer */
6645 while(jb_getall(pvt->jb,&frame) == JB_OK)
6646 iax2_frame_free(frame.data);
6647 jb_reset(pvt->jb);
6648 pvt->lag = 0;
6649 pvt->last = 0;
6650 pvt->lastsent = 0;
6651 pvt->nextpred = 0;
6652 pvt->pingtime = DEFAULT_RETRY_TIME;
6653 AST_LIST_LOCK(&frame_queue);
6654 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
6655 /* We must cancel any packets that would have been transmitted
6656 because now we're talking to someone new. It's okay, they
6657 were transmitted to someone that didn't care anyway. */
6658 if (callno == cur->callno)
6659 cur->retries = -1;
6661 AST_LIST_UNLOCK(&frame_queue);
6662 return 0;
6665 /*! \brief Acknowledgment received for OUR registration */
6666 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
6668 struct iax2_registry *reg;
6669 /* Start pessimistic */
6670 char peer[256] = "";
6671 char msgstatus[60];
6672 int refresh = 60;
6673 char ourip[256] = "<Unspecified>";
6674 struct sockaddr_in oldus;
6675 struct sockaddr_in us;
6676 int oldmsgs;
6678 memset(&us, 0, sizeof(us));
6679 if (ies->apparent_addr)
6680 bcopy(ies->apparent_addr, &us, sizeof(us));
6681 if (ies->username)
6682 ast_copy_string(peer, ies->username, sizeof(peer));
6683 if (ies->refresh)
6684 refresh = ies->refresh;
6685 if (ies->calling_number) {
6686 /* We don't do anything with it really, but maybe we should */
6688 reg = iaxs[callno]->reg;
6689 if (!reg) {
6690 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
6691 return -1;
6693 memcpy(&oldus, &reg->us, sizeof(oldus));
6694 oldmsgs = reg->messages;
6695 if (inaddrcmp(&reg->addr, sin)) {
6696 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
6697 return -1;
6699 memcpy(&reg->us, &us, sizeof(reg->us));
6700 if (ies->msgcount >= 0)
6701 reg->messages = ies->msgcount & 0xffff; /* only low 16 bits are used in the transmission of the IE */
6702 /* always refresh the registration at the interval requested by the server
6703 we are registering to
6705 reg->refresh = refresh;
6706 reg->expire = iax2_sched_replace(reg->expire, sched,
6707 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
6708 if (inaddrcmp(&oldus, &reg->us) || (reg->messages != oldmsgs)) {
6709 if (reg->messages > 255)
6710 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
6711 else if (reg->messages > 1)
6712 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
6713 else if (reg->messages > 0)
6714 ast_copy_string(msgstatus, " with 1 new message waiting\n", sizeof(msgstatus));
6715 else
6716 ast_copy_string(msgstatus, " with no messages waiting\n", sizeof(msgstatus));
6717 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
6718 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
6719 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
6721 reg->regstate = REG_STATE_REGISTERED;
6722 return 0;
6725 static int iax2_append_register(const char *hostname, const char *username,
6726 const char *secret, const char *porta)
6728 struct iax2_registry *reg;
6730 if (!(reg = ast_calloc(1, sizeof(*reg))))
6731 return -1;
6733 if (ast_dnsmgr_lookup(hostname, &reg->addr, &reg->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
6734 ast_free(reg);
6735 return -1;
6738 ast_copy_string(reg->username, username, sizeof(reg->username));
6740 if (secret)
6741 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
6743 reg->expire = -1;
6744 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
6745 reg->addr.sin_family = AF_INET;
6746 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
6748 AST_LIST_LOCK(&registrations);
6749 AST_LIST_INSERT_HEAD(&registrations, reg, entry);
6750 AST_LIST_UNLOCK(&registrations);
6752 return 0;
6755 static int iax2_register(const char *value, int lineno)
6757 char copy[256];
6758 char *username, *hostname, *secret;
6759 char *porta;
6760 char *stringp=NULL;
6762 if (!value)
6763 return -1;
6765 ast_copy_string(copy, value, sizeof(copy));
6766 stringp = copy;
6767 username = strsep(&stringp, "@");
6768 hostname = strsep(&stringp, "@");
6770 if (!hostname) {
6771 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
6772 return -1;
6775 stringp = username;
6776 username = strsep(&stringp, ":");
6777 secret = strsep(&stringp, ":");
6778 stringp = hostname;
6779 hostname = strsep(&stringp, ":");
6780 porta = strsep(&stringp, ":");
6782 if (porta && !atoi(porta)) {
6783 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
6784 return -1;
6787 return iax2_append_register(hostname, username, secret, porta);
6791 static void register_peer_exten(struct iax2_peer *peer, int onoff)
6793 char multi[256];
6794 char *stringp, *ext;
6795 if (!ast_strlen_zero(regcontext)) {
6796 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
6797 stringp = multi;
6798 while((ext = strsep(&stringp, "&"))) {
6799 if (onoff) {
6800 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
6801 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
6802 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
6803 } else
6804 ast_context_remove_extension(regcontext, ext, 1, NULL);
6808 static void prune_peers(void);
6810 static void unlink_peer(struct iax2_peer *peer)
6812 if (peer->expire > -1) {
6813 if (!ast_sched_del(sched, peer->expire)) {
6814 peer->expire = -1;
6815 peer_unref(peer);
6819 if (peer->pokeexpire > -1) {
6820 if (!ast_sched_del(sched, peer->pokeexpire)) {
6821 peer->pokeexpire = -1;
6822 peer_unref(peer);
6826 ao2_unlink(peers, peer);
6829 static void __expire_registry(const void *data)
6831 struct iax2_peer *peer = (struct iax2_peer *) data;
6833 if (!peer)
6834 return;
6836 peer->expire = -1;
6838 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
6839 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
6840 realtime_update_peer(peer->name, &peer->addr, 0);
6841 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
6842 /* Reset the address */
6843 memset(&peer->addr, 0, sizeof(peer->addr));
6844 /* Reset expiry value */
6845 peer->expiry = min_reg_expire;
6846 if (!ast_test_flag(peer, IAX_TEMPONLY))
6847 ast_db_del("IAX/Registry", peer->name);
6848 register_peer_exten(peer, 0);
6849 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
6850 if (iax2_regfunk)
6851 iax2_regfunk(peer->name, 0);
6853 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
6854 unlink_peer(peer);
6856 peer_unref(peer);
6859 static int expire_registry(const void *data)
6861 #ifdef SCHED_MULTITHREADED
6862 if (schedule_action(__expire_registry, data))
6863 #endif
6864 __expire_registry(data);
6865 return 0;
6868 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
6870 static void reg_source_db(struct iax2_peer *p)
6872 char data[80];
6873 struct in_addr in;
6874 char *c, *d;
6875 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
6876 c = strchr(data, ':');
6877 if (c) {
6878 *c = '\0';
6879 c++;
6880 if (inet_aton(data, &in)) {
6881 d = strchr(c, ':');
6882 if (d) {
6883 *d = '\0';
6884 d++;
6885 ast_verb(3, "Seeding '%s' at %s:%d for %d\n", p->name,
6886 ast_inet_ntoa(in), atoi(c), atoi(d));
6887 iax2_poke_peer(p, 0);
6888 p->expiry = atoi(d);
6889 memset(&p->addr, 0, sizeof(p->addr));
6890 p->addr.sin_family = AF_INET;
6891 p->addr.sin_addr = in;
6892 p->addr.sin_port = htons(atoi(c));
6893 if (p->expire > -1) {
6894 if (!ast_sched_del(sched, p->expire)) {
6895 p->expire = -1;
6896 peer_unref(p);
6899 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
6900 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
6901 if (p->expire == -1)
6902 peer_unref(p);
6903 if (iax2_regfunk)
6904 iax2_regfunk(p->name, 1);
6905 register_peer_exten(p, 1);
6914 * \pre iaxsl[callno] is locked
6916 * \note Since this function calls send_command_final(), the pvt struct for
6917 * the given call number may disappear while executing this function.
6919 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
6921 /* Called from IAX thread only, with proper iaxsl lock */
6922 struct iax_ie_data ied;
6923 struct iax2_peer *p;
6924 int msgcount;
6925 char data[80];
6926 int version;
6927 const char *peer_name;
6928 int res = -1;
6930 memset(&ied, 0, sizeof(ied));
6932 peer_name = ast_strdupa(iaxs[callno]->peer);
6934 /* SLD: Another find_peer call during registration - this time when we are really updating our registration */
6935 ast_mutex_unlock(&iaxsl[callno]);
6936 if (!(p = find_peer(peer_name, 1))) {
6937 ast_mutex_lock(&iaxsl[callno]);
6938 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
6939 return -1;
6941 ast_mutex_lock(&iaxsl[callno]);
6942 if (!iaxs[callno])
6943 goto return_unref;
6945 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
6946 if (sin->sin_addr.s_addr) {
6947 time_t nowtime;
6948 time(&nowtime);
6949 realtime_update_peer(peer_name, sin, nowtime);
6950 } else {
6951 realtime_update_peer(peer_name, sin, 0);
6954 if (inaddrcmp(&p->addr, sin)) {
6955 if (iax2_regfunk)
6956 iax2_regfunk(p->name, 1);
6957 /* Stash the IP address from which they registered */
6958 memcpy(&p->addr, sin, sizeof(p->addr));
6959 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
6960 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
6961 ast_db_put("IAX/Registry", p->name, data);
6962 ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
6963 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
6964 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
6965 register_peer_exten(p, 1);
6966 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name); /* Activate notification */
6967 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
6968 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
6969 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
6970 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
6971 register_peer_exten(p, 0);
6972 ast_db_del("IAX/Registry", p->name);
6973 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name); /* Activate notification */
6975 /* Update the host */
6976 /* Verify that the host is really there */
6977 iax2_poke_peer(p, callno);
6980 /* Make sure our call still exists, an INVAL at the right point may make it go away */
6981 if (!iaxs[callno]) {
6982 res = 0;
6983 goto return_unref;
6986 /* Store socket fd */
6987 p->sockfd = fd;
6988 /* Setup the expiry */
6989 if (p->expire > -1) {
6990 if (!ast_sched_del(sched, p->expire)) {
6991 p->expire = -1;
6992 peer_unref(p);
6995 /* treat an unspecified refresh interval as the minimum */
6996 if (!refresh)
6997 refresh = min_reg_expire;
6998 if (refresh > max_reg_expire) {
6999 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
7000 p->name, max_reg_expire, refresh);
7001 p->expiry = max_reg_expire;
7002 } else if (refresh < min_reg_expire) {
7003 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
7004 p->name, min_reg_expire, refresh);
7005 p->expiry = min_reg_expire;
7006 } else {
7007 p->expiry = refresh;
7009 if (p->expiry && sin->sin_addr.s_addr) {
7010 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
7011 if (p->expire == -1)
7012 peer_unref(p);
7014 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
7015 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
7016 if (sin->sin_addr.s_addr) {
7017 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
7018 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
7019 if (!ast_strlen_zero(p->mailbox)) {
7020 struct ast_event *event;
7021 int new, old;
7022 char *mailbox, *context;
7024 context = mailbox = ast_strdupa(p->mailbox);
7025 strsep(&context, "@");
7026 if (ast_strlen_zero(context))
7027 context = "default";
7029 event = ast_event_get_cached(AST_EVENT_MWI,
7030 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
7031 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
7032 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
7033 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
7034 AST_EVENT_IE_END);
7035 if (event) {
7036 new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
7037 old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
7038 ast_event_destroy(event);
7039 } else { /* Fall back on checking the mailbox directly */
7040 ast_app_inboxcount(p->mailbox, &new, &old);
7043 if (new > 255) {
7044 new = 255;
7046 if (old > 255) {
7047 old = 255;
7049 msgcount = (old << 8) | new;
7051 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
7053 if (ast_test_flag(p, IAX_HASCALLERID)) {
7054 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
7055 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
7058 version = iax_check_version(devtype);
7059 if (version)
7060 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
7062 res = 0;
7064 return_unref:
7065 peer_unref(p);
7067 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
7070 static int registry_authrequest(int callno)
7072 struct iax_ie_data ied;
7073 struct iax2_peer *p;
7074 char challenge[10];
7075 const char *peer_name;
7076 int res = -1;
7078 peer_name = ast_strdupa(iaxs[callno]->peer);
7080 /* SLD: third call to find_peer in registration */
7081 ast_mutex_unlock(&iaxsl[callno]);
7082 p = find_peer(peer_name, 1);
7083 ast_mutex_lock(&iaxsl[callno]);
7084 if (!iaxs[callno])
7085 goto return_unref;
7086 if (!p) {
7087 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
7088 goto return_unref;
7091 memset(&ied, 0, sizeof(ied));
7092 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
7093 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
7094 /* Build the challenge */
7095 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
7096 ast_string_field_set(iaxs[callno], challenge, challenge);
7097 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
7099 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
7101 res = 0;
7103 return_unref:
7104 peer_unref(p);
7106 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
7109 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
7111 struct iax2_registry *reg;
7112 /* Start pessimistic */
7113 struct iax_ie_data ied;
7114 char peer[256] = "";
7115 char challenge[256] = "";
7116 int res;
7117 int authmethods = 0;
7118 if (ies->authmethods)
7119 authmethods = ies->authmethods;
7120 if (ies->username)
7121 ast_copy_string(peer, ies->username, sizeof(peer));
7122 if (ies->challenge)
7123 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
7124 memset(&ied, 0, sizeof(ied));
7125 reg = iaxs[callno]->reg;
7126 if (reg) {
7127 if (inaddrcmp(&reg->addr, sin)) {
7128 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
7129 return -1;
7131 if (ast_strlen_zero(reg->secret)) {
7132 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
7133 reg->regstate = REG_STATE_NOAUTH;
7134 return -1;
7136 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
7137 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
7138 if (reg->secret[0] == '[') {
7139 char tmpkey[256];
7140 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
7141 tmpkey[strlen(tmpkey) - 1] = '\0';
7142 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
7143 } else
7144 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
7145 if (!res) {
7146 reg->regstate = REG_STATE_AUTHSENT;
7147 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
7148 } else
7149 return -1;
7150 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
7151 } else
7152 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
7153 return -1;
7156 static void stop_stuff(int callno)
7158 iax2_destroy_helper(iaxs[callno]);
7161 static void __auth_reject(const void *nothing)
7163 /* Called from IAX thread only, without iaxs lock */
7164 int callno = (int)(long)(nothing);
7165 struct iax_ie_data ied;
7166 ast_mutex_lock(&iaxsl[callno]);
7167 if (iaxs[callno]) {
7168 memset(&ied, 0, sizeof(ied));
7169 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
7170 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
7171 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
7172 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
7173 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
7174 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
7176 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
7178 ast_mutex_unlock(&iaxsl[callno]);
7181 static int auth_reject(const void *data)
7183 int callno = (int)(long)(data);
7184 ast_mutex_lock(&iaxsl[callno]);
7185 if (iaxs[callno])
7186 iaxs[callno]->authid = -1;
7187 ast_mutex_unlock(&iaxsl[callno]);
7188 #ifdef SCHED_MULTITHREADED
7189 if (schedule_action(__auth_reject, data))
7190 #endif
7191 __auth_reject(data);
7192 return 0;
7195 static int auth_fail(int callno, int failcode)
7197 /* Schedule sending the authentication failure in one second, to prevent
7198 guessing */
7199 if (iaxs[callno]) {
7200 iaxs[callno]->authfail = failcode;
7201 if (delayreject) {
7202 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
7203 sched, 1000, auth_reject, (void *)(long)callno);
7204 } else
7205 auth_reject((void *)(long)callno);
7207 return 0;
7210 static void __auto_hangup(const void *nothing)
7212 /* Called from IAX thread only, without iaxs lock */
7213 int callno = (int)(long)(nothing);
7214 struct iax_ie_data ied;
7215 ast_mutex_lock(&iaxsl[callno]);
7216 if (iaxs[callno]) {
7217 memset(&ied, 0, sizeof(ied));
7218 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
7219 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
7220 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
7222 ast_mutex_unlock(&iaxsl[callno]);
7225 static int auto_hangup(const void *data)
7227 int callno = (int)(long)(data);
7228 ast_mutex_lock(&iaxsl[callno]);
7229 if (iaxs[callno]) {
7230 iaxs[callno]->autoid = -1;
7232 ast_mutex_unlock(&iaxsl[callno]);
7233 #ifdef SCHED_MULTITHREADED
7234 if (schedule_action(__auto_hangup, data))
7235 #endif
7236 __auto_hangup(data);
7237 return 0;
7240 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
7242 struct iax_ie_data ied;
7243 /* Auto-hangup with 30 seconds of inactivity */
7244 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
7245 sched, 30000, auto_hangup, (void *)(long)callno);
7246 memset(&ied, 0, sizeof(ied));
7247 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
7248 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
7249 dp->flags |= CACHE_FLAG_TRANSMITTED;
7252 static int iax2_vnak(int callno)
7254 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
7257 static void vnak_retransmit(int callno, int last)
7259 struct iax_frame *f;
7261 AST_LIST_LOCK(&frame_queue);
7262 AST_LIST_TRAVERSE(&frame_queue, f, list) {
7263 /* Send a copy immediately */
7264 if ((f->callno == callno) && iaxs[f->callno] &&
7265 ((unsigned char ) (f->oseqno - last) < 128) &&
7266 (f->retries >= 0)) {
7267 send_packet(f);
7270 AST_LIST_UNLOCK(&frame_queue);
7273 static void __iax2_poke_peer_s(const void *data)
7275 struct iax2_peer *peer = (struct iax2_peer *)data;
7276 iax2_poke_peer(peer, 0);
7277 peer_unref(peer);
7280 static int iax2_poke_peer_s(const void *data)
7282 struct iax2_peer *peer = (struct iax2_peer *)data;
7283 peer->pokeexpire = -1;
7284 #ifdef SCHED_MULTITHREADED
7285 if (schedule_action(__iax2_poke_peer_s, data))
7286 #endif
7287 __iax2_poke_peer_s(data);
7288 return 0;
7291 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
7293 int res = 0;
7294 struct iax_frame *fr;
7295 struct ast_iax2_meta_hdr *meta;
7296 struct ast_iax2_meta_trunk_hdr *mth;
7297 int calls = 0;
7299 /* Point to frame */
7300 fr = (struct iax_frame *)tpeer->trunkdata;
7301 /* Point to meta data */
7302 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
7303 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
7304 if (tpeer->trunkdatalen) {
7305 /* We're actually sending a frame, so fill the meta trunk header and meta header */
7306 meta->zeros = 0;
7307 meta->metacmd = IAX_META_TRUNK;
7308 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
7309 meta->cmddata = IAX_META_TRUNK_MINI;
7310 else
7311 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
7312 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
7313 /* And the rest of the ast_iax2 header */
7314 fr->direction = DIRECTION_OUTGRESS;
7315 fr->retrans = -1;
7316 fr->transfer = 0;
7317 /* Any appropriate call will do */
7318 fr->data = fr->afdata;
7319 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
7320 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
7321 calls = tpeer->calls;
7322 #if 0
7323 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
7324 #endif
7325 /* Reset transmit trunk side data */
7326 tpeer->trunkdatalen = 0;
7327 tpeer->calls = 0;
7329 if (res < 0)
7330 return res;
7331 return calls;
7334 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
7336 /* Drop when trunk is about 5 seconds idle */
7337 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
7338 return 1;
7339 return 0;
7342 static int timing_read(int *id, int fd, short events, void *cbdata)
7344 int res, processed = 0, totalcalls = 0;
7345 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
7346 struct timeval now = ast_tvnow();
7348 if (iaxtrunkdebug)
7349 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
7351 if (timingfd > -1) {
7352 ast_timer_ack(timingfd, 1);
7355 /* For each peer that supports trunking... */
7356 AST_LIST_LOCK(&tpeers);
7357 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
7358 processed++;
7359 res = 0;
7360 ast_mutex_lock(&tpeer->lock);
7361 /* We can drop a single tpeer per pass. That makes all this logic
7362 substantially easier */
7363 if (!drop && iax2_trunk_expired(tpeer, &now)) {
7364 /* Take it out of the list, but don't free it yet, because it
7365 could be in use */
7366 AST_LIST_REMOVE_CURRENT(list);
7367 drop = tpeer;
7368 } else {
7369 res = send_trunk(tpeer, &now);
7370 trunk_timed++;
7371 if (iaxtrunkdebug)
7372 ast_verbose(" - Trunk peer (%s:%d) has %d call chunk%s in transit, %d bytes backloged and has hit a high water mark of %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), res, (res != 1) ? "s" : "", tpeer->trunkdatalen, tpeer->trunkdataalloc);
7374 totalcalls += res;
7375 res = 0;
7376 ast_mutex_unlock(&tpeer->lock);
7378 AST_LIST_TRAVERSE_SAFE_END;
7379 AST_LIST_UNLOCK(&tpeers);
7381 if (drop) {
7382 ast_mutex_lock(&drop->lock);
7383 /* Once we have this lock, we're sure nobody else is using it or could use it once we release it,
7384 because by the time they could get tpeerlock, we've already grabbed it */
7385 ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
7386 if (drop->trunkdata) {
7387 ast_free(drop->trunkdata);
7388 drop->trunkdata = NULL;
7390 ast_mutex_unlock(&drop->lock);
7391 ast_mutex_destroy(&drop->lock);
7392 ast_free(drop);
7396 if (iaxtrunkdebug)
7397 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
7398 iaxtrunkdebug = 0;
7400 return 1;
7403 struct dpreq_data {
7404 int callno;
7405 char context[AST_MAX_EXTENSION];
7406 char callednum[AST_MAX_EXTENSION];
7407 char *callerid;
7410 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
7412 unsigned short dpstatus = 0;
7413 struct iax_ie_data ied1;
7414 int mm;
7416 memset(&ied1, 0, sizeof(ied1));
7417 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
7418 /* Must be started */
7419 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
7420 dpstatus = IAX_DPSTATUS_EXISTS;
7421 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
7422 dpstatus = IAX_DPSTATUS_CANEXIST;
7423 } else {
7424 dpstatus = IAX_DPSTATUS_NONEXISTENT;
7426 if (ast_ignore_pattern(context, callednum))
7427 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
7428 if (mm)
7429 dpstatus |= IAX_DPSTATUS_MATCHMORE;
7430 if (!skiplock)
7431 ast_mutex_lock(&iaxsl[callno]);
7432 if (iaxs[callno]) {
7433 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
7434 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
7435 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
7436 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
7438 if (!skiplock)
7439 ast_mutex_unlock(&iaxsl[callno]);
7442 static void *dp_lookup_thread(void *data)
7444 /* Look up for dpreq */
7445 struct dpreq_data *dpr = data;
7446 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
7447 if (dpr->callerid)
7448 ast_free(dpr->callerid);
7449 ast_free(dpr);
7450 return NULL;
7453 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
7455 pthread_t newthread;
7456 struct dpreq_data *dpr;
7458 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
7459 return;
7461 dpr->callno = callno;
7462 ast_copy_string(dpr->context, context, sizeof(dpr->context));
7463 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
7464 if (callerid)
7465 dpr->callerid = ast_strdup(callerid);
7466 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
7467 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
7471 struct iax_dual {
7472 struct ast_channel *chan1;
7473 struct ast_channel *chan2;
7476 static void *iax_park_thread(void *stuff)
7478 struct ast_channel *chan1, *chan2;
7479 struct iax_dual *d;
7480 struct ast_frame *f;
7481 int ext;
7482 int res;
7483 d = stuff;
7484 chan1 = d->chan1;
7485 chan2 = d->chan2;
7486 ast_free(d);
7487 f = ast_read(chan1);
7488 if (f)
7489 ast_frfree(f);
7490 res = ast_park_call(chan1, chan2, 0, &ext);
7491 ast_hangup(chan2);
7492 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
7493 return NULL;
7496 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
7498 struct iax_dual *d;
7499 struct ast_channel *chan1m, *chan2m;
7500 pthread_t th;
7501 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
7502 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
7503 if (chan2m && chan1m) {
7504 /* Make formats okay */
7505 chan1m->readformat = chan1->readformat;
7506 chan1m->writeformat = chan1->writeformat;
7507 ast_channel_masquerade(chan1m, chan1);
7508 /* Setup the extensions and such */
7509 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
7510 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
7511 chan1m->priority = chan1->priority;
7513 /* We make a clone of the peer channel too, so we can play
7514 back the announcement */
7515 /* Make formats okay */
7516 chan2m->readformat = chan2->readformat;
7517 chan2m->writeformat = chan2->writeformat;
7518 ast_channel_masquerade(chan2m, chan2);
7519 /* Setup the extensions and such */
7520 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
7521 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
7522 chan2m->priority = chan2->priority;
7523 if (ast_do_masquerade(chan2m)) {
7524 ast_log(LOG_WARNING, "Masquerade failed :(\n");
7525 ast_hangup(chan2m);
7526 return -1;
7528 } else {
7529 if (chan1m)
7530 ast_hangup(chan1m);
7531 if (chan2m)
7532 ast_hangup(chan2m);
7533 return -1;
7535 if ((d = ast_calloc(1, sizeof(*d)))) {
7536 d->chan1 = chan1m;
7537 d->chan2 = chan2m;
7538 if (!ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d)) {
7539 return 0;
7541 ast_free(d);
7543 return -1;
7547 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
7549 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
7551 unsigned int ourver;
7552 char rsi[80];
7553 snprintf(rsi, sizeof(rsi), "si-%s", si);
7554 if (iax_provision_version(&ourver, rsi, 1))
7555 return 0;
7556 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
7557 if (ourver != ver)
7558 iax2_provision(sin, sockfd, NULL, rsi, 1);
7559 return 0;
7562 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
7564 jb_info stats;
7565 jb_getinfo(pvt->jb, &stats);
7567 memset(iep, 0, sizeof(*iep));
7569 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
7570 if(stats.frames_in == 0) stats.frames_in = 1;
7571 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
7572 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
7573 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
7574 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
7575 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
7578 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
7580 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
7581 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
7582 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
7583 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
7584 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
7585 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
7586 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
7589 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
7591 int i;
7592 unsigned int length, offset = 0;
7593 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
7595 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
7596 length = ies->ospblocklength[i];
7597 if (length != 0) {
7598 if (length > IAX_MAX_OSPBLOCK_SIZE) {
7599 /* OSP token block length wrong, clear buffer */
7600 offset = 0;
7601 break;
7602 } else {
7603 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
7604 offset += length;
7606 } else {
7607 break;
7610 *(full_osptoken + offset) = '\0';
7611 if (strlen(full_osptoken) != offset) {
7612 /* OSP token length wrong, clear buffer */
7613 *full_osptoken = '\0';
7616 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
7619 static void log_jitterstats(unsigned short callno)
7621 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
7622 jb_info jbinfo;
7624 ast_mutex_lock(&iaxsl[callno]);
7625 if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
7626 if(ast_test_flag(iaxs[callno], IAX_USEJITTERBUF)) {
7627 jb_getinfo(iaxs[callno]->jb, &jbinfo);
7628 localjitter = jbinfo.jitter;
7629 localdelay = jbinfo.current - jbinfo.min;
7630 locallost = jbinfo.frames_lost;
7631 locallosspct = jbinfo.losspct/1000;
7632 localdropped = jbinfo.frames_dropped;
7633 localooo = jbinfo.frames_ooo;
7634 localpackets = jbinfo.frames_in;
7636 ast_debug(3, "JB STATS:%s ping=%d ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
7637 iaxs[callno]->owner->name,
7638 iaxs[callno]->pingtime,
7639 localjitter,
7640 localdelay,
7641 locallost,
7642 locallosspct,
7643 localdropped,
7644 localooo,
7645 localpackets,
7646 iaxs[callno]->remote_rr.jitter,
7647 iaxs[callno]->remote_rr.delay,
7648 iaxs[callno]->remote_rr.losscnt,
7649 iaxs[callno]->remote_rr.losspct/1000,
7650 iaxs[callno]->remote_rr.dropped,
7651 iaxs[callno]->remote_rr.ooo,
7652 iaxs[callno]->remote_rr.packets);
7653 manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %d\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
7654 iaxs[callno]->owner->name,
7655 iaxs[callno]->pingtime,
7656 localjitter,
7657 localdelay,
7658 locallost,
7659 locallosspct,
7660 localdropped,
7661 localooo,
7662 localpackets,
7663 iaxs[callno]->remote_rr.jitter,
7664 iaxs[callno]->remote_rr.delay,
7665 iaxs[callno]->remote_rr.losscnt,
7666 iaxs[callno]->remote_rr.losspct/1000,
7667 iaxs[callno]->remote_rr.dropped,
7668 iaxs[callno]->remote_rr.ooo,
7669 iaxs[callno]->remote_rr.packets);
7671 ast_mutex_unlock(&iaxsl[callno]);
7674 static int socket_process(struct iax2_thread *thread);
7677 * \brief Handle any deferred full frames for this thread
7679 static void handle_deferred_full_frames(struct iax2_thread *thread)
7681 struct iax2_pkt_buf *pkt_buf;
7683 ast_mutex_lock(&thread->lock);
7685 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
7686 ast_mutex_unlock(&thread->lock);
7688 thread->buf = pkt_buf->buf;
7689 thread->buf_len = pkt_buf->len;
7690 thread->buf_size = pkt_buf->len + 1;
7692 socket_process(thread);
7694 thread->buf = NULL;
7695 ast_free(pkt_buf);
7697 ast_mutex_lock(&thread->lock);
7700 ast_mutex_unlock(&thread->lock);
7704 * \brief Queue the last read full frame for processing by a certain thread
7706 * If there are already any full frames queued, they are sorted
7707 * by sequence number.
7709 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
7711 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
7712 struct ast_iax2_full_hdr *fh, *cur_fh;
7714 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
7715 return;
7717 pkt_buf->len = from_here->buf_len;
7718 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
7720 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
7721 ast_mutex_lock(&to_here->lock);
7722 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
7723 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
7724 if (fh->oseqno < cur_fh->oseqno) {
7725 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
7726 break;
7729 AST_LIST_TRAVERSE_SAFE_END
7731 if (!cur_pkt_buf)
7732 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
7734 ast_mutex_unlock(&to_here->lock);
7737 static int socket_read(int *id, int fd, short events, void *cbdata)
7739 struct iax2_thread *thread;
7740 socklen_t len;
7741 time_t t;
7742 static time_t last_errtime = 0;
7743 struct ast_iax2_full_hdr *fh;
7745 if (!(thread = find_idle_thread())) {
7746 time(&t);
7747 if (t != last_errtime)
7748 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
7749 last_errtime = t;
7750 usleep(1);
7751 return 1;
7754 len = sizeof(thread->iosin);
7755 thread->iofd = fd;
7756 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
7757 thread->buf_size = sizeof(thread->readbuf);
7758 thread->buf = thread->readbuf;
7759 if (thread->buf_len < 0) {
7760 if (errno != ECONNREFUSED && errno != EAGAIN)
7761 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
7762 handle_error();
7763 thread->iostate = IAX_IOSTATE_IDLE;
7764 signal_condition(&thread->lock, &thread->cond);
7765 return 1;
7767 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) { /* simulate random loss condition */
7768 thread->iostate = IAX_IOSTATE_IDLE;
7769 signal_condition(&thread->lock, &thread->cond);
7770 return 1;
7773 /* Determine if this frame is a full frame; if so, and any thread is currently
7774 processing a full frame for the same callno from this peer, then drop this
7775 frame (and the peer will retransmit it) */
7776 fh = (struct ast_iax2_full_hdr *) thread->buf;
7777 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
7778 struct iax2_thread *cur = NULL;
7779 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
7781 AST_LIST_LOCK(&active_list);
7782 AST_LIST_TRAVERSE(&active_list, cur, list) {
7783 if ((cur->ffinfo.callno == callno) &&
7784 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
7785 break;
7787 if (cur) {
7788 /* we found another thread processing a full frame for this call,
7789 so queue it up for processing later. */
7790 defer_full_frame(thread, cur);
7791 AST_LIST_UNLOCK(&active_list);
7792 thread->iostate = IAX_IOSTATE_IDLE;
7793 signal_condition(&thread->lock, &thread->cond);
7794 return 1;
7795 } else {
7796 /* this thread is going to process this frame, so mark it */
7797 thread->ffinfo.callno = callno;
7798 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
7799 thread->ffinfo.type = fh->type;
7800 thread->ffinfo.csub = fh->csub;
7802 AST_LIST_UNLOCK(&active_list);
7805 /* Mark as ready and send on its way */
7806 thread->iostate = IAX_IOSTATE_READY;
7807 #ifdef DEBUG_SCHED_MULTITHREAD
7808 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
7809 #endif
7810 signal_condition(&thread->lock, &thread->cond);
7812 return 1;
7815 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
7816 struct iax_frame *fr)
7818 unsigned char metatype;
7819 struct ast_iax2_meta_trunk_mini *mtm;
7820 struct ast_iax2_meta_trunk_hdr *mth;
7821 struct ast_iax2_meta_trunk_entry *mte;
7822 struct iax2_trunk_peer *tpeer;
7823 unsigned int ts;
7824 void *ptr;
7825 struct timeval rxtrunktime;
7826 struct ast_frame f = { 0, };
7828 if (packet_len < sizeof(*meta)) {
7829 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
7830 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
7831 return 1;
7834 if (meta->metacmd != IAX_META_TRUNK)
7835 return 1;
7837 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
7838 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
7839 (int) (sizeof(*meta) + sizeof(*mth)));
7840 return 1;
7842 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
7843 ts = ntohl(mth->ts);
7844 metatype = meta->cmddata;
7845 packet_len -= (sizeof(*meta) + sizeof(*mth));
7846 ptr = mth->data;
7847 tpeer = find_tpeer(sin, sockfd);
7848 if (!tpeer) {
7849 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
7850 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
7851 return 1;
7853 tpeer->trunkact = ast_tvnow();
7854 if (!ts || ast_tvzero(tpeer->rxtrunktime))
7855 tpeer->rxtrunktime = tpeer->trunkact;
7856 rxtrunktime = tpeer->rxtrunktime;
7857 ast_mutex_unlock(&tpeer->lock);
7858 while (packet_len >= sizeof(*mte)) {
7859 /* Process channels */
7860 unsigned short callno, trunked_ts, len;
7862 if (metatype == IAX_META_TRUNK_MINI) {
7863 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
7864 ptr += sizeof(*mtm);
7865 packet_len -= sizeof(*mtm);
7866 len = ntohs(mtm->len);
7867 callno = ntohs(mtm->mini.callno);
7868 trunked_ts = ntohs(mtm->mini.ts);
7869 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
7870 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
7871 ptr += sizeof(*mte);
7872 packet_len -= sizeof(*mte);
7873 len = ntohs(mte->len);
7874 callno = ntohs(mte->callno);
7875 trunked_ts = 0;
7876 } else {
7877 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
7878 break;
7880 /* Stop if we don't have enough data */
7881 if (len > packet_len)
7882 break;
7883 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
7884 if (!fr->callno)
7885 continue;
7887 /* If it's a valid call, deliver the contents. If not, we
7888 drop it, since we don't have a scallno to use for an INVAL */
7889 /* Process as a mini frame */
7890 memset(&f, 0, sizeof(f));
7891 f.frametype = AST_FRAME_VOICE;
7892 if (!iaxs[fr->callno]) {
7893 /* drop it */
7894 } else if (iaxs[fr->callno]->voiceformat == 0) {
7895 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
7896 iax2_vnak(fr->callno);
7897 } else {
7898 f.subclass = iaxs[fr->callno]->voiceformat;
7899 f.datalen = len;
7900 if (f.datalen >= 0) {
7901 if (f.datalen)
7902 f.data.ptr = ptr;
7903 else
7904 f.data.ptr = NULL;
7905 if (trunked_ts)
7906 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
7907 else
7908 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
7909 /* Don't pass any packets until we're started */
7910 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
7911 struct iax_frame *duped_fr;
7913 /* Common things */
7914 f.src = "IAX2";
7915 f.mallocd = 0;
7916 f.offset = 0;
7917 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
7918 f.samples = ast_codec_get_samples(&f);
7919 else
7920 f.samples = 0;
7921 fr->outoforder = 0;
7922 iax_frame_wrap(fr, &f);
7923 duped_fr = iaxfrdup2(fr);
7924 if (duped_fr)
7925 schedule_delivery(duped_fr, 1, 1, &fr->ts);
7926 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
7927 iaxs[fr->callno]->last = fr->ts;
7929 } else {
7930 ast_log(LOG_WARNING, "Datalen < 0?\n");
7933 ast_mutex_unlock(&iaxsl[fr->callno]);
7934 ptr += len;
7935 packet_len -= len;
7938 return 1;
7941 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
7943 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
7944 AST_LIST_HEAD(, ast_var_t) *varlist;
7945 struct ast_var_t *var;
7947 if (!variablestore) {
7948 *buf = '\0';
7949 return 0;
7951 varlist = variablestore->data;
7953 AST_LIST_LOCK(varlist);
7954 AST_LIST_TRAVERSE(varlist, var, entries) {
7955 if (strcmp(var->name, data) == 0) {
7956 ast_copy_string(buf, var->value, len);
7957 break;
7960 AST_LIST_UNLOCK(varlist);
7961 return 0;
7964 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
7966 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
7967 AST_LIST_HEAD(, ast_var_t) *varlist;
7968 struct ast_var_t *var;
7970 if (!variablestore) {
7971 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
7972 if (!variablestore) {
7973 ast_log(LOG_ERROR, "Memory allocation error\n");
7974 return -1;
7976 varlist = ast_calloc(1, sizeof(*varlist));
7977 if (!varlist) {
7978 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
7979 return -1;
7982 AST_LIST_HEAD_INIT(varlist);
7983 variablestore->data = varlist;
7984 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
7985 ast_channel_datastore_add(chan, variablestore);
7986 } else
7987 varlist = variablestore->data;
7989 AST_LIST_LOCK(varlist);
7990 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
7991 if (strcmp(var->name, data) == 0) {
7992 AST_LIST_REMOVE_CURRENT(entries);
7993 ast_var_delete(var);
7994 break;
7997 AST_LIST_TRAVERSE_SAFE_END;
7998 var = ast_var_assign(data, value);
7999 if (var)
8000 AST_LIST_INSERT_TAIL(varlist, var, entries);
8001 else
8002 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
8003 AST_LIST_UNLOCK(varlist);
8004 return 0;
8007 static struct ast_custom_function iaxvar_function = {
8008 .name = "IAXVAR",
8009 .synopsis = "Sets or retrieves a remote variable",
8010 .syntax = "IAXVAR(<varname>)",
8011 .read = acf_iaxvar_read,
8012 .write = acf_iaxvar_write,
8015 static int socket_process(struct iax2_thread *thread)
8017 struct sockaddr_in sin;
8018 int res;
8019 int updatehistory=1;
8020 int new = NEW_PREVENT;
8021 int dcallno = 0;
8022 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
8023 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
8024 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
8025 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
8026 struct iax_frame *fr;
8027 struct iax_frame *cur;
8028 struct ast_frame f = { 0, };
8029 struct ast_channel *c = NULL;
8030 struct iax2_dpcache *dp;
8031 struct iax2_peer *peer;
8032 struct iax_ies ies;
8033 struct iax_ie_data ied0, ied1;
8034 int format;
8035 int fd;
8036 int exists;
8037 int minivid = 0;
8038 char empty[32]=""; /* Safety measure */
8039 struct iax_frame *duped_fr;
8040 char host_pref_buf[128];
8041 char caller_pref_buf[128];
8042 struct ast_codec_pref pref;
8043 char *using_prefs = "mine";
8045 /* allocate an iax_frame with 4096 bytes of data buffer */
8046 fr = alloca(sizeof(*fr) + 4096);
8047 memset(fr, 0, sizeof(*fr));
8048 fr->afdatalen = 4096; /* From alloca() above */
8050 /* Copy frequently used parameters to the stack */
8051 res = thread->buf_len;
8052 fd = thread->iofd;
8053 memcpy(&sin, &thread->iosin, sizeof(sin));
8055 if (res < sizeof(*mh)) {
8056 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
8057 return 1;
8059 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
8060 if (res < sizeof(*vh)) {
8061 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a video frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
8062 return 1;
8065 /* This is a video frame, get call number */
8066 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
8067 minivid = 1;
8068 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
8069 return socket_process_meta(res, meta, &sin, fd, fr);
8071 #ifdef DEBUG_SUPPORT
8072 if (res >= sizeof(*fh))
8073 iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
8074 #endif
8075 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
8076 if (res < sizeof(*fh)) {
8077 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a full frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
8078 return 1;
8081 /* Get the destination call number */
8082 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
8083 /* Retrieve the type and subclass */
8084 f.frametype = fh->type;
8085 if (f.frametype == AST_FRAME_VIDEO) {
8086 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
8087 } else {
8088 f.subclass = uncompress_subclass(fh->csub);
8091 /* Deal with POKE/PONG without allocating a callno */
8092 if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_POKE) {
8093 /* Reply back with a PONG, but don't care about the result. */
8094 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohs(fh->ts), fh->oseqno);
8095 return 1;
8096 } else if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_ACK && dcallno == 1) {
8097 /* Ignore */
8098 return 1;
8101 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
8102 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
8103 (f.subclass == IAX_COMMAND_REGREL)))
8104 new = NEW_ALLOW;
8105 } else {
8106 /* Don't know anything about it yet */
8107 f.frametype = AST_FRAME_NULL;
8108 f.subclass = 0;
8111 if (!fr->callno) {
8112 int check_dcallno = 0;
8115 * We enforce accurate destination call numbers for all full frames except
8116 * LAGRQ and PING commands. This is because older versions of Asterisk
8117 * schedule these commands to get sent very quickly, and they will sometimes
8118 * be sent before they receive the first frame from the other side. When
8119 * that happens, it doesn't contain the destination call number. However,
8120 * not checking it for these frames is safe.
8122 * Discussed in the following thread:
8123 * http://lists.digium.com/pipermail/asterisk-dev/2008-May/033217.html
8126 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
8127 check_dcallno = f.frametype == AST_FRAME_IAX ? (f.subclass != IAX_COMMAND_PING && f.subclass != IAX_COMMAND_LAGRQ) : 1;
8130 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno);
8133 if (fr->callno > 0)
8134 ast_mutex_lock(&iaxsl[fr->callno]);
8136 if (!fr->callno || !iaxs[fr->callno]) {
8137 /* A call arrived for a nonexistent destination. Unless it's an "inval"
8138 frame, reply with an inval */
8139 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
8140 /* We can only raw hangup control frames */
8141 if (((f.subclass != IAX_COMMAND_INVAL) &&
8142 (f.subclass != IAX_COMMAND_TXCNT) &&
8143 (f.subclass != IAX_COMMAND_TXACC) &&
8144 (f.subclass != IAX_COMMAND_FWDOWNL))||
8145 (f.frametype != AST_FRAME_IAX))
8146 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
8147 fd);
8149 if (fr->callno > 0)
8150 ast_mutex_unlock(&iaxsl[fr->callno]);
8151 return 1;
8153 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
8154 if (decrypt_frame(fr->callno, fh, &f, &res)) {
8155 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
8156 ast_mutex_unlock(&iaxsl[fr->callno]);
8157 return 1;
8159 #ifdef DEBUG_SUPPORT
8160 else
8161 iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
8162 #endif
8165 /* count this frame */
8166 iaxs[fr->callno]->frames_received++;
8168 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
8169 f.subclass != IAX_COMMAND_TXCNT && /* for attended transfer */
8170 f.subclass != IAX_COMMAND_TXACC) { /* for attended transfer */
8171 unsigned short new_peercallno;
8173 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
8174 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
8175 if (iaxs[fr->callno]->peercallno) {
8176 remove_by_peercallno(iaxs[fr->callno]);
8178 iaxs[fr->callno]->peercallno = new_peercallno;
8179 store_by_peercallno(iaxs[fr->callno]);
8182 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
8183 if (iaxdebug)
8184 ast_debug(1, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
8185 /* Check if it's out of order (and not an ACK or INVAL) */
8186 fr->oseqno = fh->oseqno;
8187 fr->iseqno = fh->iseqno;
8188 fr->ts = ntohl(fh->ts);
8189 #ifdef IAXTESTS
8190 if (test_resync) {
8191 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
8192 fr->ts += test_resync;
8194 #endif /* IAXTESTS */
8195 #if 0
8196 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
8197 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
8198 (f.subclass == IAX_COMMAND_NEW ||
8199 f.subclass == IAX_COMMAND_AUTHREQ ||
8200 f.subclass == IAX_COMMAND_ACCEPT ||
8201 f.subclass == IAX_COMMAND_REJECT)) ) )
8202 #endif
8203 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
8204 updatehistory = 0;
8205 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
8206 (iaxs[fr->callno]->iseqno ||
8207 ((f.subclass != IAX_COMMAND_TXCNT) &&
8208 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
8209 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
8210 (f.subclass != IAX_COMMAND_TXMEDIA) && /* for attended transfer */
8211 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
8212 (f.subclass != IAX_COMMAND_TXACC)) ||
8213 (f.frametype != AST_FRAME_IAX))) {
8214 if (
8215 ((f.subclass != IAX_COMMAND_ACK) &&
8216 (f.subclass != IAX_COMMAND_INVAL) &&
8217 (f.subclass != IAX_COMMAND_TXCNT) &&
8218 (f.subclass != IAX_COMMAND_TXREADY) && /* for attended transfer */
8219 (f.subclass != IAX_COMMAND_TXREL) && /* for attended transfer */
8220 (f.subclass != IAX_COMMAND_TXMEDIA) && /* for attended transfer */
8221 (f.subclass != IAX_COMMAND_UNQUELCH ) && /* for attended transfer */
8222 (f.subclass != IAX_COMMAND_TXACC) &&
8223 (f.subclass != IAX_COMMAND_VNAK)) ||
8224 (f.frametype != AST_FRAME_IAX)) {
8225 /* If it's not an ACK packet, it's out of order. */
8226 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
8227 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
8228 /* Check to see if we need to request retransmission,
8229 * and take sequence number wraparound into account */
8230 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
8231 /* If we've already seen it, ack it XXX There's a border condition here XXX */
8232 if ((f.frametype != AST_FRAME_IAX) ||
8233 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
8234 ast_debug(1, "Acking anyway\n");
8235 /* XXX Maybe we should handle its ack to us, but then again, it's probably outdated anyway, and if
8236 we have anything to send, we'll retransmit and get an ACK back anyway XXX */
8237 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8239 } else {
8240 /* Send a VNAK requesting retransmission */
8241 iax2_vnak(fr->callno);
8243 ast_mutex_unlock(&iaxsl[fr->callno]);
8244 return 1;
8246 } else {
8247 /* Increment unless it's an ACK or VNAK */
8248 if (((f.subclass != IAX_COMMAND_ACK) &&
8249 (f.subclass != IAX_COMMAND_INVAL) &&
8250 (f.subclass != IAX_COMMAND_TXCNT) &&
8251 (f.subclass != IAX_COMMAND_TXACC) &&
8252 (f.subclass != IAX_COMMAND_VNAK)) ||
8253 (f.frametype != AST_FRAME_IAX))
8254 iaxs[fr->callno]->iseqno++;
8256 /* A full frame */
8257 if (res < sizeof(*fh)) {
8258 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*fh));
8259 ast_mutex_unlock(&iaxsl[fr->callno]);
8260 return 1;
8262 /* Ensure text frames are NULL-terminated */
8263 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
8264 if (res < thread->buf_size)
8265 thread->buf[res++] = '\0';
8266 else /* Trims one character from the text message, but that's better than overwriting the end of the buffer. */
8267 thread->buf[res - 1] = '\0';
8269 f.datalen = res - sizeof(*fh);
8271 /* Handle implicit ACKing unless this is an INVAL, and only if this is
8272 from the real peer, not the transfer peer */
8273 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
8274 ((f.subclass != IAX_COMMAND_INVAL) ||
8275 (f.frametype != AST_FRAME_IAX))) {
8276 unsigned char x;
8277 int call_to_destroy;
8278 /* First we have to qualify that the ACKed value is within our window */
8279 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
8280 x = fr->iseqno;
8281 else
8282 x = iaxs[fr->callno]->oseqno;
8283 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
8284 /* The acknowledgement is within our window. Time to acknowledge everything
8285 that it says to */
8286 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
8287 /* Ack the packet with the given timestamp */
8288 if (iaxdebug)
8289 ast_debug(1, "Cancelling transmission of packet %d\n", x);
8290 call_to_destroy = 0;
8291 AST_LIST_LOCK(&frame_queue);
8292 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
8293 /* If it's our call, and our timestamp, mark -1 retries */
8294 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
8295 cur->retries = -1;
8296 /* Destroy call if this is the end */
8297 if (cur->final)
8298 call_to_destroy = fr->callno;
8301 AST_LIST_UNLOCK(&frame_queue);
8302 if (call_to_destroy) {
8303 if (iaxdebug)
8304 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
8305 ast_mutex_lock(&iaxsl[call_to_destroy]);
8306 iax2_destroy(call_to_destroy);
8307 ast_mutex_unlock(&iaxsl[call_to_destroy]);
8310 /* Note how much we've received acknowledgement for */
8311 if (iaxs[fr->callno])
8312 iaxs[fr->callno]->rseqno = fr->iseqno;
8313 else {
8314 /* Stop processing now */
8315 ast_mutex_unlock(&iaxsl[fr->callno]);
8316 return 1;
8318 } else {
8319 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
8322 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) && inaddrcmp(&sin, &iaxs[fr->callno]->media) &&
8323 ((f.frametype != AST_FRAME_IAX) ||
8324 ((f.subclass != IAX_COMMAND_TXACC) &&
8325 (f.subclass != IAX_COMMAND_TXCNT)))) {
8326 /* Only messages we accept from a transfer host are TXACC and TXCNT */
8327 ast_mutex_unlock(&iaxsl[fr->callno]);
8328 return 1;
8331 if (f.datalen) {
8332 if (f.frametype == AST_FRAME_IAX) {
8333 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
8334 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
8335 ast_mutex_unlock(&iaxsl[fr->callno]);
8336 return 1;
8338 f.data.ptr = NULL;
8339 f.datalen = 0;
8340 } else
8341 f.data.ptr = thread->buf + sizeof(*fh);
8342 } else {
8343 if (f.frametype == AST_FRAME_IAX)
8344 f.data.ptr = NULL;
8345 else
8346 f.data.ptr = empty;
8347 memset(&ies, 0, sizeof(ies));
8350 /* when we receive the first full frame for a new incoming channel,
8351 it is safe to start the PBX on the channel because we have now
8352 completed a 3-way handshake with the peer */
8353 if ((f.frametype == AST_FRAME_VOICE) ||
8354 (f.frametype == AST_FRAME_VIDEO) ||
8355 (f.frametype == AST_FRAME_IAX)) {
8356 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
8357 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
8358 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
8359 ast_mutex_unlock(&iaxsl[fr->callno]);
8360 return 1;
8361 } else if (ies.vars) {
8362 struct ast_datastore *variablestore;
8363 struct ast_variable *var, *prev = NULL;
8364 AST_LIST_HEAD(, ast_var_t) *varlist;
8365 varlist = ast_calloc(1, sizeof(*varlist));
8366 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
8367 if (variablestore && varlist) {
8368 variablestore->data = varlist;
8369 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
8370 AST_LIST_HEAD_INIT(varlist);
8371 for (var = ies.vars; var; var = var->next) {
8372 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
8373 if (prev)
8374 ast_free(prev);
8375 prev = var;
8376 if (!newvar) {
8377 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
8378 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8379 } else {
8380 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
8383 if (prev)
8384 ast_free(prev);
8385 ies.vars = NULL;
8386 ast_channel_datastore_add(c, variablestore);
8387 } else {
8388 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
8389 if (variablestore)
8390 ast_datastore_free(variablestore);
8391 if (varlist)
8392 ast_free(varlist);
8398 if (f.frametype == AST_FRAME_VOICE) {
8399 if (f.subclass != iaxs[fr->callno]->voiceformat) {
8400 iaxs[fr->callno]->voiceformat = f.subclass;
8401 ast_debug(1, "Ooh, voice format changed to %d\n", f.subclass);
8402 if (iaxs[fr->callno]->owner) {
8403 int orignative;
8404 retryowner:
8405 if (ast_channel_trylock(iaxs[fr->callno]->owner)) {
8406 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
8407 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
8409 if (iaxs[fr->callno]) {
8410 if (iaxs[fr->callno]->owner) {
8411 orignative = iaxs[fr->callno]->owner->nativeformats;
8412 iaxs[fr->callno]->owner->nativeformats = f.subclass;
8413 if (iaxs[fr->callno]->owner->readformat)
8414 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
8415 iaxs[fr->callno]->owner->nativeformats = orignative;
8416 ast_channel_unlock(iaxs[fr->callno]->owner);
8418 } else {
8419 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
8420 /* Free remote variables (if any) */
8421 if (ies.vars)
8422 ast_variables_destroy(ies.vars);
8423 ast_mutex_unlock(&iaxsl[fr->callno]);
8424 return 1;
8429 if (f.frametype == AST_FRAME_VIDEO) {
8430 if (f.subclass != iaxs[fr->callno]->videoformat) {
8431 ast_debug(1, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
8432 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
8435 if (f.frametype == AST_FRAME_IAX) {
8436 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
8437 /* Handle the IAX pseudo frame itself */
8438 if (iaxdebug)
8439 ast_debug(1, "IAX subclass %d received\n", f.subclass);
8441 /* Update last ts unless the frame's timestamp originated with us. */
8442 if (iaxs[fr->callno]->last < fr->ts &&
8443 f.subclass != IAX_COMMAND_ACK &&
8444 f.subclass != IAX_COMMAND_PONG &&
8445 f.subclass != IAX_COMMAND_LAGRP) {
8446 iaxs[fr->callno]->last = fr->ts;
8447 if (iaxdebug)
8448 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
8451 switch(f.subclass) {
8452 case IAX_COMMAND_ACK:
8453 /* Do nothing */
8454 break;
8455 case IAX_COMMAND_QUELCH:
8456 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8457 /* Generate Manager Hold event, if necessary*/
8458 if (iaxs[fr->callno]->owner) {
8459 manager_event(EVENT_FLAG_CALL, "Hold",
8460 "Status: On\r\n"
8461 "Channel: %s\r\n"
8462 "Uniqueid: %s\r\n",
8463 iaxs[fr->callno]->owner->name,
8464 iaxs[fr->callno]->owner->uniqueid);
8467 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
8468 if (ies.musiconhold) {
8469 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
8470 const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
8471 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
8472 S_OR(moh_suggest, NULL),
8473 !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
8474 if (!iaxs[fr->callno]) {
8475 ast_mutex_unlock(&iaxsl[fr->callno]);
8476 return 1;
8481 break;
8482 case IAX_COMMAND_UNQUELCH:
8483 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
8484 /* Generate Manager Unhold event, if necessary*/
8485 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
8486 manager_event(EVENT_FLAG_CALL, "Hold",
8487 "Status: Off\r\n"
8488 "Channel: %s\r\n"
8489 "Uniqueid: %s\r\n",
8490 iaxs[fr->callno]->owner->name,
8491 iaxs[fr->callno]->owner->uniqueid);
8494 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
8495 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
8496 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
8497 if (!iaxs[fr->callno]) {
8498 ast_mutex_unlock(&iaxsl[fr->callno]);
8499 return 1;
8503 break;
8504 case IAX_COMMAND_TXACC:
8505 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) &&
8506 (iaxs[fr->callno]->transferid == ies.transferid)) {
8507 /* Cancel any outstanding txcnt's */
8508 AST_LIST_LOCK(&frame_queue);
8509 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
8510 if ((fr->callno == cur->callno) && (cur->transfer))
8511 cur->retries = -1;
8513 AST_LIST_UNLOCK(&frame_queue);
8514 memset(&ied1, 0, sizeof(ied1));
8515 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
8516 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, iaxs[fr->callno]->transferid);
8517 if (iaxs[fr->callno]->mediareleased) {
8518 send_command_media(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos);
8519 } else {
8520 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
8522 iaxs[fr->callno]->transferring = TRANSFER_READY;
8524 break;
8525 case IAX_COMMAND_NEW:
8526 /* Ignore if it's already up */
8527 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
8528 break;
8529 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
8530 ast_mutex_unlock(&iaxsl[fr->callno]);
8531 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
8532 ast_mutex_lock(&iaxsl[fr->callno]);
8533 if (!iaxs[fr->callno]) {
8534 ast_mutex_unlock(&iaxsl[fr->callno]);
8535 return 1;
8538 /* If we're in trunk mode, do it now, and update the trunk number in our frame before continuing */
8539 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
8540 int new_callno;
8541 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
8542 fr->callno = new_callno;
8544 /* For security, always ack immediately */
8545 if (delayreject)
8546 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8547 if (check_access(fr->callno, &sin, &ies)) {
8548 /* They're not allowed on */
8549 auth_fail(fr->callno, IAX_COMMAND_REJECT);
8550 if (authdebug)
8551 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, who was trying to reach '%s@%s'\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
8552 break;
8554 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
8555 const char *context, *exten, *cid_num;
8557 context = ast_strdupa(iaxs[fr->callno]->context);
8558 exten = ast_strdupa(iaxs[fr->callno]->exten);
8559 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
8561 /* This might re-enter the IAX code and need the lock */
8562 ast_mutex_unlock(&iaxsl[fr->callno]);
8563 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
8564 ast_mutex_lock(&iaxsl[fr->callno]);
8566 if (!iaxs[fr->callno]) {
8567 ast_mutex_unlock(&iaxsl[fr->callno]);
8568 return 1;
8570 } else
8571 exists = 0;
8572 /* Get OSP token if it does exist */
8573 save_osptoken(fr, &ies);
8574 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
8575 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
8576 memset(&ied0, 0, sizeof(ied0));
8577 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
8578 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
8579 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8580 if (!iaxs[fr->callno]) {
8581 ast_mutex_unlock(&iaxsl[fr->callno]);
8582 return 1;
8584 if (authdebug)
8585 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
8586 } else {
8587 /* Select an appropriate format */
8589 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
8590 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8591 using_prefs = "reqonly";
8592 } else {
8593 using_prefs = "disabled";
8595 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
8596 memset(&pref, 0, sizeof(pref));
8597 strcpy(caller_pref_buf, "disabled");
8598 strcpy(host_pref_buf, "disabled");
8599 } else {
8600 using_prefs = "mine";
8601 /* If the information elements are in here... use them */
8602 if (ies.codec_prefs)
8603 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
8604 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
8605 /* If we are codec_first_choice we let the caller have the 1st shot at picking the codec.*/
8606 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
8607 pref = iaxs[fr->callno]->rprefs;
8608 using_prefs = "caller";
8609 } else {
8610 pref = iaxs[fr->callno]->prefs;
8612 } else
8613 pref = iaxs[fr->callno]->prefs;
8615 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
8616 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
8617 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
8619 if (!format) {
8620 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8621 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
8622 if (!format) {
8623 memset(&ied0, 0, sizeof(ied0));
8624 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8625 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8626 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8627 if (!iaxs[fr->callno]) {
8628 ast_mutex_unlock(&iaxsl[fr->callno]);
8629 return 1;
8631 if (authdebug) {
8632 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
8633 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
8634 else
8635 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
8637 } else {
8638 /* Pick one... */
8639 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
8640 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
8641 format = 0;
8642 } else {
8643 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
8644 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
8645 memset(&pref, 0, sizeof(pref));
8646 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8647 strcpy(caller_pref_buf,"disabled");
8648 strcpy(host_pref_buf,"disabled");
8649 } else {
8650 using_prefs = "mine";
8651 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
8652 /* Do the opposite of what we tried above. */
8653 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
8654 pref = iaxs[fr->callno]->prefs;
8655 } else {
8656 pref = iaxs[fr->callno]->rprefs;
8657 using_prefs = "caller";
8659 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
8661 } else /* if no codec_prefs IE do it the old way */
8662 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8666 if (!format) {
8667 memset(&ied0, 0, sizeof(ied0));
8668 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8669 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8670 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
8671 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8672 if (!iaxs[fr->callno]) {
8673 ast_mutex_unlock(&iaxsl[fr->callno]);
8674 return 1;
8676 if (authdebug)
8677 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
8678 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8679 break;
8683 if (format) {
8684 /* No authentication required, let them in */
8685 memset(&ied1, 0, sizeof(ied1));
8686 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
8687 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
8688 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
8689 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8690 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
8691 "%srequested format = %s,\n"
8692 "%srequested prefs = %s,\n"
8693 "%sactual format = %s,\n"
8694 "%shost prefs = %s,\n"
8695 "%spriority = %s\n",
8696 ast_inet_ntoa(sin.sin_addr),
8697 VERBOSE_PREFIX_4,
8698 ast_getformatname(iaxs[fr->callno]->peerformat),
8699 VERBOSE_PREFIX_4,
8700 caller_pref_buf,
8701 VERBOSE_PREFIX_4,
8702 ast_getformatname(format),
8703 VERBOSE_PREFIX_4,
8704 host_pref_buf,
8705 VERBOSE_PREFIX_4,
8706 using_prefs);
8708 iaxs[fr->callno]->chosenformat = format;
8709 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
8710 } else {
8711 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
8712 /* If this is a TBD call, we're ready but now what... */
8713 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
8717 break;
8719 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
8720 merge_encryption(iaxs[fr->callno],ies.encmethods);
8721 else
8722 iaxs[fr->callno]->encmethods = 0;
8723 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
8724 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
8725 if (!iaxs[fr->callno]) {
8726 ast_mutex_unlock(&iaxsl[fr->callno]);
8727 return 1;
8729 break;
8730 case IAX_COMMAND_DPREQ:
8731 /* Request status in the dialplan */
8732 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
8733 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
8734 if (iaxcompat) {
8735 /* Spawn a thread for the lookup */
8736 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
8737 } else {
8738 /* Just look it up */
8739 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
8742 break;
8743 case IAX_COMMAND_HANGUP:
8744 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
8745 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
8746 /* Set hangup cause according to remote */
8747 if (ies.causecode && iaxs[fr->callno]->owner)
8748 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
8749 /* Send ack immediately, before we destroy */
8750 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8751 iax2_destroy(fr->callno);
8752 break;
8753 case IAX_COMMAND_REJECT:
8754 /* Set hangup cause according to remote */
8755 if (ies.causecode && iaxs[fr->callno]->owner)
8756 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
8758 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
8759 if (iaxs[fr->callno]->owner && authdebug)
8760 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
8761 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
8762 ies.cause ? ies.cause : "<Unknown>");
8763 ast_debug(1, "Immediately destroying %d, having received reject\n",
8764 fr->callno);
8766 /* Send ack immediately, before we destroy */
8767 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
8768 fr->ts, NULL, 0, fr->iseqno);
8769 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
8770 iaxs[fr->callno]->error = EPERM;
8771 iax2_destroy(fr->callno);
8772 break;
8773 case IAX_COMMAND_TRANSFER:
8775 struct ast_channel *bridged_chan;
8777 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
8778 /* Set BLINDTRANSFER channel variables */
8780 ast_mutex_unlock(&iaxsl[fr->callno]);
8781 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
8782 ast_mutex_lock(&iaxsl[fr->callno]);
8783 if (!iaxs[fr->callno]) {
8784 ast_mutex_unlock(&iaxsl[fr->callno]);
8785 return 1;
8788 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
8789 if (!strcmp(ies.called_number, ast_parking_ext())) {
8790 struct ast_channel *saved_channel = iaxs[fr->callno]->owner;
8791 ast_mutex_unlock(&iaxsl[fr->callno]);
8792 if (iax_park(bridged_chan, saved_channel)) {
8793 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
8794 } else {
8795 ast_debug(1, "Parked call on '%s'\n", ast_bridged_channel(iaxs[fr->callno]->owner)->name);
8797 ast_mutex_lock(&iaxsl[fr->callno]);
8798 } else {
8799 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
8800 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
8801 ies.called_number, iaxs[fr->callno]->context);
8802 else {
8803 ast_debug(1, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
8804 ies.called_number, iaxs[fr->callno]->context);
8807 } else {
8808 ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
8811 break;
8813 case IAX_COMMAND_ACCEPT:
8814 /* Ignore if call is already up or needs authentication or is a TBD */
8815 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
8816 break;
8817 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
8818 /* Send ack immediately, before we destroy */
8819 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8820 iax2_destroy(fr->callno);
8821 break;
8823 if (ies.format) {
8824 iaxs[fr->callno]->peerformat = ies.format;
8825 } else {
8826 if (iaxs[fr->callno]->owner)
8827 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
8828 else
8829 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
8831 ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
8832 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
8833 memset(&ied0, 0, sizeof(ied0));
8834 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
8835 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
8836 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
8837 if (!iaxs[fr->callno]) {
8838 ast_mutex_unlock(&iaxsl[fr->callno]);
8839 return 1;
8841 if (authdebug)
8842 ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
8843 } else {
8844 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
8845 if (iaxs[fr->callno]->owner) {
8846 /* Switch us to use a compatible format */
8847 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
8848 ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
8849 retryowner2:
8850 if (ast_channel_trylock(iaxs[fr->callno]->owner)) {
8851 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
8852 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
8855 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
8856 /* Setup read/write formats properly. */
8857 if (iaxs[fr->callno]->owner->writeformat)
8858 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
8859 if (iaxs[fr->callno]->owner->readformat)
8860 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
8861 ast_channel_unlock(iaxs[fr->callno]->owner);
8865 if (iaxs[fr->callno]) {
8866 AST_LIST_LOCK(&dpcache);
8867 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
8868 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
8869 iax2_dprequest(dp, fr->callno);
8870 AST_LIST_UNLOCK(&dpcache);
8872 break;
8873 case IAX_COMMAND_POKE:
8874 /* Send back a pong packet with the original timestamp */
8875 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
8876 if (!iaxs[fr->callno]) {
8877 ast_mutex_unlock(&iaxsl[fr->callno]);
8878 return 1;
8880 break;
8881 case IAX_COMMAND_PING:
8883 struct iax_ie_data pingied;
8884 construct_rr(iaxs[fr->callno], &pingied);
8885 /* Send back a pong packet with the original timestamp */
8886 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
8888 break;
8889 case IAX_COMMAND_PONG:
8890 /* Calculate ping time */
8891 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
8892 /* save RR info */
8893 save_rr(fr, &ies);
8895 /* Good time to write jb stats for this call */
8896 log_jitterstats(fr->callno);
8898 if (iaxs[fr->callno]->peerpoke) {
8899 peer = iaxs[fr->callno]->peerpoke;
8900 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
8901 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
8902 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
8903 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
8904 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name); /* Activate notification */
8906 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
8907 if (iaxs[fr->callno]->pingtime > peer->maxms) {
8908 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
8909 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
8910 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
8913 peer->lastms = iaxs[fr->callno]->pingtime;
8914 if (peer->smoothing && (peer->lastms > -1))
8915 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
8916 else if (peer->smoothing && peer->lastms < 0)
8917 peer->historicms = (0 + peer->historicms) / 2;
8918 else
8919 peer->historicms = iaxs[fr->callno]->pingtime;
8921 /* Remove scheduled iax2_poke_noanswer */
8922 if (peer->pokeexpire > -1) {
8923 if (!ast_sched_del(sched, peer->pokeexpire)) {
8924 peer_unref(peer);
8925 peer->pokeexpire = -1;
8928 /* Schedule the next cycle */
8929 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
8930 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
8931 else
8932 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
8933 if (peer->pokeexpire == -1)
8934 peer_unref(peer);
8935 /* and finally send the ack */
8936 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8937 /* And wrap up the qualify call */
8938 iax2_destroy(fr->callno);
8939 peer->callno = 0;
8940 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
8942 break;
8943 case IAX_COMMAND_LAGRQ:
8944 case IAX_COMMAND_LAGRP:
8945 f.src = "LAGRQ";
8946 f.mallocd = 0;
8947 f.offset = 0;
8948 f.samples = 0;
8949 iax_frame_wrap(fr, &f);
8950 if(f.subclass == IAX_COMMAND_LAGRQ) {
8951 /* Received a LAGRQ - echo back a LAGRP */
8952 fr->af.subclass = IAX_COMMAND_LAGRP;
8953 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0, 0);
8954 } else {
8955 /* Received LAGRP in response to our LAGRQ */
8956 unsigned int ts;
8957 /* This is a reply we've been given, actually measure the difference */
8958 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
8959 iaxs[fr->callno]->lag = ts - fr->ts;
8960 if (iaxdebug)
8961 ast_debug(1, "Peer %s lag measured as %dms\n",
8962 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
8964 break;
8965 case IAX_COMMAND_AUTHREQ:
8966 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
8967 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8968 break;
8970 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
8971 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
8972 .subclass = AST_CONTROL_HANGUP,
8974 ast_log(LOG_WARNING,
8975 "I don't know how to authenticate %s to %s\n",
8976 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
8977 iax2_queue_frame(fr->callno, &hangup_fr);
8979 if (!iaxs[fr->callno]) {
8980 ast_mutex_unlock(&iaxsl[fr->callno]);
8981 return 1;
8983 break;
8984 case IAX_COMMAND_AUTHREP:
8985 /* For security, always ack immediately */
8986 if (delayreject)
8987 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
8988 /* Ignore once we've started */
8989 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
8990 ast_log(LOG_WARNING, "Call on %s is already up, can't start on it\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
8991 break;
8993 if (authenticate_verify(iaxs[fr->callno], &ies)) {
8994 if (authdebug)
8995 ast_log(LOG_NOTICE, "Host %s failed to authenticate as %s\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->username);
8996 memset(&ied0, 0, sizeof(ied0));
8997 auth_fail(fr->callno, IAX_COMMAND_REJECT);
8998 break;
9000 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
9001 /* This might re-enter the IAX code and need the lock */
9002 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
9003 } else
9004 exists = 0;
9005 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
9006 if (authdebug)
9007 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
9008 memset(&ied0, 0, sizeof(ied0));
9009 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
9010 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
9011 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9012 if (!iaxs[fr->callno]) {
9013 ast_mutex_unlock(&iaxsl[fr->callno]);
9014 return 1;
9016 } else {
9017 /* Select an appropriate format */
9018 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
9019 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
9020 using_prefs = "reqonly";
9021 } else {
9022 using_prefs = "disabled";
9024 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
9025 memset(&pref, 0, sizeof(pref));
9026 strcpy(caller_pref_buf, "disabled");
9027 strcpy(host_pref_buf, "disabled");
9028 } else {
9029 using_prefs = "mine";
9030 if (ies.codec_prefs)
9031 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
9032 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
9033 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
9034 pref = iaxs[fr->callno]->rprefs;
9035 using_prefs = "caller";
9036 } else {
9037 pref = iaxs[fr->callno]->prefs;
9039 } else /* if no codec_prefs IE do it the old way */
9040 pref = iaxs[fr->callno]->prefs;
9042 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
9043 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
9044 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
9046 if (!format) {
9047 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
9048 ast_debug(1, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
9049 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
9051 if (!format) {
9052 if (authdebug) {
9053 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
9054 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
9055 else
9056 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
9058 memset(&ied0, 0, sizeof(ied0));
9059 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
9060 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
9061 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9062 if (!iaxs[fr->callno]) {
9063 ast_mutex_unlock(&iaxsl[fr->callno]);
9064 return 1;
9066 } else {
9067 /* Pick one... */
9068 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
9069 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
9070 format = 0;
9071 } else {
9072 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
9073 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
9074 memset(&pref, 0, sizeof(pref));
9075 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
9076 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
9077 strcpy(caller_pref_buf,"disabled");
9078 strcpy(host_pref_buf,"disabled");
9079 } else {
9080 using_prefs = "mine";
9081 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
9082 /* Do the opposite of what we tried above. */
9083 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
9084 pref = iaxs[fr->callno]->prefs;
9085 } else {
9086 pref = iaxs[fr->callno]->rprefs;
9087 using_prefs = "caller";
9089 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
9090 } else /* if no codec_prefs IE do it the old way */
9091 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
9094 if (!format) {
9095 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
9096 if (authdebug) {
9097 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
9098 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
9099 else
9100 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
9102 memset(&ied0, 0, sizeof(ied0));
9103 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
9104 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
9105 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9106 if (!iaxs[fr->callno]) {
9107 ast_mutex_unlock(&iaxsl[fr->callno]);
9108 return 1;
9113 if (format) {
9114 /* Authentication received */
9115 memset(&ied1, 0, sizeof(ied1));
9116 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
9117 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
9118 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
9119 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
9120 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
9121 "%srequested format = %s,\n"
9122 "%srequested prefs = %s,\n"
9123 "%sactual format = %s,\n"
9124 "%shost prefs = %s,\n"
9125 "%spriority = %s\n",
9126 ast_inet_ntoa(sin.sin_addr),
9127 VERBOSE_PREFIX_4,
9128 ast_getformatname(iaxs[fr->callno]->peerformat),
9129 VERBOSE_PREFIX_4,
9130 caller_pref_buf,
9131 VERBOSE_PREFIX_4,
9132 ast_getformatname(format),
9133 VERBOSE_PREFIX_4,
9134 host_pref_buf,
9135 VERBOSE_PREFIX_4,
9136 using_prefs);
9138 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
9139 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
9140 iax2_destroy(fr->callno);
9141 else if (ies.vars) {
9142 struct ast_datastore *variablestore;
9143 struct ast_variable *var, *prev = NULL;
9144 AST_LIST_HEAD(, ast_var_t) *varlist;
9145 varlist = ast_calloc(1, sizeof(*varlist));
9146 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
9147 if (variablestore && varlist) {
9148 variablestore->data = varlist;
9149 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
9150 AST_LIST_HEAD_INIT(varlist);
9151 for (var = ies.vars; var; var = var->next) {
9152 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
9153 if (prev)
9154 ast_free(prev);
9155 prev = var;
9156 if (!newvar) {
9157 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
9158 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
9159 } else {
9160 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
9163 if (prev)
9164 ast_free(prev);
9165 ies.vars = NULL;
9166 ast_channel_datastore_add(c, variablestore);
9167 } else {
9168 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
9169 if (variablestore)
9170 ast_datastore_free(variablestore);
9171 if (varlist)
9172 ast_free(varlist);
9175 } else {
9176 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
9177 /* If this is a TBD call, we're ready but now what... */
9178 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
9182 break;
9183 case IAX_COMMAND_DIAL:
9184 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
9185 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
9186 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
9187 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
9188 if (authdebug)
9189 ast_log(LOG_NOTICE, "Rejected dial attempt from %s, request '%s@%s' does not exist\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->exten, iaxs[fr->callno]->context);
9190 memset(&ied0, 0, sizeof(ied0));
9191 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
9192 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
9193 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9194 if (!iaxs[fr->callno]) {
9195 ast_mutex_unlock(&iaxsl[fr->callno]);
9196 return 1;
9198 } else {
9199 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
9200 ast_verb(3, "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
9201 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
9202 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
9203 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
9204 iax2_destroy(fr->callno);
9205 else if (ies.vars) {
9206 struct ast_datastore *variablestore;
9207 struct ast_variable *var, *prev = NULL;
9208 AST_LIST_HEAD(, ast_var_t) *varlist;
9209 varlist = ast_calloc(1, sizeof(*varlist));
9210 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
9211 if (variablestore && varlist) {
9212 variablestore->data = varlist;
9213 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
9214 AST_LIST_HEAD_INIT(varlist);
9215 for (var = ies.vars; var; var = var->next) {
9216 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
9217 if (prev)
9218 ast_free(prev);
9219 prev = var;
9220 if (!newvar) {
9221 /* Don't abort list traversal, as this would leave ies.vars in an inconsistent state. */
9222 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
9223 } else {
9224 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
9227 if (prev)
9228 ast_free(prev);
9229 ies.vars = NULL;
9230 ast_channel_datastore_add(c, variablestore);
9231 } else {
9232 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
9233 if (variablestore)
9234 ast_datastore_free(variablestore);
9235 if (varlist)
9236 ast_free(varlist);
9241 break;
9242 case IAX_COMMAND_INVAL:
9243 iaxs[fr->callno]->error = ENOTCONN;
9244 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
9245 iax2_destroy(fr->callno);
9246 ast_debug(1, "Destroying call %d\n", fr->callno);
9247 break;
9248 case IAX_COMMAND_VNAK:
9249 ast_debug(1, "Received VNAK: resending outstanding frames\n");
9250 /* Force retransmission */
9251 vnak_retransmit(fr->callno, fr->iseqno);
9252 break;
9253 case IAX_COMMAND_REGREQ:
9254 case IAX_COMMAND_REGREL:
9255 /* For security, always ack immediately */
9256 if (delayreject)
9257 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9258 if (register_verify(fr->callno, &sin, &ies)) {
9259 if (!iaxs[fr->callno]) {
9260 ast_mutex_unlock(&iaxsl[fr->callno]);
9261 return 1;
9263 /* Send delayed failure */
9264 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
9265 break;
9267 if (!iaxs[fr->callno]) {
9268 ast_mutex_unlock(&iaxsl[fr->callno]);
9269 return 1;
9271 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
9272 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
9273 if (f.subclass == IAX_COMMAND_REGREL)
9274 memset(&sin, 0, sizeof(sin));
9275 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
9276 ast_log(LOG_WARNING, "Registry error\n");
9277 if (!iaxs[fr->callno]) {
9278 ast_mutex_unlock(&iaxsl[fr->callno]);
9279 return 1;
9281 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
9282 ast_mutex_unlock(&iaxsl[fr->callno]);
9283 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
9284 ast_mutex_lock(&iaxsl[fr->callno]);
9285 if (!iaxs[fr->callno]) {
9286 ast_mutex_unlock(&iaxsl[fr->callno]);
9287 return 1;
9290 break;
9292 registry_authrequest(fr->callno);
9293 if (!iaxs[fr->callno]) {
9294 ast_mutex_unlock(&iaxsl[fr->callno]);
9295 return 1;
9297 break;
9298 case IAX_COMMAND_REGACK:
9299 if (iax2_ack_registry(&ies, &sin, fr->callno))
9300 ast_log(LOG_WARNING, "Registration failure\n");
9301 /* Send ack immediately, before we destroy */
9302 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9303 iax2_destroy(fr->callno);
9304 break;
9305 case IAX_COMMAND_REGREJ:
9306 if (iaxs[fr->callno]->reg) {
9307 if (authdebug) {
9308 ast_log(LOG_NOTICE, "Registration of '%s' rejected: '%s' from: '%s'\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>", ast_inet_ntoa(sin.sin_addr));
9309 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
9311 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
9313 /* Send ack immediately, before we destroy */
9314 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9315 iax2_destroy(fr->callno);
9316 break;
9317 case IAX_COMMAND_REGAUTH:
9318 /* Authentication request */
9319 if (registry_rerequest(&ies, fr->callno, &sin)) {
9320 memset(&ied0, 0, sizeof(ied0));
9321 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
9322 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
9323 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9324 if (!iaxs[fr->callno]) {
9325 ast_mutex_unlock(&iaxsl[fr->callno]);
9326 return 1;
9329 break;
9330 case IAX_COMMAND_TXREJ:
9331 if ((iaxs[fr->callno]->transferring != TRANSFER_NONE) &&
9332 (iaxs[fr->callno]->transferid == ies.transferid)) {
9333 iaxs[fr->callno]->transferring = TRANSFER_NONE;
9334 ast_verb(3, "Channel '%s' transfer rejected\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
9335 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
9336 if (iaxs[fr->callno]->bridgecallno &&
9337 (iaxs[fr->callno]->transferid == iaxs[iaxs[fr->callno]->bridgecallno]->transferid)) {
9338 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
9339 memset(&ied0, 0, sizeof(ied0));
9340 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, iaxs[iaxs[fr->callno]->bridgecallno]->transferid);
9341 if (iaxs[iaxs[fr->callno]->bridgecallno]->mediareleased) {
9342 send_command_media(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied0.buf, ied0.pos);
9343 } else {
9344 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied0.buf, ied0.pos, -1);
9348 break;
9349 case IAX_COMMAND_TXREADY:
9350 if (((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
9351 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) &&
9352 (iaxs[fr->callno]->transferid == ies.transferid)) {
9353 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
9354 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
9355 else
9356 iaxs[fr->callno]->transferring = TRANSFER_READY;
9357 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
9358 if (iaxs[fr->callno]->bridgecallno) {
9359 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
9360 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
9361 /* They're both ready, now release them. */
9362 /* If a peer is media released, we must also do a media release as there may be peers in between */
9363 if (iaxs[fr->callno]->mediareleased ||
9364 iaxs[iaxs[fr->callno]->bridgecallno]->mediareleased ||
9365 (iaxs[fr->callno]->transferring == TRANSFER_MREADY)) {
9367 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
9368 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
9370 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MRELEASED;
9371 iaxs[fr->callno]->transferring = TRANSFER_MRELEASED;
9373 memset(&ied0, 0, sizeof(ied0));
9374 memset(&ied1, 0, sizeof(ied1));
9375 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
9376 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, iaxs[iaxs[fr->callno]->bridgecallno]->transferid);
9377 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
9378 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, iaxs[fr->callno]->transferid);
9379 if (iaxs[fr->callno]->mediareleased) {
9380 send_command_media(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos);
9381 } else {
9382 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
9384 if (iaxs[iaxs[fr->callno]->bridgecallno]->mediareleased) {
9385 send_command_media(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos);
9386 } else {
9387 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
9389 } else {
9390 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
9391 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
9393 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
9394 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
9395 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
9396 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
9398 /* Stop doing lag & ping requests */
9399 stop_stuff(fr->callno);
9400 stop_stuff(iaxs[fr->callno]->bridgecallno);
9402 memset(&ied0, 0, sizeof(ied0));
9403 memset(&ied1, 0, sizeof(ied1));
9404 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
9405 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, iaxs[iaxs[fr->callno]->bridgecallno]->transferid);
9406 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
9407 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, iaxs[fr->callno]->transferid);
9408 if (iaxs[fr->callno]->mediareleased) {
9409 send_command_media(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos);
9410 } else {
9411 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
9413 if (iaxs[iaxs[fr->callno]->bridgecallno]->mediareleased) {
9414 send_command_media(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos);
9415 } else {
9416 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
9423 break;
9424 case IAX_COMMAND_TXREQ:
9425 /* Try transfer only if none in progress, or use the transferid to resolve contention */
9426 if ((iaxs[fr->callno]->transferring == TRANSFER_NONE) ||
9427 (iaxs[fr->callno]->transferid <= ies.transferid)) {
9428 /* If there is a bridged channel and it is the same transfer, reject it */
9429 if (iaxs[fr->callno]->bridgecallno &&
9430 (iaxs[fr->callno]->transferid == iaxs[iaxs[fr->callno]->bridgecallno]->transferid)) {
9431 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_NONE;
9432 memset(&ied0, 0, sizeof(ied0));
9433 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, iaxs[iaxs[fr->callno]->bridgecallno]->transferid);
9434 if (iaxs[iaxs[fr->callno]->bridgecallno]->mediareleased) {
9435 send_command_media(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied0.buf, ied0.pos);
9436 } else {
9437 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, ied0.buf, ied0.pos, -1);
9439 /* Start our transfer again later */
9440 iaxs[fr->callno]->triedtransfer = 0;
9441 iaxs[iaxs[fr->callno]->bridgecallno]->triedtransfer = 0;
9443 try_transfer(iaxs[fr->callno], &ies);
9446 break;
9447 case IAX_COMMAND_TXCNT:
9448 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) &&
9449 (iaxs[fr->callno]->transferid == ies.transferid)) {
9450 memcpy(&iaxs[fr->callno]->transfer, &sin, sizeof(iaxs[fr->callno]->transfer));
9451 memset(&ied0, 0, sizeof(ied0));
9452 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, iaxs[fr->callno]->transferid);
9453 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, ied0.buf, ied0.pos);
9455 break;
9456 case IAX_COMMAND_TXREL:
9457 if ((iaxs[fr->callno]->transferring == TRANSFER_READY) &&
9458 (iaxs[fr->callno]->transferid == ies.transferid)) {
9459 /* Send ack immediately, rather than waiting until we've changed addresses */
9460 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9461 complete_transfer(fr->callno, &ies);
9462 stop_stuff(fr->callno); /* for attended transfer to work with libiax */
9464 break;
9465 case IAX_COMMAND_TXMEDIA:
9466 if ((iaxs[fr->callno]->transferring == TRANSFER_READY) &&
9467 (iaxs[fr->callno]->transferid == ies.transferid)) {
9469 AST_LIST_LOCK(&frame_queue);
9470 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
9471 /* Cancel any outstanding frames and start anew */
9472 if ((fr->callno == cur->callno) && (cur->transfer))
9473 cur->retries = -1;
9475 AST_LIST_UNLOCK(&frame_queue);
9476 /* Start sending our media to the transfer address, but otherwise leave the call as-is */
9477 memcpy(&iaxs[fr->callno]->media, &iaxs[fr->callno]->transfer, sizeof(iaxs[fr->callno]->addr));
9478 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
9479 iaxs[fr->callno]->transferring = TRANSFER_NONE;
9480 iaxs[fr->callno]->mediareleased = 1;
9482 break;
9483 case IAX_COMMAND_RTKEY:
9484 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
9485 ast_log(LOG_WARNING,
9486 "we've been told to rotate our encryption key, "
9487 "but this isn't an encrypted call. bad things will happen.\n"
9489 break;
9492 IAX_DEBUGDIGEST("Receiving", ies.challenge);
9494 ast_aes_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
9495 break;
9496 case IAX_COMMAND_DPREP:
9497 complete_dpreply(iaxs[fr->callno], &ies);
9498 break;
9499 case IAX_COMMAND_UNSUPPORT:
9500 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
9501 break;
9502 case IAX_COMMAND_FWDOWNL:
9503 /* Firmware download */
9504 if (!ast_test_flag(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
9505 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
9506 break;
9508 memset(&ied0, 0, sizeof(ied0));
9509 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
9510 if (res < 0)
9511 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
9512 else if (res > 0)
9513 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
9514 else
9515 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
9516 if (!iaxs[fr->callno]) {
9517 ast_mutex_unlock(&iaxsl[fr->callno]);
9518 return 1;
9520 break;
9521 default:
9522 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
9523 memset(&ied0, 0, sizeof(ied0));
9524 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
9525 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
9527 /* Free remote variables (if any) */
9528 if (ies.vars)
9529 ast_variables_destroy(ies.vars);
9531 /* Don't actually pass these frames along */
9532 if ((f.subclass != IAX_COMMAND_ACK) &&
9533 (f.subclass != IAX_COMMAND_TXCNT) &&
9534 (f.subclass != IAX_COMMAND_TXACC) &&
9535 (f.subclass != IAX_COMMAND_INVAL) &&
9536 (f.subclass != IAX_COMMAND_VNAK)) {
9537 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
9538 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9540 ast_mutex_unlock(&iaxsl[fr->callno]);
9541 return 1;
9543 /* Unless this is an ACK or INVAL frame, ack it */
9544 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
9545 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
9546 } else if (minivid) {
9547 f.frametype = AST_FRAME_VIDEO;
9548 if (iaxs[fr->callno]->videoformat > 0)
9549 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
9550 else {
9551 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
9552 iax2_vnak(fr->callno);
9553 ast_mutex_unlock(&iaxsl[fr->callno]);
9554 return 1;
9556 f.datalen = res - sizeof(*vh);
9557 if (f.datalen)
9558 f.data.ptr = thread->buf + sizeof(*vh);
9559 else
9560 f.data.ptr = NULL;
9561 #ifdef IAXTESTS
9562 if (test_resync) {
9563 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
9564 } else
9565 #endif /* IAXTESTS */
9566 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
9567 } else {
9568 /* A mini frame */
9569 f.frametype = AST_FRAME_VOICE;
9570 if (iaxs[fr->callno]->voiceformat > 0)
9571 f.subclass = iaxs[fr->callno]->voiceformat;
9572 else {
9573 ast_debug(1, "Received mini frame before first full voice frame\n");
9574 iax2_vnak(fr->callno);
9575 ast_mutex_unlock(&iaxsl[fr->callno]);
9576 return 1;
9578 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
9579 if (f.datalen < 0) {
9580 ast_log(LOG_WARNING, "Datalen < 0?\n");
9581 ast_mutex_unlock(&iaxsl[fr->callno]);
9582 return 1;
9584 if (f.datalen)
9585 f.data.ptr = thread->buf + sizeof(*mh);
9586 else
9587 f.data.ptr = NULL;
9588 #ifdef IAXTESTS
9589 if (test_resync) {
9590 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
9591 } else
9592 #endif /* IAXTESTS */
9593 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
9594 /* FIXME? Surely right here would be the right place to undo timestamp wraparound? */
9596 /* Don't pass any packets until we're started */
9597 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
9598 ast_mutex_unlock(&iaxsl[fr->callno]);
9599 return 1;
9601 /* Common things */
9602 f.src = "IAX2";
9603 f.mallocd = 0;
9604 f.offset = 0;
9605 f.len = 0;
9606 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
9607 f.samples = ast_codec_get_samples(&f);
9608 /* We need to byteswap incoming slinear samples from network byte order */
9609 if (f.subclass == AST_FORMAT_SLINEAR)
9610 ast_frame_byteswap_be(&f);
9611 } else
9612 f.samples = 0;
9613 iax_frame_wrap(fr, &f);
9615 /* If this is our most recent packet, use it as our basis for timestamping */
9616 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
9617 /*iaxs[fr->callno]->last = fr->ts; (do it afterwards cos schedule/forward_delivery needs the last ts too)*/
9618 fr->outoforder = 0;
9619 } else {
9620 if (iaxdebug && iaxs[fr->callno])
9621 ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
9622 fr->outoforder = -1;
9624 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
9625 duped_fr = iaxfrdup2(fr);
9626 if (duped_fr) {
9627 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
9629 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
9630 iaxs[fr->callno]->last = fr->ts;
9631 #if 1
9632 if (iaxdebug)
9633 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
9634 #endif
9636 /* Always run again */
9637 ast_mutex_unlock(&iaxsl[fr->callno]);
9638 return 1;
9641 /* Function to clean up process thread if it is cancelled */
9642 static void iax2_process_thread_cleanup(void *data)
9644 struct iax2_thread *thread = data;
9645 ast_mutex_destroy(&thread->lock);
9646 ast_cond_destroy(&thread->cond);
9647 ast_free(thread);
9648 ast_atomic_dec_and_test(&iaxactivethreadcount);
9651 static void *iax2_process_thread(void *data)
9653 struct iax2_thread *thread = data;
9654 struct timeval wait;
9655 struct timespec ts;
9656 int put_into_idle = 0;
9658 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
9659 pthread_cleanup_push(iax2_process_thread_cleanup, data);
9660 for(;;) {
9661 /* Wait for something to signal us to be awake */
9662 ast_mutex_lock(&thread->lock);
9664 /* Flag that we're ready to accept signals */
9665 thread->ready_for_signal = 1;
9667 /* Put into idle list if applicable */
9668 if (put_into_idle)
9669 insert_idle_thread(thread);
9671 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
9672 struct iax2_thread *t = NULL;
9673 /* Wait to be signalled or time out */
9674 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
9675 ts.tv_sec = wait.tv_sec;
9676 ts.tv_nsec = wait.tv_usec * 1000;
9677 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
9678 /* This thread was never put back into the available dynamic
9679 * thread list, so just go away. */
9680 if (!put_into_idle) {
9681 ast_mutex_unlock(&thread->lock);
9682 break;
9684 AST_LIST_LOCK(&dynamic_list);
9685 /* Account for the case where this thread is acquired *right* after a timeout */
9686 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
9687 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
9688 AST_LIST_UNLOCK(&dynamic_list);
9689 if (t) {
9690 /* This dynamic thread timed out waiting for a task and was
9691 * not acquired immediately after the timeout,
9692 * so it's time to go away. */
9693 ast_mutex_unlock(&thread->lock);
9694 break;
9696 /* Someone grabbed our thread *right* after we timed out.
9697 * Wait for them to set us up with something to do and signal
9698 * us to continue. */
9699 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
9700 ts.tv_sec = wait.tv_sec;
9701 ts.tv_nsec = wait.tv_usec * 1000;
9702 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
9704 ast_mutex_unlock(&thread->lock);
9705 break;
9708 } else {
9709 ast_cond_wait(&thread->cond, &thread->lock);
9712 /* Go back into our respective list */
9713 put_into_idle = 1;
9715 ast_mutex_unlock(&thread->lock);
9717 if (thread->iostate == IAX_IOSTATE_IDLE)
9718 continue;
9720 /* Add ourselves to the active list now */
9721 AST_LIST_LOCK(&active_list);
9722 AST_LIST_INSERT_HEAD(&active_list, thread, list);
9723 AST_LIST_UNLOCK(&active_list);
9725 /* See what we need to do */
9726 switch(thread->iostate) {
9727 case IAX_IOSTATE_READY:
9728 thread->actions++;
9729 thread->iostate = IAX_IOSTATE_PROCESSING;
9730 socket_process(thread);
9731 handle_deferred_full_frames(thread);
9732 break;
9733 case IAX_IOSTATE_SCHEDREADY:
9734 thread->actions++;
9735 thread->iostate = IAX_IOSTATE_PROCESSING;
9736 #ifdef SCHED_MULTITHREADED
9737 thread->schedfunc(thread->scheddata);
9738 #endif
9739 default:
9740 break;
9742 time(&thread->checktime);
9743 thread->iostate = IAX_IOSTATE_IDLE;
9744 #ifdef DEBUG_SCHED_MULTITHREAD
9745 thread->curfunc[0]='\0';
9746 #endif
9748 /* Now... remove ourselves from the active list, and return to the idle list */
9749 AST_LIST_LOCK(&active_list);
9750 AST_LIST_REMOVE(&active_list, thread, list);
9751 AST_LIST_UNLOCK(&active_list);
9753 /* Make sure another frame didn't sneak in there after we thought we were done. */
9754 handle_deferred_full_frames(thread);
9757 /*!\note For some reason, idle threads are exiting without being removed
9758 * from an idle list, which is causing memory corruption. Forcibly remove
9759 * it from the list, if it's there.
9761 AST_LIST_LOCK(&idle_list);
9762 AST_LIST_REMOVE(&idle_list, thread, list);
9763 AST_LIST_UNLOCK(&idle_list);
9765 AST_LIST_LOCK(&dynamic_list);
9766 AST_LIST_REMOVE(&dynamic_list, thread, list);
9767 AST_LIST_UNLOCK(&dynamic_list);
9769 /* I am exiting here on my own volition, I need to clean up my own data structures
9770 * Assume that I am no longer in any of the lists (idle, active, or dynamic)
9772 pthread_cleanup_pop(1);
9773 return NULL;
9776 static int iax2_do_register(struct iax2_registry *reg)
9778 struct iax_ie_data ied;
9779 if (iaxdebug)
9780 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
9782 if (reg->dnsmgr &&
9783 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
9784 /* Maybe the IP has changed, force DNS refresh */
9785 ast_dnsmgr_refresh(reg->dnsmgr);
9789 * if IP has Changed, free allocated call to create a new one with new IP
9790 * call has the pointer to IP and must be updated to the new one
9792 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
9793 int callno = reg->callno;
9794 ast_mutex_lock(&iaxsl[callno]);
9795 iax2_destroy(callno);
9796 ast_mutex_unlock(&iaxsl[callno]);
9797 reg->callno = 0;
9799 if (!reg->addr.sin_addr.s_addr) {
9800 if (iaxdebug)
9801 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
9802 /* Setup the next registration attempt */
9803 reg->expire = iax2_sched_replace(reg->expire, sched,
9804 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
9805 return -1;
9808 if (!reg->callno) {
9809 ast_debug(3, "Allocate call number\n");
9810 reg->callno = find_callno_locked(0, 0, &reg->addr, NEW_FORCE, defaultsockfd, 0);
9811 if (reg->callno < 1) {
9812 ast_log(LOG_WARNING, "Unable to create call for registration\n");
9813 return -1;
9814 } else
9815 ast_debug(3, "Registration created on call %d\n", reg->callno);
9816 iaxs[reg->callno]->reg = reg;
9817 ast_mutex_unlock(&iaxsl[reg->callno]);
9819 /* Setup the next registration a little early */
9820 reg->expire = iax2_sched_replace(reg->expire, sched,
9821 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
9822 /* Send the request */
9823 memset(&ied, 0, sizeof(ied));
9824 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
9825 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
9826 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
9827 reg->regstate = REG_STATE_REGSENT;
9828 return 0;
9831 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
9833 /* Returns 1 if provisioned, -1 if not able to find destination, or 0 if no provisioning
9834 is found for template */
9835 struct iax_ie_data provdata;
9836 struct iax_ie_data ied;
9837 unsigned int sig;
9838 struct sockaddr_in sin;
9839 int callno;
9840 struct create_addr_info cai;
9842 memset(&cai, 0, sizeof(cai));
9844 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
9846 if (iax_provision_build(&provdata, &sig, template, force)) {
9847 ast_debug(1, "No provisioning found for template '%s'\n", template);
9848 return 0;
9851 if (end) {
9852 memcpy(&sin, end, sizeof(sin));
9853 cai.sockfd = sockfd;
9854 } else if (create_addr(dest, NULL, &sin, &cai))
9855 return -1;
9857 /* Build the rest of the message */
9858 memset(&ied, 0, sizeof(ied));
9859 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
9861 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
9862 if (!callno)
9863 return -1;
9865 if (iaxs[callno]) {
9866 /* Schedule autodestruct in case they don't ever give us anything back */
9867 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
9868 sched, 15000, auto_hangup, (void *)(long)callno);
9869 ast_set_flag(iaxs[callno], IAX_PROVISION);
9870 /* Got a call number now, so go ahead and send the provisioning information */
9871 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
9873 ast_mutex_unlock(&iaxsl[callno]);
9875 return 1;
9878 static char *papp = "IAX2Provision";
9879 static char *psyn = "Provision a calling IAXy with a given template";
9880 static char *pdescrip =
9881 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
9882 "the calling entity is in fact an IAXy) with the given template or\n"
9883 "default if one is not specified. Returns -1 on error or 0 on success.\n";
9885 /*! iax2provision
9886 \ingroup applications
9888 static int iax2_prov_app(struct ast_channel *chan, void *data)
9890 int res;
9891 char *sdata;
9892 char *opts;
9893 int force =0;
9894 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
9895 if (ast_strlen_zero(data))
9896 data = "default";
9897 sdata = ast_strdupa(data);
9898 opts = strchr(sdata, '|');
9899 if (opts)
9900 *opts='\0';
9902 if (chan->tech != &iax2_tech) {
9903 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
9904 return -1;
9906 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
9907 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
9908 return -1;
9910 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
9911 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
9912 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
9913 sdata, res);
9914 return res;
9917 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
9919 int force = 0;
9920 int res;
9922 switch (cmd) {
9923 case CLI_INIT:
9924 e->command = "iax2 provision";
9925 e->usage =
9926 "Usage: iax2 provision <host> <template> [forced]\n"
9927 " Provisions the given peer or IP address using a template\n"
9928 " matching either 'template' or '*' if the template is not\n"
9929 " found. If 'forced' is specified, even empty provisioning\n"
9930 " fields will be provisioned as empty fields.\n";
9931 return NULL;
9932 case CLI_GENERATE:
9933 if (a->pos == 3)
9934 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
9935 return NULL;
9938 if (a->argc < 4)
9939 return CLI_SHOWUSAGE;
9940 if (a->argc > 4) {
9941 if (!strcasecmp(a->argv[4], "forced"))
9942 force = 1;
9943 else
9944 return CLI_SHOWUSAGE;
9946 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
9947 if (res < 0)
9948 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
9949 else if (res < 1)
9950 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
9951 else
9952 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
9953 return CLI_SUCCESS;
9956 static void __iax2_poke_noanswer(const void *data)
9958 struct iax2_peer *peer = (struct iax2_peer *)data;
9959 int callno;
9961 if (peer->lastms > -1) {
9962 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
9963 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
9964 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name); /* Activate notification */
9966 if ((callno = peer->callno) > 0) {
9967 ast_mutex_lock(&iaxsl[callno]);
9968 iax2_destroy(callno);
9969 ast_mutex_unlock(&iaxsl[callno]);
9971 peer->callno = 0;
9972 peer->lastms = -1;
9973 /* Try again quickly */
9974 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
9975 if (peer->pokeexpire == -1)
9976 peer_unref(peer);
9979 static int iax2_poke_noanswer(const void *data)
9981 struct iax2_peer *peer = (struct iax2_peer *)data;
9982 peer->pokeexpire = -1;
9983 #ifdef SCHED_MULTITHREADED
9984 if (schedule_action(__iax2_poke_noanswer, data))
9985 #endif
9986 __iax2_poke_noanswer(data);
9987 peer_unref(peer);
9988 return 0;
9991 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
9993 struct iax2_peer *peer = obj;
9995 iax2_poke_peer(peer, 0);
9997 return 0;
10000 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
10002 int callno;
10003 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
10004 /* IF we have no IP without dnsmgr, or this isn't to be monitored, return
10005 immediately after clearing things out */
10006 peer->lastms = 0;
10007 peer->historicms = 0;
10008 peer->pokeexpire = -1;
10009 peer->callno = 0;
10010 return 0;
10013 /* The peer could change the callno inside iax2_destroy, since we do deadlock avoidance */
10014 if ((callno = peer->callno) > 0) {
10015 ast_log(LOG_NOTICE, "Still have a callno...\n");
10016 ast_mutex_lock(&iaxsl[callno]);
10017 iax2_destroy(callno);
10018 ast_mutex_unlock(&iaxsl[callno]);
10020 if (heldcall)
10021 ast_mutex_unlock(&iaxsl[heldcall]);
10022 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
10023 if (heldcall)
10024 ast_mutex_lock(&iaxsl[heldcall]);
10025 if (peer->callno < 1) {
10026 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
10027 return -1;
10030 /* Speed up retransmission times for this qualify call */
10031 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
10032 iaxs[peer->callno]->peerpoke = peer;
10034 if (peer->pokeexpire > -1) {
10035 if (!ast_sched_del(sched, peer->pokeexpire)) {
10036 peer->pokeexpire = -1;
10037 peer_unref(peer);
10041 /* Queue up a new task to handle no reply */
10042 /* If the host is already unreachable then use the unreachable interval instead */
10043 if (peer->lastms < 0)
10044 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
10045 else
10046 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
10048 if (peer->pokeexpire == -1)
10049 peer_unref(peer);
10051 /* And send the poke */
10052 ast_mutex_lock(&iaxsl[callno]);
10053 if (iaxs[callno]) {
10054 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
10056 ast_mutex_unlock(&iaxsl[callno]);
10058 return 0;
10061 static void free_context(struct iax2_context *con)
10063 struct iax2_context *conl;
10064 while(con) {
10065 conl = con;
10066 con = con->next;
10067 ast_free(conl);
10071 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
10073 int callno;
10074 int res;
10075 int fmt, native;
10076 struct sockaddr_in sin;
10077 struct ast_channel *c;
10078 struct parsed_dial_string pds;
10079 struct create_addr_info cai;
10080 char *tmpstr;
10082 memset(&pds, 0, sizeof(pds));
10083 tmpstr = ast_strdupa(data);
10084 parse_dial_string(tmpstr, &pds);
10086 if (ast_strlen_zero(pds.peer)) {
10087 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10088 return NULL;
10091 memset(&cai, 0, sizeof(cai));
10092 cai.capability = iax2_capability;
10094 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_NOKEYROTATE);
10096 /* Populate our address from the given */
10097 if (create_addr(pds.peer, NULL, &sin, &cai)) {
10098 *cause = AST_CAUSE_UNREGISTERED;
10099 return NULL;
10102 if (pds.port)
10103 sin.sin_port = htons(atoi(pds.port));
10105 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
10106 if (callno < 1) {
10107 ast_log(LOG_WARNING, "Unable to create call\n");
10108 *cause = AST_CAUSE_CONGESTION;
10109 return NULL;
10112 /* If this is a trunk, update it now */
10113 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_NOKEYROTATE);
10114 if (ast_test_flag(&cai, IAX_TRUNK)) {
10115 int new_callno;
10116 if ((new_callno = make_trunk(callno, 1)) != -1)
10117 callno = new_callno;
10119 iaxs[callno]->maxtime = cai.maxtime;
10120 if (cai.found)
10121 ast_string_field_set(iaxs[callno], host, pds.peer);
10123 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
10125 ast_mutex_unlock(&iaxsl[callno]);
10127 if (c) {
10128 /* Choose a format we can live with */
10129 if (c->nativeformats & format)
10130 c->nativeformats &= format;
10131 else {
10132 native = c->nativeformats;
10133 fmt = format;
10134 res = ast_translator_best_choice(&fmt, &native);
10135 if (res < 0) {
10136 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
10137 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
10138 ast_hangup(c);
10139 return NULL;
10141 c->nativeformats = native;
10143 c->readformat = ast_best_codec(c->nativeformats);
10144 c->writeformat = c->readformat;
10147 return c;
10150 static void *sched_thread(void *ignore)
10152 int count;
10153 int res;
10154 struct timeval wait;
10155 struct timespec ts;
10157 for (;;) {
10158 pthread_testcancel();
10159 ast_mutex_lock(&sched_lock);
10160 res = ast_sched_wait(sched);
10161 if ((res > 1000) || (res < 0))
10162 res = 1000;
10163 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
10164 ts.tv_sec = wait.tv_sec;
10165 ts.tv_nsec = wait.tv_usec * 1000;
10166 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
10167 ast_mutex_unlock(&sched_lock);
10168 pthread_testcancel();
10170 count = ast_sched_runq(sched);
10171 if (count >= 20)
10172 ast_debug(1, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
10175 return NULL;
10178 static void *network_thread(void *ignore)
10180 /* Our job is simple: Send queued messages, retrying if necessary. Read frames
10181 from the network, and queue them for delivery to the channels */
10182 int res, count, wakeup;
10183 struct iax_frame *f;
10185 if (timingfd > -1)
10186 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
10188 for(;;) {
10189 pthread_testcancel();
10191 /* Go through the queue, sending messages which have not yet been
10192 sent, and scheduling retransmissions if appropriate */
10193 AST_LIST_LOCK(&frame_queue);
10194 count = 0;
10195 wakeup = -1;
10196 AST_LIST_TRAVERSE_SAFE_BEGIN(&frame_queue, f, list) {
10197 if (f->sentyet)
10198 continue;
10200 /* Try to lock the pvt, if we can't... don't fret - defer it till later */
10201 if (ast_mutex_trylock(&iaxsl[f->callno])) {
10202 wakeup = 1;
10203 continue;
10206 f->sentyet = 1;
10208 if (iaxs[f->callno]) {
10209 send_packet(f);
10210 count++;
10213 ast_mutex_unlock(&iaxsl[f->callno]);
10215 if (f->retries < 0) {
10216 /* This is not supposed to be retransmitted */
10217 AST_LIST_REMOVE_CURRENT(list);
10218 /* Free the iax frame */
10219 iax_frame_free(f);
10220 } else {
10221 /* We need reliable delivery. Schedule a retransmission */
10222 f->retries++;
10223 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
10226 AST_LIST_TRAVERSE_SAFE_END;
10227 AST_LIST_UNLOCK(&frame_queue);
10229 pthread_testcancel();
10230 if (count >= 20)
10231 ast_debug(1, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
10233 /* Now do the IO, and run scheduled tasks */
10234 res = ast_io_wait(io, wakeup);
10235 if (res >= 0) {
10236 if (res >= 20)
10237 ast_debug(1, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
10240 return NULL;
10243 static int start_network_thread(void)
10245 struct iax2_thread *thread;
10246 int threadcount = 0;
10247 int x;
10248 for (x = 0; x < iaxthreadcount; x++) {
10249 thread = ast_calloc(1, sizeof(*thread));
10250 if (thread) {
10251 thread->type = IAX_THREAD_TYPE_POOL;
10252 thread->threadnum = ++threadcount;
10253 ast_mutex_init(&thread->lock);
10254 ast_cond_init(&thread->cond, NULL);
10255 if (ast_pthread_create_detached(&thread->threadid, NULL, iax2_process_thread, thread)) {
10256 ast_log(LOG_WARNING, "Failed to create new thread!\n");
10257 ast_free(thread);
10258 thread = NULL;
10260 AST_LIST_LOCK(&idle_list);
10261 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
10262 AST_LIST_UNLOCK(&idle_list);
10265 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
10266 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
10267 ast_verb(2, "%d helper threads started\n", threadcount);
10268 return 0;
10271 static struct iax2_context *build_context(const char *context)
10273 struct iax2_context *con;
10275 if ((con = ast_calloc(1, sizeof(*con))))
10276 ast_copy_string(con->context, context, sizeof(con->context));
10278 return con;
10281 static int get_auth_methods(const char *value)
10283 int methods = 0;
10284 if (strstr(value, "rsa"))
10285 methods |= IAX_AUTH_RSA;
10286 if (strstr(value, "md5"))
10287 methods |= IAX_AUTH_MD5;
10288 if (strstr(value, "plaintext"))
10289 methods |= IAX_AUTH_PLAINTEXT;
10290 return methods;
10294 /*! \brief Check if address can be used as packet source.
10295 \return 0 address available, 1 address unavailable, -1 error
10297 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
10299 int sd;
10300 int res;
10302 sd = socket(AF_INET, SOCK_DGRAM, 0);
10303 if (sd < 0) {
10304 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
10305 return -1;
10308 res = bind(sd, sa, salen);
10309 if (res < 0) {
10310 ast_debug(1, "Can't bind: %s\n", strerror(errno));
10311 close(sd);
10312 return 1;
10315 close(sd);
10316 return 0;
10319 /*! \brief Parse the "sourceaddress" value,
10320 lookup in netsock list and set peer's sockfd. Defaults to defaultsockfd if
10321 not found. */
10322 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
10324 struct sockaddr_in sin;
10325 int nonlocal = 1;
10326 int port = IAX_DEFAULT_PORTNO;
10327 int sockfd = defaultsockfd;
10328 char *tmp;
10329 char *addr;
10330 char *portstr;
10332 if (!(tmp = ast_strdupa(srcaddr)))
10333 return -1;
10335 addr = strsep(&tmp, ":");
10336 portstr = tmp;
10338 if (portstr) {
10339 port = atoi(portstr);
10340 if (port < 1)
10341 port = IAX_DEFAULT_PORTNO;
10344 if (!ast_get_ip(&sin, addr)) {
10345 struct ast_netsock *sock;
10346 int res;
10348 sin.sin_port = 0;
10349 sin.sin_family = AF_INET;
10350 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
10351 if (res == 0) {
10352 /* ip address valid. */
10353 sin.sin_port = htons(port);
10354 if (!(sock = ast_netsock_find(netsock, &sin)))
10355 sock = ast_netsock_find(outsock, &sin);
10356 if (sock) {
10357 sockfd = ast_netsock_sockfd(sock);
10358 nonlocal = 0;
10359 } else {
10360 unsigned int orig_saddr = sin.sin_addr.s_addr;
10361 /* INADDR_ANY matches anyway! */
10362 sin.sin_addr.s_addr = INADDR_ANY;
10363 if (ast_netsock_find(netsock, &sin)) {
10364 sin.sin_addr.s_addr = orig_saddr;
10365 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
10366 if (sock) {
10367 sockfd = ast_netsock_sockfd(sock);
10368 ast_netsock_unref(sock);
10369 nonlocal = 0;
10370 } else {
10371 nonlocal = 2;
10378 peer->sockfd = sockfd;
10380 if (nonlocal == 1) {
10381 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
10382 srcaddr, peer->name);
10383 return -1;
10384 } else if (nonlocal == 2) {
10385 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
10386 srcaddr, peer->name);
10387 return -1;
10388 } else {
10389 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
10390 return 0;
10394 static void peer_destructor(void *obj)
10396 struct iax2_peer *peer = obj;
10397 int callno = peer->callno;
10399 ast_free_ha(peer->ha);
10401 if (callno > 0) {
10402 ast_mutex_lock(&iaxsl[callno]);
10403 iax2_destroy(callno);
10404 ast_mutex_unlock(&iaxsl[callno]);
10407 register_peer_exten(peer, 0);
10409 if (peer->dnsmgr)
10410 ast_dnsmgr_release(peer->dnsmgr);
10412 if (peer->mwi_event_sub)
10413 ast_event_unsubscribe(peer->mwi_event_sub);
10415 ast_string_field_free_memory(peer);
10418 /*! \brief Create peer structure based on configuration */
10419 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
10421 struct iax2_peer *peer = NULL;
10422 struct ast_ha *oldha = NULL;
10423 int maskfound = 0;
10424 int found = 0;
10425 int firstpass = 1;
10426 struct iax2_peer tmp_peer = {
10427 .name = name,
10430 if (!temponly) {
10431 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
10432 if (peer && !ast_test_flag(peer, IAX_DELME))
10433 firstpass = 0;
10436 if (peer) {
10437 found++;
10438 if (firstpass) {
10439 oldha = peer->ha;
10440 peer->ha = NULL;
10442 unlink_peer(peer);
10443 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
10444 peer->expire = -1;
10445 peer->pokeexpire = -1;
10446 peer->sockfd = defaultsockfd;
10447 if (ast_string_field_init(peer, 32))
10448 peer = peer_unref(peer);
10451 if (peer) {
10452 if (firstpass) {
10453 if (ast_test_flag(&globalflags, IAX_NOKEYROTATE)) {
10454 ast_copy_flags(peer, &globalflags, IAX_NOKEYROTATE);
10456 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
10457 peer->encmethods = iax2_encryption;
10458 peer->adsi = adsi;
10459 ast_string_field_set(peer,secret,"");
10460 if (!found) {
10461 ast_string_field_set(peer, name, name);
10462 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
10463 peer->expiry = min_reg_expire;
10465 peer->prefs = prefs;
10466 peer->capability = iax2_capability;
10467 peer->smoothing = 0;
10468 peer->pokefreqok = DEFAULT_FREQ_OK;
10469 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
10470 ast_string_field_set(peer,context,"");
10471 ast_string_field_set(peer,peercontext,"");
10472 ast_clear_flag(peer, IAX_HASCALLERID);
10473 ast_string_field_set(peer, cid_name, "");
10474 ast_string_field_set(peer, cid_num, "");
10477 if (!v) {
10478 v = alt;
10479 alt = NULL;
10481 while(v) {
10482 if (!strcasecmp(v->name, "secret")) {
10483 ast_string_field_set(peer, secret, v->value);
10484 } else if (!strcasecmp(v->name, "mailbox")) {
10485 ast_string_field_set(peer, mailbox, v->value);
10486 } else if (!strcasecmp(v->name, "hasvoicemail")) {
10487 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
10488 ast_string_field_set(peer, mailbox, name);
10490 } else if (!strcasecmp(v->name, "mohinterpret")) {
10491 ast_string_field_set(peer, mohinterpret, v->value);
10492 } else if (!strcasecmp(v->name, "mohsuggest")) {
10493 ast_string_field_set(peer, mohsuggest, v->value);
10494 } else if (!strcasecmp(v->name, "dbsecret")) {
10495 ast_string_field_set(peer, dbsecret, v->value);
10496 } else if (!strcasecmp(v->name, "trunk")) {
10497 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
10498 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
10499 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without DAHDI timing\n", peer->name);
10500 ast_clear_flag(peer, IAX_TRUNK);
10502 } else if (!strcasecmp(v->name, "auth")) {
10503 peer->authmethods = get_auth_methods(v->value);
10504 } else if (!strcasecmp(v->name, "encryption")) {
10505 peer->encmethods = get_encrypt_methods(v->value);
10506 } else if (!strcasecmp(v->name, "keyrotate")) {
10507 if (ast_false(v->value))
10508 ast_set_flag(peer, IAX_NOKEYROTATE);
10509 else
10510 ast_clear_flag(peer, IAX_NOKEYROTATE);
10511 } else if (!strcasecmp(v->name, "transfer")) {
10512 if (!strcasecmp(v->value, "mediaonly")) {
10513 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
10514 } else if (ast_true(v->value)) {
10515 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
10516 } else
10517 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
10518 } else if (!strcasecmp(v->name, "jitterbuffer")) {
10519 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
10520 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
10521 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
10522 } else if (!strcasecmp(v->name, "host")) {
10523 if (!strcasecmp(v->value, "dynamic")) {
10524 /* They'll register with us */
10525 ast_set_flag(peer, IAX_DYNAMIC);
10526 if (!found) {
10527 /* Initialize stuff iff we're not found, otherwise
10528 we keep going with what we had */
10529 memset(&peer->addr.sin_addr, 0, 4);
10530 if (peer->addr.sin_port) {
10531 /* If we've already got a port, make it the default rather than absolute */
10532 peer->defaddr.sin_port = peer->addr.sin_port;
10533 peer->addr.sin_port = 0;
10536 } else {
10537 /* Non-dynamic. Make sure we become that way if we're not */
10538 AST_SCHED_DEL(sched, peer->expire);
10539 ast_clear_flag(peer, IAX_DYNAMIC);
10540 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
10541 return peer_unref(peer);
10542 if (!peer->addr.sin_port)
10543 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
10545 if (!maskfound)
10546 inet_aton("255.255.255.255", &peer->mask);
10547 } else if (!strcasecmp(v->name, "defaultip")) {
10548 if (ast_get_ip(&peer->defaddr, v->value))
10549 return peer_unref(peer);
10550 } else if (!strcasecmp(v->name, "sourceaddress")) {
10551 peer_set_srcaddr(peer, v->value);
10552 } else if (!strcasecmp(v->name, "permit") ||
10553 !strcasecmp(v->name, "deny")) {
10554 peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
10555 } else if (!strcasecmp(v->name, "mask")) {
10556 maskfound++;
10557 inet_aton(v->value, &peer->mask);
10558 } else if (!strcasecmp(v->name, "context")) {
10559 ast_string_field_set(peer, context, v->value);
10560 } else if (!strcasecmp(v->name, "regexten")) {
10561 ast_string_field_set(peer, regexten, v->value);
10562 } else if (!strcasecmp(v->name, "peercontext")) {
10563 ast_string_field_set(peer, peercontext, v->value);
10564 } else if (!strcasecmp(v->name, "port")) {
10565 if (ast_test_flag(peer, IAX_DYNAMIC))
10566 peer->defaddr.sin_port = htons(atoi(v->value));
10567 else
10568 peer->addr.sin_port = htons(atoi(v->value));
10569 } else if (!strcasecmp(v->name, "username")) {
10570 ast_string_field_set(peer, username, v->value);
10571 } else if (!strcasecmp(v->name, "allow")) {
10572 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
10573 } else if (!strcasecmp(v->name, "disallow")) {
10574 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
10575 } else if (!strcasecmp(v->name, "callerid")) {
10576 if (!ast_strlen_zero(v->value)) {
10577 char name2[80];
10578 char num2[80];
10579 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
10580 ast_string_field_set(peer, cid_name, name2);
10581 ast_string_field_set(peer, cid_num, num2);
10582 } else {
10583 ast_string_field_set(peer, cid_name, "");
10584 ast_string_field_set(peer, cid_num, "");
10586 ast_set_flag(peer, IAX_HASCALLERID);
10587 } else if (!strcasecmp(v->name, "fullname")) {
10588 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
10589 ast_set_flag(peer, IAX_HASCALLERID);
10590 } else if (!strcasecmp(v->name, "cid_number")) {
10591 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
10592 ast_set_flag(peer, IAX_HASCALLERID);
10593 } else if (!strcasecmp(v->name, "sendani")) {
10594 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
10595 } else if (!strcasecmp(v->name, "inkeys")) {
10596 ast_string_field_set(peer, inkeys, v->value);
10597 } else if (!strcasecmp(v->name, "outkey")) {
10598 ast_string_field_set(peer, outkey, v->value);
10599 } else if (!strcasecmp(v->name, "qualify")) {
10600 if (!strcasecmp(v->value, "no")) {
10601 peer->maxms = 0;
10602 } else if (!strcasecmp(v->value, "yes")) {
10603 peer->maxms = DEFAULT_MAXMS;
10604 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
10605 ast_log(LOG_WARNING, "Qualification of peer '%s' should be 'yes', 'no', or a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
10606 peer->maxms = 0;
10608 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
10609 peer->smoothing = ast_true(v->value);
10610 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
10611 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
10612 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when OK should a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
10614 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
10615 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
10616 ast_log(LOG_WARNING, "Qualification testing frequency of peer '%s' when NOT OK should be a number of milliseconds at line %d of iax.conf\n", peer->name, v->lineno);
10617 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
10618 } else if (!strcasecmp(v->name, "timezone")) {
10619 ast_string_field_set(peer, zonetag, v->value);
10620 } else if (!strcasecmp(v->name, "adsi")) {
10621 peer->adsi = ast_true(v->value);
10622 }/* else if (strcasecmp(v->name,"type")) */
10623 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10624 v = v->next;
10625 if (!v) {
10626 v = alt;
10627 alt = NULL;
10630 if (!peer->authmethods)
10631 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
10632 ast_clear_flag(peer, IAX_DELME);
10633 /* Make sure these are IPv4 addresses */
10634 peer->addr.sin_family = AF_INET;
10637 if (oldha)
10638 ast_free_ha(oldha);
10640 if (!ast_strlen_zero(peer->mailbox)) {
10641 char *mailbox, *context;
10642 context = mailbox = ast_strdupa(peer->mailbox);
10643 strsep(&context, "@");
10644 if (ast_strlen_zero(context))
10645 context = "default";
10646 peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
10647 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
10648 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
10649 AST_EVENT_IE_END);
10652 return peer;
10655 static void user_destructor(void *obj)
10657 struct iax2_user *user = obj;
10659 ast_free_ha(user->ha);
10660 free_context(user->contexts);
10661 if(user->vars) {
10662 ast_variables_destroy(user->vars);
10663 user->vars = NULL;
10665 ast_string_field_free_memory(user);
10668 /*! \brief Create in-memory user structure from configuration */
10669 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
10671 struct iax2_user *user = NULL;
10672 struct iax2_context *con, *conl = NULL;
10673 struct ast_ha *oldha = NULL;
10674 struct iax2_context *oldcon = NULL;
10675 int format;
10676 int firstpass=1;
10677 int oldcurauthreq = 0;
10678 char *varname = NULL, *varval = NULL;
10679 struct ast_variable *tmpvar = NULL;
10680 struct iax2_user tmp_user = {
10681 .name = name,
10684 if (!temponly) {
10685 user = ao2_find(users, &tmp_user, OBJ_POINTER);
10686 if (user && !ast_test_flag(user, IAX_DELME))
10687 firstpass = 0;
10690 if (user) {
10691 if (firstpass) {
10692 oldcurauthreq = user->curauthreq;
10693 oldha = user->ha;
10694 oldcon = user->contexts;
10695 user->ha = NULL;
10696 user->contexts = NULL;
10698 /* Already in the list, remove it and it will be added back (or FREE'd) */
10699 ao2_unlink(users, user);
10700 } else {
10701 user = ao2_alloc(sizeof(*user), user_destructor);
10704 if (user) {
10705 if (firstpass) {
10706 ast_string_field_free_memory(user);
10707 memset(user, 0, sizeof(struct iax2_user));
10708 if (ast_string_field_init(user, 32)) {
10709 user = user_unref(user);
10710 goto cleanup;
10712 user->maxauthreq = maxauthreq;
10713 user->curauthreq = oldcurauthreq;
10714 user->prefs = prefs;
10715 user->capability = iax2_capability;
10716 user->encmethods = iax2_encryption;
10717 user->adsi = adsi;
10718 ast_string_field_set(user, name, name);
10719 ast_string_field_set(user, language, language);
10720 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_NOKEYROTATE);
10721 ast_clear_flag(user, IAX_HASCALLERID);
10722 ast_string_field_set(user, cid_name, "");
10723 ast_string_field_set(user, cid_num, "");
10725 if (!v) {
10726 v = alt;
10727 alt = NULL;
10729 while(v) {
10730 if (!strcasecmp(v->name, "context")) {
10731 con = build_context(v->value);
10732 if (con) {
10733 if (conl)
10734 conl->next = con;
10735 else
10736 user->contexts = con;
10737 conl = con;
10739 } else if (!strcasecmp(v->name, "permit") ||
10740 !strcasecmp(v->name, "deny")) {
10741 user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
10742 } else if (!strcasecmp(v->name, "setvar")) {
10743 varname = ast_strdupa(v->value);
10744 if (varname && (varval = strchr(varname,'='))) {
10745 *varval = '\0';
10746 varval++;
10747 if((tmpvar = ast_variable_new(varname, varval, ""))) {
10748 tmpvar->next = user->vars;
10749 user->vars = tmpvar;
10752 } else if (!strcasecmp(v->name, "allow")) {
10753 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
10754 } else if (!strcasecmp(v->name, "disallow")) {
10755 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
10756 } else if (!strcasecmp(v->name, "trunk")) {
10757 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
10758 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
10759 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without DAHDI timing\n", user->name);
10760 ast_clear_flag(user, IAX_TRUNK);
10762 } else if (!strcasecmp(v->name, "auth")) {
10763 user->authmethods = get_auth_methods(v->value);
10764 } else if (!strcasecmp(v->name, "encryption")) {
10765 user->encmethods = get_encrypt_methods(v->value);
10766 } else if (!strcasecmp(v->name, "keyrotate")) {
10767 if (ast_false(v->value))
10768 ast_set_flag(user, IAX_NOKEYROTATE);
10769 else
10770 ast_clear_flag(user, IAX_NOKEYROTATE);
10771 } else if (!strcasecmp(v->name, "transfer")) {
10772 if (!strcasecmp(v->value, "mediaonly")) {
10773 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
10774 } else if (ast_true(v->value)) {
10775 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
10776 } else
10777 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
10778 } else if (!strcasecmp(v->name, "codecpriority")) {
10779 if(!strcasecmp(v->value, "caller"))
10780 ast_set_flag(user, IAX_CODEC_USER_FIRST);
10781 else if(!strcasecmp(v->value, "disabled"))
10782 ast_set_flag(user, IAX_CODEC_NOPREFS);
10783 else if(!strcasecmp(v->value, "reqonly")) {
10784 ast_set_flag(user, IAX_CODEC_NOCAP);
10785 ast_set_flag(user, IAX_CODEC_NOPREFS);
10787 } else if (!strcasecmp(v->name, "jitterbuffer")) {
10788 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
10789 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
10790 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
10791 } else if (!strcasecmp(v->name, "dbsecret")) {
10792 ast_string_field_set(user, dbsecret, v->value);
10793 } else if (!strcasecmp(v->name, "secret")) {
10794 if (!ast_strlen_zero(user->secret)) {
10795 char *old = ast_strdupa(user->secret);
10797 ast_string_field_build(user, secret, "%s;%s", old, v->value);
10798 } else
10799 ast_string_field_set(user, secret, v->value);
10800 } else if (!strcasecmp(v->name, "callerid")) {
10801 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
10802 char name2[80];
10803 char num2[80];
10804 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
10805 ast_string_field_set(user, cid_name, name2);
10806 ast_string_field_set(user, cid_num, num2);
10807 ast_set_flag(user, IAX_HASCALLERID);
10808 } else {
10809 ast_clear_flag(user, IAX_HASCALLERID);
10810 ast_string_field_set(user, cid_name, "");
10811 ast_string_field_set(user, cid_num, "");
10813 } else if (!strcasecmp(v->name, "fullname")) {
10814 if (!ast_strlen_zero(v->value)) {
10815 ast_string_field_set(user, cid_name, v->value);
10816 ast_set_flag(user, IAX_HASCALLERID);
10817 } else {
10818 ast_string_field_set(user, cid_name, "");
10819 if (ast_strlen_zero(user->cid_num))
10820 ast_clear_flag(user, IAX_HASCALLERID);
10822 } else if (!strcasecmp(v->name, "cid_number")) {
10823 if (!ast_strlen_zero(v->value)) {
10824 ast_string_field_set(user, cid_num, v->value);
10825 ast_set_flag(user, IAX_HASCALLERID);
10826 } else {
10827 ast_string_field_set(user, cid_num, "");
10828 if (ast_strlen_zero(user->cid_name))
10829 ast_clear_flag(user, IAX_HASCALLERID);
10831 } else if (!strcasecmp(v->name, "accountcode")) {
10832 ast_string_field_set(user, accountcode, v->value);
10833 } else if (!strcasecmp(v->name, "mohinterpret")) {
10834 ast_string_field_set(user, mohinterpret, v->value);
10835 } else if (!strcasecmp(v->name, "mohsuggest")) {
10836 ast_string_field_set(user, mohsuggest, v->value);
10837 } else if (!strcasecmp(v->name, "parkinglot")) {
10838 ast_string_field_set(user, parkinglot, v->value);
10839 } else if (!strcasecmp(v->name, "language")) {
10840 ast_string_field_set(user, language, v->value);
10841 } else if (!strcasecmp(v->name, "amaflags")) {
10842 format = ast_cdr_amaflags2int(v->value);
10843 if (format < 0) {
10844 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
10845 } else {
10846 user->amaflags = format;
10848 } else if (!strcasecmp(v->name, "inkeys")) {
10849 ast_string_field_set(user, inkeys, v->value);
10850 } else if (!strcasecmp(v->name, "maxauthreq")) {
10851 user->maxauthreq = atoi(v->value);
10852 if (user->maxauthreq < 0)
10853 user->maxauthreq = 0;
10854 } else if (!strcasecmp(v->name, "adsi")) {
10855 user->adsi = ast_true(v->value);
10856 }/* else if (strcasecmp(v->name,"type")) */
10857 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
10858 v = v->next;
10859 if (!v) {
10860 v = alt;
10861 alt = NULL;
10864 if (!user->authmethods) {
10865 if (!ast_strlen_zero(user->secret)) {
10866 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
10867 if (!ast_strlen_zero(user->inkeys))
10868 user->authmethods |= IAX_AUTH_RSA;
10869 } else if (!ast_strlen_zero(user->inkeys)) {
10870 user->authmethods = IAX_AUTH_RSA;
10871 } else {
10872 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
10875 ast_clear_flag(user, IAX_DELME);
10877 cleanup:
10878 if (oldha)
10879 ast_free_ha(oldha);
10880 if (oldcon)
10881 free_context(oldcon);
10882 return user;
10885 static int peer_delme_cb(void *obj, void *arg, int flags)
10887 struct iax2_peer *peer = obj;
10889 ast_set_flag(peer, IAX_DELME);
10891 return 0;
10894 static int user_delme_cb(void *obj, void *arg, int flags)
10896 struct iax2_user *user = obj;
10898 ast_set_flag(user, IAX_DELME);
10900 return 0;
10903 static void delete_users(void)
10905 struct iax2_registry *reg;
10907 ao2_callback(users, 0, user_delme_cb, NULL);
10909 AST_LIST_LOCK(&registrations);
10910 while ((reg = AST_LIST_REMOVE_HEAD(&registrations, entry))) {
10911 AST_SCHED_DEL(sched, reg->expire);
10912 if (reg->callno) {
10913 int callno = reg->callno;
10914 ast_mutex_lock(&iaxsl[callno]);
10915 if (iaxs[callno]) {
10916 iaxs[callno]->reg = NULL;
10917 iax2_destroy(callno);
10919 ast_mutex_unlock(&iaxsl[callno]);
10921 if (reg->dnsmgr)
10922 ast_dnsmgr_release(reg->dnsmgr);
10923 ast_free(reg);
10925 AST_LIST_UNLOCK(&registrations);
10927 ao2_callback(peers, 0, peer_delme_cb, NULL);
10930 static void prune_users(void)
10932 struct iax2_user *user;
10933 struct ao2_iterator i;
10935 i = ao2_iterator_init(users, 0);
10936 while ((user = ao2_iterator_next(&i))) {
10937 if (ast_test_flag(user, IAX_DELME))
10938 ao2_unlink(users, user);
10939 user_unref(user);
10943 /* Prune peers who still are supposed to be deleted */
10944 static void prune_peers(void)
10946 struct iax2_peer *peer;
10947 struct ao2_iterator i;
10949 i = ao2_iterator_init(peers, 0);
10950 while ((peer = ao2_iterator_next(&i))) {
10951 if (ast_test_flag(peer, IAX_DELME))
10952 unlink_peer(peer);
10953 peer_unref(peer);
10957 static void set_config_destroy(void)
10959 strcpy(accountcode, "");
10960 strcpy(language, "");
10961 strcpy(mohinterpret, "default");
10962 strcpy(mohsuggest, "");
10963 global_max_trunk_mtu = MAX_TRUNK_MTU;
10964 trunkmaxsize = MAX_TRUNKDATA;
10965 amaflags = 0;
10966 delayreject = 0;
10967 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
10968 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
10969 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
10970 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
10971 delete_users();
10974 /*! \brief Load configuration */
10975 static int set_config(char *config_file, int reload)
10977 struct ast_config *cfg, *ucfg;
10978 int capability=iax2_capability;
10979 struct ast_variable *v;
10980 char *cat;
10981 const char *utype;
10982 const char *tosval;
10983 int format;
10984 int portno = IAX_DEFAULT_PORTNO;
10985 int x;
10986 int mtuv;
10987 struct iax2_user *user;
10988 struct iax2_peer *peer;
10989 struct ast_netsock *ns;
10990 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
10991 #if 0
10992 static unsigned short int last_port=0;
10993 #endif
10995 cfg = ast_config_load(config_file, config_flags);
10997 if (!cfg) {
10998 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
10999 return -1;
11000 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
11001 ucfg = ast_config_load("users.conf", config_flags);
11002 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
11003 return 0;
11004 /* Otherwise we need to reread both files */
11005 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
11006 cfg = ast_config_load(config_file, config_flags);
11007 } else { /* iax.conf changed, gotta reread users.conf, too */
11008 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
11009 ucfg = ast_config_load("users.conf", config_flags);
11012 if (reload) {
11013 set_config_destroy();
11016 /* Reset global codec prefs */
11017 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
11019 /* Reset Global Flags */
11020 memset(&globalflags, 0, sizeof(globalflags));
11021 ast_set_flag(&globalflags, IAX_RTUPDATE);
11023 #ifdef SO_NO_CHECK
11024 nochecksums = 0;
11025 #endif
11026 /* Reset default parking lot */
11027 default_parkinglot[0] = '\0';
11029 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
11030 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
11032 maxauthreq = 3;
11034 srvlookup = 0;
11036 v = ast_variable_browse(cfg, "general");
11038 /* Seed initial tos value */
11039 tosval = ast_variable_retrieve(cfg, "general", "tos");
11040 if (tosval) {
11041 if (ast_str2tos(tosval, &qos.tos))
11042 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
11044 /* Seed initial cos value */
11045 tosval = ast_variable_retrieve(cfg, "general", "cos");
11046 if (tosval) {
11047 if (ast_str2cos(tosval, &qos.cos))
11048 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
11050 while(v) {
11051 if (!strcasecmp(v->name, "bindport")){
11052 if (reload)
11053 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
11054 else
11055 portno = atoi(v->value);
11056 } else if (!strcasecmp(v->name, "pingtime"))
11057 ping_time = atoi(v->value);
11058 else if (!strcasecmp(v->name, "iaxthreadcount")) {
11059 if (reload) {
11060 if (atoi(v->value) != iaxthreadcount)
11061 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
11062 } else {
11063 iaxthreadcount = atoi(v->value);
11064 if (iaxthreadcount < 1) {
11065 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
11066 iaxthreadcount = 1;
11067 } else if (iaxthreadcount > 256) {
11068 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
11069 iaxthreadcount = 256;
11072 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
11073 if (reload) {
11074 AST_LIST_LOCK(&dynamic_list);
11075 iaxmaxthreadcount = atoi(v->value);
11076 AST_LIST_UNLOCK(&dynamic_list);
11077 } else {
11078 iaxmaxthreadcount = atoi(v->value);
11079 if (iaxmaxthreadcount < 0) {
11080 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
11081 iaxmaxthreadcount = 0;
11082 } else if (iaxmaxthreadcount > 256) {
11083 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
11084 iaxmaxthreadcount = 256;
11087 } else if (!strcasecmp(v->name, "nochecksums")) {
11088 #ifdef SO_NO_CHECK
11089 if (ast_true(v->value))
11090 nochecksums = 1;
11091 else
11092 nochecksums = 0;
11093 #else
11094 if (ast_true(v->value))
11095 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
11096 #endif
11098 else if (!strcasecmp(v->name, "maxjitterbuffer"))
11099 maxjitterbuffer = atoi(v->value);
11100 else if (!strcasecmp(v->name, "resyncthreshold"))
11101 resyncthreshold = atoi(v->value);
11102 else if (!strcasecmp(v->name, "maxjitterinterps"))
11103 maxjitterinterps = atoi(v->value);
11104 else if (!strcasecmp(v->name, "jittertargetextra"))
11105 jittertargetextra = atoi(v->value);
11106 else if (!strcasecmp(v->name, "lagrqtime"))
11107 lagrq_time = atoi(v->value);
11108 else if (!strcasecmp(v->name, "maxregexpire"))
11109 max_reg_expire = atoi(v->value);
11110 else if (!strcasecmp(v->name, "minregexpire"))
11111 min_reg_expire = atoi(v->value);
11112 else if (!strcasecmp(v->name, "bindaddr")) {
11113 if (reload) {
11114 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
11115 } else {
11116 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
11117 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
11118 } else {
11119 if (strchr(v->value, ':'))
11120 ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
11121 else
11122 ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
11123 if (defaultsockfd < 0)
11124 defaultsockfd = ast_netsock_sockfd(ns);
11125 ast_netsock_unref(ns);
11128 } else if (!strcasecmp(v->name, "authdebug"))
11129 authdebug = ast_true(v->value);
11130 else if (!strcasecmp(v->name, "encryption"))
11131 iax2_encryption = get_encrypt_methods(v->value);
11132 else if (!strcasecmp(v->name, "keyrotate")) {
11133 if (ast_false(v->value))
11134 ast_set_flag((&globalflags), IAX_NOKEYROTATE);
11135 else
11136 ast_clear_flag((&globalflags), IAX_NOKEYROTATE);
11137 } else if (!strcasecmp(v->name, "transfer")) {
11138 if (!strcasecmp(v->value, "mediaonly")) {
11139 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
11140 } else if (ast_true(v->value)) {
11141 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
11142 } else
11143 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
11144 } else if (!strcasecmp(v->name, "codecpriority")) {
11145 if(!strcasecmp(v->value, "caller"))
11146 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
11147 else if(!strcasecmp(v->value, "disabled"))
11148 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
11149 else if(!strcasecmp(v->value, "reqonly")) {
11150 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
11151 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
11153 } else if (!strcasecmp(v->name, "jitterbuffer"))
11154 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
11155 else if (!strcasecmp(v->name, "forcejitterbuffer"))
11156 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
11157 else if (!strcasecmp(v->name, "delayreject"))
11158 delayreject = ast_true(v->value);
11159 else if (!strcasecmp(v->name, "allowfwdownload"))
11160 ast_set2_flag((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
11161 else if (!strcasecmp(v->name, "rtcachefriends"))
11162 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
11163 else if (!strcasecmp(v->name, "rtignoreregexpire"))
11164 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
11165 else if (!strcasecmp(v->name, "rtupdate"))
11166 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
11167 else if (!strcasecmp(v->name, "trunktimestamps"))
11168 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
11169 else if (!strcasecmp(v->name, "rtautoclear")) {
11170 int i = atoi(v->value);
11171 if(i > 0)
11172 global_rtautoclear = i;
11173 else
11174 i = 0;
11175 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
11176 } else if (!strcasecmp(v->name, "trunkfreq")) {
11177 trunkfreq = atoi(v->value);
11178 if (trunkfreq < 10)
11179 trunkfreq = 10;
11180 } else if (!strcasecmp(v->name, "trunkmtu")) {
11181 mtuv = atoi(v->value);
11182 if (mtuv == 0 )
11183 global_max_trunk_mtu = 0;
11184 else if (mtuv >= 172 && mtuv < 4000)
11185 global_max_trunk_mtu = mtuv;
11186 else
11187 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
11188 mtuv, v->lineno);
11189 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
11190 trunkmaxsize = atoi(v->value);
11191 if (trunkmaxsize == 0)
11192 trunkmaxsize = MAX_TRUNKDATA;
11193 } else if (!strcasecmp(v->name, "autokill")) {
11194 if (sscanf(v->value, "%d", &x) == 1) {
11195 if (x >= 0)
11196 autokill = x;
11197 else
11198 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
11199 } else if (ast_true(v->value)) {
11200 autokill = DEFAULT_MAXMS;
11201 } else {
11202 autokill = 0;
11204 } else if (!strcasecmp(v->name, "bandwidth")) {
11205 if (!strcasecmp(v->value, "low")) {
11206 capability = IAX_CAPABILITY_LOWBANDWIDTH;
11207 } else if (!strcasecmp(v->value, "medium")) {
11208 capability = IAX_CAPABILITY_MEDBANDWIDTH;
11209 } else if (!strcasecmp(v->value, "high")) {
11210 capability = IAX_CAPABILITY_FULLBANDWIDTH;
11211 } else
11212 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
11213 } else if (!strcasecmp(v->name, "allow")) {
11214 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
11215 } else if (!strcasecmp(v->name, "disallow")) {
11216 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
11217 } else if (!strcasecmp(v->name, "register")) {
11218 iax2_register(v->value, v->lineno);
11219 } else if (!strcasecmp(v->name, "iaxcompat")) {
11220 iaxcompat = ast_true(v->value);
11221 } else if (!strcasecmp(v->name, "regcontext")) {
11222 ast_copy_string(regcontext, v->value, sizeof(regcontext));
11223 /* Create context if it doesn't exist already */
11224 ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
11225 } else if (!strcasecmp(v->name, "tos")) {
11226 if (ast_str2tos(v->value, &qos.tos))
11227 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
11228 } else if (!strcasecmp(v->name, "cos")) {
11229 if (ast_str2cos(v->value, &qos.cos))
11230 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
11231 } else if (!strcasecmp(v->name, "parkinglot")) {
11232 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
11233 } else if (!strcasecmp(v->name, "accountcode")) {
11234 ast_copy_string(accountcode, v->value, sizeof(accountcode));
11235 } else if (!strcasecmp(v->name, "mohinterpret")) {
11236 ast_copy_string(mohinterpret, v->value, sizeof(user->mohinterpret));
11237 } else if (!strcasecmp(v->name, "mohsuggest")) {
11238 ast_copy_string(mohsuggest, v->value, sizeof(user->mohsuggest));
11239 } else if (!strcasecmp(v->name, "amaflags")) {
11240 format = ast_cdr_amaflags2int(v->value);
11241 if (format < 0) {
11242 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
11243 } else {
11244 amaflags = format;
11246 } else if (!strcasecmp(v->name, "language")) {
11247 ast_copy_string(language, v->value, sizeof(language));
11248 } else if (!strcasecmp(v->name, "maxauthreq")) {
11249 maxauthreq = atoi(v->value);
11250 if (maxauthreq < 0)
11251 maxauthreq = 0;
11252 } else if (!strcasecmp(v->name, "adsi")) {
11253 adsi = ast_true(v->value);
11254 } else if (!strcasecmp(v->name, "srvlookup")) {
11255 srvlookup = ast_true(v->value);
11256 } /*else if (strcasecmp(v->name,"type")) */
11257 /* ast_log(LOG_WARNING, "Ignoring %s\n", v->name); */
11258 v = v->next;
11261 if (defaultsockfd < 0) {
11262 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
11263 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
11264 } else {
11265 ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
11266 defaultsockfd = ast_netsock_sockfd(ns);
11267 ast_netsock_unref(ns);
11270 if (reload) {
11271 ast_netsock_release(outsock);
11272 outsock = ast_netsock_list_alloc();
11273 if (!outsock) {
11274 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
11275 return -1;
11277 ast_netsock_init(outsock);
11280 if (min_reg_expire > max_reg_expire) {
11281 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
11282 min_reg_expire, max_reg_expire, max_reg_expire);
11283 min_reg_expire = max_reg_expire;
11285 iax2_capability = capability;
11287 if (ucfg) {
11288 struct ast_variable *gen;
11289 int genhasiax;
11290 int genregisteriax;
11291 const char *hasiax, *registeriax;
11293 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
11294 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
11295 gen = ast_variable_browse(ucfg, "general");
11296 cat = ast_category_browse(ucfg, NULL);
11297 while (cat) {
11298 if (strcasecmp(cat, "general")) {
11299 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
11300 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
11301 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
11302 /* Start with general parameters, then specific parameters, user and peer */
11303 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
11304 if (user) {
11305 ao2_link(users, user);
11306 user = user_unref(user);
11308 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
11309 if (peer) {
11310 if (ast_test_flag(peer, IAX_DYNAMIC))
11311 reg_source_db(peer);
11312 ao2_link(peers, peer);
11313 peer = peer_unref(peer);
11316 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
11317 char tmp[256];
11318 const char *host = ast_variable_retrieve(ucfg, cat, "host");
11319 const char *username = ast_variable_retrieve(ucfg, cat, "username");
11320 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
11321 if (!host)
11322 host = ast_variable_retrieve(ucfg, "general", "host");
11323 if (!username)
11324 username = ast_variable_retrieve(ucfg, "general", "username");
11325 if (!secret)
11326 secret = ast_variable_retrieve(ucfg, "general", "secret");
11327 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
11328 if (!ast_strlen_zero(secret))
11329 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
11330 else
11331 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
11332 iax2_register(tmp, 0);
11336 cat = ast_category_browse(ucfg, cat);
11338 ast_config_destroy(ucfg);
11341 cat = ast_category_browse(cfg, NULL);
11342 while(cat) {
11343 if (strcasecmp(cat, "general")) {
11344 utype = ast_variable_retrieve(cfg, cat, "type");
11345 if (utype) {
11346 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
11347 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
11348 if (user) {
11349 ao2_link(users, user);
11350 user = user_unref(user);
11353 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
11354 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
11355 if (peer) {
11356 if (ast_test_flag(peer, IAX_DYNAMIC))
11357 reg_source_db(peer);
11358 ao2_link(peers, peer);
11359 peer = peer_unref(peer);
11361 } else if (strcasecmp(utype, "user")) {
11362 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
11364 } else
11365 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
11367 cat = ast_category_browse(cfg, cat);
11369 ast_config_destroy(cfg);
11370 return 1;
11373 static void poke_all_peers(void)
11375 struct ao2_iterator i;
11376 struct iax2_peer *peer;
11378 i = ao2_iterator_init(peers, 0);
11379 while ((peer = ao2_iterator_next(&i))) {
11380 iax2_poke_peer(peer, 0);
11381 peer_unref(peer);
11384 static int reload_config(void)
11386 char *config = "iax.conf";
11387 struct iax2_registry *reg;
11389 if (set_config(config, 1) > 0) {
11390 prune_peers();
11391 prune_users();
11392 trunk_timed = trunk_untimed = 0;
11393 trunk_nmaxmtu = trunk_maxmtu = 0;
11394 memset(&debugaddr, '\0', sizeof(debugaddr));
11396 AST_LIST_LOCK(&registrations);
11397 AST_LIST_TRAVERSE(&registrations, reg, entry)
11398 iax2_do_register(reg);
11399 AST_LIST_UNLOCK(&registrations);
11401 /* Qualify hosts, too */
11402 poke_all_peers();
11405 reload_firmware(0);
11406 iax_provision_reload(1);
11407 ast_unload_realtime("iaxpeers");
11409 return 0;
11412 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11414 switch (cmd) {
11415 case CLI_INIT:
11416 e->command = "iax2 reload";
11417 e->usage =
11418 "Usage: iax2 reload\n"
11419 " Reloads IAX configuration from iax.conf\n";
11420 return NULL;
11421 case CLI_GENERATE:
11422 return NULL;
11425 reload_config();
11427 return CLI_SUCCESS;
11430 static int reload(void)
11432 return reload_config();
11435 static int cache_get_callno_locked(const char *data)
11437 struct sockaddr_in sin;
11438 int x;
11439 int callno;
11440 struct iax_ie_data ied;
11441 struct create_addr_info cai;
11442 struct parsed_dial_string pds;
11443 char *tmpstr;
11445 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
11446 /* Look for an *exact match* call. Once a call is negotiated, it can only
11447 look up entries for a single context */
11448 if (!ast_mutex_trylock(&iaxsl[x])) {
11449 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
11450 return x;
11451 ast_mutex_unlock(&iaxsl[x]);
11455 /* No match found, we need to create a new one */
11457 memset(&cai, 0, sizeof(cai));
11458 memset(&ied, 0, sizeof(ied));
11459 memset(&pds, 0, sizeof(pds));
11461 tmpstr = ast_strdupa(data);
11462 parse_dial_string(tmpstr, &pds);
11464 if (ast_strlen_zero(pds.peer)) {
11465 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
11466 return -1;
11469 /* Populate our address from the given */
11470 if (create_addr(pds.peer, NULL, &sin, &cai))
11471 return -1;
11473 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
11474 pds.peer, pds.username, pds.password, pds.context);
11476 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11477 if (callno < 1) {
11478 ast_log(LOG_WARNING, "Unable to create call\n");
11479 return -1;
11482 ast_string_field_set(iaxs[callno], dproot, data);
11483 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
11485 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
11486 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
11487 /* the string format is slightly different from a standard dial string,
11488 because the context appears in the 'exten' position
11490 if (pds.exten)
11491 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
11492 if (pds.username)
11493 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
11494 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
11495 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
11496 /* Keep password handy */
11497 if (pds.password)
11498 ast_string_field_set(iaxs[callno], secret, pds.password);
11499 if (pds.key)
11500 ast_string_field_set(iaxs[callno], outkey, pds.key);
11501 /* Start the call going */
11502 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
11504 return callno;
11507 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
11509 struct iax2_dpcache *dp = NULL;
11510 struct timeval now = ast_tvnow();
11511 int x, com[2], timeout, old = 0, outfd, doabort, callno;
11512 struct ast_channel *c = NULL;
11513 struct ast_frame *f = NULL;
11515 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
11516 if (ast_tvcmp(now, dp->expiry) > 0) {
11517 AST_LIST_REMOVE_CURRENT(cache_list);
11518 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
11519 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
11520 else
11521 ast_free(dp);
11522 continue;
11524 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
11525 break;
11527 AST_LIST_TRAVERSE_SAFE_END;
11529 if (!dp) {
11530 /* No matching entry. Create a new one. */
11531 /* First, can we make a callno? */
11532 if ((callno = cache_get_callno_locked(data)) < 0) {
11533 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
11534 return NULL;
11536 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
11537 ast_mutex_unlock(&iaxsl[callno]);
11538 return NULL;
11540 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
11541 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
11542 dp->expiry = ast_tvnow();
11543 dp->orig = dp->expiry;
11544 /* Expires in 30 mins by default */
11545 dp->expiry.tv_sec += iaxdefaultdpcache;
11546 dp->flags = CACHE_FLAG_PENDING;
11547 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
11548 dp->waiters[x] = -1;
11549 /* Insert into the lists */
11550 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
11551 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
11552 /* Send the request if we're already up */
11553 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
11554 iax2_dprequest(dp, callno);
11555 ast_mutex_unlock(&iaxsl[callno]);
11558 /* By here we must have a dp */
11559 if (dp->flags & CACHE_FLAG_PENDING) {
11560 /* Okay, here it starts to get nasty. We need a pipe now to wait
11561 for a reply to come back so long as it's pending */
11562 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
11563 /* Find an empty slot */
11564 if (dp->waiters[x] < 0)
11565 break;
11567 if (x >= ARRAY_LEN(dp->waiters)) {
11568 ast_log(LOG_WARNING, "No more waiter positions available\n");
11569 return NULL;
11571 if (pipe(com)) {
11572 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
11573 return NULL;
11575 dp->waiters[x] = com[1];
11576 /* Okay, now we wait */
11577 timeout = iaxdefaulttimeout * 1000;
11578 /* Temporarily unlock */
11579 AST_LIST_UNLOCK(&dpcache);
11580 /* Defer any dtmf */
11581 if (chan)
11582 old = ast_channel_defer_dtmf(chan);
11583 doabort = 0;
11584 while(timeout) {
11585 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
11586 if (outfd > -1)
11587 break;
11588 if (!c)
11589 continue;
11590 if (!(f = ast_read(c))) {
11591 doabort = 1;
11592 break;
11594 ast_frfree(f);
11596 if (!timeout) {
11597 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
11599 AST_LIST_LOCK(&dpcache);
11600 dp->waiters[x] = -1;
11601 close(com[1]);
11602 close(com[0]);
11603 if (doabort) {
11604 /* Don't interpret anything, just abort. Not sure what th epoint
11605 of undeferring dtmf on a hung up channel is but hey whatever */
11606 if (!old && chan)
11607 ast_channel_undefer_dtmf(chan);
11608 return NULL;
11610 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
11611 /* Now to do non-independent analysis the results of our wait */
11612 if (dp->flags & CACHE_FLAG_PENDING) {
11613 /* Still pending... It's a timeout. Wake everybody up. Consider it no longer
11614 pending. Don't let it take as long to timeout. */
11615 dp->flags &= ~CACHE_FLAG_PENDING;
11616 dp->flags |= CACHE_FLAG_TIMEOUT;
11617 /* Expire after only 60 seconds now. This is designed to help reduce backlog in heavily loaded
11618 systems without leaving it unavailable once the server comes back online */
11619 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
11620 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
11621 if (dp->waiters[x] > -1)
11622 write(dp->waiters[x], "asdf", 4);
11626 /* Our caller will obtain the rest */
11627 if (!old && chan)
11628 ast_channel_undefer_dtmf(chan);
11630 return dp;
11633 /*! \brief Part of the IAX2 switch interface */
11634 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
11636 int res = 0;
11637 struct iax2_dpcache *dp = NULL;
11638 #if 0
11639 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
11640 #endif
11641 if ((priority != 1) && (priority != 2))
11642 return 0;
11644 AST_LIST_LOCK(&dpcache);
11645 if ((dp = find_cache(chan, data, context, exten, priority))) {
11646 if (dp->flags & CACHE_FLAG_EXISTS)
11647 res = 1;
11648 } else {
11649 ast_log(LOG_WARNING, "Unable to make DP cache\n");
11651 AST_LIST_UNLOCK(&dpcache);
11653 return res;
11656 /*! \brief part of the IAX2 dial plan switch interface */
11657 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
11659 int res = 0;
11660 struct iax2_dpcache *dp = NULL;
11661 #if 0
11662 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
11663 #endif
11664 if ((priority != 1) && (priority != 2))
11665 return 0;
11667 AST_LIST_LOCK(&dpcache);
11668 if ((dp = find_cache(chan, data, context, exten, priority))) {
11669 if (dp->flags & CACHE_FLAG_CANEXIST)
11670 res = 1;
11671 } else {
11672 ast_log(LOG_WARNING, "Unable to make DP cache\n");
11674 AST_LIST_UNLOCK(&dpcache);
11676 return res;
11679 /*! \brief Part of the IAX2 Switch interface */
11680 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
11682 int res = 0;
11683 struct iax2_dpcache *dp = NULL;
11684 #if 0
11685 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
11686 #endif
11687 if ((priority != 1) && (priority != 2))
11688 return 0;
11690 AST_LIST_LOCK(&dpcache);
11691 if ((dp = find_cache(chan, data, context, exten, priority))) {
11692 if (dp->flags & CACHE_FLAG_MATCHMORE)
11693 res = 1;
11694 } else {
11695 ast_log(LOG_WARNING, "Unable to make DP cache\n");
11697 AST_LIST_UNLOCK(&dpcache);
11699 return res;
11702 /*! \brief Execute IAX2 dialplan switch */
11703 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
11705 char odata[256];
11706 char req[256];
11707 char *ncontext;
11708 struct iax2_dpcache *dp = NULL;
11709 struct ast_app *dial = NULL;
11710 #if 0
11711 ast_log(LOG_NOTICE, "iax2_exec: con: %s, exten: %s, pri: %d, cid: %s, data: %s, newstack: %d\n", context, exten, priority, callerid ? callerid : "<unknown>", data, newstack);
11712 #endif
11713 if (priority == 2) {
11714 /* Indicate status, can be overridden in dialplan */
11715 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
11716 if (dialstatus) {
11717 dial = pbx_findapp(dialstatus);
11718 if (dial)
11719 pbx_exec(chan, dial, "");
11721 return -1;
11722 } else if (priority != 1)
11723 return -1;
11725 AST_LIST_LOCK(&dpcache);
11726 if ((dp = find_cache(chan, data, context, exten, priority))) {
11727 if (dp->flags & CACHE_FLAG_EXISTS) {
11728 ast_copy_string(odata, data, sizeof(odata));
11729 ncontext = strchr(odata, '/');
11730 if (ncontext) {
11731 *ncontext = '\0';
11732 ncontext++;
11733 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
11734 } else {
11735 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
11737 ast_verb(3, "Executing Dial('%s')\n", req);
11738 } else {
11739 AST_LIST_UNLOCK(&dpcache);
11740 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
11741 return -1;
11744 AST_LIST_UNLOCK(&dpcache);
11746 if ((dial = pbx_findapp("Dial")))
11747 return pbx_exec(chan, dial, req);
11748 else
11749 ast_log(LOG_WARNING, "No dial application registered\n");
11751 return -1;
11754 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
11756 struct iax2_peer *peer;
11757 char *peername, *colname;
11759 peername = ast_strdupa(data);
11761 /* if our channel, return the IP address of the endpoint of current channel */
11762 if (!strcmp(peername,"CURRENTCHANNEL")) {
11763 unsigned short callno;
11764 if (chan->tech != &iax2_tech)
11765 return -1;
11766 callno = PTR_TO_CALLNO(chan->tech_pvt);
11767 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
11768 return 0;
11771 if ((colname = strchr(peername, ',')))
11772 *colname++ = '\0';
11773 else
11774 colname = "ip";
11776 if (!(peer = find_peer(peername, 1)))
11777 return -1;
11779 if (!strcasecmp(colname, "ip")) {
11780 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
11781 } else if (!strcasecmp(colname, "status")) {
11782 peer_status(peer, buf, len);
11783 } else if (!strcasecmp(colname, "mailbox")) {
11784 ast_copy_string(buf, peer->mailbox, len);
11785 } else if (!strcasecmp(colname, "context")) {
11786 ast_copy_string(buf, peer->context, len);
11787 } else if (!strcasecmp(colname, "expire")) {
11788 snprintf(buf, len, "%d", peer->expire);
11789 } else if (!strcasecmp(colname, "dynamic")) {
11790 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
11791 } else if (!strcasecmp(colname, "callerid_name")) {
11792 ast_copy_string(buf, peer->cid_name, len);
11793 } else if (!strcasecmp(colname, "callerid_num")) {
11794 ast_copy_string(buf, peer->cid_num, len);
11795 } else if (!strcasecmp(colname, "codecs")) {
11796 ast_getformatname_multiple(buf, len -1, peer->capability);
11797 } else if (!strncasecmp(colname, "codec[", 6)) {
11798 char *codecnum, *ptr;
11799 int codec = 0;
11801 codecnum = strchr(colname, '[');
11802 *codecnum = '\0';
11803 codecnum++;
11804 if ((ptr = strchr(codecnum, ']'))) {
11805 *ptr = '\0';
11807 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
11808 ast_copy_string(buf, ast_getformatname(codec), len);
11812 peer_unref(peer);
11814 return 0;
11817 struct ast_custom_function iaxpeer_function = {
11818 .name = "IAXPEER",
11819 .synopsis = "Gets IAX peer information",
11820 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[,item])",
11821 .read = function_iaxpeer,
11822 .desc = "If peername specified, valid items are:\n"
11823 "- ip (default) The IP address.\n"
11824 "- status The peer's status (if qualify=yes)\n"
11825 "- mailbox The configured mailbox.\n"
11826 "- context The configured context.\n"
11827 "- expire The epoch time of the next expire.\n"
11828 "- dynamic Is it dynamic? (yes/no).\n"
11829 "- callerid_name The configured Caller ID name.\n"
11830 "- callerid_num The configured Caller ID number.\n"
11831 "- codecs The configured codecs.\n"
11832 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
11833 "\n"
11834 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
11835 "\n"
11838 static int acf_channel_write(struct ast_channel *chan, const char *function, char *args, const char *value)
11840 struct chan_iax2_pvt *pvt;
11841 unsigned int callno;
11842 int res = 0;
11844 if (!chan || chan->tech != &iax2_tech) {
11845 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
11846 return -1;
11849 callno = PTR_TO_CALLNO(chan->tech_pvt);
11850 ast_mutex_lock(&iaxsl[callno]);
11851 if (!(pvt = iaxs[callno])) {
11852 ast_mutex_unlock(&iaxsl[callno]);
11853 return -1;
11856 if (!strcasecmp(args, "osptoken"))
11857 ast_string_field_set(pvt, osptoken, value);
11858 else
11859 res = -1;
11861 ast_mutex_unlock(&iaxsl[callno]);
11863 return res;
11866 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
11868 struct chan_iax2_pvt *pvt;
11869 unsigned int callno;
11870 int res = 0;
11872 if (!chan || chan->tech != &iax2_tech) {
11873 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
11874 return -1;
11877 callno = PTR_TO_CALLNO(chan->tech_pvt);
11878 ast_mutex_lock(&iaxsl[callno]);
11879 if (!(pvt = iaxs[callno])) {
11880 ast_mutex_unlock(&iaxsl[callno]);
11881 return -1;
11884 if (!strcasecmp(args, "osptoken")) {
11885 ast_copy_string(buf, pvt->osptoken, buflen);
11886 } else if (!strcasecmp(args, "peerip")) {
11887 ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
11888 } else if (!strcasecmp(args, "peername")) {
11889 ast_copy_string(buf, pvt->username, buflen);
11890 } else {
11891 res = -1;
11894 ast_mutex_unlock(&iaxsl[callno]);
11896 return res;
11899 /*! \brief Part of the device state notification system ---*/
11900 static int iax2_devicestate(void *data)
11902 struct parsed_dial_string pds;
11903 char *tmp = ast_strdupa(data);
11904 struct iax2_peer *p;
11905 int res = AST_DEVICE_INVALID;
11907 memset(&pds, 0, sizeof(pds));
11908 parse_dial_string(tmp, &pds);
11910 if (ast_strlen_zero(pds.peer)) {
11911 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
11912 return res;
11915 ast_debug(3, "Checking device state for device %s\n", pds.peer);
11917 /* SLD: FIXME: second call to find_peer during registration */
11918 if (!(p = find_peer(pds.peer, 1)))
11919 return res;
11921 res = AST_DEVICE_UNAVAILABLE;
11922 ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
11923 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
11925 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
11926 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
11927 /* Peer is registered, or have default IP address
11928 and a valid registration */
11929 if (p->historicms == 0 || p->historicms <= p->maxms)
11930 /* let the core figure out whether it is in use or not */
11931 res = AST_DEVICE_UNKNOWN;
11934 peer_unref(p);
11936 return res;
11939 static struct ast_switch iax2_switch =
11941 name: "IAX2",
11942 description: "IAX Remote Dialplan Switch",
11943 exists: iax2_exists,
11944 canmatch: iax2_canmatch,
11945 exec: iax2_exec,
11946 matchmore: iax2_matchmore,
11950 { { "iax2", "show", "cache", NULL },
11951 iax2_show_cache, "Display IAX cached dialplan",
11952 show_cache_usage },
11954 { { "iax2", "show", "channels", NULL },
11955 iax2_show_channels, "List active IAX channels",
11956 show_channels_usage },
11958 { { "iax2", "show", "firmware", NULL },
11959 iax2_show_firmware, "List available IAX firmwares",
11960 show_firmware_usage },
11962 { { "iax2", "show", "netstats", NULL },
11963 iax2_show_netstats, "List active IAX channel netstats",
11964 show_netstats_usage },
11966 { { "iax2", "show", "peers", NULL },
11967 iax2_show_peers, "List defined IAX peers",
11968 show_peers_usage },
11970 { { "iax2", "show", "registry", NULL },
11971 iax2_show_registry, "Display IAX registration status",
11972 show_reg_usage },
11974 { { "iax2", "show", "stats", NULL },
11975 iax2_show_stats, "Display IAX statistics",
11976 show_stats_usage },
11978 { { "iax2", "show", "threads", NULL },
11979 iax2_show_threads, "Display IAX helper thread info",
11980 show_threads_usage },
11982 { { "iax2", "unregister", NULL },
11983 iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry",
11984 unregister_usage, complete_iax2_unregister },
11986 { { "iax2", "set", "mtu", NULL },
11987 iax2_set_mtu, "Set the IAX systemwide trunking MTU",
11988 set_mtu_usage, NULL, NULL },
11990 { { "iax2", "show", "users", NULL },
11991 iax2_show_users, "List defined IAX users",
11992 show_users_usage },
11994 { { "iax2", "prune", "realtime", NULL },
11995 iax2_prune_realtime, "Prune a cached realtime lookup",
11996 prune_realtime_usage, complete_iax2_show_peer },
11998 { { "iax2", "reload", NULL },
11999 iax2_reload, "Reload IAX configuration",
12000 iax2_reload_usage },
12002 { { "iax2", "show", "peer", NULL },
12003 iax2_show_peer, "Show details on specific IAX peer",
12004 show_peer_usage, complete_iax2_show_peer },
12006 { { "iax2", "set", "debug", NULL },
12007 iax2_do_debug, "Enable IAX debugging",
12008 debug_usage },
12010 { { "iax2", "set", "debug", "trunk", NULL },
12011 iax2_do_trunk_debug, "Enable IAX trunk debugging",
12012 debug_trunk_usage },
12014 { { "iax2", "set", "debug", "jb", NULL },
12015 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
12016 debug_jb_usage },
12018 { { "iax2", "set", "debug", "off", NULL },
12019 iax2_no_debug, "Disable IAX debugging",
12020 no_debug_usage },
12022 { { "iax2", "set", "debug", "trunk", "off", NULL },
12023 iax2_no_trunk_debug, "Disable IAX trunk debugging",
12024 no_debug_trunk_usage },
12026 { { "iax2", "set", "debug", "jb", "off", NULL },
12027 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
12028 no_debug_jb_usage },
12030 { { "iax2", "test", "losspct", NULL },
12031 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
12032 iax2_test_losspct_usage },
12034 { { "iax2", "provision", NULL },
12035 iax2_prov_cmd, "Provision an IAX device",
12036 show_prov_usage, iax2_prov_complete_template_3rd },
12038 #ifdef IAXTESTS
12039 { { "iax2", "test", "late", NULL },
12040 iax2_test_late, "Test the receipt of a late frame",
12041 iax2_test_late_usage },
12043 { { "iax2", "test", "resync", NULL },
12044 iax2_test_resync, "Test a resync in received timestamps",
12045 iax2_test_resync_usage },
12047 { { "iax2", "test", "jitter", NULL },
12048 iax2_test_jitter, "Simulates jitter for testing",
12049 iax2_test_jitter_usage },
12050 #endif
12053 static struct ast_cli_entry cli_iax2[] = {
12054 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
12055 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
12056 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
12057 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
12058 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
12059 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
12060 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
12061 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
12062 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
12063 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
12064 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
12065 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
12066 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
12067 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
12068 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
12069 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
12070 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
12071 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
12072 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
12073 #ifdef IAXTESTS
12074 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
12075 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
12076 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
12077 #endif /* IAXTESTS */
12080 static int __unload_module(void)
12082 struct iax2_thread *thread = NULL;
12083 struct ast_context *con;
12084 int x;
12086 /* Make sure threads do not hold shared resources when they are canceled */
12088 /* Grab the sched lock resource to keep it away from threads about to die */
12089 /* Cancel the network thread, close the net socket */
12090 if (netthreadid != AST_PTHREADT_NULL) {
12091 AST_LIST_LOCK(&frame_queue);
12092 ast_mutex_lock(&sched_lock);
12093 pthread_cancel(netthreadid);
12094 ast_cond_signal(&sched_cond);
12095 ast_mutex_unlock(&sched_lock); /* Release the schedule lock resource */
12096 AST_LIST_UNLOCK(&frame_queue);
12097 pthread_join(netthreadid, NULL);
12099 if (schedthreadid != AST_PTHREADT_NULL) {
12100 ast_mutex_lock(&sched_lock);
12101 pthread_cancel(schedthreadid);
12102 ast_cond_signal(&sched_cond);
12103 ast_mutex_unlock(&sched_lock);
12104 pthread_join(schedthreadid, NULL);
12107 /* Call for all threads to halt */
12108 AST_LIST_LOCK(&idle_list);
12109 while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list)))
12110 pthread_cancel(thread->threadid);
12111 AST_LIST_UNLOCK(&idle_list);
12113 AST_LIST_LOCK(&active_list);
12114 while ((thread = AST_LIST_REMOVE_HEAD(&active_list, list)))
12115 pthread_cancel(thread->threadid);
12116 AST_LIST_UNLOCK(&active_list);
12118 AST_LIST_LOCK(&dynamic_list);
12119 while ((thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list)))
12120 pthread_cancel(thread->threadid);
12121 AST_LIST_UNLOCK(&dynamic_list);
12123 /* Wait for threads to exit */
12124 while(0 < iaxactivethreadcount)
12125 usleep(10000);
12127 ast_netsock_release(netsock);
12128 ast_netsock_release(outsock);
12129 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
12130 if (iaxs[x]) {
12131 iax2_destroy(x);
12134 ast_manager_unregister( "IAXpeers" );
12135 ast_manager_unregister( "IAXpeerlist" );
12136 ast_manager_unregister( "IAXnetstats" );
12137 ast_unregister_application(papp);
12138 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
12139 ast_unregister_switch(&iax2_switch);
12140 ast_channel_unregister(&iax2_tech);
12141 delete_users();
12142 iax_provision_unload();
12143 sched_context_destroy(sched);
12144 reload_firmware(1);
12146 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
12147 ast_mutex_destroy(&iaxsl[x]);
12150 ao2_ref(peers, -1);
12151 ao2_ref(users, -1);
12152 ao2_ref(iax_peercallno_pvts, -1);
12154 if (timingfd > -1) {
12155 ast_timer_close(timingfd);
12158 con = ast_context_find(regcontext);
12159 if (con)
12160 ast_context_destroy(con, "IAX2");
12161 ast_unload_realtime("iaxpeers");
12162 return 0;
12165 static int unload_module(void)
12167 ast_custom_function_unregister(&iaxpeer_function);
12168 ast_custom_function_unregister(&iaxvar_function);
12169 return __unload_module();
12172 static int peer_set_sock_cb(void *obj, void *arg, int flags)
12174 struct iax2_peer *peer = obj;
12176 if (peer->sockfd < 0)
12177 peer->sockfd = defaultsockfd;
12179 return 0;
12182 static int pvt_hash_cb(const void *obj, const int flags)
12184 const struct chan_iax2_pvt *pvt = obj;
12186 return pvt->peercallno;
12189 static int pvt_cmp_cb(void *obj, void *arg, int flags)
12191 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
12193 /* The frames_received field is used to hold whether we're matching
12194 * against a full frame or not ... */
12196 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
12197 pvt2->frames_received) ? CMP_MATCH : 0;
12200 /*! \brief Load IAX2 module, load configuraiton ---*/
12201 static int load_module(void)
12203 char *config = "iax.conf";
12204 int x = 0;
12205 struct iax2_registry *reg = NULL;
12207 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
12208 if (!peers)
12209 return AST_MODULE_LOAD_FAILURE;
12210 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
12211 if (!users) {
12212 ao2_ref(peers, -1);
12213 return AST_MODULE_LOAD_FAILURE;
12215 iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb);
12216 if (!iax_peercallno_pvts) {
12217 ao2_ref(peers, -1);
12218 ao2_ref(users, -1);
12219 return AST_MODULE_LOAD_FAILURE;
12222 ast_custom_function_register(&iaxpeer_function);
12223 ast_custom_function_register(&iaxvar_function);
12225 iax_set_output(iax_debug_output);
12226 iax_set_error(iax_error_output);
12227 jb_setoutput(jb_error_output, jb_warning_output, NULL);
12229 memset(iaxs, 0, sizeof(iaxs));
12231 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
12232 ast_mutex_init(&iaxsl[x]);
12235 ast_cond_init(&sched_cond, NULL);
12237 if (!(sched = sched_context_create())) {
12238 ast_log(LOG_ERROR, "Failed to create scheduler context\n");
12239 return AST_MODULE_LOAD_FAILURE;
12242 if (!(io = io_context_create())) {
12243 ast_log(LOG_ERROR, "Failed to create I/O context\n");
12244 sched_context_destroy(sched);
12245 return AST_MODULE_LOAD_FAILURE;
12248 if (!(netsock = ast_netsock_list_alloc())) {
12249 ast_log(LOG_ERROR, "Failed to create netsock list\n");
12250 io_context_destroy(io);
12251 sched_context_destroy(sched);
12252 return AST_MODULE_LOAD_FAILURE;
12254 ast_netsock_init(netsock);
12256 outsock = ast_netsock_list_alloc();
12257 if (!outsock) {
12258 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
12259 io_context_destroy(io);
12260 sched_context_destroy(sched);
12261 return AST_MODULE_LOAD_FAILURE;
12263 ast_netsock_init(outsock);
12265 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
12267 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
12269 ast_manager_register( "IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers, "List IAX Peers" );
12270 ast_manager_register( "IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list, "List IAX Peers" );
12271 ast_manager_register( "IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats, "Show IAX Netstats" );
12273 if(set_config(config, 0) == -1)
12274 return AST_MODULE_LOAD_DECLINE;
12276 timingfd = ast_timer_open();
12277 if (timingfd > -1) {
12278 ast_timer_set_rate(timingfd, trunkfreq);
12281 if (ast_channel_register(&iax2_tech)) {
12282 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
12283 __unload_module();
12284 return AST_MODULE_LOAD_FAILURE;
12287 if (ast_register_switch(&iax2_switch))
12288 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
12290 if (start_network_thread()) {
12291 ast_log(LOG_ERROR, "Unable to start network thread\n");
12292 __unload_module();
12293 return AST_MODULE_LOAD_FAILURE;
12294 } else
12295 ast_verb(2, "IAX Ready and Listening\n");
12297 AST_LIST_LOCK(&registrations);
12298 AST_LIST_TRAVERSE(&registrations, reg, entry)
12299 iax2_do_register(reg);
12300 AST_LIST_UNLOCK(&registrations);
12302 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
12303 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
12306 reload_firmware(0);
12307 iax_provision_reload(0);
12309 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
12311 return AST_MODULE_LOAD_SUCCESS;
12314 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
12315 .load = load_module,
12316 .unload = unload_module,
12317 .reload = reload,