00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036 #include "asterisk.h"
00037
00038 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00039
00040 #include <stdlib.h>
00041 #include <stdio.h>
00042 #include <sys/types.h>
00043 #include <sys/mman.h>
00044 #include <dirent.h>
00045 #include <sys/socket.h>
00046 #include <netinet/in.h>
00047 #include <arpa/inet.h>
00048 #include <netinet/in_systm.h>
00049 #include <netinet/ip.h>
00050 #include <sys/time.h>
00051 #include <sys/signal.h>
00052 #include <signal.h>
00053 #include <string.h>
00054 #include <strings.h>
00055 #include <errno.h>
00056 #include <unistd.h>
00057 #include <netdb.h>
00058 #include <fcntl.h>
00059 #include <sys/stat.h>
00060 #include <regex.h>
00061
00062 #if defined(HAVE_ZAPTEL) || defined (HAVE_DAHDI)
00063 #include <sys/ioctl.h>
00064 #include "asterisk/dahdi_compat.h"
00065 #endif
00066
00067 #include "asterisk/lock.h"
00068 #include "asterisk/frame.h"
00069 #include "asterisk/channel.h"
00070 #include "asterisk/logger.h"
00071 #include "asterisk/module.h"
00072 #include "asterisk/pbx.h"
00073 #include "asterisk/sched.h"
00074 #include "asterisk/io.h"
00075 #include "asterisk/config.h"
00076 #include "asterisk/options.h"
00077 #include "asterisk/cli.h"
00078 #include "asterisk/translate.h"
00079 #include "asterisk/md5.h"
00080 #include "asterisk/cdr.h"
00081 #include "asterisk/crypto.h"
00082 #include "asterisk/acl.h"
00083 #include "asterisk/manager.h"
00084 #include "asterisk/callerid.h"
00085 #include "asterisk/app.h"
00086 #include "asterisk/astdb.h"
00087 #include "asterisk/musiconhold.h"
00088 #include "asterisk/features.h"
00089 #include "asterisk/utils.h"
00090 #include "asterisk/causes.h"
00091 #include "asterisk/localtime.h"
00092 #include "asterisk/aes.h"
00093 #include "asterisk/dnsmgr.h"
00094 #include "asterisk/devicestate.h"
00095 #include "asterisk/netsock.h"
00096 #include "asterisk/stringfields.h"
00097 #include "asterisk/linkedlists.h"
00098 #include "asterisk/astobj2.h"
00099
00100 #include "iax2.h"
00101 #include "iax2-parser.h"
00102 #include "iax2-provision.h"
00103 #include "jitterbuf.h"
00104
00105
00106
00107 #define SCHED_MULTITHREADED
00108
00109
00110
00111 #define DEBUG_SCHED_MULTITHREAD
00112
00113 #ifndef IPTOS_MINCOST
00114 #define IPTOS_MINCOST 0x02
00115 #endif
00116
00117 #ifdef SO_NO_CHECK
00118 static int nochecksums = 0;
00119 #endif
00120
00121
00122 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00123 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00124
00125 #define DEFAULT_THREAD_COUNT 10
00126 #define DEFAULT_MAX_THREAD_COUNT 100
00127 #define DEFAULT_RETRY_TIME 1000
00128 #define MEMORY_SIZE 100
00129 #define DEFAULT_DROP 3
00130
00131 #define DEBUG_SUPPORT
00132
00133 #define MIN_REUSE_TIME 60
00134
00135
00136 #define GAMMA (0.01)
00137
00138 static struct ast_codec_pref prefs;
00139
00140 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00141
00142 static char context[80] = "default";
00143
00144 static char language[MAX_LANGUAGE] = "";
00145 static char regcontext[AST_MAX_CONTEXT] = "";
00146
00147 static int maxauthreq = 3;
00148 static int max_retries = 4;
00149 static int ping_time = 21;
00150 static int lagrq_time = 10;
00151 static int maxjitterbuffer=1000;
00152 static int resyncthreshold=1000;
00153 static int maxjitterinterps=10;
00154 static int trunkfreq = 20;
00155 static int authdebug = 1;
00156 static int autokill = 0;
00157 static int iaxcompat = 0;
00158
00159 static int iaxdefaultdpcache=10 * 60;
00160
00161 static int iaxdefaulttimeout = 5;
00162
00163 static unsigned int tos = 0;
00164
00165 static int min_reg_expire;
00166 static int max_reg_expire;
00167
00168 static int timingfd = -1;
00169
00170 static struct ast_netsock_list *netsock;
00171 static struct ast_netsock_list *outsock;
00172 static int defaultsockfd = -1;
00173
00174 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00175
00176
00177 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
00178
00179 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00180 ~AST_FORMAT_SLINEAR & \
00181 ~AST_FORMAT_ULAW & \
00182 ~AST_FORMAT_ALAW & \
00183 ~AST_FORMAT_G722)
00184
00185 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00186 ~AST_FORMAT_G726 & \
00187 ~AST_FORMAT_G726_AAL2 & \
00188 ~AST_FORMAT_ADPCM)
00189
00190 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
00191 ~AST_FORMAT_G723_1)
00192
00193
00194 #define DEFAULT_MAXMS 2000
00195 #define DEFAULT_FREQ_OK 60 * 1000
00196 #define DEFAULT_FREQ_NOTOK 10 * 1000
00197
00198 static struct io_context *io;
00199 static struct sched_context *sched;
00200
00201 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00202
00203 static int iaxdebug = 0;
00204
00205 static int iaxtrunkdebug = 0;
00206
00207 static int test_losspct = 0;
00208 #ifdef IAXTESTS
00209 static int test_late = 0;
00210 static int test_resync = 0;
00211 static int test_jit = 0;
00212 static int test_jitpct = 0;
00213 #endif
00214
00215 static char accountcode[AST_MAX_ACCOUNT_CODE];
00216 static char mohinterpret[MAX_MUSICCLASS];
00217 static char mohsuggest[MAX_MUSICCLASS];
00218 static int amaflags = 0;
00219 static int adsi = 0;
00220 static int delayreject = 0;
00221 static int iax2_encryption = 0;
00222
00223 static struct ast_flags globalflags = { 0 };
00224
00225 static pthread_t netthreadid = AST_PTHREADT_NULL;
00226 static pthread_t schedthreadid = AST_PTHREADT_NULL;
00227 AST_MUTEX_DEFINE_STATIC(sched_lock);
00228 static ast_cond_t sched_cond;
00229
00230 enum {
00231 IAX_STATE_STARTED = (1 << 0),
00232 IAX_STATE_AUTHENTICATED = (1 << 1),
00233 IAX_STATE_TBD = (1 << 2),
00234 IAX_STATE_UNCHANGED = (1 << 3),
00235 } iax2_state;
00236
00237 struct iax2_context {
00238 char context[AST_MAX_CONTEXT];
00239 struct iax2_context *next;
00240 };
00241
00242 enum {
00243 IAX_HASCALLERID = (1 << 0),
00244 IAX_DELME = (1 << 1),
00245 IAX_TEMPONLY = (1 << 2),
00246 IAX_TRUNK = (1 << 3),
00247 IAX_NOTRANSFER = (1 << 4),
00248 IAX_USEJITTERBUF = (1 << 5),
00249 IAX_DYNAMIC = (1 << 6),
00250 IAX_SENDANI = (1 << 7),
00251
00252 IAX_ALREADYGONE = (1 << 9),
00253 IAX_PROVISION = (1 << 10),
00254 IAX_QUELCH = (1 << 11),
00255 IAX_ENCRYPTED = (1 << 12),
00256 IAX_KEYPOPULATED = (1 << 13),
00257 IAX_CODEC_USER_FIRST = (1 << 14),
00258 IAX_CODEC_NOPREFS = (1 << 15),
00259 IAX_CODEC_NOCAP = (1 << 16),
00260 IAX_RTCACHEFRIENDS = (1 << 17),
00261 IAX_RTUPDATE = (1 << 18),
00262 IAX_RTAUTOCLEAR = (1 << 19),
00263 IAX_FORCEJITTERBUF = (1 << 20),
00264 IAX_RTIGNOREREGEXPIRE = (1 << 21),
00265 IAX_TRUNKTIMESTAMPS = (1 << 22),
00266 IAX_TRANSFERMEDIA = (1 << 23),
00267 IAX_MAXAUTHREQ = (1 << 24),
00268 IAX_DELAYPBXSTART = (1 << 25),
00269
00270
00271 IAX_ALLOWFWDOWNLOAD = (1 << 26),
00272 } iax2_flags;
00273
00274 static int global_rtautoclear = 120;
00275
00276 static int reload_config(void);
00277 static int iax2_reload(int fd, int argc, char *argv[]);
00278
00279
00280 struct iax2_user {
00281 AST_DECLARE_STRING_FIELDS(
00282 AST_STRING_FIELD(name);
00283 AST_STRING_FIELD(secret);
00284 AST_STRING_FIELD(dbsecret);
00285 AST_STRING_FIELD(accountcode);
00286 AST_STRING_FIELD(mohinterpret);
00287 AST_STRING_FIELD(mohsuggest);
00288 AST_STRING_FIELD(inkeys);
00289 AST_STRING_FIELD(language);
00290 AST_STRING_FIELD(cid_num);
00291 AST_STRING_FIELD(cid_name);
00292 );
00293
00294 int authmethods;
00295 int encmethods;
00296 int amaflags;
00297 int adsi;
00298 unsigned int flags;
00299 int capability;
00300 int maxauthreq;
00301 int curauthreq;
00302 struct ast_codec_pref prefs;
00303 struct ast_ha *ha;
00304 struct iax2_context *contexts;
00305 struct ast_variable *vars;
00306 };
00307
00308 struct iax2_peer {
00309 AST_DECLARE_STRING_FIELDS(
00310 AST_STRING_FIELD(name);
00311 AST_STRING_FIELD(username);
00312 AST_STRING_FIELD(secret);
00313 AST_STRING_FIELD(dbsecret);
00314 AST_STRING_FIELD(outkey);
00315
00316 AST_STRING_FIELD(regexten);
00317 AST_STRING_FIELD(context);
00318 AST_STRING_FIELD(peercontext);
00319 AST_STRING_FIELD(mailbox);
00320 AST_STRING_FIELD(mohinterpret);
00321 AST_STRING_FIELD(mohsuggest);
00322 AST_STRING_FIELD(inkeys);
00323
00324 AST_STRING_FIELD(cid_num);
00325 AST_STRING_FIELD(cid_name);
00326 AST_STRING_FIELD(zonetag);
00327 );
00328 struct ast_codec_pref prefs;
00329 struct ast_dnsmgr_entry *dnsmgr;
00330 struct sockaddr_in addr;
00331 int formats;
00332 int sockfd;
00333 struct in_addr mask;
00334 int adsi;
00335 unsigned int flags;
00336
00337
00338 struct sockaddr_in defaddr;
00339 int authmethods;
00340 int encmethods;
00341
00342 int expire;
00343 int expiry;
00344 int capability;
00345
00346
00347 int callno;
00348 int pokeexpire;
00349 int lastms;
00350 int maxms;
00351
00352 int pokefreqok;
00353 int pokefreqnotok;
00354 int historicms;
00355 int smoothing;
00356
00357 struct ast_ha *ha;
00358 };
00359
00360 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00361
00362 static struct iax2_trunk_peer {
00363 ast_mutex_t lock;
00364 int sockfd;
00365 struct sockaddr_in addr;
00366 struct timeval txtrunktime;
00367 struct timeval rxtrunktime;
00368 struct timeval lasttxtime;
00369 struct timeval trunkact;
00370 unsigned int lastsent;
00371
00372 unsigned char *trunkdata;
00373 unsigned int trunkdatalen;
00374 unsigned int trunkdataalloc;
00375 struct iax2_trunk_peer *next;
00376 int trunkerror;
00377 int calls;
00378 } *tpeers = NULL;
00379
00380 AST_MUTEX_DEFINE_STATIC(tpeerlock);
00381
00382 struct iax_firmware {
00383 struct iax_firmware *next;
00384 int fd;
00385 int mmaplen;
00386 int dead;
00387 struct ast_iax2_firmware_header *fwh;
00388 unsigned char *buf;
00389 };
00390
00391 enum iax_reg_state {
00392 REG_STATE_UNREGISTERED = 0,
00393 REG_STATE_REGSENT,
00394 REG_STATE_AUTHSENT,
00395 REG_STATE_REGISTERED,
00396 REG_STATE_REJECTED,
00397 REG_STATE_TIMEOUT,
00398 REG_STATE_NOAUTH
00399 };
00400
00401 enum iax_transfer_state {
00402 TRANSFER_NONE = 0,
00403 TRANSFER_BEGIN,
00404 TRANSFER_READY,
00405 TRANSFER_RELEASED,
00406 TRANSFER_PASSTHROUGH,
00407 TRANSFER_MBEGIN,
00408 TRANSFER_MREADY,
00409 TRANSFER_MRELEASED,
00410 TRANSFER_MPASSTHROUGH,
00411 TRANSFER_MEDIA,
00412 TRANSFER_MEDIAPASS
00413 };
00414
00415 struct iax2_registry {
00416 struct sockaddr_in addr;
00417 char username[80];
00418 char secret[80];
00419 char random[80];
00420 int expire;
00421 int refresh;
00422 enum iax_reg_state regstate;
00423 int messages;
00424 int callno;
00425 struct sockaddr_in us;
00426 struct ast_dnsmgr_entry *dnsmgr;
00427 AST_LIST_ENTRY(iax2_registry) entry;
00428 };
00429
00430 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00431
00432
00433 #define MIN_RETRY_TIME 100
00434 #define MAX_RETRY_TIME 10000
00435
00436 #define MAX_JITTER_BUFFER 50
00437 #define MIN_JITTER_BUFFER 10
00438
00439 #define DEFAULT_TRUNKDATA 640 * 10
00440 #define MAX_TRUNKDATA 640 * 200
00441
00442 #define MAX_TIMESTAMP_SKEW 160
00443
00444
00445 #define TS_GAP_FOR_JB_RESYNC 5000
00446
00447 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00448 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00449 static int iaxdynamicthreadcount = 0;
00450 static int iaxdynamicthreadnum = 0;
00451 static int iaxactivethreadcount = 0;
00452
00453 struct iax_rr {
00454 int jitter;
00455 int losspct;
00456 int losscnt;
00457 int packets;
00458 int delay;
00459 int dropped;
00460 int ooo;
00461 };
00462
00463 struct chan_iax2_pvt {
00464
00465 int sockfd;
00466
00467 int voiceformat;
00468
00469 int videoformat;
00470
00471 int svoiceformat;
00472
00473 int svideoformat;
00474
00475 int capability;
00476
00477 unsigned int last;
00478
00479 unsigned int lastsent;
00480
00481 unsigned int lastvsent;
00482
00483 unsigned int nextpred;
00484
00485 int notsilenttx;
00486
00487 unsigned int pingtime;
00488
00489 int maxtime;
00490
00491 struct sockaddr_in addr;
00492
00493 struct ast_codec_pref prefs;
00494
00495 struct ast_codec_pref rprefs;
00496
00497 unsigned short callno;
00498
00499 unsigned short peercallno;
00500
00501
00502
00503 int chosenformat;
00504
00505 int peerformat;
00506
00507 int peercapability;
00508
00509 struct timeval offset;
00510
00511 struct timeval rxcore;
00512
00513 jitterbuf *jb;
00514
00515 int jbid;
00516
00517 int lag;
00518
00519 int error;
00520
00521 struct ast_channel *owner;
00522
00523 struct ast_flags state;
00524
00525 int expiry;
00526
00527 unsigned char oseqno;
00528
00529 unsigned char rseqno;
00530
00531 unsigned char iseqno;
00532
00533 unsigned char aseqno;
00534
00535 AST_DECLARE_STRING_FIELDS(
00536
00537 AST_STRING_FIELD(peer);
00538
00539 AST_STRING_FIELD(context);
00540
00541 AST_STRING_FIELD(cid_num);
00542 AST_STRING_FIELD(cid_name);
00543
00544 AST_STRING_FIELD(ani);
00545
00546 AST_STRING_FIELD(dnid);
00547
00548 AST_STRING_FIELD(rdnis);
00549
00550 AST_STRING_FIELD(exten);
00551
00552 AST_STRING_FIELD(username);
00553
00554 AST_STRING_FIELD(secret);
00555
00556 AST_STRING_FIELD(challenge);
00557
00558 AST_STRING_FIELD(inkeys);
00559
00560 AST_STRING_FIELD(outkey);
00561
00562 AST_STRING_FIELD(language);
00563
00564 AST_STRING_FIELD(host);
00565
00566 AST_STRING_FIELD(dproot);
00567 AST_STRING_FIELD(accountcode);
00568 AST_STRING_FIELD(mohinterpret);
00569 AST_STRING_FIELD(mohsuggest);
00570 );
00571
00572
00573 int authmethods;
00574
00575 int encmethods;
00576
00577 aes_encrypt_ctx ecx;
00578
00579 aes_decrypt_ctx dcx;
00580
00581 unsigned char semirand[32];
00582
00583 struct iax2_registry *reg;
00584
00585 struct iax2_peer *peerpoke;
00586
00587 unsigned int flags;
00588 int adsi;
00589
00590
00591 enum iax_transfer_state transferring;
00592
00593 int transferid;
00594
00595 struct sockaddr_in transfer;
00596
00597 unsigned short transfercallno;
00598
00599 aes_encrypt_ctx tdcx;
00600
00601
00602 int peeradsicpe;
00603
00604
00605 unsigned short bridgecallno;
00606
00607 int pingid;
00608 int lagid;
00609 int autoid;
00610 int authid;
00611 int authfail;
00612 int initid;
00613 int calling_ton;
00614 int calling_tns;
00615 int calling_pres;
00616 int amaflags;
00617 struct iax2_dpcache *dpentries;
00618 struct ast_variable *vars;
00619
00620 struct iax_rr remote_rr;
00621
00622 int min;
00623
00624 int frames_dropped;
00625
00626 int frames_received;
00627 };
00628
00629 static struct ast_iax2_queue {
00630 AST_LIST_HEAD(, iax_frame) queue;
00631 int count;
00632 } iaxq;
00633
00634
00635
00636
00637
00638
00639
00640
00641 #ifdef LOW_MEMORY
00642 #define MAX_PEER_BUCKETS 1
00643
00644 #else
00645 #define MAX_PEER_BUCKETS 1
00646
00647 #endif
00648 static struct ao2_container *peers;
00649
00650 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00651 static struct ao2_container *users;
00652
00653 static struct ast_firmware_list {
00654 struct iax_firmware *wares;
00655 ast_mutex_t lock;
00656 } waresl;
00657
00658
00659 #define CACHE_FLAG_EXISTS (1 << 0)
00660
00661 #define CACHE_FLAG_NONEXISTENT (1 << 1)
00662
00663 #define CACHE_FLAG_CANEXIST (1 << 2)
00664
00665 #define CACHE_FLAG_PENDING (1 << 3)
00666
00667 #define CACHE_FLAG_TIMEOUT (1 << 4)
00668
00669 #define CACHE_FLAG_TRANSMITTED (1 << 5)
00670
00671 #define CACHE_FLAG_UNKNOWN (1 << 6)
00672
00673 #define CACHE_FLAG_MATCHMORE (1 << 7)
00674
00675 static struct iax2_dpcache {
00676 char peercontext[AST_MAX_CONTEXT];
00677 char exten[AST_MAX_EXTENSION];
00678 struct timeval orig;
00679 struct timeval expiry;
00680 int flags;
00681 unsigned short callno;
00682 int waiters[256];
00683 struct iax2_dpcache *next;
00684 struct iax2_dpcache *peer;
00685 } *dpcache;
00686
00687 AST_MUTEX_DEFINE_STATIC(dpcache_lock);
00688
00689 static void reg_source_db(struct iax2_peer *p);
00690 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00691
00692 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00693
00694 #define IAX_IOSTATE_IDLE 0
00695 #define IAX_IOSTATE_READY 1
00696 #define IAX_IOSTATE_PROCESSING 2
00697 #define IAX_IOSTATE_SCHEDREADY 3
00698
00699 #define IAX_TYPE_POOL 1
00700 #define IAX_TYPE_DYNAMIC 2
00701
00702 struct iax2_pkt_buf {
00703 AST_LIST_ENTRY(iax2_pkt_buf) entry;
00704 size_t len;
00705 unsigned char buf[1];
00706 };
00707
00708 struct iax2_thread {
00709 AST_LIST_ENTRY(iax2_thread) list;
00710 int type;
00711 int iostate;
00712 #ifdef SCHED_MULTITHREADED
00713 void (*schedfunc)(const void *);
00714 const void *scheddata;
00715 #endif
00716 #ifdef DEBUG_SCHED_MULTITHREAD
00717 char curfunc[80];
00718 #endif
00719 int actions;
00720 pthread_t threadid;
00721 int threadnum;
00722 struct sockaddr_in iosin;
00723 unsigned char readbuf[4096];
00724 unsigned char *buf;
00725 ssize_t buf_len;
00726 size_t buf_size;
00727 int iofd;
00728 time_t checktime;
00729 ast_mutex_t lock;
00730 ast_cond_t cond;
00731 unsigned int ready_for_signal:1;
00732
00733
00734
00735
00736 struct {
00737 unsigned short callno;
00738 struct sockaddr_in sin;
00739 unsigned char type;
00740 unsigned char csub;
00741 } ffinfo;
00742
00743
00744
00745 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
00746 };
00747
00748
00749 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
00750 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
00751 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
00752
00753 static void *iax2_process_thread(void *data);
00754
00755 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
00756 {
00757 ast_mutex_lock(lock);
00758 ast_cond_signal(cond);
00759 ast_mutex_unlock(lock);
00760 }
00761
00762 static void iax_debug_output(const char *data)
00763 {
00764 if (iaxdebug)
00765 ast_verbose("%s", data);
00766 }
00767
00768 static void iax_error_output(const char *data)
00769 {
00770 ast_log(LOG_WARNING, "%s", data);
00771 }
00772
00773 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
00774 {
00775 va_list args;
00776 char buf[1024];
00777
00778 va_start(args, fmt);
00779 vsnprintf(buf, 1024, fmt, args);
00780 va_end(args);
00781
00782 ast_log(LOG_ERROR, "%s", buf);
00783 }
00784
00785 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
00786 {
00787 va_list args;
00788 char buf[1024];
00789
00790 va_start(args, fmt);
00791 vsnprintf(buf, 1024, fmt, args);
00792 va_end(args);
00793
00794 ast_log(LOG_WARNING, "%s", buf);
00795 }
00796
00797 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
00798 {
00799 va_list args;
00800 char buf[1024];
00801
00802 va_start(args, fmt);
00803 vsnprintf(buf, 1024, fmt, args);
00804 va_end(args);
00805
00806 ast_verbose("%s", buf);
00807 }
00808
00809
00810 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS];
00811 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
00812 static struct timeval lastused[ARRAY_LEN(iaxs)];
00813
00814
00815
00816
00817
00818
00819
00820
00821
00822
00823 static struct ao2_container *iax_peercallno_pvts;
00824
00825
00826
00827 #define TRUNK_CALL_START ARRAY_LEN(iaxs) / 2
00828
00829 static int maxtrunkcall = TRUNK_CALL_START;
00830 static int maxnontrunkcall = 1;
00831
00832 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);
00833 static int expire_registry(const void *data);
00834 static int iax2_answer(struct ast_channel *c);
00835 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
00836 static int iax2_devicestate(void *data);
00837 static int iax2_digit_begin(struct ast_channel *c, char digit);
00838 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
00839 static int iax2_do_register(struct iax2_registry *reg);
00840 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
00841 static int iax2_hangup(struct ast_channel *c);
00842 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
00843 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
00844 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
00845 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
00846 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
00847 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
00848 static int iax2_sendtext(struct ast_channel *c, const char *text);
00849 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
00850 static int iax2_transfer(struct ast_channel *c, const char *dest);
00851 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
00852 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
00853 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
00854 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
00855 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
00856 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
00857 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
00858 static struct ast_frame *iax2_read(struct ast_channel *c);
00859 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
00860 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
00861 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
00862 static void prune_peers(void);
00863
00864 static const struct ast_channel_tech iax2_tech = {
00865 .type = "IAX2",
00866 .description = tdesc,
00867 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
00868 .properties = AST_CHAN_TP_WANTSJITTER,
00869 .requester = iax2_request,
00870 .devicestate = iax2_devicestate,
00871 .send_digit_begin = iax2_digit_begin,
00872 .send_digit_end = iax2_digit_end,
00873 .send_text = iax2_sendtext,
00874 .send_image = iax2_sendimage,
00875 .send_html = iax2_sendhtml,
00876 .call = iax2_call,
00877 .hangup = iax2_hangup,
00878 .answer = iax2_answer,
00879 .read = iax2_read,
00880 .write = iax2_write,
00881 .write_video = iax2_write,
00882 .indicate = iax2_indicate,
00883 .setoption = iax2_setoption,
00884 .bridge = iax2_bridge,
00885 .transfer = iax2_transfer,
00886 .fixup = iax2_fixup,
00887 };
00888
00889
00890
00891
00892 static void insert_idle_thread(struct iax2_thread *thread)
00893 {
00894 if (thread->type == IAX_TYPE_DYNAMIC) {
00895 AST_LIST_LOCK(&dynamic_list);
00896 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
00897 AST_LIST_UNLOCK(&dynamic_list);
00898 } else {
00899 AST_LIST_LOCK(&idle_list);
00900 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
00901 AST_LIST_UNLOCK(&idle_list);
00902 }
00903
00904 return;
00905 }
00906
00907 static struct iax2_thread *find_idle_thread(void)
00908 {
00909 pthread_attr_t attr;
00910 struct iax2_thread *thread = NULL;
00911
00912
00913 AST_LIST_LOCK(&idle_list);
00914 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
00915 AST_LIST_UNLOCK(&idle_list);
00916
00917
00918 if (thread == NULL) {
00919 AST_LIST_LOCK(&dynamic_list);
00920 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
00921
00922 if (thread == NULL && iaxmaxthreadcount > iaxdynamicthreadcount) {
00923
00924 if ((thread = ast_calloc(1, sizeof(*thread)))) {
00925 thread->threadnum = iaxdynamicthreadnum++;
00926 thread->type = IAX_TYPE_DYNAMIC;
00927 ast_mutex_init(&thread->lock);
00928 ast_cond_init(&thread->cond, NULL);
00929 pthread_attr_init(&attr);
00930 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
00931 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
00932 free(thread);
00933 thread = NULL;
00934 } else {
00935
00936 iaxdynamicthreadcount++;
00937
00938
00939 while (!thread->ready_for_signal)
00940 usleep(1);
00941 }
00942 }
00943 }
00944 AST_LIST_UNLOCK(&dynamic_list);
00945 }
00946
00947
00948
00949 if (thread)
00950 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
00951
00952 return thread;
00953 }
00954
00955 #ifdef SCHED_MULTITHREADED
00956 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
00957 {
00958 struct iax2_thread *thread = NULL;
00959 static time_t lasterror;
00960 static time_t t;
00961
00962 thread = find_idle_thread();
00963
00964 if (thread != NULL) {
00965 thread->schedfunc = func;
00966 thread->scheddata = data;
00967 thread->iostate = IAX_IOSTATE_SCHEDREADY;
00968 #ifdef DEBUG_SCHED_MULTITHREAD
00969 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
00970 #endif
00971 signal_condition(&thread->lock, &thread->cond);
00972 return 0;
00973 }
00974 time(&t);
00975 if (t != lasterror && option_debug)
00976 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for scheduling!\n");
00977 lasterror = t;
00978
00979 return -1;
00980 }
00981 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
00982 #endif
00983
00984 static int iax2_sched_add(struct sched_context *con, int when, ast_sched_cb callback, const void *data)
00985 {
00986 int res;
00987
00988 res = ast_sched_add(con, when, callback, data);
00989 signal_condition(&sched_lock, &sched_cond);
00990
00991 return res;
00992 }
00993
00994 static int send_ping(const void *data);
00995
00996 static void __send_ping(const void *data)
00997 {
00998 int callno = (long) data;
00999
01000 ast_mutex_lock(&iaxsl[callno]);
01001
01002 if (iaxs[callno]) {
01003 if (iaxs[callno]->peercallno) {
01004 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01005 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01006 } else {
01007
01008 iaxs[callno]->pingid = -1;
01009 }
01010 } else if (option_debug > 0) {
01011 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);
01012 }
01013
01014 ast_mutex_unlock(&iaxsl[callno]);
01015 }
01016
01017 static int send_ping(const void *data)
01018 {
01019 #ifdef SCHED_MULTITHREADED
01020 if (schedule_action(__send_ping, data))
01021 #endif
01022 __send_ping(data);
01023
01024 return 0;
01025 }
01026
01027 static int get_encrypt_methods(const char *s)
01028 {
01029 int e;
01030 if (!strcasecmp(s, "aes128"))
01031 e = IAX_ENCRYPT_AES128;
01032 else if (ast_true(s))
01033 e = IAX_ENCRYPT_AES128;
01034 else
01035 e = 0;
01036 return e;
01037 }
01038
01039 static int send_lagrq(const void *data);
01040
01041 static void __send_lagrq(const void *data)
01042 {
01043 int callno = (long) data;
01044
01045 ast_mutex_lock(&iaxsl[callno]);
01046
01047 if (iaxs[callno]) {
01048 if (iaxs[callno]->peercallno) {
01049 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01050 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01051 } else {
01052
01053 iaxs[callno]->lagid = -1;
01054 }
01055 } else {
01056 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);
01057 }
01058
01059 ast_mutex_unlock(&iaxsl[callno]);
01060 }
01061
01062 static int send_lagrq(const void *data)
01063 {
01064 #ifdef SCHED_MULTITHREADED
01065 if (schedule_action(__send_lagrq, data))
01066 #endif
01067 __send_lagrq(data);
01068
01069 return 0;
01070 }
01071
01072 static unsigned char compress_subclass(int subclass)
01073 {
01074 int x;
01075 int power=-1;
01076
01077 if (subclass < IAX_FLAG_SC_LOG)
01078 return subclass;
01079
01080 for (x = 0; x < IAX_MAX_SHIFT; x++) {
01081 if (subclass & (1 << x)) {
01082 if (power > -1) {
01083 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
01084 return 0;
01085 } else
01086 power = x;
01087 }
01088 }
01089 return power | IAX_FLAG_SC_LOG;
01090 }
01091
01092 static int uncompress_subclass(unsigned char csub)
01093 {
01094
01095 if (csub & IAX_FLAG_SC_LOG) {
01096
01097 if (csub == 0xff)
01098 return -1;
01099 else
01100 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01101 }
01102 else
01103 return csub;
01104 }
01105
01106
01107
01108
01109 static int peer_hash_cb(const void *obj, const int flags)
01110 {
01111 const struct iax2_peer *peer = obj;
01112
01113 return ast_str_hash(peer->name);
01114 }
01115
01116
01117
01118
01119 static int peer_cmp_cb(void *obj, void *arg, int flags)
01120 {
01121 struct iax2_peer *peer = obj, *peer2 = arg;
01122
01123 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01124 }
01125
01126
01127
01128
01129 static int user_hash_cb(const void *obj, const int flags)
01130 {
01131 const struct iax2_user *user = obj;
01132
01133 return ast_str_hash(user->name);
01134 }
01135
01136
01137
01138
01139 static int user_cmp_cb(void *obj, void *arg, int flags)
01140 {
01141 struct iax2_user *user = obj, *user2 = arg;
01142
01143 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01144 }
01145
01146
01147
01148
01149
01150 static struct iax2_peer *find_peer(const char *name, int realtime)
01151 {
01152 struct iax2_peer *peer = NULL;
01153 struct iax2_peer tmp_peer = {
01154 .name = name,
01155 };
01156
01157 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01158
01159
01160 if(!peer && realtime)
01161 peer = realtime_peer(name, NULL);
01162
01163 return peer;
01164 }
01165
01166 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01167 {
01168 ao2_ref(peer, +1);
01169 return peer;
01170 }
01171
01172 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01173 {
01174 ao2_ref(peer, -1);
01175 return NULL;
01176 }
01177
01178 static inline struct iax2_user *user_ref(struct iax2_user *user)
01179 {
01180 ao2_ref(user, +1);
01181 return user;
01182 }
01183
01184 static inline struct iax2_user *user_unref(struct iax2_user *user)
01185 {
01186 ao2_ref(user, -1);
01187 return NULL;
01188 }
01189
01190 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01191 {
01192 struct iax2_peer *peer = NULL;
01193 int res = 0;
01194 struct ao2_iterator i;
01195
01196 i = ao2_iterator_init(peers, 0);
01197 while ((peer = ao2_iterator_next(&i))) {
01198 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01199 (peer->addr.sin_port == sin.sin_port)) {
01200 ast_copy_string(host, peer->name, len);
01201 peer_unref(peer);
01202 res = 1;
01203 break;
01204 }
01205 peer_unref(peer);
01206 }
01207
01208 if (!peer) {
01209 peer = realtime_peer(NULL, &sin);
01210 if (peer) {
01211 ast_copy_string(host, peer->name, len);
01212 peer_unref(peer);
01213 res = 1;
01214 }
01215 }
01216
01217 return res;
01218 }
01219
01220 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01221 {
01222
01223 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
01224 struct iax2_user *user;
01225 struct iax2_user tmp_user = {
01226 .name = pvt->username,
01227 };
01228
01229 user = ao2_find(users, &tmp_user, OBJ_POINTER);
01230 if (user) {
01231 ast_atomic_fetchadd_int(&user->curauthreq, -1);
01232 user = user_unref(user);
01233 }
01234
01235 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
01236 }
01237
01238
01239 AST_SCHED_DEL(sched, pvt->pingid);
01240 AST_SCHED_DEL(sched, pvt->lagid);
01241 AST_SCHED_DEL(sched, pvt->autoid);
01242 AST_SCHED_DEL(sched, pvt->authid);
01243 AST_SCHED_DEL(sched, pvt->initid);
01244 AST_SCHED_DEL(sched, pvt->jbid);
01245 }
01246
01247 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
01248 {
01249 if (!pvt->peercallno) {
01250 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
01251 return;
01252 }
01253
01254 ao2_link(iax_peercallno_pvts, pvt);
01255 }
01256
01257 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
01258 {
01259 if (!pvt->peercallno) {
01260 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
01261 return;
01262 }
01263
01264 ao2_unlink(iax_peercallno_pvts, pvt);
01265 }
01266
01267 static void update_max_trunk(void)
01268 {
01269 int max = TRUNK_CALL_START;
01270 int x;
01271
01272
01273 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
01274 if (iaxs[x]) {
01275 max = x + 1;
01276 }
01277 }
01278
01279 maxtrunkcall = max;
01280 if (option_debug && iaxdebug)
01281 ast_log(LOG_DEBUG, "New max trunk callno is %d\n", max);
01282 }
01283
01284 static void iax2_frame_free(struct iax_frame *fr)
01285 {
01286 AST_SCHED_DEL(sched, fr->retrans);
01287 iax_frame_free(fr);
01288 }
01289
01290 static void iax2_destroy(int callno)
01291 {
01292 struct chan_iax2_pvt *pvt;
01293 struct ast_channel *owner;
01294
01295 retry:
01296 pvt = iaxs[callno];
01297 gettimeofday(&lastused[callno], NULL);
01298
01299 owner = pvt ? pvt->owner : NULL;
01300
01301 if (owner) {
01302 if (ast_mutex_trylock(&owner->lock)) {
01303 if (option_debug > 2)
01304 ast_log(LOG_DEBUG, "Avoiding IAX destroy deadlock\n");
01305 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01306 goto retry;
01307 }
01308 }
01309 if (!owner && iaxs[callno]) {
01310 AST_SCHED_DEL_SPINLOCK(sched, iaxs[callno]->lagid, &iaxsl[callno]);
01311 AST_SCHED_DEL_SPINLOCK(sched, iaxs[callno]->pingid, &iaxsl[callno]);
01312 iaxs[callno] = NULL;
01313 }
01314
01315 if (pvt) {
01316 if (!owner) {
01317 pvt->owner = NULL;
01318 } else {
01319
01320
01321
01322 ast_queue_hangup(owner);
01323 }
01324
01325 if (pvt->peercallno) {
01326 remove_by_peercallno(pvt);
01327 }
01328
01329 if (!owner) {
01330 ao2_ref(pvt, -1);
01331 pvt = NULL;
01332 }
01333 }
01334
01335 if (owner) {
01336 ast_mutex_unlock(&owner->lock);
01337 }
01338
01339 if (callno & 0x4000) {
01340 update_max_trunk();
01341 }
01342 }
01343
01344 static int scheduled_destroy(const void *vid)
01345 {
01346 short callno = PTR_TO_CALLNO(vid);
01347 ast_mutex_lock(&iaxsl[callno]);
01348 if (iaxs[callno]) {
01349 if (option_debug) {
01350 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01351 }
01352 iax2_destroy(callno);
01353 }
01354 ast_mutex_unlock(&iaxsl[callno]);
01355 return 0;
01356 }
01357
01358 static void pvt_destructor(void *obj)
01359 {
01360 struct chan_iax2_pvt *pvt = obj;
01361 struct iax_frame *cur = NULL;
01362
01363 iax2_destroy_helper(pvt);
01364
01365
01366 ast_set_flag(pvt, IAX_ALREADYGONE);
01367
01368 AST_LIST_LOCK(&iaxq.queue);
01369 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
01370
01371 if (cur->callno == pvt->callno) {
01372 cur->retries = -1;
01373 }
01374 }
01375 AST_LIST_UNLOCK(&iaxq.queue);
01376
01377 if (pvt->reg) {
01378 pvt->reg->callno = 0;
01379 }
01380
01381 if (!pvt->owner) {
01382 jb_frame frame;
01383 if (pvt->vars) {
01384 ast_variables_destroy(pvt->vars);
01385 pvt->vars = NULL;
01386 }
01387
01388 while (jb_getall(pvt->jb, &frame) == JB_OK) {
01389 iax2_frame_free(frame.data);
01390 }
01391
01392 jb_destroy(pvt->jb);
01393 ast_string_field_free_memory(pvt);
01394 }
01395 }
01396
01397 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01398 {
01399 struct chan_iax2_pvt *tmp;
01400 jb_conf jbconf;
01401
01402 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01403 return NULL;
01404 }
01405
01406 if (ast_string_field_init(tmp, 32)) {
01407 ao2_ref(tmp, -1);
01408 tmp = NULL;
01409 return NULL;
01410 }
01411
01412 tmp->prefs = prefs;
01413 tmp->callno = 0;
01414 tmp->peercallno = 0;
01415 tmp->transfercallno = 0;
01416 tmp->bridgecallno = 0;
01417 tmp->pingid = -1;
01418 tmp->lagid = -1;
01419 tmp->autoid = -1;
01420 tmp->authid = -1;
01421 tmp->initid = -1;
01422
01423 ast_string_field_set(tmp,exten, "s");
01424 ast_string_field_set(tmp,host, host);
01425
01426 tmp->jb = jb_new();
01427 tmp->jbid = -1;
01428 jbconf.max_jitterbuf = maxjitterbuffer;
01429 jbconf.resync_threshold = resyncthreshold;
01430 jbconf.max_contig_interp = maxjitterinterps;
01431 jb_setconf(tmp->jb,&jbconf);
01432
01433 return tmp;
01434 }
01435
01436 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01437 {
01438 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01439 if (new) {
01440 size_t afdatalen = new->afdatalen;
01441 memcpy(new, fr, sizeof(*new));
01442 iax_frame_wrap(new, &fr->af);
01443 new->afdatalen = afdatalen;
01444 new->data = NULL;
01445 new->datalen = 0;
01446 new->direction = DIRECTION_INGRESS;
01447 new->retrans = -1;
01448 }
01449 return new;
01450 }
01451
01452 #define NEW_PREVENT 0
01453 #define NEW_ALLOW 1
01454 #define NEW_FORCE 2
01455
01456 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, struct chan_iax2_pvt *cur, int check_dcallno)
01457 {
01458 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01459 (cur->addr.sin_port == sin->sin_port)) {
01460
01461 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01462 (check_dcallno ? dcallno == cur->callno : 1) ) {
01463
01464 return 1;
01465 }
01466 }
01467 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01468 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01469
01470 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
01471 return 1;
01472 }
01473 return 0;
01474 }
01475
01476 static void update_max_nontrunk(void)
01477 {
01478 int max = 1;
01479 int x;
01480
01481 for (x=1;x<TRUNK_CALL_START - 1; x++) {
01482 if (iaxs[x])
01483 max = x + 1;
01484 }
01485 maxnontrunkcall = max;
01486 if (option_debug && iaxdebug)
01487 ast_log(LOG_DEBUG, "New max nontrunk callno is %d\n", max);
01488 }
01489
01490 static int make_trunk(unsigned short callno, int locked)
01491 {
01492 int x;
01493 int res= 0;
01494 struct timeval now;
01495 if (iaxs[callno]->oseqno) {
01496 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
01497 return -1;
01498 }
01499 if (callno & TRUNK_CALL_START) {
01500 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
01501 return -1;
01502 }
01503 gettimeofday(&now, NULL);
01504 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
01505 ast_mutex_lock(&iaxsl[x]);
01506 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
01507
01508
01509
01510
01511
01512 AST_SCHED_DEL(sched, iaxs[callno]->pingid);
01513 AST_SCHED_DEL(sched, iaxs[callno]->lagid);
01514 iaxs[x] = iaxs[callno];
01515 iaxs[x]->callno = x;
01516 iaxs[callno] = NULL;
01517 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
01518 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
01519 if (locked)
01520 ast_mutex_unlock(&iaxsl[callno]);
01521 res = x;
01522 if (!locked)
01523 ast_mutex_unlock(&iaxsl[x]);
01524 break;
01525 }
01526 ast_mutex_unlock(&iaxsl[x]);
01527 }
01528 if (x >= ARRAY_LEN(iaxs) - 1) {
01529 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
01530 return -1;
01531 }
01532 if (option_debug)
01533 ast_log(LOG_DEBUG, "Made call %d into trunk call %d\n", callno, x);
01534
01535 update_max_trunk();
01536 update_max_nontrunk();
01537 return res;
01538 }
01539
01540
01541
01542
01543 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
01544 {
01545 int res = 0;
01546 int x;
01547 struct timeval now;
01548 char host[80];
01549
01550 if (new <= NEW_ALLOW) {
01551 if (callno) {
01552 struct chan_iax2_pvt *pvt;
01553 struct chan_iax2_pvt tmp_pvt = {
01554 .callno = dcallno,
01555 .peercallno = callno,
01556
01557 .frames_received = check_dcallno,
01558 };
01559
01560 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
01561
01562 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
01563 if (return_locked) {
01564 ast_mutex_lock(&iaxsl[pvt->callno]);
01565 }
01566 res = pvt->callno;
01567 ao2_ref(pvt, -1);
01568 pvt = NULL;
01569 return res;
01570 }
01571 }
01572
01573
01574
01575 if (dcallno) {
01576 ast_mutex_lock(&iaxsl[dcallno]);
01577 }
01578 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
01579 iaxs[dcallno]->peercallno = callno;
01580 res = dcallno;
01581 store_by_peercallno(iaxs[dcallno]);
01582 if (!res || !return_locked) {
01583 ast_mutex_unlock(&iaxsl[dcallno]);
01584 }
01585 return res;
01586 }
01587 if (dcallno) {
01588 ast_mutex_unlock(&iaxsl[dcallno]);
01589 }
01590
01591 #ifdef IAX_OLD_FIND
01592
01593
01594
01595
01596
01597
01598
01599
01600
01601
01602
01603 for (x = 1; !res && x < maxnontrunkcall; x++) {
01604 ast_mutex_lock(&iaxsl[x]);
01605 if (iaxs[x]) {
01606
01607 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
01608 res = x;
01609 }
01610 }
01611 if (!res || !return_locked)
01612 ast_mutex_unlock(&iaxsl[x]);
01613 }
01614
01615 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
01616 ast_mutex_lock(&iaxsl[x]);
01617 if (iaxs[x]) {
01618
01619 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
01620 res = x;
01621 }
01622 }
01623 if (!res || !return_locked)
01624 ast_mutex_unlock(&iaxsl[x]);
01625 }
01626
01627 if (res) {
01628 ast_log(LOG_WARNING, "Old call search code found call number %d that was not in hash table!\n", res);
01629 }
01630 #endif
01631 }
01632 if (!res && (new >= NEW_ALLOW)) {
01633 int start, found = 0;
01634
01635
01636
01637
01638
01639
01640
01641 if (!iax2_getpeername(*sin, host, sizeof(host)))
01642 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
01643
01644 now = ast_tvnow();
01645 start = 2 + (ast_random() % (TRUNK_CALL_START - 1));
01646 for (x = start; 1; x++) {
01647 if (x == TRUNK_CALL_START) {
01648 x = 1;
01649 continue;
01650 }
01651
01652
01653 ast_mutex_lock(&iaxsl[x]);
01654 if (!iaxs[x] && ((now.tv_sec - lastused[x].tv_sec) > MIN_REUSE_TIME)) {
01655 found = 1;
01656 break;
01657 }
01658 ast_mutex_unlock(&iaxsl[x]);
01659
01660 if (x == start - 1) {
01661 break;
01662 }
01663 }
01664
01665 if (x == start - 1 && !found) {
01666 ast_log(LOG_WARNING, "No more space\n");
01667 return 0;
01668 }
01669 iaxs[x] = new_iax(sin, host);
01670 update_max_nontrunk();
01671 if (iaxs[x]) {
01672 if (option_debug && iaxdebug)
01673 ast_log(LOG_DEBUG, "Creating new call structure %d\n", x);
01674 iaxs[x]->sockfd = sockfd;
01675 iaxs[x]->addr.sin_port = sin->sin_port;
01676 iaxs[x]->addr.sin_family = sin->sin_family;
01677 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
01678 iaxs[x]->peercallno = callno;
01679 iaxs[x]->callno = x;
01680 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
01681 iaxs[x]->expiry = min_reg_expire;
01682 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
01683 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
01684 iaxs[x]->amaflags = amaflags;
01685 ast_copy_flags(iaxs[x], (&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
01686
01687 ast_string_field_set(iaxs[x], accountcode, accountcode);
01688 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
01689 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
01690
01691 if (iaxs[x]->peercallno) {
01692 store_by_peercallno(iaxs[x]);
01693 }
01694 } else {
01695 ast_log(LOG_WARNING, "Out of resources\n");
01696 ast_mutex_unlock(&iaxsl[x]);
01697 return 0;
01698 }
01699 if (!return_locked)
01700 ast_mutex_unlock(&iaxsl[x]);
01701 res = x;
01702 }
01703 return res;
01704 }
01705
01706 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
01707
01708 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
01709 }
01710
01711 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
01712
01713 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
01714 }
01715
01716
01717
01718
01719
01720
01721
01722
01723
01724
01725
01726 static int iax2_queue_frame(int callno, struct ast_frame *f)
01727 {
01728 for (;;) {
01729 if (iaxs[callno] && iaxs[callno]->owner) {
01730 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
01731
01732 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01733 } else {
01734 ast_queue_frame(iaxs[callno]->owner, f);
01735 ast_mutex_unlock(&iaxs[callno]->owner->lock);
01736 break;
01737 }
01738 } else
01739 break;
01740 }
01741 return 0;
01742 }
01743
01744
01745
01746
01747
01748
01749
01750
01751
01752
01753
01754
01755
01756
01757 static int iax2_queue_hangup(int callno)
01758 {
01759 for (;;) {
01760 if (iaxs[callno] && iaxs[callno]->owner) {
01761 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
01762
01763 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01764 } else {
01765 ast_queue_hangup(iaxs[callno]->owner);
01766 ast_mutex_unlock(&iaxs[callno]->owner->lock);
01767 break;
01768 }
01769 } else
01770 break;
01771 }
01772 return 0;
01773 }
01774
01775
01776
01777
01778
01779
01780
01781
01782
01783
01784
01785
01786
01787
01788 static int iax2_queue_control_data(int callno,
01789 enum ast_control_frame_type control, const void *data, size_t datalen)
01790 {
01791 for (;;) {
01792 if (iaxs[callno] && iaxs[callno]->owner) {
01793 if (ast_mutex_trylock(&iaxs[callno]->owner->lock)) {
01794
01795 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01796 } else {
01797 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
01798 ast_mutex_unlock(&iaxs[callno]->owner->lock);
01799 break;
01800 }
01801 } else
01802 break;
01803 }
01804 return 0;
01805 }
01806 static void destroy_firmware(struct iax_firmware *cur)
01807 {
01808
01809 if (cur->fwh) {
01810 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
01811 }
01812 close(cur->fd);
01813 free(cur);
01814 }
01815
01816 static int try_firmware(char *s)
01817 {
01818 struct stat stbuf;
01819 struct iax_firmware *cur;
01820 int ifd;
01821 int fd;
01822 int res;
01823
01824 struct ast_iax2_firmware_header *fwh, fwh2;
01825 struct MD5Context md5;
01826 unsigned char sum[16];
01827 unsigned char buf[1024];
01828 int len, chunk;
01829 char *s2;
01830 char *last;
01831 s2 = alloca(strlen(s) + 100);
01832 if (!s2) {
01833 ast_log(LOG_WARNING, "Alloca failed!\n");
01834 return -1;
01835 }
01836 last = strrchr(s, '/');
01837 if (last)
01838 last++;
01839 else
01840 last = s;
01841 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
01842 res = stat(s, &stbuf);
01843 if (res < 0) {
01844 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
01845 return -1;
01846 }
01847
01848 if (S_ISDIR(stbuf.st_mode))
01849 return -1;
01850 ifd = open(s, O_RDONLY);
01851 if (ifd < 0) {
01852 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
01853 return -1;
01854 }
01855 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, 0600);
01856 if (fd < 0) {
01857 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
01858 close(ifd);
01859 return -1;
01860 }
01861
01862 unlink(s2);
01863
01864
01865 len = stbuf.st_size;
01866 while(len) {
01867 chunk = len;
01868 if (chunk > sizeof(buf))
01869 chunk = sizeof(buf);
01870 res = read(ifd, buf, chunk);
01871 if (res != chunk) {
01872 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
01873 close(ifd);
01874 close(fd);
01875 return -1;
01876 }
01877 res = write(fd, buf, chunk);
01878 if (res != chunk) {
01879 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
01880 close(ifd);
01881 close(fd);
01882 return -1;
01883 }
01884 len -= chunk;
01885 }
01886 close(ifd);
01887
01888 lseek(fd, 0, SEEK_SET);
01889 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
01890 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
01891 close(fd);
01892 return -1;
01893 }
01894 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
01895 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
01896 close(fd);
01897 return -1;
01898 }
01899 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
01900 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
01901 close(fd);
01902 return -1;
01903 }
01904 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
01905 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
01906 close(fd);
01907 return -1;
01908 }
01909 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
01910 if (fwh == (void *) -1) {
01911 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
01912 close(fd);
01913 return -1;
01914 }
01915 MD5Init(&md5);
01916 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
01917 MD5Final(sum, &md5);
01918 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
01919 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
01920 munmap((void*)fwh, stbuf.st_size);
01921 close(fd);
01922 return -1;
01923 }
01924 cur = waresl.wares;
01925 while(cur) {
01926 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
01927
01928 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
01929
01930 break;
01931
01932
01933 munmap((void*)fwh, stbuf.st_size);
01934 close(fd);
01935 return 0;
01936 }
01937 cur = cur->next;
01938 }
01939 if (!cur) {
01940
01941 if ((cur = ast_calloc(1, sizeof(*cur)))) {
01942 cur->fd = -1;
01943 cur->next = waresl.wares;
01944 waresl.wares = cur;
01945 }
01946 }
01947 if (cur) {
01948 if (cur->fwh) {
01949 munmap((void*)cur->fwh, cur->mmaplen);
01950 }
01951 if (cur->fd > -1)
01952 close(cur->fd);
01953 cur->fwh = fwh;
01954 cur->fd = fd;
01955 cur->mmaplen = stbuf.st_size;
01956 cur->dead = 0;
01957 }
01958 return 0;
01959 }
01960
01961 static int iax_check_version(char *dev)
01962 {
01963 int res = 0;
01964 struct iax_firmware *cur;
01965 if (!ast_strlen_zero(dev)) {
01966 ast_mutex_lock(&waresl.lock);
01967 cur = waresl.wares;
01968 while(cur) {
01969 if (!strcmp(dev, (char *)cur->fwh->devname)) {
01970 res = ntohs(cur->fwh->version);
01971 break;
01972 }
01973 cur = cur->next;
01974 }
01975 ast_mutex_unlock(&waresl.lock);
01976 }
01977 return res;
01978 }
01979
01980 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
01981 {
01982 int res = -1;
01983 unsigned int bs = desc & 0xff;
01984 unsigned int start = (desc >> 8) & 0xffffff;
01985 unsigned int bytes;
01986 struct iax_firmware *cur;
01987 if (!ast_strlen_zero((char *)dev) && bs) {
01988 start *= bs;
01989 ast_mutex_lock(&waresl.lock);
01990 cur = waresl.wares;
01991 while(cur) {
01992 if (!strcmp((char *)dev, (char *)cur->fwh->devname)) {
01993 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
01994 if (start < ntohl(cur->fwh->datalen)) {
01995 bytes = ntohl(cur->fwh->datalen) - start;
01996 if (bytes > bs)
01997 bytes = bs;
01998 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
01999 } else {
02000 bytes = 0;
02001 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
02002 }
02003 if (bytes == bs)
02004 res = 0;
02005 else
02006 res = 1;
02007 break;
02008 }
02009 cur = cur->next;
02010 }
02011 ast_mutex_unlock(&waresl.lock);
02012 }
02013 return res;
02014 }
02015
02016
02017 static void reload_firmware(int unload)
02018 {
02019 struct iax_firmware *cur, *curl, *curp;
02020 DIR *fwd;
02021 struct dirent *de;
02022 char dir[256];
02023 char fn[256];
02024
02025 ast_mutex_lock(&waresl.lock);
02026 cur = waresl.wares;
02027 while(cur) {
02028 cur->dead = 1;
02029 cur = cur->next;
02030 }
02031
02032
02033 if (!unload) {
02034 snprintf(dir, sizeof(dir), "%s/firmware/iax", (char *)ast_config_AST_DATA_DIR);
02035 fwd = opendir(dir);
02036 if (fwd) {
02037 while((de = readdir(fwd))) {
02038 if (de->d_name[0] != '.') {
02039 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
02040 if (!try_firmware(fn)) {
02041 if (option_verbose > 1)
02042 ast_verbose(VERBOSE_PREFIX_2 "Loaded firmware '%s'\n", de->d_name);
02043 }
02044 }
02045 }
02046 closedir(fwd);
02047 } else
02048 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
02049 }
02050
02051
02052 cur = waresl.wares;
02053 curp = NULL;
02054 while(cur) {
02055 curl = cur;
02056 cur = cur->next;
02057 if (curl->dead) {
02058 if (curp) {
02059 curp->next = cur;
02060 } else {
02061 waresl.wares = cur;
02062 }
02063 destroy_firmware(curl);
02064 } else {
02065 curp = cur;
02066 }
02067 }
02068 ast_mutex_unlock(&waresl.lock);
02069 }
02070
02071
02072
02073
02074
02075
02076
02077
02078
02079 static int __do_deliver(void *data)
02080 {
02081
02082
02083 struct iax_frame *fr = data;
02084 fr->retrans = -1;
02085 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
02086 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
02087 iax2_queue_frame(fr->callno, &fr->af);
02088
02089 iax2_frame_free(fr);
02090
02091 return 0;
02092 }
02093
02094 static int handle_error(void)
02095 {
02096
02097
02098
02099 #if 0
02100 struct sockaddr_in *sin;
02101 int res;
02102 struct msghdr m;
02103 struct sock_extended_err e;
02104 m.msg_name = NULL;
02105 m.msg_namelen = 0;
02106 m.msg_iov = NULL;
02107 m.msg_control = &e;
02108 m.msg_controllen = sizeof(e);
02109 m.msg_flags = 0;
02110 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
02111 if (res < 0)
02112 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
02113 else {
02114 if (m.msg_controllen) {
02115 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
02116 if (sin)
02117 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
02118 else
02119 ast_log(LOG_WARNING, "No address detected??\n");
02120 } else {
02121 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
02122 }
02123 }
02124 #endif
02125 return 0;
02126 }
02127
02128 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
02129 {
02130 int res;
02131 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
02132 sizeof(*sin));
02133 if (res < 0) {
02134 if (option_debug)
02135 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
02136 handle_error();
02137 } else
02138 res = 0;
02139 return res;
02140 }
02141
02142 static int send_packet(struct iax_frame *f)
02143 {
02144 int res;
02145 int callno;
02146
02147 if( f == NULL ) {
02148 ast_log(LOG_ERROR, "send_packet( NULL )\n");
02149 ast_backtrace();
02150 return -1;
02151 }
02152
02153 callno = f->callno;
02154
02155
02156 if (!callno || !iaxs[callno] || iaxs[callno]->error)
02157 return -1;
02158
02159
02160 if (option_debug > 2 && iaxdebug)
02161 ast_log(LOG_DEBUG, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
02162 if (f->transfer) {
02163 if (iaxdebug)
02164 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
02165 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer,
02166 sizeof(iaxs[callno]->transfer));
02167 } else {
02168 if (iaxdebug)
02169 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
02170 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr,
02171 sizeof(iaxs[callno]->addr));
02172 }
02173 if (res < 0) {
02174 if (option_debug && iaxdebug)
02175 ast_log(LOG_DEBUG, "Received error: %s\n", strerror(errno));
02176 handle_error();
02177 } else
02178 res = 0;
02179 return res;
02180 }
02181
02182
02183
02184
02185
02186 static int iax2_predestroy(int callno)
02187 {
02188 struct ast_channel *c;
02189 struct chan_iax2_pvt *pvt = iaxs[callno];
02190
02191 if (!pvt)
02192 return -1;
02193 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
02194 iax2_destroy_helper(pvt);
02195 ast_set_flag(pvt, IAX_ALREADYGONE);
02196 }
02197 c = pvt->owner;
02198 if (c) {
02199 c->tech_pvt = NULL;
02200 iax2_queue_hangup(callno);
02201 pvt->owner = NULL;
02202 ast_module_unref(ast_module_info->self);
02203 }
02204 return 0;
02205 }
02206
02207 static int update_packet(struct iax_frame *f)
02208 {
02209
02210 struct ast_iax2_full_hdr *fh = f->data;
02211
02212 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
02213
02214 f->iseqno = iaxs[f->callno]->iseqno;
02215 fh->iseqno = f->iseqno;
02216 return 0;
02217 }
02218
02219 static int attempt_transmit(const void *data);
02220 static void __attempt_transmit(const void *data)
02221 {
02222
02223
02224 struct iax_frame *f = (struct iax_frame *)data;
02225 int freeme=0;
02226 int callno = f->callno;
02227
02228 if (callno)
02229 ast_mutex_lock(&iaxsl[callno]);
02230 if (callno && iaxs[callno]) {
02231 if ((f->retries < 0) ||
02232 (f->retries >= max_retries) ) {
02233
02234 if (f->retries >= max_retries) {
02235 if (f->transfer) {
02236
02237 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
02238 } else if (f->final) {
02239 if (f->final)
02240 iax2_destroy(callno);
02241 } else {
02242 if (iaxs[callno]->owner)
02243 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);
02244 iaxs[callno]->error = ETIMEDOUT;
02245 if (iaxs[callno]->owner) {
02246 struct ast_frame fr = { 0, };
02247
02248 fr.frametype = AST_FRAME_CONTROL;
02249 fr.subclass = AST_CONTROL_HANGUP;
02250 iax2_queue_frame(callno, &fr);
02251
02252 if (iaxs[callno] && iaxs[callno]->owner)
02253 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
02254 } else {
02255 if (iaxs[callno]->reg) {
02256 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
02257 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
02258 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
02259 }
02260 iax2_destroy(callno);
02261 }
02262 }
02263
02264 }
02265 freeme++;
02266 } else {
02267
02268 update_packet(f);
02269
02270 send_packet(f);
02271 f->retries++;
02272
02273 f->retrytime *= 10;
02274 if (f->retrytime > MAX_RETRY_TIME)
02275 f->retrytime = MAX_RETRY_TIME;
02276
02277 if (f->transfer && (f->retrytime > 1000))
02278 f->retrytime = 1000;
02279 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
02280 }
02281 } else {
02282
02283 f->retries = -1;
02284 freeme++;
02285 }
02286 if (callno)
02287 ast_mutex_unlock(&iaxsl[callno]);
02288
02289 if (freeme) {
02290
02291 AST_LIST_LOCK(&iaxq.queue);
02292 AST_LIST_REMOVE(&iaxq.queue, f, list);
02293 iaxq.count--;
02294 AST_LIST_UNLOCK(&iaxq.queue);
02295 f->retrans = -1;
02296
02297 iax2_frame_free(f);
02298 }
02299 }
02300
02301 static int attempt_transmit(const void *data)
02302 {
02303 #ifdef SCHED_MULTITHREADED
02304 if (schedule_action(__attempt_transmit, data))
02305 #endif
02306 __attempt_transmit(data);
02307 return 0;
02308 }
02309
02310 static int iax2_prune_realtime(int fd, int argc, char *argv[])
02311 {
02312 struct iax2_peer *peer;
02313
02314 if (argc != 4)
02315 return RESULT_SHOWUSAGE;
02316 if (!strcmp(argv[3],"all")) {
02317 reload_config();
02318 ast_cli(fd, "OK cache is flushed.\n");
02319 } else if ((peer = find_peer(argv[3], 0))) {
02320 if(ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
02321 ast_set_flag(peer, IAX_RTAUTOCLEAR);
02322 expire_registry(peer_ref(peer));
02323 ast_cli(fd, "OK peer %s was removed from the cache.\n", argv[3]);
02324 } else {
02325 ast_cli(fd, "SORRY peer %s is not eligible for this operation.\n", argv[3]);
02326 }
02327 peer_unref(peer);
02328 } else {
02329 ast_cli(fd, "SORRY peer %s was not found in the cache.\n", argv[3]);
02330 }
02331
02332 return RESULT_SUCCESS;
02333 }
02334
02335 static int iax2_test_losspct(int fd, int argc, char *argv[])
02336 {
02337 if (argc != 4)
02338 return RESULT_SHOWUSAGE;
02339
02340 test_losspct = atoi(argv[3]);
02341
02342 return RESULT_SUCCESS;
02343 }
02344
02345 #ifdef IAXTESTS
02346 static int iax2_test_late(int fd, int argc, char *argv[])
02347 {
02348 if (argc != 4)
02349 return RESULT_SHOWUSAGE;
02350
02351 test_late = atoi(argv[3]);
02352
02353 return RESULT_SUCCESS;
02354 }
02355
02356 static int iax2_test_resync(int fd, int argc, char *argv[])
02357 {
02358 if (argc != 4)
02359 return RESULT_SHOWUSAGE;
02360
02361 test_resync = atoi(argv[3]);
02362
02363 return RESULT_SUCCESS;
02364 }
02365
02366 static int iax2_test_jitter(int fd, int argc, char *argv[])
02367 {
02368 if (argc < 4 || argc > 5)
02369 return RESULT_SHOWUSAGE;
02370
02371 test_jit = atoi(argv[3]);
02372 if (argc == 5)
02373 test_jitpct = atoi(argv[4]);
02374
02375 return RESULT_SUCCESS;
02376 }
02377 #endif
02378
02379
02380
02381 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
02382 {
02383 int res = 0;
02384 if (peer->maxms) {
02385 if (peer->lastms < 0) {
02386 ast_copy_string(status, "UNREACHABLE", statuslen);
02387 } else if (peer->lastms > peer->maxms) {
02388 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
02389 res = 1;
02390 } else if (peer->lastms) {
02391 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
02392 res = 1;
02393 } else {
02394 ast_copy_string(status, "UNKNOWN", statuslen);
02395 }
02396 } else {
02397 ast_copy_string(status, "Unmonitored", statuslen);
02398 res = -1;
02399 }
02400 return res;
02401 }
02402
02403
02404 static int iax2_show_peer(int fd, int argc, char *argv[])
02405 {
02406 char status[30];
02407 char cbuf[256];
02408 struct iax2_peer *peer;
02409 char codec_buf[512];
02410 int x = 0, codec = 0, load_realtime = 0;
02411
02412 if (argc < 4)
02413 return RESULT_SHOWUSAGE;
02414
02415 load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? 1 : 0;
02416
02417 peer = find_peer(argv[3], load_realtime);
02418 if (peer) {
02419 ast_cli(fd,"\n\n");
02420 ast_cli(fd, " * Name : %s\n", peer->name);
02421 ast_cli(fd, " Secret : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
02422 ast_cli(fd, " Context : %s\n", peer->context);
02423 ast_cli(fd, " Mailbox : %s\n", peer->mailbox);
02424 ast_cli(fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes":"No");
02425 ast_cli(fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
02426 ast_cli(fd, " Expire : %d\n", peer->expire);
02427 ast_cli(fd, " ACL : %s\n", (peer->ha?"Yes":"No"));
02428 ast_cli(fd, " Addr->IP : %s Port %d\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)", ntohs(peer->addr.sin_port));
02429 ast_cli(fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
02430 ast_cli(fd, " Username : %s\n", peer->username);
02431 ast_cli(fd, " Codecs : ");
02432 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
02433 ast_cli(fd, "%s\n", codec_buf);
02434
02435 ast_cli(fd, " Codec Order : (");
02436 for(x = 0; x < 32 ; x++) {
02437 codec = ast_codec_pref_index(&peer->prefs,x);
02438 if(!codec)
02439 break;
02440 ast_cli(fd, "%s", ast_getformatname(codec));
02441 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
02442 ast_cli(fd, "|");
02443 }
02444
02445 if (!x)
02446 ast_cli(fd, "none");
02447 ast_cli(fd, ")\n");
02448
02449 ast_cli(fd, " Status : ");
02450 peer_status(peer, status, sizeof(status));
02451 ast_cli(fd, "%s\n",status);
02452 ast_cli(fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
02453 ast_cli(fd,"\n");
02454 peer_unref(peer);
02455 } else {
02456 ast_cli(fd,"Peer %s not found.\n", argv[3]);
02457 ast_cli(fd,"\n");
02458 }
02459
02460 return RESULT_SUCCESS;
02461 }
02462
02463 static char *complete_iax2_show_peer(const char *line, const char *word, int pos, int state)
02464 {
02465 int which = 0;
02466 struct iax2_peer *peer;
02467 char *res = NULL;
02468 int wordlen = strlen(word);
02469 struct ao2_iterator i;
02470
02471
02472 if (pos != 3)
02473 return NULL;
02474
02475 i = ao2_iterator_init(peers, 0);
02476 while ((peer = ao2_iterator_next(&i))) {
02477 if (!strncasecmp(peer->name, word, wordlen) && ++which > state) {
02478 res = ast_strdup(peer->name);
02479 peer_unref(peer);
02480 break;
02481 }
02482 peer_unref(peer);
02483 }
02484
02485 return res;
02486 }
02487
02488 static int iax2_show_stats(int fd, int argc, char *argv[])
02489 {
02490 struct iax_frame *cur;
02491 int cnt = 0, dead=0, final=0;
02492
02493 if (argc != 3)
02494 return RESULT_SHOWUSAGE;
02495
02496 AST_LIST_LOCK(&iaxq.queue);
02497 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
02498 if (cur->retries < 0)
02499 dead++;
02500 if (cur->final)
02501 final++;
02502 cnt++;
02503 }
02504 AST_LIST_UNLOCK(&iaxq.queue);
02505
02506 ast_cli(fd, " IAX Statistics\n");
02507 ast_cli(fd, "---------------------\n");
02508 ast_cli(fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
02509 ast_cli(fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
02510
02511 return RESULT_SUCCESS;
02512 }
02513
02514 static int iax2_show_cache(int fd, int argc, char *argv[])
02515 {
02516 struct iax2_dpcache *dp;
02517 char tmp[1024], *pc;
02518 int s;
02519 int x,y;
02520 struct timeval tv;
02521 gettimeofday(&tv, NULL);
02522 ast_mutex_lock(&dpcache_lock);
02523 dp = dpcache;
02524 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
02525 while(dp) {
02526 s = dp->expiry.tv_sec - tv.tv_sec;
02527 tmp[0] = '\0';
02528 if (dp->flags & CACHE_FLAG_EXISTS)
02529 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
02530 if (dp->flags & CACHE_FLAG_NONEXISTENT)
02531 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
02532 if (dp->flags & CACHE_FLAG_CANEXIST)
02533 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
02534 if (dp->flags & CACHE_FLAG_PENDING)
02535 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
02536 if (dp->flags & CACHE_FLAG_TIMEOUT)
02537 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
02538 if (dp->flags & CACHE_FLAG_TRANSMITTED)
02539 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
02540 if (dp->flags & CACHE_FLAG_MATCHMORE)
02541 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
02542 if (dp->flags & CACHE_FLAG_UNKNOWN)
02543 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
02544
02545 if (!ast_strlen_zero(tmp))
02546 tmp[strlen(tmp) - 1] = '\0';
02547 else
02548 ast_copy_string(tmp, "(none)", sizeof(tmp));
02549 y=0;
02550 pc = strchr(dp->peercontext, '@');
02551 if (!pc)
02552 pc = dp->peercontext;
02553 else
02554 pc++;
02555 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
02556 if (dp->waiters[x] > -1)
02557 y++;
02558 if (s > 0)
02559 ast_cli(fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
02560 else
02561 ast_cli(fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
02562 dp = dp->next;
02563 }
02564 ast_mutex_unlock(&dpcache_lock);
02565 return RESULT_SUCCESS;
02566 }
02567
02568 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
02569
02570 static void unwrap_timestamp(struct iax_frame *fr)
02571 {
02572
02573
02574 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
02575 const int lower_mask = (1 << ts_shift) - 1;
02576 const int upper_mask = ~lower_mask;
02577 const int last_upper = iaxs[fr->callno]->last & upper_mask;
02578
02579 if ( (fr->ts & upper_mask) == last_upper ) {
02580 const int x = fr->ts - iaxs[fr->callno]->last;
02581 const int threshold = (ts_shift == 15) ? 25000 : 50000;
02582
02583 if (x < -threshold) {
02584
02585
02586
02587
02588 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
02589 if (option_debug && iaxdebug)
02590 ast_log(LOG_DEBUG, "schedule_delivery: pushed forward timestamp\n");
02591 } else if (x > threshold) {
02592
02593
02594
02595
02596 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
02597 if (option_debug && iaxdebug)
02598 ast_log(LOG_DEBUG, "schedule_delivery: pushed back timestamp\n");
02599 }
02600 }
02601 }
02602
02603 static int get_from_jb(const void *p);
02604
02605 static void update_jbsched(struct chan_iax2_pvt *pvt)
02606 {
02607 int when;
02608
02609 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
02610
02611 when = jb_next(pvt->jb) - when;
02612
02613 AST_SCHED_DEL(sched, pvt->jbid);
02614
02615 if(when <= 0) {
02616
02617 when = 1;
02618 }
02619
02620 pvt->jbid = iax2_sched_add(sched, when, get_from_jb, CALLNO_TO_PTR(pvt->callno));
02621 }
02622
02623 static void __get_from_jb(const void *p)
02624 {
02625 int callno = PTR_TO_CALLNO(p);
02626 struct chan_iax2_pvt *pvt = NULL;
02627 struct iax_frame *fr;
02628 jb_frame frame;
02629 int ret;
02630 long now;
02631 long next;
02632 struct timeval tv;
02633
02634
02635 ast_mutex_lock(&iaxsl[callno]);
02636 pvt = iaxs[callno];
02637 if (!pvt) {
02638
02639 ast_mutex_unlock(&iaxsl[callno]);
02640 return;
02641 }
02642
02643 if( pvt->jb == NULL ) {
02644 ast_log( LOG_ERROR, "__get_from_jb(): why p->jb is null?\n" );
02645 ast_backtrace();
02646 return;
02647 }
02648
02649 pvt->jbid = -1;
02650
02651 gettimeofday(&tv,NULL);
02652
02653
02654
02655 tv.tv_usec += 1000;
02656
02657 now = ast_tvdiff_ms(tv, pvt->rxcore);
02658
02659 if(now >= (next = jb_next(pvt->jb))) {
02660 ret = jb_get(pvt->jb,&frame,now,ast_codec_interp_len(pvt->voiceformat));
02661 switch(ret) {
02662 case JB_OK:
02663 fr = frame.data;
02664 __do_deliver(fr);
02665
02666 pvt = iaxs[callno];
02667 break;
02668 case JB_INTERP:
02669 {
02670 struct ast_frame af = { 0, };
02671
02672
02673 af.frametype = AST_FRAME_VOICE;
02674 af.subclass = pvt->voiceformat;
02675 af.samples = frame.ms * 8;
02676 af.src = "IAX2 JB interpolation";
02677 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
02678 af.offset = AST_FRIENDLY_OFFSET;
02679
02680
02681
02682 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
02683 iax2_queue_frame(callno, &af);
02684
02685 pvt = iaxs[callno];
02686 }
02687 }
02688 break;
02689 case JB_DROP:
02690 iax2_frame_free(frame.data);
02691 break;
02692 case JB_NOFRAME:
02693 case JB_EMPTY:
02694
02695 break;
02696 default:
02697
02698 break;
02699 }
02700 }
02701 if (pvt)
02702 update_jbsched(pvt);
02703 ast_mutex_unlock(&iaxsl[callno]);
02704 }
02705
02706 static int get_from_jb(const void *data)
02707 {
02708 #ifdef SCHED_MULTITHREADED
02709 if (schedule_action(__get_from_jb, data))
02710 #endif
02711 __get_from_jb(data);
02712 return 0;
02713 }
02714
02715
02716
02717
02718
02719
02720
02721 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
02722 {
02723 int type, len;
02724 int ret;
02725 int needfree = 0;
02726 struct ast_channel *owner = NULL;
02727 struct ast_channel *bridge = NULL;
02728
02729
02730 unwrap_timestamp(fr);
02731
02732
02733 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
02734 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
02735 else {
02736 #if 0
02737 if (option_debug)
02738 ast_log(LOG_DEBUG, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
02739 #endif
02740 fr->af.delivery = ast_tv(0,0);
02741 }
02742
02743 type = JB_TYPE_CONTROL;
02744 len = 0;
02745
02746 if(fr->af.frametype == AST_FRAME_VOICE) {
02747 type = JB_TYPE_VOICE;
02748 len = ast_codec_get_samples(&fr->af) / 8;
02749 } else if(fr->af.frametype == AST_FRAME_CNG) {
02750 type = JB_TYPE_SILENCE;
02751 }
02752
02753 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
02754 if (tsout)
02755 *tsout = fr->ts;
02756 __do_deliver(fr);
02757 return -1;
02758 }
02759
02760 if ((owner = iaxs[fr->callno]->owner))
02761 bridge = ast_bridged_channel(owner);
02762
02763
02764
02765 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
02766 jb_frame frame;
02767
02768
02769 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
02770 __do_deliver(frame.data);
02771
02772 if (!iaxs[fr->callno])
02773 return -1;
02774 }
02775
02776 jb_reset(iaxs[fr->callno]->jb);
02777
02778 AST_SCHED_DEL(sched, iaxs[fr->callno]->jbid);
02779
02780
02781 if (tsout)
02782 *tsout = fr->ts;
02783 __do_deliver(fr);
02784 return -1;
02785 }
02786
02787
02788
02789 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
02790 calc_rxstamp(iaxs[fr->callno],fr->ts));
02791 if (ret == JB_DROP) {
02792 needfree++;
02793 } else if (ret == JB_SCHED) {
02794 update_jbsched(iaxs[fr->callno]);
02795 }
02796 if (tsout)
02797 *tsout = fr->ts;
02798 if (needfree) {
02799
02800 iax2_frame_free(fr);
02801 return -1;
02802 }
02803 return 0;
02804 }
02805
02806 static int iax2_transmit(struct iax_frame *fr)
02807 {
02808
02809
02810
02811 fr->sentyet = 0;
02812 AST_LIST_LOCK(&iaxq.queue);
02813 AST_LIST_INSERT_TAIL(&iaxq.queue, fr, list);
02814 iaxq.count++;
02815 AST_LIST_UNLOCK(&iaxq.queue);
02816
02817 if (netthreadid != AST_PTHREADT_NULL)
02818 pthread_kill(netthreadid, SIGURG);
02819 signal_condition(&sched_lock, &sched_cond);
02820 return 0;
02821 }
02822
02823
02824
02825 static int iax2_digit_begin(struct ast_channel *c, char digit)
02826 {
02827 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
02828 }
02829
02830 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
02831 {
02832 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
02833 }
02834
02835 static int iax2_sendtext(struct ast_channel *c, const char *text)
02836 {
02837
02838 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
02839 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
02840 }
02841
02842 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
02843 {
02844 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data, img->datalen, -1);
02845 }
02846
02847 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
02848 {
02849 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
02850 }
02851
02852 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
02853 {
02854 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
02855 ast_mutex_lock(&iaxsl[callno]);
02856 if (iaxs[callno])
02857 iaxs[callno]->owner = newchan;
02858 else
02859 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
02860 ast_mutex_unlock(&iaxsl[callno]);
02861 return 0;
02862 }
02863
02864
02865
02866
02867
02868 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
02869 {
02870 struct ast_variable *var = NULL;
02871 struct ast_variable *tmp;
02872 struct iax2_peer *peer=NULL;
02873 time_t regseconds = 0, nowtime;
02874 int dynamic=0;
02875
02876 if (peername) {
02877 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", NULL);
02878 if (!var && sin)
02879 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), NULL);
02880 } else if (sin) {
02881 char porta[25];
02882 sprintf(porta, "%d", ntohs(sin->sin_port));
02883 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
02884 if (var) {
02885
02886 for (tmp = var; tmp; tmp = tmp->next) {
02887 if (!strcasecmp(tmp->name, "name"))
02888 peername = tmp->value;
02889 }
02890 }
02891 }
02892 if (!var && peername) {
02893 var = ast_load_realtime("iaxpeers", "name", peername, NULL);
02894
02895
02896
02897
02898
02899
02900 if (var && sin) {
02901 for (tmp = var; tmp; tmp = tmp->next) {
02902 if (!strcasecmp(tmp->name, "host")) {
02903 struct ast_hostent ahp;
02904 struct hostent *hp;
02905 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
02906
02907 ast_variables_destroy(var);
02908 var = NULL;
02909 }
02910 break;
02911 }
02912 }
02913 }
02914 }
02915 if (!var)
02916 return NULL;
02917
02918 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
02919
02920 if (!peer) {
02921 ast_variables_destroy(var);
02922 return NULL;
02923 }
02924
02925 for (tmp = var; tmp; tmp = tmp->next) {
02926
02927 if (!strcasecmp(tmp->name, "type")) {
02928 if (strcasecmp(tmp->value, "friend") &&
02929 strcasecmp(tmp->value, "peer")) {
02930
02931 peer = peer_unref(peer);
02932 break;
02933 }
02934 } else if (!strcasecmp(tmp->name, "regseconds")) {
02935 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
02936 } else if (!strcasecmp(tmp->name, "ipaddr")) {
02937 inet_aton(tmp->value, &(peer->addr.sin_addr));
02938 } else if (!strcasecmp(tmp->name, "port")) {
02939 peer->addr.sin_port = htons(atoi(tmp->value));
02940 } else if (!strcasecmp(tmp->name, "host")) {
02941 if (!strcasecmp(tmp->value, "dynamic"))
02942 dynamic = 1;
02943 }
02944 }
02945
02946 ast_variables_destroy(var);
02947
02948 if (!peer)
02949 return NULL;
02950
02951 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
02952 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
02953 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
02954 if (peer->expire > -1) {
02955 if (!ast_sched_del(sched, peer->expire)) {
02956 peer->expire = -1;
02957 peer_unref(peer);
02958 }
02959 }
02960 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
02961 if (peer->expire == -1)
02962 peer_unref(peer);
02963 }
02964 ao2_link(peers, peer);
02965 if (ast_test_flag(peer, IAX_DYNAMIC))
02966 reg_source_db(peer);
02967 } else {
02968 ast_set_flag(peer, IAX_TEMPONLY);
02969 }
02970
02971 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
02972 time(&nowtime);
02973 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
02974 memset(&peer->addr, 0, sizeof(peer->addr));
02975 realtime_update_peer(peer->name, &peer->addr, 0);
02976 if (option_debug)
02977 ast_log(LOG_DEBUG, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
02978 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
02979 }
02980 else {
02981 if (option_debug)
02982 ast_log(LOG_DEBUG, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
02983 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
02984 }
02985 }
02986
02987 return peer;
02988 }
02989
02990 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
02991 {
02992 struct ast_variable *var;
02993 struct ast_variable *tmp;
02994 struct iax2_user *user=NULL;
02995
02996 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", NULL);
02997 if (!var)
02998 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), NULL);
02999 if (!var && sin) {
03000 char porta[6];
03001 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
03002 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
03003 if (!var)
03004 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, NULL);
03005 }
03006 if (!var) {
03007 var = ast_load_realtime("iaxusers", "name", username, NULL);
03008
03009
03010
03011
03012
03013
03014 if (var) {
03015 for (tmp = var; tmp; tmp = tmp->next) {
03016 if (!strcasecmp(tmp->name, "host")) {
03017 struct ast_hostent ahp;
03018 struct hostent *hp;
03019 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(&hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
03020
03021 ast_variables_destroy(var);
03022 var = NULL;
03023 }
03024 break;
03025 }
03026 }
03027 }
03028 }
03029 if (!var)
03030 return NULL;
03031
03032 tmp = var;
03033 while(tmp) {
03034
03035 if (!strcasecmp(tmp->name, "type")) {
03036 if (strcasecmp(tmp->value, "friend") &&
03037 strcasecmp(tmp->value, "user")) {
03038 return NULL;
03039 }
03040 }
03041 tmp = tmp->next;
03042 }
03043
03044 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
03045
03046 ast_variables_destroy(var);
03047
03048 if (!user)
03049 return NULL;
03050
03051 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
03052 ast_set_flag(user, IAX_RTCACHEFRIENDS);
03053 ao2_link(users, user);
03054 } else {
03055 ast_set_flag(user, IAX_TEMPONLY);
03056 }
03057
03058 return user;
03059 }
03060
03061 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
03062 {
03063 char port[10];
03064 char regseconds[20];
03065
03066 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
03067 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
03068 ast_update_realtime("iaxpeers", "name", peername,
03069 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
03070 "regseconds", regseconds, NULL);
03071 }
03072
03073 struct create_addr_info {
03074 int capability;
03075 unsigned int flags;
03076 int maxtime;
03077 int encmethods;
03078 int found;
03079 int sockfd;
03080 int adsi;
03081 char username[80];
03082 char secret[80];
03083 char outkey[80];
03084 char timezone[80];
03085 char prefs[32];
03086 char context[AST_MAX_CONTEXT];
03087 char peercontext[AST_MAX_CONTEXT];
03088 char mohinterpret[MAX_MUSICCLASS];
03089 char mohsuggest[MAX_MUSICCLASS];
03090 };
03091
03092 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
03093 {
03094 struct ast_hostent ahp;
03095 struct hostent *hp;
03096 struct iax2_peer *peer;
03097 int res = -1;
03098 struct ast_codec_pref ourprefs;
03099
03100 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
03101 cai->sockfd = defaultsockfd;
03102 cai->maxtime = 0;
03103 sin->sin_family = AF_INET;
03104
03105 if (!(peer = find_peer(peername, 1))) {
03106 cai->found = 0;
03107
03108 hp = ast_gethostbyname(peername, &ahp);
03109 if (hp) {
03110 memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
03111 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
03112
03113
03114 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
03115 if (c)
03116 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
03117 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
03118 return 0;
03119 } else {
03120 ast_log(LOG_WARNING, "No such host: %s\n", peername);
03121 return -1;
03122 }
03123 }
03124
03125 cai->found = 1;
03126
03127
03128 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
03129 goto return_unref;
03130
03131
03132 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
03133 goto return_unref;
03134
03135 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
03136 cai->maxtime = peer->maxms;
03137 cai->capability = peer->capability;
03138 cai->encmethods = peer->encmethods;
03139 cai->sockfd = peer->sockfd;
03140 cai->adsi = peer->adsi;
03141 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
03142
03143 if (c) {
03144 ast_log(LOG_DEBUG, "prepending %x to prefs\n", c->nativeformats);
03145 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
03146 }
03147 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
03148 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
03149 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
03150 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
03151 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
03152 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
03153 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
03154 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
03155 if (ast_strlen_zero(peer->dbsecret)) {
03156 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
03157 } else {
03158 char *family;
03159 char *key = NULL;
03160
03161 family = ast_strdupa(peer->dbsecret);
03162 key = strchr(family, '/');
03163 if (key)
03164 *key++ = '\0';
03165 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
03166 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
03167 goto return_unref;
03168 }
03169 }
03170
03171 if (peer->addr.sin_addr.s_addr) {
03172 sin->sin_addr = peer->addr.sin_addr;
03173 sin->sin_port = peer->addr.sin_port;
03174 } else {
03175 sin->sin_addr = peer->defaddr.sin_addr;
03176 sin->sin_port = peer->defaddr.sin_port;
03177 }
03178
03179 res = 0;
03180
03181 return_unref:
03182 peer_unref(peer);
03183
03184 return res;
03185 }
03186
03187 static void __auto_congest(const void *nothing)
03188 {
03189 int callno = PTR_TO_CALLNO(nothing);
03190 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
03191 ast_mutex_lock(&iaxsl[callno]);
03192 if (iaxs[callno]) {
03193 iaxs[callno]->initid = -1;
03194 iax2_queue_frame(callno, &f);
03195 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
03196 }
03197 ast_mutex_unlock(&iaxsl[callno]);
03198 }
03199
03200 static int auto_congest(const void *data)
03201 {
03202 #ifdef SCHED_MULTITHREADED
03203 if (schedule_action(__auto_congest, data))
03204 #endif
03205 __auto_congest(data);
03206 return 0;
03207 }
03208
03209 static unsigned int iax2_datetime(const char *tz)
03210 {
03211 time_t t;
03212 struct tm tm;
03213 unsigned int tmp;
03214 time(&t);
03215 if (!ast_strlen_zero(tz))
03216 ast_localtime(&t, &tm, tz);
03217 else
03218 ast_localtime(&t, &tm, NULL);
03219 tmp = (tm.tm_sec >> 1) & 0x1f;
03220 tmp |= (tm.tm_min & 0x3f) << 5;
03221 tmp |= (tm.tm_hour & 0x1f) << 11;
03222 tmp |= (tm.tm_mday & 0x1f) << 16;
03223 tmp |= ((tm.tm_mon + 1) & 0xf) << 21;
03224 tmp |= ((tm.tm_year - 100) & 0x7f) << 25;
03225 return tmp;
03226 }
03227
03228 struct parsed_dial_string {
03229 char *username;
03230 char *password;
03231 char *key;
03232 char *peer;
03233 char *port;
03234 char *exten;
03235 char *context;
03236 char *options;
03237 };
03238
03239 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int command, int ts, unsigned char seqno)
03240 {
03241 struct ast_iax2_full_hdr f = { .scallno = htons(0x8000 | callno), .dcallno = htons(dcallno),
03242 .ts = htonl(ts), .iseqno = seqno, .oseqno = 0, .type = AST_FRAME_IAX,
03243 .csub = compress_subclass(command) };
03244
03245 return sendto(defaultsockfd, &f, sizeof(f), 0, (struct sockaddr *)sin, sizeof(*sin));
03246 }
03247
03248
03249
03250
03251
03252
03253
03254
03255
03256
03257
03258
03259
03260
03261
03262
03263
03264
03265
03266 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
03267 {
03268 if (ast_strlen_zero(data))
03269 return;
03270
03271 pds->peer = strsep(&data, "/");
03272 pds->exten = strsep(&data, "/");
03273 pds->options = data;
03274
03275 if (pds->exten) {
03276 data = pds->exten;
03277 pds->exten = strsep(&data, "@");
03278 pds->context = data;
03279 }
03280
03281 if (strchr(pds->peer, '@')) {
03282 data = pds->peer;
03283 pds->username = strsep(&data, "@");
03284 pds->peer = data;
03285 }
03286
03287 if (pds->username) {
03288 data = pds->username;
03289 pds->username = strsep(&data, ":");
03290 pds->password = data;
03291 }
03292
03293 data = pds->peer;
03294 pds->peer = strsep(&data, ":");
03295 pds->port = data;
03296
03297
03298
03299
03300 if (pds->password && (pds->password[0] == '[')) {
03301 pds->key = ast_strip_quoted(pds->password, "[", "]");
03302 pds->password = NULL;
03303 }
03304 }
03305
03306 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
03307 {
03308 struct sockaddr_in sin;
03309 char *l=NULL, *n=NULL, *tmpstr;
03310 struct iax_ie_data ied;
03311 char *defaultrdest = "s";
03312 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03313 struct parsed_dial_string pds;
03314 struct create_addr_info cai;
03315
03316 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
03317 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
03318 return -1;
03319 }
03320
03321 memset(&cai, 0, sizeof(cai));
03322 cai.encmethods = iax2_encryption;
03323
03324 memset(&pds, 0, sizeof(pds));
03325 tmpstr = ast_strdupa(dest);
03326 parse_dial_string(tmpstr, &pds);
03327
03328 if (ast_strlen_zero(pds.peer)) {
03329 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
03330 return -1;
03331 }
03332
03333 if (!pds.exten) {
03334 pds.exten = defaultrdest;
03335 }
03336
03337 if (create_addr(pds.peer, c, &sin, &cai)) {
03338 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
03339 return -1;
03340 }
03341
03342 if (!pds.username && !ast_strlen_zero(cai.username))
03343 pds.username = cai.username;
03344 if (!pds.password && !ast_strlen_zero(cai.secret))
03345 pds.password = cai.secret;
03346 if (!pds.key && !ast_strlen_zero(cai.outkey))
03347 pds.key = cai.outkey;
03348 if (!pds.context && !ast_strlen_zero(cai.peercontext))
03349 pds.context = cai.peercontext;
03350
03351
03352 ast_copy_string(c->context, cai.context, sizeof(c->context));
03353
03354 if (pds.port)
03355 sin.sin_port = htons(atoi(pds.port));
03356
03357 l = c->cid.cid_num;
03358 n = c->cid.cid_name;
03359
03360
03361 memset(&ied, 0, sizeof(ied));
03362
03363
03364 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
03365 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
03366 if (pds.options && strchr(pds.options, 'a')) {
03367
03368 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
03369 }
03370
03371 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
03372
03373 if (l) {
03374 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
03375 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
03376 } else {
03377 if (n)
03378 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
03379 else
03380 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
03381 }
03382
03383 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
03384 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
03385
03386 if (n)
03387 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
03388 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
03389 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
03390
03391 if (!ast_strlen_zero(c->language))
03392 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
03393 if (!ast_strlen_zero(c->cid.cid_dnid))
03394 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
03395 if (!ast_strlen_zero(c->cid.cid_rdnis))
03396 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
03397
03398 if (pds.context)
03399 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
03400
03401 if (pds.username)
03402 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
03403
03404 if (cai.encmethods)
03405 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
03406
03407 ast_mutex_lock(&iaxsl[callno]);
03408
03409 if (!ast_strlen_zero(c->context))
03410 ast_string_field_set(iaxs[callno], context, c->context);
03411
03412 if (pds.username)
03413 ast_string_field_set(iaxs[callno], username, pds.username);
03414
03415 iaxs[callno]->encmethods = cai.encmethods;
03416
03417 iaxs[callno]->adsi = cai.adsi;
03418
03419 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
03420 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
03421
03422 if (pds.key)
03423 ast_string_field_set(iaxs[callno], outkey, pds.key);
03424 if (pds.password)
03425 ast_string_field_set(iaxs[callno], secret, pds.password);
03426
03427 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
03428 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
03429 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
03430 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
03431
03432 if (iaxs[callno]->maxtime) {
03433
03434 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
03435 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
03436 } else if (autokill) {
03437 iaxs[callno]->pingtime = autokill / 2;
03438 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
03439 }
03440
03441
03442 iaxs[callno]->sockfd = cai.sockfd;
03443
03444
03445 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
03446
03447 ast_mutex_unlock(&iaxsl[callno]);
03448 ast_setstate(c, AST_STATE_RINGING);
03449
03450 return 0;
03451 }
03452
03453 static int iax2_hangup(struct ast_channel *c)
03454 {
03455 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03456 struct iax_ie_data ied;
03457 int alreadygone;
03458 memset(&ied, 0, sizeof(ied));
03459 ast_mutex_lock(&iaxsl[callno]);
03460 if (callno && iaxs[callno]) {
03461 if (option_debug)
03462 ast_log(LOG_DEBUG, "We're hanging up %s with cause %i now...\n", c->name, c->hangupcause);
03463 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
03464
03465 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
03466 if (!iaxs[callno]->error && !alreadygone) {
03467 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
03468 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
03469 }
03470 if (!iaxs[callno]) {
03471 ast_mutex_unlock(&iaxsl[callno]);
03472 return 0;
03473 }
03474 }
03475
03476 iax2_predestroy(callno);
03477
03478 if (iaxs[callno] && alreadygone) {
03479 if (option_debug)
03480 ast_log(LOG_DEBUG, "Really destroying %s now...\n", c->name);
03481 iax2_destroy(callno);
03482 } else if (iaxs[callno]) {
03483 ast_sched_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno));
03484 }
03485 } else if (c->tech_pvt) {
03486
03487
03488
03489
03490 c->tech_pvt = NULL;
03491 }
03492 ast_mutex_unlock(&iaxsl[callno]);
03493 if (option_verbose > 2)
03494 ast_verbose(VERBOSE_PREFIX_3 "Hungup '%s'\n", c->name);
03495 return 0;
03496 }
03497
03498
03499
03500
03501 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
03502 {
03503 unsigned short callno = pvt->callno;
03504
03505 if (!pvt->peercallno) {
03506
03507 int count = 10;
03508 while (count-- && pvt && !pvt->peercallno) {
03509 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03510 pvt = iaxs[callno];
03511 }
03512 if (!pvt->peercallno) {
03513 return -1;
03514 }
03515 }
03516
03517 return 0;
03518 }
03519
03520 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
03521 {
03522 struct ast_option_header *h;
03523 int res;
03524
03525 switch (option) {
03526 case AST_OPTION_TXGAIN:
03527 case AST_OPTION_RXGAIN:
03528
03529 errno = ENOSYS;
03530 return -1;
03531 default:
03532 {
03533 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03534 struct chan_iax2_pvt *pvt;
03535
03536 ast_mutex_lock(&iaxsl[callno]);
03537 pvt = iaxs[callno];
03538
03539 if (wait_for_peercallno(pvt)) {
03540 ast_mutex_unlock(&iaxsl[callno]);
03541 return -1;
03542 }
03543
03544 ast_mutex_unlock(&iaxsl[callno]);
03545
03546 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
03547 return -1;
03548 }
03549
03550 h->flag = AST_OPTION_FLAG_REQUEST;
03551 h->option = htons(option);
03552 memcpy(h->data, data, datalen);
03553 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
03554 AST_CONTROL_OPTION, 0, (unsigned char *) h,
03555 datalen + sizeof(*h), -1);
03556 free(h);
03557 return res;
03558 }
03559 }
03560 }
03561
03562 static struct ast_frame *iax2_read(struct ast_channel *c)
03563 {
03564 ast_log(LOG_NOTICE, "I should never be called!\n");
03565 return &ast_null_frame;
03566 }
03567
03568 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
03569 {
03570 int res;
03571 struct iax_ie_data ied0;
03572 struct iax_ie_data ied1;
03573 unsigned int transferid = (unsigned int)ast_random();
03574 memset(&ied0, 0, sizeof(ied0));
03575 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
03576 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
03577 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
03578
03579 memset(&ied1, 0, sizeof(ied1));
03580 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
03581 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
03582 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
03583
03584 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
03585 if (res)
03586 return -1;
03587 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
03588 if (res)
03589 return -1;
03590 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
03591 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
03592 return 0;
03593 }
03594
03595 static void lock_both(unsigned short callno0, unsigned short callno1)
03596 {
03597 ast_mutex_lock(&iaxsl[callno0]);
03598 while (ast_mutex_trylock(&iaxsl[callno1])) {
03599 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
03600 }
03601 }
03602
03603 static void unlock_both(unsigned short callno0, unsigned short callno1)
03604 {
03605 ast_mutex_unlock(&iaxsl[callno1]);
03606 ast_mutex_unlock(&iaxsl[callno0]);
03607 }
03608
03609 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)
03610 {
03611 struct ast_channel *cs[3];
03612 struct ast_channel *who, *other;
03613 int to = -1;
03614 int res = -1;
03615 int transferstarted=0;
03616 struct ast_frame *f;
03617 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
03618 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
03619 struct timeval waittimer = {0, 0}, tv;
03620
03621 lock_both(callno0, callno1);
03622 if (!iaxs[callno0] || !iaxs[callno1]) {
03623 unlock_both(callno0, callno1);
03624 return AST_BRIDGE_FAILED;
03625 }
03626
03627 if (!flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) {
03628 iaxs[callno0]->bridgecallno = callno1;
03629 iaxs[callno1]->bridgecallno = callno0;
03630 }
03631
03632 if (iaxs[callno0]->transferring && iaxs[callno1]->transferring) {
03633 transferstarted = 1;
03634 }
03635 unlock_both(callno0, callno1);
03636
03637
03638 cs[0] = c0;
03639 cs[1] = c1;
03640 for (;;) {
03641
03642 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
03643 if (option_verbose > 2)
03644 ast_verbose(VERBOSE_PREFIX_3 "Can't masquerade, we're different...\n");
03645
03646 if (c0->tech == &iax2_tech) {
03647 ast_mutex_lock(&iaxsl[callno0]);
03648 iaxs[callno0]->bridgecallno = 0;
03649 ast_mutex_unlock(&iaxsl[callno0]);
03650 }
03651 if (c1->tech == &iax2_tech) {
03652 ast_mutex_lock(&iaxsl[callno1]);
03653 iaxs[callno1]->bridgecallno = 0;
03654 ast_mutex_unlock(&iaxsl[callno1]);
03655 }
03656 return AST_BRIDGE_FAILED_NOWARN;
03657 }
03658 if (c0->nativeformats != c1->nativeformats) {
03659 if (option_verbose > 2) {
03660 char buf0[255];
03661 char buf1[255];
03662 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
03663 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
03664 ast_verbose(VERBOSE_PREFIX_3 "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
03665 }
03666
03667 lock_both(callno0, callno1);
03668 if (iaxs[callno0])
03669 iaxs[callno0]->bridgecallno = 0;
03670 if (iaxs[callno1])
03671 iaxs[callno1]->bridgecallno = 0;
03672 unlock_both(callno0, callno1);
03673 return AST_BRIDGE_FAILED_NOWARN;
03674 }
03675
03676 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
03677
03678 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
03679 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
03680 ast_log(LOG_WARNING, "Unable to start the transfer\n");
03681 transferstarted = 1;
03682 }
03683 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
03684
03685 gettimeofday(&tv, NULL);
03686 if (ast_tvzero(waittimer)) {
03687 waittimer = tv;
03688 } else if (tv.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
03689 c0->_softhangup |= AST_SOFTHANGUP_DEV;
03690 c1->_softhangup |= AST_SOFTHANGUP_DEV;
03691 *fo = NULL;
03692 *rc = c0;
03693 res = AST_BRIDGE_COMPLETE;
03694 break;
03695 }
03696 }
03697 to = 1000;
03698 who = ast_waitfor_n(cs, 2, &to);
03699 if (timeoutms > -1) {
03700 timeoutms -= (1000 - to);
03701 if (timeoutms < 0)
03702 timeoutms = 0;
03703 }
03704 if (!who) {
03705 if (!timeoutms) {
03706 res = AST_BRIDGE_RETRY;
03707 break;
03708 }
03709 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
03710 res = AST_BRIDGE_FAILED;
03711 break;
03712 }
03713 continue;
03714 }
03715 f = ast_read(who);
03716 if (!f) {
03717 *fo = NULL;
03718 *rc = who;
03719 res = AST_BRIDGE_COMPLETE;
03720 break;
03721 }
03722 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
03723 *fo = f;
03724 *rc = who;
03725 res = AST_BRIDGE_COMPLETE;
03726 break;
03727 }
03728 other = (who == c0) ? c1 : c0;
03729 if ((f->frametype == AST_FRAME_VOICE) ||
03730 (f->frametype == AST_FRAME_TEXT) ||
03731 (f->frametype == AST_FRAME_VIDEO) ||
03732 (f->frametype == AST_FRAME_IMAGE) ||
03733 (f->frametype == AST_FRAME_DTMF)) {
03734
03735
03736
03737 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
03738 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
03739 *rc = who;
03740 *fo = f;
03741 res = AST_BRIDGE_COMPLETE;
03742
03743 break;
03744 }
03745
03746 ast_write(other, f);
03747 }
03748 ast_frfree(f);
03749
03750 cs[2] = cs[0];
03751 cs[0] = cs[1];
03752 cs[1] = cs[2];
03753 }
03754 lock_both(callno0, callno1);
03755 if(iaxs[callno0])
03756 iaxs[callno0]->bridgecallno = 0;
03757 if(iaxs[callno1])
03758 iaxs[callno1]->bridgecallno = 0;
03759 unlock_both(callno0, callno1);
03760 return res;
03761 }
03762
03763 static int iax2_answer(struct ast_channel *c)
03764 {
03765 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03766 if (option_debug)
03767 ast_log(LOG_DEBUG, "Answering IAX2 call\n");
03768 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
03769 }
03770
03771 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
03772 {
03773 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03774 struct chan_iax2_pvt *pvt;
03775 int res = 0;
03776
03777 if (option_debug && iaxdebug)
03778 ast_log(LOG_DEBUG, "Indicating condition %d\n", condition);
03779
03780 ast_mutex_lock(&iaxsl[callno]);
03781 pvt = iaxs[callno];
03782
03783 if (wait_for_peercallno(pvt)) {
03784 res = -1;
03785 goto done;
03786 }
03787
03788 switch (condition) {
03789 case AST_CONTROL_HOLD:
03790 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
03791 ast_moh_start(c, data, pvt->mohinterpret);
03792 goto done;
03793 }
03794 break;
03795 case AST_CONTROL_UNHOLD:
03796 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
03797 ast_moh_stop(c);
03798 goto done;
03799 }
03800 }
03801
03802 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
03803
03804 done:
03805 ast_mutex_unlock(&iaxsl[callno]);
03806
03807 return res;
03808 }
03809
03810 static int iax2_transfer(struct ast_channel *c, const char *dest)
03811 {
03812 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
03813 struct iax_ie_data ied;
03814 char tmp[256], *context;
03815 ast_copy_string(tmp, dest, sizeof(tmp));
03816 context = strchr(tmp, '@');
03817 if (context) {
03818 *context = '\0';
03819 context++;
03820 }
03821 memset(&ied, 0, sizeof(ied));
03822 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
03823 if (context)
03824 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
03825 if (option_debug)
03826 ast_log(LOG_DEBUG, "Transferring '%s' to '%s'\n", c->name, dest);
03827 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
03828 }
03829
03830 static int iax2_getpeertrunk(struct sockaddr_in sin)
03831 {
03832 struct iax2_peer *peer;
03833 int res = 0;
03834 struct ao2_iterator i;
03835
03836 i = ao2_iterator_init(peers, 0);
03837 while ((peer = ao2_iterator_next(&i))) {
03838 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
03839 (peer->addr.sin_port == sin.sin_port)) {
03840 res = ast_test_flag(peer, IAX_TRUNK);
03841 peer_unref(peer);
03842 break;
03843 }
03844 peer_unref(peer);
03845 }
03846
03847 return res;
03848 }
03849
03850
03851 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
03852 {
03853 struct ast_channel *tmp;
03854 struct chan_iax2_pvt *i;
03855 struct ast_variable *v = NULL;
03856
03857 if (!(i = iaxs[callno])) {
03858 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
03859 return NULL;
03860 }
03861
03862
03863 ast_mutex_unlock(&iaxsl[callno]);
03864 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);
03865 ast_mutex_lock(&iaxsl[callno]);
03866 if (i != iaxs[callno]) {
03867 if (tmp) {
03868
03869 ast_mutex_unlock(&iaxsl[callno]);
03870 ast_channel_free(tmp);
03871 ast_mutex_lock(&iaxsl[callno]);
03872 }
03873 return NULL;
03874 }
03875
03876 if (!tmp)
03877 return NULL;
03878 tmp->tech = &iax2_tech;
03879
03880 tmp->nativeformats = capability;
03881 tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
03882 tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
03883 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
03884
03885
03886
03887 if (!ast_strlen_zero(i->ani))
03888 tmp->cid.cid_ani = ast_strdup(i->ani);
03889 else
03890 tmp->cid.cid_ani = ast_strdup(i->cid_num);
03891 tmp->cid.cid_dnid = ast_strdup(i->dnid);
03892 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
03893 tmp->cid.cid_pres = i->calling_pres;
03894 tmp->cid.cid_ton = i->calling_ton;
03895 tmp->cid.cid_tns = i->calling_tns;
03896 if (!ast_strlen_zero(i->language))
03897 ast_string_field_set(tmp, language, i->language);
03898 if (!ast_strlen_zero(i->accountcode))
03899 ast_string_field_set(tmp, accountcode, i->accountcode);
03900 if (i->amaflags)
03901 tmp->amaflags = i->amaflags;
03902 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
03903 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
03904 if (i->adsi)
03905 tmp->adsicpe = i->peeradsicpe;
03906 else
03907 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
03908 i->owner = tmp;
03909 i->capability = capability;
03910
03911 for (v = i->vars ; v ; v = v->next)
03912 pbx_builtin_setvar_helper(tmp, v->name, v->value);
03913
03914 if (state != AST_STATE_DOWN) {
03915 if (ast_pbx_start(tmp)) {
03916 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
03917 ast_hangup(tmp);
03918 i->owner = NULL;
03919 return NULL;
03920 }
03921 }
03922
03923 ast_module_ref(ast_module_info->self);
03924
03925 return tmp;
03926 }
03927
03928 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *tv)
03929 {
03930 unsigned long int mssincetx;
03931 long int ms, pred;
03932
03933 tpeer->trunkact = *tv;
03934 mssincetx = ast_tvdiff_ms(*tv, tpeer->lasttxtime);
03935 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
03936
03937 tpeer->txtrunktime = *tv;
03938 tpeer->lastsent = 999999;
03939 }
03940
03941 tpeer->lasttxtime = *tv;
03942
03943
03944 ms = ast_tvdiff_ms(*tv, tpeer->txtrunktime);
03945
03946 pred = tpeer->lastsent + sampms;
03947 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
03948 ms = pred;
03949
03950
03951 if (ms == tpeer->lastsent)
03952 ms = tpeer->lastsent + 1;
03953 tpeer->lastsent = ms;
03954 return ms;
03955 }
03956
03957 static unsigned int fix_peerts(struct timeval *tv, int callno, unsigned int ts)
03958 {
03959 long ms;
03960 if (ast_tvzero(iaxs[callno]->rxcore)) {
03961
03962 gettimeofday(&iaxs[callno]->rxcore, NULL);
03963
03964 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
03965 }
03966
03967 ms = ast_tvdiff_ms(*tv, iaxs[callno]->rxcore);
03968
03969 return ms + ts;
03970 }
03971
03972 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
03973 {
03974 int ms;
03975 int voice = 0;
03976 int genuine = 0;
03977 int adjust;
03978 struct timeval *delivery = NULL;
03979
03980
03981
03982
03983
03984
03985
03986
03987 if (f) {
03988 if (f->frametype == AST_FRAME_VOICE) {
03989 voice = 1;
03990 delivery = &f->delivery;
03991 } else if (f->frametype == AST_FRAME_IAX) {
03992 genuine = 1;
03993 } else if (f->frametype == AST_FRAME_CNG) {
03994 p->notsilenttx = 0;
03995 }
03996 }
03997 if (ast_tvzero(p->offset)) {
03998 gettimeofday(&p->offset, NULL);
03999
04000 p->offset.tv_usec -= p->offset.tv_usec % 20000;
04001 }
04002
04003 if (ts)
04004 return ts;
04005
04006 if (delivery && !ast_tvzero(*delivery)) {
04007 ms = ast_tvdiff_ms(*delivery, p->offset);
04008 if (option_debug > 2 && iaxdebug)
04009 ast_log(LOG_DEBUG, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
04010 } else {
04011 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
04012 if (ms < 0)
04013 ms = 0;
04014 if (voice) {
04015
04016 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
04017
04018
04019
04020
04021
04022
04023
04024
04025
04026
04027
04028
04029
04030
04031
04032
04033
04034
04035 adjust = (ms - p->nextpred);
04036 if (adjust < 0)
04037 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
04038 else if (adjust > 0)
04039 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
04040
04041 if (!p->nextpred) {
04042 p->nextpred = ms;
04043 if (p->nextpred <= p->lastsent)
04044 p->nextpred = p->lastsent + 3;
04045 }
04046 ms = p->nextpred;
04047 } else {
04048
04049
04050
04051
04052
04053
04054
04055
04056
04057 if (option_debug && iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
04058 ast_log(LOG_DEBUG, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
04059 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
04060
04061 if (f->samples >= 8)
04062 {
04063 int diff = ms % (f->samples / 8);
04064 if (diff)
04065 ms += f->samples/8 - diff;
04066 }
04067
04068 p->nextpred = ms;
04069 p->notsilenttx = 1;
04070 }
04071 } else if ( f->frametype == AST_FRAME_VIDEO ) {
04072
04073
04074
04075
04076
04077
04078
04079
04080 if ( (unsigned int)ms < p->lastsent )
04081 ms = p->lastsent;
04082 } else {
04083
04084
04085 if (genuine) {
04086
04087 if (ms <= p->lastsent)
04088 ms = p->lastsent + 3;
04089 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
04090
04091 ms = p->lastsent + 3;
04092 }
04093 }
04094 }
04095 p->lastsent = ms;
04096 if (voice)
04097 p->nextpred = p->nextpred + f->samples / 8;
04098 return ms;
04099 }
04100
04101 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
04102 {
04103
04104
04105 int ms;
04106 #ifdef IAXTESTS
04107 int jit;
04108 #endif
04109
04110 if (ast_tvzero(p->rxcore)) {
04111 p->rxcore = ast_tvnow();
04112 if (option_debug && iaxdebug)
04113 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
04114 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
04115 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
04116 #if 1
04117 if (option_debug && iaxdebug)
04118 ast_log(LOG_DEBUG, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
04119 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
04120 #endif
04121 }
04122
04123 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
04124 #ifdef IAXTESTS
04125 if (test_jit) {
04126 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
04127 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
04128 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
04129 jit = -jit;
04130 ms += jit;
04131 }
04132 }
04133 if (test_late) {
04134 ms += test_late;
04135 test_late = 0;
04136 }
04137 #endif
04138 return ms;
04139 }
04140
04141 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
04142 {
04143 struct iax2_trunk_peer *tpeer;
04144
04145
04146 ast_mutex_lock(&tpeerlock);
04147 for (tpeer = tpeers; tpeer; tpeer = tpeer->next) {
04148
04149 if (!inaddrcmp(&tpeer->addr, sin)) {
04150 ast_mutex_lock(&tpeer->lock);
04151 break;
04152 }
04153 }
04154 if (!tpeer) {
04155 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
04156 ast_mutex_init(&tpeer->lock);
04157 tpeer->lastsent = 9999;
04158 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
04159 tpeer->trunkact = ast_tvnow();
04160 ast_mutex_lock(&tpeer->lock);
04161 tpeer->next = tpeers;
04162 tpeer->sockfd = fd;
04163 tpeers = tpeer;
04164 #ifdef SO_NO_CHECK
04165 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
04166 #endif
04167 if (option_debug)
04168 ast_log(LOG_DEBUG, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
04169 }
04170 }
04171 ast_mutex_unlock(&tpeerlock);
04172 return tpeer;
04173 }
04174
04175 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
04176 {
04177 struct ast_frame *f;
04178 struct iax2_trunk_peer *tpeer;
04179 void *tmp, *ptr;
04180 struct ast_iax2_meta_trunk_entry *met;
04181 struct ast_iax2_meta_trunk_mini *mtm;
04182
04183 f = &fr->af;
04184 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
04185 if (tpeer) {
04186 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
04187
04188 if (tpeer->trunkdataalloc < MAX_TRUNKDATA) {
04189 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
04190 ast_mutex_unlock(&tpeer->lock);
04191 return -1;
04192 }
04193
04194 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
04195 tpeer->trunkdata = tmp;
04196 if (option_debug)
04197 ast_log(LOG_DEBUG, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
04198 } else {
04199 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));
04200 ast_mutex_unlock(&tpeer->lock);
04201 return -1;
04202 }
04203 }
04204
04205
04206 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
04207 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
04208 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
04209 mtm->len = htons(f->datalen);
04210 mtm->mini.callno = htons(pvt->callno);
04211 mtm->mini.ts = htons(0xffff & fr->ts);
04212 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
04213 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
04214 } else {
04215 met = (struct ast_iax2_meta_trunk_entry *)ptr;
04216
04217 met->callno = htons(pvt->callno);
04218 met->len = htons(f->datalen);
04219
04220 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
04221 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
04222 }
04223
04224 memcpy(ptr, f->data, f->datalen);
04225 tpeer->trunkdatalen += f->datalen;
04226
04227 tpeer->calls++;
04228 ast_mutex_unlock(&tpeer->lock);
04229 }
04230 return 0;
04231 }
04232
04233 static void build_enc_keys(const unsigned char *digest, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
04234 {
04235 aes_encrypt_key128(digest, ecx);
04236 aes_decrypt_key128(digest, dcx);
04237 }
04238
04239 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, aes_decrypt_ctx *dcx)
04240 {
04241 #if 0
04242
04243 int x;
04244 if (len % 16)
04245 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
04246 for (x=0;x<len;x++)
04247 dst[x] = src[x] ^ 0xff;
04248 #else
04249 unsigned char lastblock[16] = { 0 };
04250 int x;
04251 while(len > 0) {
04252 aes_decrypt(src, dst, dcx);
04253 for (x=0;x<16;x++)
04254 dst[x] ^= lastblock[x];
04255 memcpy(lastblock, src, sizeof(lastblock));
04256 dst += 16;
04257 src += 16;
04258 len -= 16;
04259 }
04260 #endif
04261 }
04262
04263 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, aes_encrypt_ctx *ecx)
04264 {
04265 #if 0
04266
04267 int x;
04268 if (len % 16)
04269 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
04270 for (x=0;x<len;x++)
04271 dst[x] = src[x] ^ 0xff;
04272 #else
04273 unsigned char curblock[16] = { 0 };
04274 int x;
04275 while(len > 0) {
04276 for (x=0;x<16;x++)
04277 curblock[x] ^= src[x];
04278 aes_encrypt(curblock, dst, ecx);
04279 memcpy(curblock, dst, sizeof(curblock));
04280 dst += 16;
04281 src += 16;
04282 len -= 16;
04283 }
04284 #endif
04285 }
04286
04287 static int decode_frame(aes_decrypt_ctx *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
04288 {
04289 int padding;
04290 unsigned char *workspace;
04291
04292 workspace = alloca(*datalen);
04293 memset(f, 0, sizeof(*f));
04294 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
04295 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
04296 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
04297 return -1;
04298
04299 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
04300
04301 padding = 16 + (workspace[15] & 0xf);
04302 if (option_debug && iaxdebug)
04303 ast_log(LOG_DEBUG, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
04304 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
04305 return -1;
04306
04307 *datalen -= padding;
04308 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
04309 f->frametype = fh->type;
04310 if (f->frametype == AST_FRAME_VIDEO) {
04311 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
04312 } else {
04313 f->subclass = uncompress_subclass(fh->csub);
04314 }
04315 } else {
04316 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
04317 if (option_debug && iaxdebug)
04318 ast_log(LOG_DEBUG, "Decoding mini with length %d\n", *datalen);
04319 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
04320 return -1;
04321
04322 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
04323 padding = 16 + (workspace[15] & 0x0f);
04324 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
04325 return -1;
04326 *datalen -= padding;
04327 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
04328 }
04329 return 0;
04330 }
04331
04332 static int encrypt_frame(aes_encrypt_ctx *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
04333 {
04334 int padding;
04335 unsigned char *workspace;
04336 workspace = alloca(*datalen + 32);
04337 if (!workspace)
04338 return -1;
04339 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
04340 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
04341 if (option_debug && iaxdebug)
04342 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
04343 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
04344 padding = 16 + (padding & 0xf);
04345 memcpy(workspace, poo, padding);
04346 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
04347 workspace[15] &= 0xf0;
04348 workspace[15] |= (padding & 0xf);
04349 if (option_debug && iaxdebug)
04350 ast_log(LOG_DEBUG, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
04351 *datalen += padding;
04352 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
04353 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
04354 memcpy(poo, workspace + *datalen - 32, 32);
04355 } else {
04356 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
04357 if (option_debug && iaxdebug)
04358 ast_log(LOG_DEBUG, "Encoding mini frame with length %d\n", *datalen);
04359 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
04360 padding = 16 + (padding & 0xf);
04361 memcpy(workspace, poo, padding);
04362 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
04363 workspace[15] &= 0xf0;
04364 workspace[15] |= (padding & 0x0f);
04365 *datalen += padding;
04366 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
04367 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
04368 memcpy(poo, workspace + *datalen - 32, 32);
04369 }
04370 return 0;
04371 }
04372
04373 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
04374 {
04375 int res=-1;
04376 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
04377
04378 struct MD5Context md5;
04379 unsigned char digest[16];
04380 char *tmppw, *stringp;
04381
04382 tmppw = ast_strdupa(iaxs[callno]->secret);
04383 stringp = tmppw;
04384 while ((tmppw = strsep(&stringp, ";"))) {
04385 MD5Init(&md5);
04386 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
04387 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
04388 MD5Final(digest, &md5);
04389 build_enc_keys(digest, &iaxs[callno]->ecx, &iaxs[callno]->dcx);
04390 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
04391 if (!res) {
04392 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
04393 break;
04394 }
04395 }
04396 } else
04397 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
04398 return res;
04399 }
04400
04401 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
04402 {
04403
04404
04405
04406 struct ast_iax2_full_hdr *fh;
04407 struct ast_iax2_mini_hdr *mh;
04408 struct ast_iax2_video_hdr *vh;
04409 struct {
04410 struct iax_frame fr2;
04411 unsigned char buffer[4096];
04412 } frb;
04413 struct iax_frame *fr;
04414 int res;
04415 int sendmini=0;
04416 unsigned int lastsent;
04417 unsigned int fts;
04418
04419 frb.fr2.afdatalen = sizeof(frb.buffer);
04420
04421 if (!pvt) {
04422 ast_log(LOG_WARNING, "No private structure for packet?\n");
04423 return -1;
04424 }
04425
04426 lastsent = pvt->lastsent;
04427
04428
04429 fts = calc_timestamp(pvt, ts, f);
04430
04431
04432
04433
04434 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
04435 return 0;
04436
04437
04438 if ((ast_test_flag(pvt, IAX_TRUNK) ||
04439 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
04440 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
04441 &&
04442 (f->frametype == AST_FRAME_VOICE)
04443 &&
04444 (f->subclass == pvt->svoiceformat)
04445 ) {
04446
04447 now = 1;
04448
04449 sendmini = 1;
04450 }
04451 if ( f->frametype == AST_FRAME_VIDEO ) {
04452
04453
04454
04455
04456
04457 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
04458 ((f->subclass & ~0x1) == pvt->svideoformat)
04459 ) {
04460 now = 1;
04461 sendmini = 1;
04462 } else {
04463 now = 0;
04464 sendmini = 0;
04465 }
04466 pvt->lastvsent = fts;
04467 }
04468
04469 if (now) {
04470 fr = &frb.fr2;
04471 } else
04472 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));
04473 if (!fr) {
04474 ast_log(LOG_WARNING, "Out of memory\n");
04475 return -1;
04476 }
04477
04478 iax_frame_wrap(fr, f);
04479
04480 fr->ts = fts;
04481 fr->callno = pvt->callno;
04482 fr->transfer = transfer;
04483 fr->final = final;
04484 if (!sendmini) {
04485
04486 if (seqno > -1)
04487 fr->oseqno = seqno;
04488 else
04489 fr->oseqno = pvt->oseqno++;
04490 fr->iseqno = pvt->iseqno;
04491 fh = (struct ast_iax2_full_hdr *)(fr->af.data - sizeof(struct ast_iax2_full_hdr));
04492 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
04493 fh->ts = htonl(fr->ts);
04494 fh->oseqno = fr->oseqno;
04495 if (transfer) {
04496 fh->iseqno = 0;
04497 } else
04498 fh->iseqno = fr->iseqno;
04499
04500 if (!transfer)
04501 pvt->aseqno = fr->iseqno;
04502 fh->type = fr->af.frametype & 0xFF;
04503 if (fr->af.frametype == AST_FRAME_VIDEO)
04504 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
04505 else
04506 fh->csub = compress_subclass(fr->af.subclass);
04507 if (transfer) {
04508 fr->dcallno = pvt->transfercallno;
04509 } else
04510 fr->dcallno = pvt->peercallno;
04511 fh->dcallno = htons(fr->dcallno);
04512 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
04513 fr->data = fh;
04514 fr->retries = 0;
04515
04516 fr->retrytime = pvt->pingtime * 2;
04517 if (fr->retrytime < MIN_RETRY_TIME)
04518 fr->retrytime = MIN_RETRY_TIME;
04519 if (fr->retrytime > MAX_RETRY_TIME)
04520 fr->retrytime = MAX_RETRY_TIME;
04521
04522 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
04523 fr->retries = -1;
04524 else if (f->frametype == AST_FRAME_VOICE)
04525 pvt->svoiceformat = f->subclass;
04526 else if (f->frametype == AST_FRAME_VIDEO)
04527 pvt->svideoformat = f->subclass & ~0x1;
04528 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
04529 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
04530 if (iaxdebug) {
04531 if (fr->transfer)
04532 iax_showframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
04533 else
04534 iax_showframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
04535 }
04536 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
04537 } else
04538 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
04539 }
04540
04541 if (now) {
04542 res = send_packet(fr);
04543 } else
04544 res = iax2_transmit(fr);
04545 } else {
04546 if (ast_test_flag(pvt, IAX_TRUNK)) {
04547 iax2_trunk_queue(pvt, fr);
04548 res = 0;
04549 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
04550
04551 fr->oseqno = -1;
04552 fr->iseqno = -1;
04553 vh = (struct ast_iax2_video_hdr *)(fr->af.data - sizeof(struct ast_iax2_video_hdr));
04554 vh->zeros = 0;
04555 vh->callno = htons(0x8000 | fr->callno);
04556 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
04557 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
04558 fr->data = vh;
04559 fr->retries = -1;
04560 res = send_packet(fr);
04561 } else {
04562
04563 fr->oseqno = -1;
04564 fr->iseqno = -1;
04565
04566 mh = (struct ast_iax2_mini_hdr *)(fr->af.data - sizeof(struct ast_iax2_mini_hdr));
04567 mh->callno = htons(fr->callno);
04568 mh->ts = htons(fr->ts & 0xFFFF);
04569 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
04570 fr->data = mh;
04571 fr->retries = -1;
04572 if (pvt->transferring == TRANSFER_MEDIAPASS)
04573 fr->transfer = 1;
04574 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
04575 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
04576 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
04577 } else
04578 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
04579 }
04580 res = send_packet(fr);
04581 }
04582 }
04583 return res;
04584 }
04585
04586 static int iax2_show_users(int fd, int argc, char *argv[])
04587 {
04588 regex_t regexbuf;
04589 int havepattern = 0;
04590
04591 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
04592 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
04593
04594 struct iax2_user *user = NULL;
04595 char auth[90];
04596 char *pstr = "";
04597 struct ao2_iterator i;
04598
04599 switch (argc) {
04600 case 5:
04601 if (!strcasecmp(argv[3], "like")) {
04602 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
04603 return RESULT_SHOWUSAGE;
04604 havepattern = 1;
04605 } else
04606 return RESULT_SHOWUSAGE;
04607 case 3:
04608 break;
04609 default:
04610 return RESULT_SHOWUSAGE;
04611 }
04612
04613 ast_cli(fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
04614 i = ao2_iterator_init(users, 0);
04615 for (user = ao2_iterator_next(&i); user;
04616 user_unref(user), user = ao2_iterator_next(&i)) {
04617 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0))
04618 continue;
04619
04620 if (!ast_strlen_zero(user->secret)) {
04621 ast_copy_string(auth,user->secret,sizeof(auth));
04622 } else if (!ast_strlen_zero(user->inkeys)) {
04623 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
04624 } else
04625 ast_copy_string(auth, "-no secret-", sizeof(auth));
04626
04627 if(ast_test_flag(user,IAX_CODEC_NOCAP))
04628 pstr = "REQ Only";
04629 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
04630 pstr = "Disabled";
04631 else
04632 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
04633
04634 ast_cli(fd, FORMAT2, user->name, auth, user->authmethods,
04635 user->contexts ? user->contexts->context : context,
04636 user->ha ? "Yes" : "No", pstr);
04637 }
04638
04639 if (havepattern)
04640 regfree(®exbuf);
04641
04642 return RESULT_SUCCESS;
04643 #undef FORMAT
04644 #undef FORMAT2
04645 }
04646
04647 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
04648 {
04649 regex_t regexbuf;
04650 int havepattern = 0;
04651 int total_peers = 0;
04652 int online_peers = 0;
04653 int offline_peers = 0;
04654 int unmonitored_peers = 0;
04655 struct ao2_iterator i;
04656
04657 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
04658 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
04659
04660 struct iax2_peer *peer = NULL;
04661 char name[256];
04662 int registeredonly=0;
04663 char *term = manager ? "\r\n" : "\n";
04664
04665 switch (argc) {
04666 case 6:
04667 if (!strcasecmp(argv[3], "registered"))
04668 registeredonly = 1;
04669 else
04670 return RESULT_SHOWUSAGE;
04671 if (!strcasecmp(argv[4], "like")) {
04672 if (regcomp(®exbuf, argv[5], REG_EXTENDED | REG_NOSUB))
04673 return RESULT_SHOWUSAGE;
04674 havepattern = 1;
04675 } else
04676 return RESULT_SHOWUSAGE;
04677 break;
04678 case 5:
04679 if (!strcasecmp(argv[3], "like")) {
04680 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
04681 return RESULT_SHOWUSAGE;
04682 havepattern = 1;
04683 } else
04684 return RESULT_SHOWUSAGE;
04685 break;
04686 case 4:
04687 if (!strcasecmp(argv[3], "registered"))
04688 registeredonly = 1;
04689 else
04690 return RESULT_SHOWUSAGE;
04691 break;
04692 case 3:
04693 break;
04694 default:
04695 return RESULT_SHOWUSAGE;
04696 }
04697
04698
04699 if (s)
04700 astman_append(s, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
04701 else
04702 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
04703
04704 i = ao2_iterator_init(peers, 0);
04705 for (peer = ao2_iterator_next(&i); peer;
04706 peer_unref(peer), peer = ao2_iterator_next(&i)) {
04707 char nm[20];
04708 char status[20];
04709 char srch[2000];
04710 int retstatus;
04711
04712 if (registeredonly && !peer->addr.sin_addr.s_addr)
04713 continue;
04714 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0))
04715 continue;
04716
04717 if (!ast_strlen_zero(peer->username))
04718 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
04719 else
04720 ast_copy_string(name, peer->name, sizeof(name));
04721
04722 retstatus = peer_status(peer, status, sizeof(status));
04723 if (retstatus > 0)
04724 online_peers++;
04725 else if (!retstatus)
04726 offline_peers++;
04727 else
04728 unmonitored_peers++;
04729
04730 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
04731
04732 snprintf(srch, sizeof(srch), FORMAT, name,
04733 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
04734 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
04735 nm,
04736 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
04737 peer->encmethods ? "(E)" : " ", status, term);
04738
04739 if (s)
04740 astman_append(s, FORMAT, name,
04741 peer->addr.sin_addr.s_addr ? ast_inet_ntoa( peer->addr.sin_addr) : "(Unspecified)",
04742 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
04743 nm,
04744 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
04745 peer->encmethods ? "(E)" : " ", status, term);
04746 else
04747 ast_cli(fd, FORMAT, name,
04748 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
04749 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
04750 nm,
04751 ntohs(peer->addr.sin_port), ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
04752 peer->encmethods ? "(E)" : " ", status, term);
04753 total_peers++;
04754 }
04755
04756 if (s)
04757 astman_append(s,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
04758 else
04759 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
04760
04761 if (havepattern)
04762 regfree(®exbuf);
04763
04764 return RESULT_SUCCESS;
04765 #undef FORMAT
04766 #undef FORMAT2
04767 }
04768
04769 static int iax2_show_threads(int fd, int argc, char *argv[])
04770 {
04771 struct iax2_thread *thread = NULL;
04772 time_t t;
04773 int threadcount = 0, dynamiccount = 0;
04774 char type;
04775
04776 if (argc != 3)
04777 return RESULT_SHOWUSAGE;
04778
04779 ast_cli(fd, "IAX2 Thread Information\n");
04780 time(&t);
04781 ast_cli(fd, "Idle Threads:\n");
04782 AST_LIST_LOCK(&idle_list);
04783 AST_LIST_TRAVERSE(&idle_list, thread, list) {
04784 #ifdef DEBUG_SCHED_MULTITHREAD
04785 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
04786 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
04787 #else
04788 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
04789 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
04790 #endif
04791 threadcount++;
04792 }
04793 AST_LIST_UNLOCK(&idle_list);
04794 ast_cli(fd, "Active Threads:\n");
04795 AST_LIST_LOCK(&active_list);
04796 AST_LIST_TRAVERSE(&active_list, thread, list) {
04797 if (thread->type == IAX_TYPE_DYNAMIC)
04798 type = 'D';
04799 else
04800 type = 'P';
04801 #ifdef DEBUG_SCHED_MULTITHREAD
04802 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d, func ='%s'\n",
04803 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
04804 #else
04805 ast_cli(fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
04806 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
04807 #endif
04808 threadcount++;
04809 }
04810 AST_LIST_UNLOCK(&active_list);
04811 ast_cli(fd, "Dynamic Threads:\n");
04812 AST_LIST_LOCK(&dynamic_list);
04813 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
04814 #ifdef DEBUG_SCHED_MULTITHREAD
04815 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d, func ='%s'\n",
04816 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
04817 #else
04818 ast_cli(fd, "Thread %d: state=%d, update=%d, actions=%d\n",
04819 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
04820 #endif
04821 dynamiccount++;
04822 }
04823 AST_LIST_UNLOCK(&dynamic_list);
04824 ast_cli(fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
04825 return RESULT_SUCCESS;
04826 }
04827
04828 static int iax2_show_peers(int fd, int argc, char *argv[])
04829 {
04830 return __iax2_show_peers(0, fd, NULL, argc, argv);
04831 }
04832 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
04833 {
04834 ast_cli_netstats(s, -1, 0);
04835 astman_append(s, "\r\n");
04836 return RESULT_SUCCESS;
04837 }
04838
04839 static int iax2_show_firmware(int fd, int argc, char *argv[])
04840 {
04841 #define FORMAT2 "%-15.15s %-15.15s %-15.15s\n"
04842 #if !defined(__FreeBSD__)
04843 #define FORMAT "%-15.15s %-15d %-15d\n"
04844 #else
04845 #define FORMAT "%-15.15s %-15d %-15d\n"
04846 #endif
04847 struct iax_firmware *cur;
04848 if ((argc != 3) && (argc != 4))
04849 return RESULT_SHOWUSAGE;
04850 ast_mutex_lock(&waresl.lock);
04851
04852 ast_cli(fd, FORMAT2, "Device", "Version", "Size");
04853 for (cur = waresl.wares;cur;cur = cur->next) {
04854 if ((argc == 3) || (!strcasecmp(argv[3], (char *)cur->fwh->devname)))
04855 ast_cli(fd, FORMAT, cur->fwh->devname, ntohs(cur->fwh->version),
04856 (int)ntohl(cur->fwh->datalen));
04857 }
04858 ast_mutex_unlock(&waresl.lock);
04859 return RESULT_SUCCESS;
04860 #undef FORMAT
04861 #undef FORMAT2
04862 }
04863
04864
04865 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
04866 {
04867 char *a[] = { "iax2", "show", "users" };
04868 int ret;
04869 const char *id = astman_get_header(m,"ActionID");
04870
04871 if (!ast_strlen_zero(id))
04872 astman_append(s, "ActionID: %s\r\n",id);
04873 ret = __iax2_show_peers(1, -1, s, 3, a );
04874 astman_append(s, "\r\n\r\n" );
04875 return ret;
04876 }
04877
04878 static char *regstate2str(int regstate)
04879 {
04880 switch(regstate) {
04881 case REG_STATE_UNREGISTERED:
04882 return "Unregistered";
04883 case REG_STATE_REGSENT:
04884 return "Request Sent";
04885 case REG_STATE_AUTHSENT:
04886 return "Auth. Sent";
04887 case REG_STATE_REGISTERED:
04888 return "Registered";
04889 case REG_STATE_REJECTED:
04890 return "Rejected";
04891 case REG_STATE_TIMEOUT:
04892 return "Timeout";
04893 case REG_STATE_NOAUTH:
04894 return "No Authentication";
04895 default:
04896 return "Unknown";
04897 }
04898 }
04899
04900 static int iax2_show_registry(int fd, int argc, char *argv[])
04901 {
04902 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
04903 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
04904 struct iax2_registry *reg = NULL;
04905
04906 char host[80];
04907 char perceived[80];
04908 if (argc != 3)
04909 return RESULT_SHOWUSAGE;
04910 ast_cli(fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
04911 AST_LIST_LOCK(®istrations);
04912 AST_LIST_TRAVERSE(®istrations, reg, entry) {
04913 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
04914 if (reg->us.sin_addr.s_addr)
04915 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
04916 else
04917 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
04918 ast_cli(fd, FORMAT, host,
04919 (reg->dnsmgr) ? "Y" : "N",
04920 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
04921 }
04922 AST_LIST_UNLOCK(®istrations);
04923 return RESULT_SUCCESS;
04924 #undef FORMAT
04925 #undef FORMAT2
04926 }
04927
04928 static int iax2_show_channels(int fd, int argc, char *argv[])
04929 {
04930 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s\n"
04931 #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"
04932 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
04933 int x;
04934 int numchans = 0;
04935
04936 if (argc != 3)
04937 return RESULT_SHOWUSAGE;
04938 ast_cli(fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format");
04939 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
04940 ast_mutex_lock(&iaxsl[x]);
04941 if (iaxs[x]) {
04942 int lag, jitter, localdelay;
04943 jb_info jbinfo;
04944
04945 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
04946 jb_getinfo(iaxs[x]->jb, &jbinfo);
04947 jitter = jbinfo.jitter;
04948 localdelay = jbinfo.current - jbinfo.min;
04949 } else {
04950 jitter = -1;
04951 localdelay = 0;
04952 }
04953 lag = iaxs[x]->remote_rr.delay;
04954 ast_cli(fd, FORMAT,
04955 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
04956 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
04957 S_OR(iaxs[x]->username, "(None)"),
04958 iaxs[x]->callno, iaxs[x]->peercallno,
04959 iaxs[x]->oseqno, iaxs[x]->iseqno,
04960 lag,
04961 jitter,
04962 localdelay,
04963 ast_getformatname(iaxs[x]->voiceformat) );
04964 numchans++;
04965 }
04966 ast_mutex_unlock(&iaxsl[x]);
04967 }
04968 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
04969 return RESULT_SUCCESS;
04970 #undef FORMAT
04971 #undef FORMAT2
04972 #undef FORMATB
04973 }
04974
04975 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
04976 {
04977 int x;
04978 int numchans = 0;
04979 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
04980 ast_mutex_lock(&iaxsl[x]);
04981 if (iaxs[x]) {
04982 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
04983 char *fmt;
04984 jb_info jbinfo;
04985
04986 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
04987 jb_getinfo(iaxs[x]->jb, &jbinfo);
04988 localjitter = jbinfo.jitter;
04989 localdelay = jbinfo.current - jbinfo.min;
04990 locallost = jbinfo.frames_lost;
04991 locallosspct = jbinfo.losspct/1000;
04992 localdropped = jbinfo.frames_dropped;
04993 localooo = jbinfo.frames_ooo;
04994 } else {
04995 localjitter = -1;
04996 localdelay = 0;
04997 locallost = -1;
04998 locallosspct = -1;
04999 localdropped = 0;
05000 localooo = -1;
05001 }
05002 if (limit_fmt)
05003 fmt = "%-25.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d\n";
05004 else
05005 fmt = "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d\n";
05006 if (s)
05007
05008 astman_append(s, fmt,
05009 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
05010 iaxs[x]->pingtime,
05011 localjitter,
05012 localdelay,
05013 locallost,
05014 locallosspct,
05015 localdropped,
05016 localooo,
05017 iaxs[x]->frames_received/1000,
05018 iaxs[x]->remote_rr.jitter,
05019 iaxs[x]->remote_rr.delay,
05020 iaxs[x]->remote_rr.losscnt,
05021 iaxs[x]->remote_rr.losspct,
05022 iaxs[x]->remote_rr.dropped,
05023 iaxs[x]->remote_rr.ooo,
05024 iaxs[x]->remote_rr.packets/1000);
05025 else
05026 ast_cli(fd, fmt,
05027 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
05028 iaxs[x]->pingtime,
05029 localjitter,
05030 localdelay,
05031 locallost,
05032 locallosspct,
05033 localdropped,
05034 localooo,
05035 iaxs[x]->frames_received/1000,
05036 iaxs[x]->remote_rr.jitter,
05037 iaxs[x]->remote_rr.delay,
05038 iaxs[x]->remote_rr.losscnt,
05039 iaxs[x]->remote_rr.losspct,
05040 iaxs[x]->remote_rr.dropped,
05041 iaxs[x]->remote_rr.ooo,
05042 iaxs[x]->remote_rr.packets/1000
05043 );
05044 numchans++;
05045 }
05046 ast_mutex_unlock(&iaxsl[x]);
05047 }
05048 return numchans;
05049 }
05050
05051 static int iax2_show_netstats(int fd, int argc, char *argv[])
05052 {
05053 int numchans = 0;
05054 if (argc != 3)
05055 return RESULT_SHOWUSAGE;
05056 ast_cli(fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
05057 ast_cli(fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts\n");
05058 numchans = ast_cli_netstats(NULL, fd, 1);
05059 ast_cli(fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
05060 return RESULT_SUCCESS;
05061 }
05062
05063 static int iax2_do_debug(int fd, int argc, char *argv[])
05064 {
05065 if (argc < 2 || argc > 3)
05066 return RESULT_SHOWUSAGE;
05067 iaxdebug = 1;
05068 ast_cli(fd, "IAX2 Debugging Enabled\n");
05069 return RESULT_SUCCESS;
05070 }
05071
05072 static int iax2_do_trunk_debug(int fd, int argc, char *argv[])
05073 {
05074 if (argc < 3 || argc > 4)
05075 return RESULT_SHOWUSAGE;
05076 iaxtrunkdebug = 1;
05077 ast_cli(fd, "IAX2 Trunk Debug Requested\n");
05078 return RESULT_SUCCESS;
05079 }
05080
05081 static int iax2_do_jb_debug(int fd, int argc, char *argv[])
05082 {
05083 if (argc < 3 || argc > 4)
05084 return RESULT_SHOWUSAGE;
05085 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
05086 ast_cli(fd, "IAX2 Jitterbuffer Debugging Enabled\n");
05087 return RESULT_SUCCESS;
05088 }
05089
05090 static int iax2_no_debug(int fd, int argc, char *argv[])
05091 {
05092 if (argc < 3 || argc > 4)
05093 return RESULT_SHOWUSAGE;
05094 iaxdebug = 0;
05095 ast_cli(fd, "IAX2 Debugging Disabled\n");
05096 return RESULT_SUCCESS;
05097 }
05098
05099 static int iax2_no_trunk_debug(int fd, int argc, char *argv[])
05100 {
05101 if (argc < 4 || argc > 5)
05102 return RESULT_SHOWUSAGE;
05103 iaxtrunkdebug = 0;
05104 ast_cli(fd, "IAX2 Trunk Debugging Disabled\n");
05105 return RESULT_SUCCESS;
05106 }
05107
05108 static int iax2_no_jb_debug(int fd, int argc, char *argv[])
05109 {
05110 if (argc < 4 || argc > 5)
05111 return RESULT_SHOWUSAGE;
05112 jb_setoutput(jb_error_output, jb_warning_output, NULL);
05113 jb_debug_output("\n");
05114 ast_cli(fd, "IAX2 Jitterbuffer Debugging Disabled\n");
05115 return RESULT_SUCCESS;
05116 }
05117
05118 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
05119 {
05120 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05121 int res = -1;
05122 ast_mutex_lock(&iaxsl[callno]);
05123 if (iaxs[callno]) {
05124
05125 if (!iaxs[callno]->error) {
05126 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
05127 res = 0;
05128
05129 else if (f->frametype == AST_FRAME_NULL)
05130 res = 0;
05131 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
05132 res = 0;
05133 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
05134 res = 0;
05135 else
05136
05137 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
05138 } else {
05139 if (option_debug)
05140 ast_log(LOG_DEBUG, "Write error: %s\n", strerror(errno));
05141 }
05142 }
05143
05144 ast_mutex_unlock(&iaxsl[callno]);
05145 return res;
05146 }
05147
05148 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
05149 int now, int transfer, int final)
05150 {
05151 struct ast_frame f = { 0, };
05152
05153 f.frametype = type;
05154 f.subclass = command;
05155 f.datalen = datalen;
05156 f.src = __FUNCTION__;
05157 f.data = (void *) data;
05158
05159 return iax2_send(i, &f, ts, seqno, now, transfer, final);
05160 }
05161
05162 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
05163 {
05164 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
05165 }
05166
05167 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
05168 {
05169 int res;
05170 ast_mutex_lock(&iaxsl[callno]);
05171 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
05172 ast_mutex_unlock(&iaxsl[callno]);
05173 return res;
05174 }
05175
05176
05177
05178
05179
05180
05181 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)
05182 {
05183 int call_num = i->callno;
05184
05185 iax2_predestroy(i->callno);
05186 if (!iaxs[call_num])
05187 return -1;
05188 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
05189 }
05190
05191 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)
05192 {
05193 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
05194 }
05195
05196 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
05197 {
05198 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
05199 }
05200
05201 static int apply_context(struct iax2_context *con, const char *context)
05202 {
05203 while(con) {
05204 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
05205 return -1;
05206 con = con->next;
05207 }
05208 return 0;
05209 }
05210
05211
05212 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
05213 {
05214
05215 int res = -1;
05216 int version = 2;
05217 struct iax2_user *user = NULL, *best = NULL;
05218 int bestscore = 0;
05219 int gotcapability = 0;
05220 struct ast_variable *v = NULL, *tmpvar = NULL;
05221 struct ao2_iterator i;
05222
05223 if (!iaxs[callno])
05224 return res;
05225 if (ies->called_number)
05226 ast_string_field_set(iaxs[callno], exten, ies->called_number);
05227 if (ies->calling_number) {
05228 ast_shrink_phone_number(ies->calling_number);
05229 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
05230 }
05231 if (ies->calling_name)
05232 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
05233 if (ies->calling_ani)
05234 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
05235 if (ies->dnid)
05236 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
05237 if (ies->rdnis)
05238 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
05239 if (ies->called_context)
05240 ast_string_field_set(iaxs[callno], context, ies->called_context);
05241 if (ies->language)
05242 ast_string_field_set(iaxs[callno], language, ies->language);
05243 if (ies->username)
05244 ast_string_field_set(iaxs[callno], username, ies->username);
05245 if (ies->calling_ton > -1)
05246 iaxs[callno]->calling_ton = ies->calling_ton;
05247 if (ies->calling_tns > -1)
05248 iaxs[callno]->calling_tns = ies->calling_tns;
05249 if (ies->calling_pres > -1)
05250 iaxs[callno]->calling_pres = ies->calling_pres;
05251 if (ies->format)
05252 iaxs[callno]->peerformat = ies->format;
05253 if (ies->adsicpe)
05254 iaxs[callno]->peeradsicpe = ies->adsicpe;
05255 if (ies->capability) {
05256 gotcapability = 1;
05257 iaxs[callno]->peercapability = ies->capability;
05258 }
05259 if (ies->version)
05260 version = ies->version;
05261
05262
05263 if(ies->codec_prefs) {
05264 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
05265 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
05266 }
05267
05268 if (!gotcapability)
05269 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
05270 if (version > IAX_PROTO_VERSION) {
05271 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
05272 ast_inet_ntoa(sin->sin_addr), version);
05273 return res;
05274 }
05275
05276 i = ao2_iterator_init(users, 0);
05277 while ((user = ao2_iterator_next(&i))) {
05278 if ((ast_strlen_zero(iaxs[callno]->username) ||
05279 !strcmp(iaxs[callno]->username, user->name))
05280 && ast_apply_ha(user->ha, sin)
05281 && (ast_strlen_zero(iaxs[callno]->context) ||
05282 apply_context(user->contexts, iaxs[callno]->context))) {
05283 if (!ast_strlen_zero(iaxs[callno]->username)) {
05284
05285 if (best)
05286 user_unref(best);
05287 best = user;
05288 break;
05289 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
05290
05291 if (user->ha) {
05292
05293 if (bestscore < 4) {
05294 bestscore = 4;
05295 if (best)
05296 user_unref(best);
05297 best = user;
05298 continue;
05299 }
05300 } else {
05301
05302 if (bestscore < 3) {
05303 bestscore = 3;
05304 if (best)
05305 user_unref(best);
05306 best = user;
05307 continue;
05308 }
05309 }
05310 } else {
05311 if (user->ha) {
05312
05313 if (bestscore < 2) {
05314 bestscore = 2;
05315 if (best)
05316 user_unref(best);
05317 best = user;
05318 continue;
05319 }
05320 } else {
05321
05322 if (bestscore < 1) {
05323 bestscore = 1;
05324 if (best)
05325 user_unref(best);
05326 best = user;
05327 continue;
05328 }
05329 }
05330 }
05331 }
05332 user_unref(user);
05333 }
05334 user = best;
05335 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
05336 user = realtime_user(iaxs[callno]->username, sin);
05337 if (user && !ast_strlen_zero(iaxs[callno]->context) &&
05338 !apply_context(user->contexts, iaxs[callno]->context)) {
05339 user = user_unref(user);
05340 }
05341 }
05342 if (user) {
05343
05344
05345 for (v = user->vars ; v ; v = v->next) {
05346 if((tmpvar = ast_variable_new(v->name, v->value))) {
05347 tmpvar->next = iaxs[callno]->vars;
05348 iaxs[callno]->vars = tmpvar;
05349 }
05350 }
05351
05352 if (user->maxauthreq > 0)
05353 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
05354 iaxs[callno]->prefs = user->prefs;
05355 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST);
05356 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOPREFS);
05357 ast_copy_flags(iaxs[callno], user, IAX_CODEC_NOCAP);
05358 iaxs[callno]->encmethods = user->encmethods;
05359
05360 if (ast_strlen_zero(iaxs[callno]->username))
05361 ast_string_field_set(iaxs[callno], username, user->name);
05362
05363 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
05364 iaxs[callno]->capability = user->capability;
05365
05366 if (ast_strlen_zero(iaxs[callno]->context)) {
05367 if (user->contexts)
05368 ast_string_field_set(iaxs[callno], context, user->contexts->context);
05369 else
05370 ast_string_field_set(iaxs[callno], context, context);
05371 }
05372
05373 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
05374
05375 iaxs[callno]->authmethods = user->authmethods;
05376 iaxs[callno]->adsi = user->adsi;
05377
05378 if (ast_test_flag(user, IAX_HASCALLERID)) {
05379 iaxs[callno]->calling_tns = 0;
05380 iaxs[callno]->calling_ton = 0;
05381 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
05382 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
05383 ast_string_field_set(iaxs[callno], ani, user->cid_num);
05384 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
05385 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
05386 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
05387 }
05388 if (!ast_strlen_zero(user->accountcode))
05389 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
05390 if (!ast_strlen_zero(user->mohinterpret))
05391 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
05392 if (!ast_strlen_zero(user->mohsuggest))
05393 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
05394 if (user->amaflags)
05395 iaxs[callno]->amaflags = user->amaflags;
05396 if (!ast_strlen_zero(user->language))
05397 ast_string_field_set(iaxs[callno], language, user->language);
05398 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
05399
05400 if (!ast_strlen_zero(user->dbsecret)) {
05401 char *family, *key=NULL;
05402 char buf[80];
05403 family = ast_strdupa(user->dbsecret);
05404 key = strchr(family, '/');
05405 if (key) {
05406 *key = '\0';
05407 key++;
05408 }
05409 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
05410 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
05411 else
05412 ast_string_field_set(iaxs[callno], secret, buf);
05413 } else
05414 ast_string_field_set(iaxs[callno], secret, user->secret);
05415 res = 0;
05416 user = user_unref(user);
05417 }
05418 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
05419 return res;
05420 }
05421
05422 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
05423 {
05424 struct ast_iax2_full_hdr fh;
05425 fh.scallno = htons(src | IAX_FLAG_FULL);
05426 fh.dcallno = htons(dst);
05427 fh.ts = 0;
05428 fh.oseqno = 0;
05429 fh.iseqno = 0;
05430 fh.type = AST_FRAME_IAX;
05431 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
05432 if (iaxdebug)
05433 iax_showframe(NULL, &fh, 0, sin, 0);
05434 if (option_debug)
05435 ast_log(LOG_DEBUG, "Raw Hangup %s:%d, src=%d, dst=%d\n",
05436 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
05437 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
05438 }
05439
05440 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
05441 {
05442
05443 p->encmethods &= enc;
05444 if (p->encmethods) {
05445 if (p->encmethods & IAX_ENCRYPT_AES128)
05446 p->encmethods = IAX_ENCRYPT_AES128;
05447 else
05448 p->encmethods = 0;
05449 }
05450 }
05451
05452
05453
05454
05455
05456
05457
05458 static int authenticate_request(int call_num)
05459 {
05460 struct iax_ie_data ied;
05461 int res = -1, authreq_restrict = 0;
05462 char challenge[10];
05463 struct chan_iax2_pvt *p = iaxs[call_num];
05464
05465 memset(&ied, 0, sizeof(ied));
05466
05467
05468 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
05469 struct iax2_user *user, tmp_user = {
05470 .name = p->username,
05471 };
05472
05473 user = ao2_find(users, &tmp_user, OBJ_POINTER);
05474 if (user) {
05475 if (user->curauthreq == user->maxauthreq)
05476 authreq_restrict = 1;
05477 else
05478 user->curauthreq++;
05479 user = user_unref(user);
05480 }
05481 }
05482
05483
05484 if (authreq_restrict) {
05485 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
05486 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
05487 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
05488 return 0;
05489 }
05490
05491 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
05492 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
05493 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
05494 ast_string_field_set(p, challenge, challenge);
05495
05496 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
05497 }
05498 if (p->encmethods)
05499 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
05500
05501 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
05502
05503 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
05504
05505 if (p->encmethods)
05506 ast_set_flag(p, IAX_ENCRYPTED);
05507
05508 return res;
05509 }
05510
05511 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
05512 {
05513 char requeststr[256];
05514 char md5secret[256] = "";
05515 char secret[256] = "";
05516 char rsasecret[256] = "";
05517 int res = -1;
05518 int x;
05519 struct iax2_user *user, tmp_user = {
05520 .name = p->username,
05521 };
05522
05523 user = ao2_find(users, &tmp_user, OBJ_POINTER);
05524 if (user) {
05525 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
05526 ast_atomic_fetchadd_int(&user->curauthreq, -1);
05527 ast_clear_flag(p, IAX_MAXAUTHREQ);
05528 }
05529 ast_string_field_set(p, host, user->name);
05530 user = user_unref(user);
05531 }
05532
05533 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
05534 return res;
05535 if (ies->password)
05536 ast_copy_string(secret, ies->password, sizeof(secret));
05537 if (ies->md5_result)
05538 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
05539 if (ies->rsa_result)
05540 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
05541 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
05542 struct ast_key *key;
05543 char *keyn;
05544 char tmpkey[256];
05545 char *stringp=NULL;
05546 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
05547 stringp=tmpkey;
05548 keyn = strsep(&stringp, ":");
05549 while(keyn) {
05550 key = ast_key_get(keyn, AST_KEY_PUBLIC);
05551 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
05552 res = 0;
05553 break;
05554 } else if (!key)
05555 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
05556 keyn = strsep(&stringp, ":");
05557 }
05558 } else if (p->authmethods & IAX_AUTH_MD5) {
05559 struct MD5Context md5;
05560 unsigned char digest[16];
05561 char *tmppw, *stringp;
05562
05563 tmppw = ast_strdupa(p->secret);
05564 stringp = tmppw;
05565 while((tmppw = strsep(&stringp, ";"))) {
05566 MD5Init(&md5);
05567 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
05568 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
05569 MD5Final(digest, &md5);
05570
05571 for (x=0;x<16;x++)
05572 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
05573 if (!strcasecmp(requeststr, md5secret)) {
05574 res = 0;
05575 break;
05576 }
05577 }
05578 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
05579 if (!strcmp(secret, p->secret))
05580 res = 0;
05581 }
05582 return res;
05583 }
05584
05585
05586 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
05587 {
05588 char requeststr[256] = "";
05589 char peer[256] = "";
05590 char md5secret[256] = "";
05591 char rsasecret[256] = "";
05592 char secret[256] = "";
05593 struct iax2_peer *p = NULL;
05594 struct ast_key *key;
05595 char *keyn;
05596 int x;
05597 int expire = 0;
05598 int res = -1;
05599
05600 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED);
05601
05602 if (ies->username)
05603 ast_copy_string(peer, ies->username, sizeof(peer));
05604 if (ies->password)
05605 ast_copy_string(secret, ies->password, sizeof(secret));
05606 if (ies->md5_result)
05607 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
05608 if (ies->rsa_result)
05609 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
05610 if (ies->refresh)
05611 expire = ies->refresh;
05612
05613 if (ast_strlen_zero(peer)) {
05614 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
05615 return -1;
05616 }
05617
05618
05619 ast_mutex_unlock(&iaxsl[callno]);
05620 p = find_peer(peer, 1);
05621 ast_mutex_lock(&iaxsl[callno]);
05622 if (!p || !iaxs[callno]) {
05623 if (authdebug && !p)
05624 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
05625 goto return_unref;
05626 }
05627
05628 if (!ast_test_flag(p, IAX_DYNAMIC)) {
05629 if (authdebug)
05630 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
05631 goto return_unref;
05632 }
05633
05634 if (!ast_apply_ha(p->ha, sin)) {
05635 if (authdebug)
05636 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
05637 goto return_unref;
05638 }
05639 if (!inaddrcmp(&p->addr, sin))
05640 ast_set_flag(&iaxs[callno]->state, IAX_STATE_UNCHANGED);
05641 ast_string_field_set(iaxs[callno], secret, p->secret);
05642 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
05643
05644 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
05645 if (!ast_strlen_zero(p->inkeys)) {
05646 char tmpkeys[256];
05647 char *stringp=NULL;
05648 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
05649 stringp=tmpkeys;
05650 keyn = strsep(&stringp, ":");
05651 while(keyn) {
05652 key = ast_key_get(keyn, AST_KEY_PUBLIC);
05653 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
05654 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
05655 break;
05656 } else if (!key)
05657 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
05658 keyn = strsep(&stringp, ":");
05659 }
05660 if (!keyn) {
05661 if (authdebug)
05662 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
05663 goto return_unref;
05664 }
05665 } else {
05666 if (authdebug)
05667 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
05668 goto return_unref;
05669 }
05670 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
05671 struct MD5Context md5;
05672 unsigned char digest[16];
05673 char *tmppw, *stringp;
05674
05675 tmppw = ast_strdupa(p->secret);
05676 stringp = tmppw;
05677 while((tmppw = strsep(&stringp, ";"))) {
05678 MD5Init(&md5);
05679 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
05680 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
05681 MD5Final(digest, &md5);
05682 for (x=0;x<16;x++)
05683 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
05684 if (!strcasecmp(requeststr, md5secret))
05685 break;
05686 }
05687 if (tmppw) {
05688 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
05689 } else {
05690 if (authdebug)
05691 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
05692 goto return_unref;
05693 }
05694 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
05695
05696 if (strcmp(secret, p->secret)) {
05697 if (authdebug)
05698 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
05699 goto return_unref;
05700 } else
05701 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
05702 } else if (!ast_strlen_zero(md5secret) || !ast_strlen_zero(secret)) {
05703 if (authdebug)
05704 ast_log(LOG_NOTICE, "Inappropriate authentication received\n");
05705 goto return_unref;
05706 }
05707 ast_string_field_set(iaxs[callno], peer, peer);
05708
05709 if (expire && (expire < iaxs[callno]->expiry))
05710 iaxs[callno]->expiry = expire;
05711
05712 ast_device_state_changed("IAX2/%s", p->name);
05713
05714 res = 0;
05715
05716 return_unref:
05717 if (p)
05718 peer_unref(p);
05719
05720 return res;
05721 }
05722
05723 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, aes_encrypt_ctx *ecx, aes_decrypt_ctx *dcx)
05724 {
05725 int res = -1;
05726 int x;
05727 if (!ast_strlen_zero(keyn)) {
05728 if (!(authmethods & IAX_AUTH_RSA)) {
05729 if (ast_strlen_zero(secret))
05730 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));
05731 } else if (ast_strlen_zero(challenge)) {
05732 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
05733 } else {
05734 char sig[256];
05735 struct ast_key *key;
05736 key = ast_key_get(keyn, AST_KEY_PRIVATE);
05737 if (!key) {
05738 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
05739 } else {
05740 if (ast_sign(key, (char*)challenge, sig)) {
05741 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
05742 res = -1;
05743 } else {
05744 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
05745 res = 0;
05746 }
05747 }
05748 }
05749 }
05750
05751 if (res && !ast_strlen_zero(secret)) {
05752 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
05753 struct MD5Context md5;
05754 unsigned char digest[16];
05755 char digres[128];
05756 MD5Init(&md5);
05757 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
05758 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
05759 MD5Final(digest, &md5);
05760
05761 for (x=0;x<16;x++)
05762 sprintf(digres + (x << 1), "%2.2x", digest[x]);
05763 if (ecx && dcx)
05764 build_enc_keys(digest, ecx, dcx);
05765 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
05766 res = 0;
05767 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
05768 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
05769 res = 0;
05770 } else
05771 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
05772 }
05773 return res;
05774 }
05775
05776
05777
05778
05779
05780 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
05781 {
05782 struct iax2_peer *peer = NULL;
05783
05784 int res = -1;
05785 int authmethods = 0;
05786 struct iax_ie_data ied;
05787 uint16_t callno = p->callno;
05788
05789 memset(&ied, 0, sizeof(ied));
05790
05791 if (ies->username)
05792 ast_string_field_set(p, username, ies->username);
05793 if (ies->challenge)
05794 ast_string_field_set(p, challenge, ies->challenge);
05795 if (ies->authmethods)
05796 authmethods = ies->authmethods;
05797 if (authmethods & IAX_AUTH_MD5)
05798 merge_encryption(p, ies->encmethods);
05799 else
05800 p->encmethods = 0;
05801
05802
05803 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
05804
05805 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, &p->ecx, &p->dcx);
05806 } else {
05807 struct ao2_iterator i = ao2_iterator_init(peers, 0);
05808 while ((peer = ao2_iterator_next(&i))) {
05809 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
05810
05811 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
05812
05813 && (!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)))
05814
05815 ) {
05816 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
05817 if (!res) {
05818 peer_unref(peer);
05819 break;
05820 }
05821 }
05822 peer_unref(peer);
05823 }
05824 if (!peer) {
05825
05826
05827 const char *peer_name = ast_strdupa(p->peer);
05828 ast_mutex_unlock(&iaxsl[callno]);
05829 if ((peer = realtime_peer(peer_name, NULL))) {
05830 ast_mutex_lock(&iaxsl[callno]);
05831 if (!(p = iaxs[callno])) {
05832 peer_unref(peer);
05833 return -1;
05834 }
05835 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, &p->ecx, &p->dcx);
05836 peer_unref(peer);
05837 }
05838 if (!peer) {
05839 ast_mutex_lock(&iaxsl[callno]);
05840 if (!(p = iaxs[callno]))
05841 return -1;
05842 }
05843 }
05844 }
05845 if (ies->encmethods)
05846 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
05847 if (!res)
05848 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
05849 return res;
05850 }
05851
05852 static int iax2_do_register(struct iax2_registry *reg);
05853
05854 static void __iax2_do_register_s(const void *data)
05855 {
05856 struct iax2_registry *reg = (struct iax2_registry *)data;
05857 reg->expire = -1;
05858 iax2_do_register(reg);
05859 }
05860
05861 static int iax2_do_register_s(const void *data)
05862 {
05863 #ifdef SCHED_MULTITHREADED
05864 if (schedule_action(__iax2_do_register_s, data))
05865 #endif
05866 __iax2_do_register_s(data);
05867 return 0;
05868 }
05869
05870 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
05871 {
05872 int newcall = 0;
05873 char newip[256];
05874 struct iax_ie_data ied;
05875 struct sockaddr_in new;
05876
05877
05878 memset(&ied, 0, sizeof(ied));
05879 if (ies->apparent_addr)
05880 bcopy(ies->apparent_addr, &new, sizeof(new));
05881 if (ies->callno)
05882 newcall = ies->callno;
05883 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
05884 ast_log(LOG_WARNING, "Invalid transfer request\n");
05885 return -1;
05886 }
05887 pvt->transfercallno = newcall;
05888 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
05889 inet_aton(newip, &pvt->transfer.sin_addr);
05890 pvt->transfer.sin_family = AF_INET;
05891 pvt->transferring = TRANSFER_BEGIN;
05892 pvt->transferid = ies->transferid;
05893 if (ies->transferid)
05894 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
05895 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
05896 return 0;
05897 }
05898
05899 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
05900 {
05901 char exten[256] = "";
05902 int status = CACHE_FLAG_UNKNOWN;
05903 int expiry = iaxdefaultdpcache;
05904 int x;
05905 int matchmore = 0;
05906 struct iax2_dpcache *dp, *prev;
05907
05908 if (ies->called_number)
05909 ast_copy_string(exten, ies->called_number, sizeof(exten));
05910
05911 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
05912 status = CACHE_FLAG_EXISTS;
05913 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
05914 status = CACHE_FLAG_CANEXIST;
05915 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
05916 status = CACHE_FLAG_NONEXISTENT;
05917
05918 if (ies->dpstatus & IAX_DPSTATUS_IGNOREPAT) {
05919
05920 }
05921 if (ies->refresh)
05922 expiry = ies->refresh;
05923 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
05924 matchmore = CACHE_FLAG_MATCHMORE;
05925 ast_mutex_lock(&dpcache_lock);
05926 prev = NULL;
05927 dp = pvt->dpentries;
05928 while(dp) {
05929 if (!strcmp(dp->exten, exten)) {
05930
05931 if (prev)
05932 prev->peer = dp->peer;
05933 else
05934 pvt->dpentries = dp->peer;
05935 dp->peer = NULL;
05936 dp->callno = 0;
05937 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
05938 if (dp->flags & CACHE_FLAG_PENDING) {
05939 dp->flags &= ~CACHE_FLAG_PENDING;
05940 dp->flags |= status;
05941 dp->flags |= matchmore;
05942 }
05943
05944 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
05945 if (dp->waiters[x] > -1) {
05946 if (write(dp->waiters[x], "asdf", 4) < 0) {
05947 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
05948 }
05949 }
05950 }
05951 }
05952 prev = dp;
05953 dp = dp->peer;
05954 }
05955 ast_mutex_unlock(&dpcache_lock);
05956 return 0;
05957 }
05958
05959 static int complete_transfer(int callno, struct iax_ies *ies)
05960 {
05961 int peercallno = 0;
05962 struct chan_iax2_pvt *pvt = iaxs[callno];
05963 struct iax_frame *cur;
05964 jb_frame frame;
05965
05966 if (ies->callno)
05967 peercallno = ies->callno;
05968
05969 if (peercallno < 1) {
05970 ast_log(LOG_WARNING, "Invalid transfer request\n");
05971 return -1;
05972 }
05973 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
05974 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
05975
05976 pvt->oseqno = 0;
05977 pvt->rseqno = 0;
05978 pvt->iseqno = 0;
05979 pvt->aseqno = 0;
05980
05981 if (pvt->peercallno) {
05982 remove_by_peercallno(pvt);
05983 }
05984 pvt->peercallno = peercallno;
05985 store_by_peercallno(pvt);
05986
05987 pvt->transferring = TRANSFER_NONE;
05988 pvt->svoiceformat = -1;
05989 pvt->voiceformat = 0;
05990 pvt->svideoformat = -1;
05991 pvt->videoformat = 0;
05992 pvt->transfercallno = -1;
05993 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
05994 memset(&pvt->offset, 0, sizeof(pvt->offset));
05995
05996 while(jb_getall(pvt->jb,&frame) == JB_OK)
05997 iax2_frame_free(frame.data);
05998 jb_reset(pvt->jb);
05999 pvt->lag = 0;
06000 pvt->last = 0;
06001 pvt->lastsent = 0;
06002 pvt->nextpred = 0;
06003 pvt->pingtime = DEFAULT_RETRY_TIME;
06004 AST_LIST_LOCK(&iaxq.queue);
06005 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
06006
06007
06008
06009 if (callno == cur->callno)
06010 cur->retries = -1;
06011 }
06012 AST_LIST_UNLOCK(&iaxq.queue);
06013 return 0;
06014 }
06015
06016
06017 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
06018 {
06019 struct iax2_registry *reg;
06020
06021 char peer[256] = "";
06022 char msgstatus[60];
06023 int refresh = 60;
06024 char ourip[256] = "<Unspecified>";
06025 struct sockaddr_in oldus;
06026 struct sockaddr_in us;
06027 int oldmsgs;
06028
06029 memset(&us, 0, sizeof(us));
06030 if (ies->apparent_addr)
06031 bcopy(ies->apparent_addr, &us, sizeof(us));
06032 if (ies->username)
06033 ast_copy_string(peer, ies->username, sizeof(peer));
06034 if (ies->refresh)
06035 refresh = ies->refresh;
06036 if (ies->calling_number) {
06037
06038 }
06039 reg = iaxs[callno]->reg;
06040 if (!reg) {
06041 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
06042 return -1;
06043 }
06044 memcpy(&oldus, ®->us, sizeof(oldus));
06045 oldmsgs = reg->messages;
06046 if (inaddrcmp(®->addr, sin)) {
06047 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
06048 return -1;
06049 }
06050 memcpy(®->us, &us, sizeof(reg->us));
06051 if (ies->msgcount >= 0)
06052 reg->messages = ies->msgcount & 0xffff;
06053
06054
06055
06056 reg->refresh = refresh;
06057 AST_SCHED_DEL(sched, reg->expire);
06058 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
06059 if (inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) {
06060 if (option_verbose > 2) {
06061 if (reg->messages > 255)
06062 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
06063 else if (reg->messages > 1)
06064 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
06065 else if (reg->messages > 0)
06066 snprintf(msgstatus, sizeof(msgstatus), " with 1 new message waiting\n");
06067 else
06068 snprintf(msgstatus, sizeof(msgstatus), " with no messages waiting\n");
06069 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
06070 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
06071 }
06072 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
06073 }
06074 reg->regstate = REG_STATE_REGISTERED;
06075 return 0;
06076 }
06077
06078 static int iax2_register(char *value, int lineno)
06079 {
06080 struct iax2_registry *reg;
06081 char copy[256];
06082 char *username, *hostname, *secret;
06083 char *porta;
06084 char *stringp=NULL;
06085
06086 if (!value)
06087 return -1;
06088 ast_copy_string(copy, value, sizeof(copy));
06089 stringp=copy;
06090 username = strsep(&stringp, "@");
06091 hostname = strsep(&stringp, "@");
06092 if (!hostname) {
06093 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
06094 return -1;
06095 }
06096 stringp=username;
06097 username = strsep(&stringp, ":");
06098 secret = strsep(&stringp, ":");
06099 stringp=hostname;
06100 hostname = strsep(&stringp, ":");
06101 porta = strsep(&stringp, ":");
06102
06103 if (porta && !atoi(porta)) {
06104 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
06105 return -1;
06106 }
06107 if (!(reg = ast_calloc(1, sizeof(*reg))))
06108 return -1;
06109 if (ast_dnsmgr_lookup(hostname, ®->addr.sin_addr, ®->dnsmgr) < 0) {
06110 free(reg);
06111 return -1;
06112 }
06113 ast_copy_string(reg->username, username, sizeof(reg->username));
06114 if (secret)
06115 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
06116 reg->expire = -1;
06117 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
06118 reg->addr.sin_family = AF_INET;
06119 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
06120 AST_LIST_LOCK(®istrations);
06121 AST_LIST_INSERT_HEAD(®istrations, reg, entry);
06122 AST_LIST_UNLOCK(®istrations);
06123
06124 return 0;
06125 }
06126
06127 static void register_peer_exten(struct iax2_peer *peer, int onoff)
06128 {
06129 char multi[256];
06130 char *stringp, *ext;
06131 if (!ast_strlen_zero(regcontext)) {
06132 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
06133 stringp = multi;
06134 while((ext = strsep(&stringp, "&"))) {
06135 if (onoff) {
06136 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
06137 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
06138 "Noop", ast_strdup(peer->name), ast_free, "IAX2");
06139 } else
06140 ast_context_remove_extension(regcontext, ext, 1, NULL);
06141 }
06142 }
06143 }
06144 static void prune_peers(void);
06145
06146 static void unlink_peer(struct iax2_peer *peer)
06147 {
06148 if (peer->expire > -1) {
06149 if (!ast_sched_del(sched, peer->expire)) {
06150 peer->expire = -1;
06151 peer_unref(peer);
06152 }
06153 }
06154
06155 if (peer->pokeexpire > -1) {
06156 if (!ast_sched_del(sched, peer->pokeexpire)) {
06157 peer->pokeexpire = -1;
06158 peer_unref(peer);
06159 }
06160 }
06161
06162 ao2_unlink(peers, peer);
06163 }
06164
06165 static void __expire_registry(const void *data)
06166 {
06167 struct iax2_peer *peer = (struct iax2_peer *) data;
06168
06169 if (!peer)
06170 return;
06171
06172 peer->expire = -1;
06173
06174 if (option_debug)
06175 ast_log(LOG_DEBUG, "Expiring registration for peer '%s'\n", peer->name);
06176 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
06177 realtime_update_peer(peer->name, &peer->addr, 0);
06178 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
06179
06180 memset(&peer->addr, 0, sizeof(peer->addr));
06181
06182 peer->expiry = min_reg_expire;
06183 if (!ast_test_flag(peer, IAX_TEMPONLY))
06184 ast_db_del("IAX/Registry", peer->name);
06185 register_peer_exten(peer, 0);
06186 ast_device_state_changed("IAX2/%s", peer->name);
06187 if (iax2_regfunk)
06188 iax2_regfunk(peer->name, 0);
06189
06190 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
06191 unlink_peer(peer);
06192
06193 peer_unref(peer);
06194 }
06195
06196 static int expire_registry(const void *data)
06197 {
06198 #ifdef SCHED_MULTITHREADED
06199 if (schedule_action(__expire_registry, data))
06200 #endif
06201 __expire_registry(data);
06202 return 0;
06203 }
06204
06205 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
06206
06207 static void reg_source_db(struct iax2_peer *p)
06208 {
06209 char data[80];
06210 struct in_addr in;
06211 char *c, *d;
06212 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
06213 c = strchr(data, ':');
06214 if (c) {
06215 *c = '\0';
06216 c++;
06217 if (inet_aton(data, &in)) {
06218 d = strchr(c, ':');
06219 if (d) {
06220 *d = '\0';
06221 d++;
06222 if (option_verbose > 2)
06223 ast_verbose(VERBOSE_PREFIX_3 "Seeding '%s' at %s:%d for %d\n", p->name,
06224 ast_inet_ntoa(in), atoi(c), atoi(d));
06225 iax2_poke_peer(p, 0);
06226 p->expiry = atoi(d);
06227 memset(&p->addr, 0, sizeof(p->addr));
06228 p->addr.sin_family = AF_INET;
06229 p->addr.sin_addr = in;
06230 p->addr.sin_port = htons(atoi(c));
06231 if (p->expire > -1) {
06232 if (!ast_sched_del(sched, p->expire)) {
06233 p->expire = -1;
06234 peer_unref(p);
06235 }
06236 }
06237 ast_device_state_changed("IAX2/%s", p->name);
06238 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
06239 if (p->expire == -1)
06240 peer_unref(p);
06241 if (iax2_regfunk)
06242 iax2_regfunk(p->name, 1);
06243 register_peer_exten(p, 1);
06244 }
06245
06246 }
06247 }
06248 }
06249 }
06250
06251
06252
06253
06254
06255
06256
06257 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
06258 {
06259
06260 struct iax_ie_data ied;
06261 struct iax2_peer *p;
06262 int msgcount;
06263 char data[80];
06264 int version;
06265 const char *peer_name;
06266 int res = -1;
06267
06268 memset(&ied, 0, sizeof(ied));
06269
06270 peer_name = ast_strdupa(iaxs[callno]->peer);
06271
06272
06273 ast_mutex_unlock(&iaxsl[callno]);
06274 if (!(p = find_peer(peer_name, 1))) {
06275 ast_mutex_lock(&iaxsl[callno]);
06276 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
06277 return -1;
06278 }
06279 ast_mutex_lock(&iaxsl[callno]);
06280 if (!iaxs[callno])
06281 goto return_unref;
06282
06283 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
06284 if (sin->sin_addr.s_addr) {
06285 time_t nowtime;
06286 time(&nowtime);
06287 realtime_update_peer(peer_name, sin, nowtime);
06288 } else {
06289 realtime_update_peer(peer_name, sin, 0);
06290 }
06291 }
06292 if (inaddrcmp(&p->addr, sin)) {
06293 if (iax2_regfunk)
06294 iax2_regfunk(p->name, 1);
06295
06296 memcpy(&p->addr, sin, sizeof(p->addr));
06297 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
06298 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
06299 ast_db_put("IAX/Registry", p->name, data);
06300 if (option_verbose > 2)
06301 ast_verbose(VERBOSE_PREFIX_3 "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
06302 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
06303 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
06304 register_peer_exten(p, 1);
06305 ast_device_state_changed("IAX2/%s", p->name);
06306 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
06307 if (option_verbose > 2)
06308 ast_verbose(VERBOSE_PREFIX_3 "Unregistered IAX2 '%s' (%s)\n", p->name,
06309 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
06310 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
06311 register_peer_exten(p, 0);
06312 ast_db_del("IAX/Registry", p->name);
06313 ast_device_state_changed("IAX2/%s", p->name);
06314 }
06315
06316
06317 iax2_poke_peer(p, callno);
06318 }
06319
06320
06321 if (!iaxs[callno]) {
06322 res = -1;
06323 goto return_unref;
06324 }
06325
06326
06327 p->sockfd = fd;
06328
06329 if (p->expire > -1) {
06330 if (!ast_sched_del(sched, p->expire)) {
06331 p->expire = -1;
06332 peer_unref(p);
06333 }
06334 }
06335
06336 if (!refresh)
06337 refresh = min_reg_expire;
06338 if (refresh > max_reg_expire) {
06339 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
06340 p->name, max_reg_expire, refresh);
06341 p->expiry = max_reg_expire;
06342 } else if (refresh < min_reg_expire) {
06343 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
06344 p->name, min_reg_expire, refresh);
06345 p->expiry = min_reg_expire;
06346 } else {
06347 p->expiry = refresh;
06348 }
06349 if (p->expiry && sin->sin_addr.s_addr) {
06350 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
06351 if (p->expire == -1)
06352 peer_unref(p);
06353 }
06354 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
06355 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
06356 if (sin->sin_addr.s_addr) {
06357 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
06358 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
06359 if (!ast_strlen_zero(p->mailbox)) {
06360 int new, old;
06361 ast_app_inboxcount(p->mailbox, &new, &old);
06362 if (new > 255)
06363 new = 255;
06364 if (old > 255)
06365 old = 255;
06366 msgcount = (old << 8) | new;
06367 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
06368 }
06369 if (ast_test_flag(p, IAX_HASCALLERID)) {
06370 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
06371 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
06372 }
06373 }
06374 version = iax_check_version(devtype);
06375 if (version)
06376 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
06377
06378 res = 0;
06379
06380 return_unref:
06381 peer_unref(p);
06382
06383 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
06384 }
06385
06386 static int registry_authrequest(int callno)
06387 {
06388 struct iax_ie_data ied;
06389 struct iax2_peer *p;
06390 char challenge[10];
06391 const char *peer_name;
06392 int res = -1;
06393
06394 peer_name = ast_strdupa(iaxs[callno]->peer);
06395
06396
06397 ast_mutex_unlock(&iaxsl[callno]);
06398 p = find_peer(peer_name, 1);
06399 ast_mutex_lock(&iaxsl[callno]);
06400 if (!iaxs[callno])
06401 goto return_unref;
06402 if (!p) {
06403 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
06404 goto return_unref;
06405 }
06406
06407 memset(&ied, 0, sizeof(ied));
06408 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
06409 if (p->authmethods & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
06410
06411 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
06412 ast_string_field_set(iaxs[callno], challenge, challenge);
06413 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
06414 }
06415 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
06416
06417 res = 0;
06418
06419 return_unref:
06420 peer_unref(p);
06421
06422 return res ? res : send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1);;
06423 }
06424
06425 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
06426 {
06427 struct iax2_registry *reg;
06428
06429 struct iax_ie_data ied;
06430 char peer[256] = "";
06431 char challenge[256] = "";
06432 int res;
06433 int authmethods = 0;
06434 if (ies->authmethods)
06435 authmethods = ies->authmethods;
06436 if (ies->username)
06437 ast_copy_string(peer, ies->username, sizeof(peer));
06438 if (ies->challenge)
06439 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
06440 memset(&ied, 0, sizeof(ied));
06441 reg = iaxs[callno]->reg;
06442 if (reg) {
06443 if (inaddrcmp(®->addr, sin)) {
06444 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
06445 return -1;
06446 }
06447 if (ast_strlen_zero(reg->secret)) {
06448 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
06449 reg->regstate = REG_STATE_NOAUTH;
06450 return -1;
06451 }
06452 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
06453 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
06454 if (reg->secret[0] == '[') {
06455 char tmpkey[256];
06456 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
06457 tmpkey[strlen(tmpkey) - 1] = '\0';
06458 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL, NULL);
06459 } else
06460 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL, NULL);
06461 if (!res) {
06462 reg->regstate = REG_STATE_AUTHSENT;
06463 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
06464 } else
06465 return -1;
06466 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
06467 } else
06468 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
06469 return -1;
06470 }
06471
06472 static void stop_stuff(int callno)
06473 {
06474 iax2_destroy_helper(iaxs[callno]);
06475 }
06476
06477 static void __auth_reject(const void *nothing)
06478 {
06479
06480 int callno = (int)(long)(nothing);
06481 struct iax_ie_data ied;
06482 ast_mutex_lock(&iaxsl[callno]);
06483 if (iaxs[callno]) {
06484 memset(&ied, 0, sizeof(ied));
06485 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
06486 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
06487 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
06488 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
06489 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
06490 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
06491 }
06492 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
06493 }
06494 ast_mutex_unlock(&iaxsl[callno]);
06495 }
06496
06497 static int auth_reject(const void *data)
06498 {
06499 int callno = (int)(long)(data);
06500 ast_mutex_lock(&iaxsl[callno]);
06501 if (iaxs[callno])
06502 iaxs[callno]->authid = -1;
06503 ast_mutex_unlock(&iaxsl[callno]);
06504 #ifdef SCHED_MULTITHREADED
06505 if (schedule_action(__auth_reject, data))
06506 #endif
06507 __auth_reject(data);
06508 return 0;
06509 }
06510
06511 static int auth_fail(int callno, int failcode)
06512 {
06513
06514
06515 if (iaxs[callno]) {
06516 iaxs[callno]->authfail = failcode;
06517 if (delayreject) {
06518 AST_SCHED_DEL(sched, iaxs[callno]->authid);
06519 iaxs[callno]->authid = iax2_sched_add(sched, 1000, auth_reject, (void *)(long)callno);
06520 } else
06521 auth_reject((void *)(long)callno);
06522 }
06523 return 0;
06524 }
06525
06526 static void __auto_hangup(const void *nothing)
06527 {
06528
06529 int callno = (int)(long)(nothing);
06530 struct iax_ie_data ied;
06531 ast_mutex_lock(&iaxsl[callno]);
06532 if (iaxs[callno]) {
06533 memset(&ied, 0, sizeof(ied));
06534 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
06535 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
06536 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
06537 }
06538 ast_mutex_unlock(&iaxsl[callno]);
06539 }
06540
06541 static int auto_hangup(const void *data)
06542 {
06543 int callno = (int)(long)(data);
06544 ast_mutex_lock(&iaxsl[callno]);
06545 if (iaxs[callno]) {
06546 iaxs[callno]->autoid = -1;
06547 }
06548 ast_mutex_unlock(&iaxsl[callno]);
06549 #ifdef SCHED_MULTITHREADED
06550 if (schedule_action(__auto_hangup, data))
06551 #endif
06552 __auto_hangup(data);
06553 return 0;
06554 }
06555
06556 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
06557 {
06558 struct iax_ie_data ied;
06559
06560 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
06561 iaxs[callno]->autoid = iax2_sched_add(sched, 30000, auto_hangup, (void *)(long)callno);
06562 memset(&ied, 0, sizeof(ied));
06563 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
06564 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
06565 dp->flags |= CACHE_FLAG_TRANSMITTED;
06566 }
06567
06568 static int iax2_vnak(int callno)
06569 {
06570 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
06571 }
06572
06573 static void vnak_retransmit(int callno, int last)
06574 {
06575 struct iax_frame *f;
06576
06577 AST_LIST_LOCK(&iaxq.queue);
06578 AST_LIST_TRAVERSE(&iaxq.queue, f, list) {
06579
06580 if ((f->callno == callno) && iaxs[f->callno] &&
06581 ((unsigned char ) (f->oseqno - last) < 128) &&
06582 (f->retries >= 0)) {
06583 send_packet(f);
06584 }
06585 }
06586 AST_LIST_UNLOCK(&iaxq.queue);
06587 }
06588
06589 static void __iax2_poke_peer_s(const void *data)
06590 {
06591 struct iax2_peer *peer = (struct iax2_peer *)data;
06592 iax2_poke_peer(peer, 0);
06593 peer_unref(peer);
06594 }
06595
06596 static int iax2_poke_peer_s(const void *data)
06597 {
06598 struct iax2_peer *peer = (struct iax2_peer *)data;
06599 peer->pokeexpire = -1;
06600 #ifdef SCHED_MULTITHREADED
06601 if (schedule_action(__iax2_poke_peer_s, data))
06602 #endif
06603 __iax2_poke_peer_s(data);
06604 return 0;
06605 }
06606
06607 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
06608 {
06609 int res = 0;
06610 struct iax_frame *fr;
06611 struct ast_iax2_meta_hdr *meta;
06612 struct ast_iax2_meta_trunk_hdr *mth;
06613 int calls = 0;
06614
06615
06616 fr = (struct iax_frame *)tpeer->trunkdata;
06617
06618 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
06619 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
06620 if (tpeer->trunkdatalen) {
06621
06622 meta->zeros = 0;
06623 meta->metacmd = IAX_META_TRUNK;
06624 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
06625 meta->cmddata = IAX_META_TRUNK_MINI;
06626 else
06627 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
06628 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
06629
06630 fr->direction = DIRECTION_OUTGRESS;
06631 fr->retrans = -1;
06632 fr->transfer = 0;
06633
06634 fr->data = fr->afdata;
06635 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
06636 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
06637 calls = tpeer->calls;
06638 #if 0
06639 if (option_debug)
06640 ast_log(LOG_DEBUG, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
06641 #endif
06642
06643 tpeer->trunkdatalen = 0;
06644 tpeer->calls = 0;
06645 }
06646 if (res < 0)
06647 return res;
06648 return calls;
06649 }
06650
06651 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
06652 {
06653
06654 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
06655 return 1;
06656 return 0;
06657 }
06658
06659 static int timing_read(int *id, int fd, short events, void *cbdata)
06660 {
06661 char buf[1024];
06662 int res;
06663 struct iax2_trunk_peer *tpeer, *prev = NULL, *drop=NULL;
06664 int processed = 0;
06665 int totalcalls = 0;
06666 #ifdef DAHDI_TIMERACK
06667 int x = 1;
06668 #endif
06669 struct timeval now;
06670 if (iaxtrunkdebug)
06671 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", MAX_TRUNKDATA);
06672 gettimeofday(&now, NULL);
06673 if (events & AST_IO_PRI) {
06674 #ifdef DAHDI_TIMERACK
06675
06676 if (ioctl(fd, DAHDI_TIMERACK, &x)) {
06677 ast_log(LOG_WARNING, "Unable to acknowledge timer. IAX trunking will fail!\n");
06678 usleep(1);
06679 return -1;
06680 }
06681 #endif
06682 } else {
06683
06684 res = read(fd, buf, sizeof(buf));
06685 if (res < 1) {
06686 ast_log(LOG_WARNING, "Unable to read from timing fd\n");
06687 return 1;
06688 }
06689 }
06690
06691 ast_mutex_lock(&tpeerlock);
06692 tpeer = tpeers;
06693 while(tpeer) {
06694 processed++;
06695 res = 0;
06696 ast_mutex_lock(&tpeer->lock);
06697
06698
06699 if (!drop && iax2_trunk_expired(tpeer, &now)) {
06700
06701
06702 if (prev)
06703 prev->next = tpeer->next;
06704 else
06705 tpeers = tpeer->next;
06706 drop = tpeer;
06707 } else {
06708 res = send_trunk(tpeer, &now);
06709 if (iaxtrunkdebug)
06710 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);
06711 }
06712 totalcalls += res;
06713 res = 0;
06714 ast_mutex_unlock(&tpeer->lock);
06715 prev = tpeer;
06716 tpeer = tpeer->next;
06717 }
06718 ast_mutex_unlock(&tpeerlock);
06719 if (drop) {
06720 ast_mutex_lock(&drop->lock);
06721
06722
06723 if (option_debug)
06724 ast_log(LOG_DEBUG, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
06725 if (drop->trunkdata) {
06726 free(drop->trunkdata);
06727 drop->trunkdata = NULL;
06728 }
06729 ast_mutex_unlock(&drop->lock);
06730 ast_mutex_destroy(&drop->lock);
06731 free(drop);
06732
06733 }
06734 if (iaxtrunkdebug)
06735 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
06736 iaxtrunkdebug =0;
06737 return 1;
06738 }
06739
06740 struct dpreq_data {
06741 int callno;
06742 char context[AST_MAX_EXTENSION];
06743 char callednum[AST_MAX_EXTENSION];
06744 char *callerid;
06745 };
06746
06747 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
06748 {
06749 unsigned short dpstatus = 0;
06750 struct iax_ie_data ied1;
06751 int mm;
06752
06753 memset(&ied1, 0, sizeof(ied1));
06754 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
06755
06756 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
06757 dpstatus = IAX_DPSTATUS_EXISTS;
06758 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
06759 dpstatus = IAX_DPSTATUS_CANEXIST;
06760 } else {
06761 dpstatus = IAX_DPSTATUS_NONEXISTENT;
06762 }
06763 if (ast_ignore_pattern(context, callednum))
06764 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
06765 if (mm)
06766 dpstatus |= IAX_DPSTATUS_MATCHMORE;
06767 if (!skiplock)
06768 ast_mutex_lock(&iaxsl[callno]);
06769 if (iaxs[callno]) {
06770 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
06771 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
06772 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
06773 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
06774 }
06775 if (!skiplock)
06776 ast_mutex_unlock(&iaxsl[callno]);
06777 }
06778
06779 static void *dp_lookup_thread(void *data)
06780 {
06781
06782 struct dpreq_data *dpr = data;
06783 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
06784 if (dpr->callerid)
06785 free(dpr->callerid);
06786 free(dpr);
06787 return NULL;
06788 }
06789
06790 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
06791 {
06792 pthread_t newthread;
06793 struct dpreq_data *dpr;
06794 pthread_attr_t attr;
06795
06796 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
06797 return;
06798
06799 pthread_attr_init(&attr);
06800 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
06801
06802 dpr->callno = callno;
06803 ast_copy_string(dpr->context, context, sizeof(dpr->context));
06804 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
06805 if (callerid)
06806 dpr->callerid = ast_strdup(callerid);
06807 if (ast_pthread_create(&newthread, &attr, dp_lookup_thread, dpr)) {
06808 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
06809 }
06810
06811 pthread_attr_destroy(&attr);
06812 }
06813
06814 struct iax_dual {
06815 struct ast_channel *chan1;
06816 struct ast_channel *chan2;
06817 };
06818
06819 static void *iax_park_thread(void *stuff)
06820 {
06821 struct ast_channel *chan1, *chan2;
06822 struct iax_dual *d;
06823 struct ast_frame *f;
06824 int ext;
06825 int res;
06826 d = stuff;
06827 chan1 = d->chan1;
06828 chan2 = d->chan2;
06829 free(d);
06830 f = ast_read(chan1);
06831 if (f)
06832 ast_frfree(f);
06833 res = ast_park_call(chan1, chan2, 0, &ext);
06834 ast_hangup(chan2);
06835 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
06836 return NULL;
06837 }
06838
06839 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
06840 {
06841 struct iax_dual *d;
06842 struct ast_channel *chan1m, *chan2m;
06843 pthread_t th;
06844 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
06845 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
06846 if (chan2m && chan1m) {
06847
06848 chan1m->readformat = chan1->readformat;
06849 chan1m->writeformat = chan1->writeformat;
06850 ast_channel_masquerade(chan1m, chan1);
06851
06852 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
06853 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
06854 chan1m->priority = chan1->priority;
06855
06856
06857
06858
06859 chan2m->readformat = chan2->readformat;
06860 chan2m->writeformat = chan2->writeformat;
06861 ast_channel_masquerade(chan2m, chan2);
06862
06863 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
06864 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
06865 chan2m->priority = chan2->priority;
06866 if (ast_do_masquerade(chan2m)) {
06867 ast_log(LOG_WARNING, "Masquerade failed :(\n");
06868 ast_hangup(chan2m);
06869 return -1;
06870 }
06871 } else {
06872 if (chan1m)
06873 ast_hangup(chan1m);
06874 if (chan2m)
06875 ast_hangup(chan2m);
06876 return -1;
06877 }
06878 if ((d = ast_calloc(1, sizeof(*d)))) {
06879 pthread_attr_t attr;
06880
06881 pthread_attr_init(&attr);
06882 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
06883
06884 d->chan1 = chan1m;
06885 d->chan2 = chan2m;
06886 if (!ast_pthread_create_background(&th, &attr, iax_park_thread, d)) {
06887 pthread_attr_destroy(&attr);
06888 return 0;
06889 }
06890 pthread_attr_destroy(&attr);
06891 free(d);
06892 }
06893 return -1;
06894 }
06895
06896
06897 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
06898
06899 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
06900 {
06901 unsigned int ourver;
06902 char rsi[80];
06903 snprintf(rsi, sizeof(rsi), "si-%s", si);
06904 if (iax_provision_version(&ourver, rsi, 1))
06905 return 0;
06906 if (option_debug)
06907 ast_log(LOG_DEBUG, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
06908 if (ourver != ver)
06909 iax2_provision(sin, sockfd, NULL, rsi, 1);
06910 return 0;
06911 }
06912
06913 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
06914 {
06915 jb_info stats;
06916 jb_getinfo(pvt->jb, &stats);
06917
06918 memset(iep, 0, sizeof(*iep));
06919
06920 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
06921 if(stats.frames_in == 0) stats.frames_in = 1;
06922 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
06923 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
06924 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
06925 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
06926 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
06927 }
06928
06929 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
06930 {
06931 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
06932 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
06933 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
06934 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
06935 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
06936 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
06937 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
06938 }
06939
06940 static int socket_process(struct iax2_thread *thread);
06941
06942
06943
06944
06945 static void handle_deferred_full_frames(struct iax2_thread *thread)
06946 {
06947 struct iax2_pkt_buf *pkt_buf;
06948
06949 ast_mutex_lock(&thread->lock);
06950
06951 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
06952 ast_mutex_unlock(&thread->lock);
06953
06954 thread->buf = pkt_buf->buf;
06955 thread->buf_len = pkt_buf->len;
06956 thread->buf_size = pkt_buf->len + 1;
06957
06958 socket_process(thread);
06959
06960 thread->buf = NULL;
06961 ast_free(pkt_buf);
06962
06963 ast_mutex_lock(&thread->lock);
06964 }
06965
06966 ast_mutex_unlock(&thread->lock);
06967 }
06968
06969
06970
06971
06972
06973
06974
06975 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
06976 {
06977 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
06978 struct ast_iax2_full_hdr *fh, *cur_fh;
06979
06980 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
06981 return;
06982
06983 pkt_buf->len = from_here->buf_len;
06984 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
06985
06986 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
06987 ast_mutex_lock(&to_here->lock);
06988 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
06989 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
06990 if (fh->oseqno < cur_fh->oseqno) {
06991 AST_LIST_INSERT_BEFORE_CURRENT(&to_here->full_frames, pkt_buf, entry);
06992 break;
06993 }
06994 }
06995 AST_LIST_TRAVERSE_SAFE_END
06996
06997 if (!cur_pkt_buf)
06998 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
06999
07000 ast_mutex_unlock(&to_here->lock);
07001 }
07002
07003 static int socket_read(int *id, int fd, short events, void *cbdata)
07004 {
07005 struct iax2_thread *thread;
07006 socklen_t len;
07007 time_t t;
07008 static time_t last_errtime = 0;
07009 struct ast_iax2_full_hdr *fh;
07010
07011 if (!(thread = find_idle_thread())) {
07012 time(&t);
07013 if (t != last_errtime && option_debug)
07014 ast_log(LOG_DEBUG, "Out of idle IAX2 threads for I/O, pausing!\n");
07015 last_errtime = t;
07016 usleep(1);
07017 return 1;
07018 }
07019
07020 len = sizeof(thread->iosin);
07021 thread->iofd = fd;
07022 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
07023 thread->buf_size = sizeof(thread->readbuf);
07024 thread->buf = thread->readbuf;
07025 if (thread->buf_len < 0) {
07026 if (errno != ECONNREFUSED && errno != EAGAIN)
07027 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
07028 handle_error();
07029 thread->iostate = IAX_IOSTATE_IDLE;
07030 signal_condition(&thread->lock, &thread->cond);
07031 return 1;
07032 }
07033 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) {
07034 thread->iostate = IAX_IOSTATE_IDLE;
07035 signal_condition(&thread->lock, &thread->cond);
07036 return 1;
07037 }
07038
07039
07040
07041
07042 fh = (struct ast_iax2_full_hdr *) thread->buf;
07043 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
07044 struct iax2_thread *cur = NULL;
07045 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
07046
07047 AST_LIST_LOCK(&active_list);
07048 AST_LIST_TRAVERSE(&active_list, cur, list) {
07049 if ((cur->ffinfo.callno == callno) &&
07050 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
07051 break;
07052 }
07053 if (cur) {
07054
07055
07056 defer_full_frame(thread, cur);
07057 AST_LIST_UNLOCK(&active_list);
07058 thread->iostate = IAX_IOSTATE_IDLE;
07059 signal_condition(&thread->lock, &thread->cond);
07060 return 1;
07061 } else {
07062
07063 thread->ffinfo.callno = callno;
07064 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
07065 thread->ffinfo.type = fh->type;
07066 thread->ffinfo.csub = fh->csub;
07067 }
07068 AST_LIST_UNLOCK(&active_list);
07069 }
07070
07071
07072 thread->iostate = IAX_IOSTATE_READY;
07073 #ifdef DEBUG_SCHED_MULTITHREAD
07074 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
07075 #endif
07076 signal_condition(&thread->lock, &thread->cond);
07077
07078 return 1;
07079 }
07080
07081 static int socket_process(struct iax2_thread *thread)
07082 {
07083 struct sockaddr_in sin;
07084 int res;
07085 int updatehistory=1;
07086 int new = NEW_PREVENT;
07087 void *ptr;
07088 int dcallno = 0;
07089 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
07090 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
07091 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
07092 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
07093 struct ast_iax2_meta_trunk_hdr *mth;
07094 struct ast_iax2_meta_trunk_entry *mte;
07095 struct ast_iax2_meta_trunk_mini *mtm;
07096 struct iax_frame *fr;
07097 struct iax_frame *cur;
07098 struct ast_frame f = { 0, };
07099 struct ast_channel *c;
07100 struct iax2_dpcache *dp;
07101 struct iax2_peer *peer;
07102 struct iax2_trunk_peer *tpeer;
07103 struct timeval rxtrunktime;
07104 struct iax_ies ies;
07105 struct iax_ie_data ied0, ied1;
07106 int format;
07107 int fd;
07108 int exists;
07109 int minivid = 0;
07110 unsigned int ts;
07111 char empty[32]="";
07112 struct iax_frame *duped_fr;
07113 char host_pref_buf[128];
07114 char caller_pref_buf[128];
07115 struct ast_codec_pref pref;
07116 char *using_prefs = "mine";
07117
07118
07119 fr = alloca(sizeof(*fr) + 4096);
07120 memset(fr, 0, sizeof(*fr));
07121 fr->afdatalen = 4096;
07122
07123
07124 res = thread->buf_len;
07125 fd = thread->iofd;
07126 memcpy(&sin, &thread->iosin, sizeof(sin));
07127
07128 if (res < sizeof(*mh)) {
07129 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*mh));
07130 return 1;
07131 }
07132 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
07133 if (res < sizeof(*vh)) {
07134 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));
07135 return 1;
07136 }
07137
07138
07139 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
07140 minivid = 1;
07141 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000)) {
07142 unsigned char metatype;
07143
07144 if (res < sizeof(*meta)) {
07145 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07146 return 1;
07147 }
07148
07149
07150 switch(meta->metacmd) {
07151 case IAX_META_TRUNK:
07152 if (res < (sizeof(*meta) + sizeof(*mth))) {
07153 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %zd min)\n", res,
07154 sizeof(*meta) + sizeof(*mth));
07155 return 1;
07156 }
07157 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
07158 ts = ntohl(mth->ts);
07159 metatype = meta->cmddata;
07160 res -= (sizeof(*meta) + sizeof(*mth));
07161 ptr = mth->data;
07162 tpeer = find_tpeer(&sin, fd);
07163 if (!tpeer) {
07164 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07165 return 1;
07166 }
07167 tpeer->trunkact = ast_tvnow();
07168 if (!ts || ast_tvzero(tpeer->rxtrunktime))
07169 tpeer->rxtrunktime = tpeer->trunkact;
07170 rxtrunktime = tpeer->rxtrunktime;
07171 ast_mutex_unlock(&tpeer->lock);
07172 while(res >= sizeof(*mte)) {
07173
07174 unsigned short callno, trunked_ts, len;
07175
07176 if (metatype == IAX_META_TRUNK_MINI) {
07177 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
07178 ptr += sizeof(*mtm);
07179 res -= sizeof(*mtm);
07180 len = ntohs(mtm->len);
07181 callno = ntohs(mtm->mini.callno);
07182 trunked_ts = ntohs(mtm->mini.ts);
07183 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
07184 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
07185 ptr += sizeof(*mte);
07186 res -= sizeof(*mte);
07187 len = ntohs(mte->len);
07188 callno = ntohs(mte->callno);
07189 trunked_ts = 0;
07190 } else {
07191 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07192 break;
07193 }
07194
07195 if (len > res)
07196 break;
07197 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, &sin, NEW_PREVENT, fd, 0);
07198 if (fr->callno) {
07199
07200
07201
07202 memset(&f, 0, sizeof(f));
07203 f.frametype = AST_FRAME_VOICE;
07204 if (iaxs[fr->callno]) {
07205 if (iaxs[fr->callno]->voiceformat > 0) {
07206 f.subclass = iaxs[fr->callno]->voiceformat;
07207 f.datalen = len;
07208 if (f.datalen >= 0) {
07209 if (f.datalen)
07210 f.data = ptr;
07211 if(trunked_ts) {
07212 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
07213 } else
07214 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
07215
07216 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
07217
07218 f.src = "IAX2";
07219 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
07220 f.samples = ast_codec_get_samples(&f);
07221 iax_frame_wrap(fr, &f);
07222 duped_fr = iaxfrdup2(fr);
07223 if (duped_fr) {
07224 schedule_delivery(duped_fr, updatehistory, 1, &fr->ts);
07225 }
07226
07227 if (fr && fr->callno && iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
07228 iaxs[fr->callno]->last = fr->ts;
07229 #if 1
07230 if (option_debug && iaxdebug)
07231 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
07232 #endif
07233 }
07234 }
07235 } else {
07236 ast_log(LOG_WARNING, "Datalen < 0?\n");
07237 }
07238 } else {
07239 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
07240 iax2_vnak(fr->callno);
07241 }
07242 }
07243 ast_mutex_unlock(&iaxsl[fr->callno]);
07244 }
07245 ptr += len;
07246 res -= len;
07247 }
07248
07249 }
07250 return 1;
07251 }
07252
07253 #ifdef DEBUG_SUPPORT
07254 if (iaxdebug && (res >= sizeof(*fh)))
07255 iax_showframe(NULL, fh, 1, &sin, res - sizeof(*fh));
07256 #endif
07257 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
07258 if (res < sizeof(*fh)) {
07259 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));
07260 return 1;
07261 }
07262
07263
07264 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
07265
07266 f.frametype = fh->type;
07267 if (f.frametype == AST_FRAME_VIDEO) {
07268 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
07269 } else {
07270 f.subclass = uncompress_subclass(fh->csub);
07271 }
07272
07273
07274 if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_POKE) {
07275
07276 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohs(fh->ts), fh->iseqno + 1);
07277 return 1;
07278 } else if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_ACK && dcallno == 1) {
07279
07280 return 1;
07281 }
07282
07283 if ((f.frametype == AST_FRAME_IAX) && ((f.subclass == IAX_COMMAND_NEW) || (f.subclass == IAX_COMMAND_REGREQ) ||
07284 (f.subclass == IAX_COMMAND_POKE) || (f.subclass == IAX_COMMAND_FWDOWNL) ||
07285 (f.subclass == IAX_COMMAND_REGREL)))
07286 new = NEW_ALLOW;
07287 } else {
07288
07289 f.frametype = AST_FRAME_NULL;
07290 f.subclass = 0;
07291 }
07292
07293 if (!fr->callno) {
07294 int check_dcallno = 0;
07295
07296
07297
07298
07299
07300
07301
07302
07303
07304
07305
07306
07307
07308 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
07309 check_dcallno = f.frametype == AST_FRAME_IAX ? (f.subclass != IAX_COMMAND_PING && f.subclass != IAX_COMMAND_LAGRQ) : 1;
07310 }
07311
07312 fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno);
07313 }
07314
07315 if (fr->callno > 0)
07316 ast_mutex_lock(&iaxsl[fr->callno]);
07317
07318 if (!fr->callno || !iaxs[fr->callno]) {
07319
07320
07321 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
07322
07323 if (((f.subclass != IAX_COMMAND_INVAL) &&
07324 (f.subclass != IAX_COMMAND_TXCNT) &&
07325 (f.subclass != IAX_COMMAND_TXACC) &&
07326 (f.subclass != IAX_COMMAND_FWDOWNL))||
07327 (f.frametype != AST_FRAME_IAX))
07328 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
07329 fd);
07330 }
07331 if (fr->callno > 0)
07332 ast_mutex_unlock(&iaxsl[fr->callno]);
07333 return 1;
07334 }
07335 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
07336 if (decrypt_frame(fr->callno, fh, &f, &res)) {
07337 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
07338 ast_mutex_unlock(&iaxsl[fr->callno]);
07339 return 1;
07340 }
07341 #ifdef DEBUG_SUPPORT
07342 else if (iaxdebug)
07343 iax_showframe(NULL, fh, 3, &sin, res - sizeof(*fh));
07344 #endif
07345 }
07346
07347
07348 iaxs[fr->callno]->frames_received++;
07349
07350 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
07351 f.subclass != IAX_COMMAND_TXCNT &&
07352 f.subclass != IAX_COMMAND_TXACC) {
07353 unsigned short new_peercallno;
07354
07355 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
07356 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
07357 if (iaxs[fr->callno]->peercallno) {
07358 remove_by_peercallno(iaxs[fr->callno]);
07359 }
07360 iaxs[fr->callno]->peercallno = new_peercallno;
07361 store_by_peercallno(iaxs[fr->callno]);
07362 }
07363 }
07364 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
07365 if (option_debug && iaxdebug)
07366 ast_log(LOG_DEBUG, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
07367
07368 fr->oseqno = fh->oseqno;
07369 fr->iseqno = fh->iseqno;
07370 fr->ts = ntohl(fh->ts);
07371 #ifdef IAXTESTS
07372 if (test_resync) {
07373 if (option_debug)
07374 ast_log(LOG_DEBUG, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
07375 fr->ts += test_resync;
07376 }
07377 #endif
07378 #if 0
07379 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
07380 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
07381 (f.subclass == IAX_COMMAND_NEW ||
07382 f.subclass == IAX_COMMAND_AUTHREQ ||
07383 f.subclass == IAX_COMMAND_ACCEPT ||
07384 f.subclass == IAX_COMMAND_REJECT)) ) )
07385 #endif
07386 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
07387 updatehistory = 0;
07388 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
07389 (iaxs[fr->callno]->iseqno ||
07390 ((f.subclass != IAX_COMMAND_TXCNT) &&
07391 (f.subclass != IAX_COMMAND_TXREADY) &&
07392 (f.subclass != IAX_COMMAND_TXREL) &&
07393 (f.subclass != IAX_COMMAND_UNQUELCH ) &&
07394 (f.subclass != IAX_COMMAND_TXACC)) ||
07395 (f.frametype != AST_FRAME_IAX))) {
07396 if (
07397 ((f.subclass != IAX_COMMAND_ACK) &&
07398 (f.subclass != IAX_COMMAND_INVAL) &&
07399 (f.subclass != IAX_COMMAND_TXCNT) &&
07400 (f.subclass != IAX_COMMAND_TXREADY) &&
07401 (f.subclass != IAX_COMMAND_TXREL) &&
07402 (f.subclass != IAX_COMMAND_UNQUELCH ) &&
07403 (f.subclass != IAX_COMMAND_TXACC) &&
07404 (f.subclass != IAX_COMMAND_VNAK)) ||
07405 (f.frametype != AST_FRAME_IAX)) {
07406
07407 if (option_debug)
07408 ast_log(LOG_DEBUG, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
07409 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
07410
07411
07412 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
07413
07414 if ((f.frametype != AST_FRAME_IAX) ||
07415 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
07416 if (option_debug)
07417 ast_log(LOG_DEBUG, "Acking anyway\n");
07418
07419
07420 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
07421 }
07422 } else {
07423
07424 iax2_vnak(fr->callno);
07425 }
07426 ast_mutex_unlock(&iaxsl[fr->callno]);
07427 return 1;
07428 }
07429 } else {
07430
07431 if (((f.subclass != IAX_COMMAND_ACK) &&
07432 (f.subclass != IAX_COMMAND_INVAL) &&
07433 (f.subclass != IAX_COMMAND_TXCNT) &&
07434 (f.subclass != IAX_COMMAND_TXACC) &&
07435 (f.subclass != IAX_COMMAND_VNAK)) ||
07436 (f.frametype != AST_FRAME_IAX))
07437 iaxs[fr->callno]->iseqno++;
07438 }
07439
07440 if (res < sizeof(*fh)) {
07441 ast_log(LOG_WARNING, "midget packet received (%d of %zd min)\n", res, sizeof(*fh));
07442 ast_mutex_unlock(&iaxsl[fr->callno]);
07443 return 1;
07444 }
07445
07446 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
07447 if (res < thread->buf_size)
07448 thread->buf[res++] = '\0';
07449 else
07450 thread->buf[res - 1] = '\0';
07451 }
07452 f.datalen = res - sizeof(*fh);
07453
07454
07455
07456 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
07457 ((f.subclass != IAX_COMMAND_INVAL) ||
07458 (f.frametype != AST_FRAME_IAX))) {
07459 unsigned char x;
07460 int call_to_destroy;
07461
07462
07463
07464 for (x=iaxs[fr->callno]->rseqno; x != iaxs[fr->callno]->oseqno; x++)
07465 if (fr->iseqno == x)
07466 break;
07467 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
07468
07469
07470 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
07471
07472 if (option_debug && iaxdebug)
07473 ast_log(LOG_DEBUG, "Cancelling transmission of packet %d\n", x);
07474 call_to_destroy = 0;
07475 AST_LIST_LOCK(&iaxq.queue);
07476 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
07477
07478 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
07479 cur->retries = -1;
07480
07481 if (cur->final)
07482 call_to_destroy = fr->callno;
07483 }
07484 }
07485 AST_LIST_UNLOCK(&iaxq.queue);
07486 if (call_to_destroy) {
07487 if (iaxdebug && option_debug)
07488 ast_log(LOG_DEBUG, "Really destroying %d, having been acked on final message\n", call_to_destroy);
07489 ast_mutex_lock(&iaxsl[call_to_destroy]);
07490 iax2_destroy(call_to_destroy);
07491 ast_mutex_unlock(&iaxsl[call_to_destroy]);
07492 }
07493 }
07494
07495 if (iaxs[fr->callno])
07496 iaxs[fr->callno]->rseqno = fr->iseqno;
07497 else {
07498
07499 ast_mutex_unlock(&iaxsl[fr->callno]);
07500 return 1;
07501 }
07502 } else if (option_debug)
07503 ast_log(LOG_DEBUG, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
07504 }
07505 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
07506 ((f.frametype != AST_FRAME_IAX) ||
07507 ((f.subclass != IAX_COMMAND_TXACC) &&
07508 (f.subclass != IAX_COMMAND_TXCNT)))) {
07509
07510 ast_mutex_unlock(&iaxsl[fr->callno]);
07511 return 1;
07512 }
07513
07514 if (f.datalen) {
07515 if (f.frametype == AST_FRAME_IAX) {
07516 if (iax_parse_ies(&ies, thread->buf + sizeof(*fh), f.datalen)) {
07517 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
07518 ast_mutex_unlock(&iaxsl[fr->callno]);
07519 return 1;
07520 }
07521 f.data = NULL;
07522 f.datalen = 0;
07523 } else
07524 f.data = thread->buf + sizeof(*fh);
07525 } else {
07526 if (f.frametype == AST_FRAME_IAX)
07527 f.data = NULL;
07528 else
07529 f.data = empty;
07530 memset(&ies, 0, sizeof(ies));
07531 }
07532
07533
07534
07535
07536 if ((f.frametype == AST_FRAME_VOICE) ||
07537 (f.frametype == AST_FRAME_VIDEO) ||
07538 (f.frametype == AST_FRAME_IAX)) {
07539 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
07540 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
07541 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
07542 ast_mutex_unlock(&iaxsl[fr->callno]);
07543 return 1;
07544 }
07545 }
07546 }
07547
07548 if (f.frametype == AST_FRAME_VOICE) {
07549 if (f.subclass != iaxs[fr->callno]->voiceformat) {
07550 iaxs[fr->callno]->voiceformat = f.subclass;
07551 if (option_debug)
07552 ast_log(LOG_DEBUG, "Ooh, voice format changed to %d\n", f.subclass);
07553 if (iaxs[fr->callno]->owner) {
07554 int orignative;
07555 retryowner:
07556 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
07557 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
07558 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner;
07559 }
07560 if (iaxs[fr->callno]) {
07561 if (iaxs[fr->callno]->owner) {
07562 orignative = iaxs[fr->callno]->owner->nativeformats;
07563 iaxs[fr->callno]->owner->nativeformats = f.subclass;
07564 if (iaxs[fr->callno]->owner->readformat)
07565 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
07566 iaxs[fr->callno]->owner->nativeformats = orignative;
07567 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
07568 }
07569 } else {
07570 if (option_debug)
07571 ast_log(LOG_DEBUG, "Neat, somebody took away the channel at a magical time but i found it!\n");
07572 ast_mutex_unlock(&iaxsl[fr->callno]);
07573 return 1;
07574 }
07575 }
07576 }
07577 }
07578 if (f.frametype == AST_FRAME_VIDEO) {
07579 if (f.subclass != iaxs[fr->callno]->videoformat) {
07580 if (option_debug)
07581 ast_log(LOG_DEBUG, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
07582 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
07583 }
07584 }
07585 if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
07586 if (f.subclass == AST_CONTROL_BUSY) {
07587 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
07588 } else if (f.subclass == AST_CONTROL_CONGESTION) {
07589 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
07590 }
07591 }
07592 if (f.frametype == AST_FRAME_IAX) {
07593 AST_SCHED_DEL(sched, iaxs[fr->callno]->initid);
07594
07595 if (option_debug && iaxdebug)
07596 ast_log(LOG_DEBUG, "IAX subclass %d received\n", f.subclass);
07597
07598
07599 if (iaxs[fr->callno]->last < fr->ts &&
07600 f.subclass != IAX_COMMAND_ACK &&
07601 f.subclass != IAX_COMMAND_PONG &&
07602 f.subclass != IAX_COMMAND_LAGRP) {
07603 iaxs[fr->callno]->last = fr->ts;
07604 if (option_debug && iaxdebug)
07605 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
07606 }
07607
07608 switch(f.subclass) {
07609 case IAX_COMMAND_ACK:
07610
07611 break;
07612 case IAX_COMMAND_QUELCH:
07613 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
07614
07615 if (iaxs[fr->callno]->owner) {
07616 manager_event(EVENT_FLAG_CALL, "Hold",
07617 "Channel: %s\r\n"
07618 "Uniqueid: %s\r\n",
07619 iaxs[fr->callno]->owner->name,
07620 iaxs[fr->callno]->owner->uniqueid);
07621 }
07622
07623 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
07624 if (ies.musiconhold) {
07625 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
07626 const char *mohsuggest = iaxs[fr->callno]->mohsuggest;
07627 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
07628 S_OR(mohsuggest, NULL),
07629 !ast_strlen_zero(mohsuggest) ? strlen(mohsuggest) + 1 : 0);
07630 if (!iaxs[fr->callno]) {
07631 ast_mutex_unlock(&iaxsl[fr->callno]);
07632 return 1;
07633 }
07634 }
07635 }
07636 }
07637 break;
07638 case IAX_COMMAND_UNQUELCH:
07639 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
07640
07641 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
07642 manager_event(EVENT_FLAG_CALL, "Unhold",
07643 "Channel: %s\r\n"
07644 "Uniqueid: %s\r\n",
07645 iaxs[fr->callno]->owner->name,
07646 iaxs[fr->callno]->owner->uniqueid);
07647 }
07648
07649 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
07650 if (iaxs[fr->callno]->owner && ast_bridged_channel(iaxs[fr->callno]->owner)) {
07651 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
07652 if (!iaxs[fr->callno]) {
07653 ast_mutex_unlock(&iaxsl[fr->callno]);
07654 return 1;
07655 }
07656 }
07657 }
07658 break;
07659 case IAX_COMMAND_TXACC:
07660 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
07661
07662 AST_LIST_LOCK(&iaxq.queue);
07663 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
07664
07665 if ((fr->callno == cur->callno) && (cur->transfer))
07666 cur->retries = -1;
07667 }
07668 AST_LIST_UNLOCK(&iaxq.queue);
07669 memset(&ied1, 0, sizeof(ied1));
07670 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
07671 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
07672 iaxs[fr->callno]->transferring = TRANSFER_READY;
07673 }
07674 break;
07675 case IAX_COMMAND_NEW:
07676
07677 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
07678 break;
07679 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
07680 ast_mutex_unlock(&iaxsl[fr->callno]);
07681 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
07682 ast_mutex_lock(&iaxsl[fr->callno]);
07683 if (!iaxs[fr->callno]) {
07684 ast_mutex_unlock(&iaxsl[fr->callno]);
07685 return 1;
07686 }
07687 }
07688
07689 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
07690 int new_callno;
07691 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
07692 fr->callno = new_callno;
07693 }
07694
07695 if (delayreject)
07696 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
07697 if (check_access(fr->callno, &sin, &ies)) {
07698
07699 auth_fail(fr->callno, IAX_COMMAND_REJECT);
07700 if (authdebug)
07701 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);
07702 break;
07703 }
07704 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
07705 const char *context, *exten, *cid_num;
07706
07707 context = ast_strdupa(iaxs[fr->callno]->context);
07708 exten = ast_strdupa(iaxs[fr->callno]->exten);
07709 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
07710
07711
07712 ast_mutex_unlock(&iaxsl[fr->callno]);
07713 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
07714 ast_mutex_lock(&iaxsl[fr->callno]);
07715
07716 if (!iaxs[fr->callno]) {
07717 ast_mutex_unlock(&iaxsl[fr->callno]);
07718 return 1;
07719 }
07720 } else
07721 exists = 0;
07722 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
07723 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
07724 memset(&ied0, 0, sizeof(ied0));
07725 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
07726 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
07727 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
07728 if (!iaxs[fr->callno]) {
07729 ast_mutex_unlock(&iaxsl[fr->callno]);
07730 return 1;
07731 }
07732 if (authdebug)
07733 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);
07734 } else {
07735
07736
07737 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
07738 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
07739 using_prefs = "reqonly";
07740 } else {
07741 using_prefs = "disabled";
07742 }
07743 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
07744 memset(&pref, 0, sizeof(pref));
07745 strcpy(caller_pref_buf, "disabled");
07746 strcpy(host_pref_buf, "disabled");
07747 } else {
07748 using_prefs = "mine";
07749
07750 if (ies.codec_prefs)
07751 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
07752 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
07753
07754 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
07755 pref = iaxs[fr->callno]->rprefs;
07756 using_prefs = "caller";
07757 } else {
07758 pref = iaxs[fr->callno]->prefs;
07759 }
07760 } else
07761 pref = iaxs[fr->callno]->prefs;
07762
07763 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
07764 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
07765 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
07766 }
07767 if (!format) {
07768 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
07769 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
07770 if (!format) {
07771 memset(&ied0, 0, sizeof(ied0));
07772 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
07773 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
07774 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
07775 if (!iaxs[fr->callno]) {
07776 ast_mutex_unlock(&iaxsl[fr->callno]);
07777 return 1;
07778 }
07779 if (authdebug) {
07780 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
07781 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);
07782 else
07783 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);
07784 }
07785 } else {
07786
07787 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
07788 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
07789 format = 0;
07790 } else {
07791 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
07792 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
07793 memset(&pref, 0, sizeof(pref));
07794 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
07795 strcpy(caller_pref_buf,"disabled");
07796 strcpy(host_pref_buf,"disabled");
07797 } else {
07798 using_prefs = "mine";
07799 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
07800
07801 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
07802 pref = iaxs[fr->callno]->prefs;
07803 } else {
07804 pref = iaxs[fr->callno]->rprefs;
07805 using_prefs = "caller";
07806 }
07807 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
07808
07809 } else
07810 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
07811 }
07812 }
07813
07814 if (!format) {
07815 memset(&ied0, 0, sizeof(ied0));
07816 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
07817 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
07818 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
07819 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
07820 if (!iaxs[fr->callno]) {
07821 ast_mutex_unlock(&iaxsl[fr->callno]);
07822 return 1;
07823 }
07824 if (authdebug)
07825 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);
07826 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
07827 break;
07828 }
07829 }
07830 }
07831 if (format) {
07832
07833 memset(&ied1, 0, sizeof(ied1));
07834 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
07835 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
07836 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
07837 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
07838 if (option_verbose > 2)
07839 ast_verbose(VERBOSE_PREFIX_3 "Accepting UNAUTHENTICATED call from %s:\n"
07840 "%srequested format = %s,\n"
07841 "%srequested prefs = %s,\n"
07842 "%sactual format = %s,\n"
07843 "%shost prefs = %s,\n"
07844 "%spriority = %s\n",
07845 ast_inet_ntoa(sin.sin_addr),
07846 VERBOSE_PREFIX_4,
07847 ast_getformatname(iaxs[fr->callno]->peerformat),
07848 VERBOSE_PREFIX_4,
07849 caller_pref_buf,
07850 VERBOSE_PREFIX_4,
07851 ast_getformatname(format),
07852 VERBOSE_PREFIX_4,
07853 host_pref_buf,
07854 VERBOSE_PREFIX_4,
07855 using_prefs);
07856
07857 iaxs[fr->callno]->chosenformat = format;
07858 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
07859 } else {
07860 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
07861
07862 if (option_verbose > 2)
07863 ast_verbose(VERBOSE_PREFIX_3 "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
07864 }
07865 }
07866 }
07867 break;
07868 }
07869 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
07870 merge_encryption(iaxs[fr->callno],ies.encmethods);
07871 else
07872 iaxs[fr->callno]->encmethods = 0;
07873 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
07874 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
07875 if (!iaxs[fr->callno]) {
07876 ast_mutex_unlock(&iaxsl[fr->callno]);
07877 return 1;
07878 }
07879 break;
07880 case IAX_COMMAND_DPREQ:
07881
07882 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
07883 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
07884 if (iaxcompat) {
07885
07886 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
07887 } else {
07888
07889 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
07890 }
07891 }
07892 break;
07893 case IAX_COMMAND_HANGUP:
07894 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
07895 if (option_debug)
07896 ast_log(LOG_DEBUG, "Immediately destroying %d, having received hangup\n", fr->callno);
07897
07898 if (ies.causecode && iaxs[fr->callno]->owner)
07899 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
07900
07901 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
07902 iax2_destroy(fr->callno);
07903 break;
07904 case IAX_COMMAND_REJECT:
07905
07906 if (ies.causecode && iaxs[fr->callno]->owner)
07907 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
07908
07909 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
07910 if (iaxs[fr->callno]->owner && authdebug)
07911 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
07912 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
07913 ies.cause ? ies.cause : "<Unknown>");
07914 if (option_debug)
07915 ast_log(LOG_DEBUG, "Immediately destroying %d, having received reject\n",
07916 fr->callno);
07917 }
07918
07919 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
07920 fr->ts, NULL, 0, fr->iseqno);
07921 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
07922 iaxs[fr->callno]->error = EPERM;
07923 iax2_destroy(fr->callno);
07924 break;
07925 case IAX_COMMAND_TRANSFER:
07926 {
07927 struct ast_channel *bridged_chan;
07928
07929 if (iaxs[fr->callno]->owner && (bridged_chan = ast_bridged_channel(iaxs[fr->callno]->owner)) && ies.called_number) {
07930
07931
07932 ast_mutex_unlock(&iaxsl[fr->callno]);
07933 pbx_builtin_setvar_helper(iaxs[fr->callno]->owner, "BLINDTRANSFER", bridged_chan->name);
07934 ast_mutex_lock(&iaxsl[fr->callno]);
07935 if (!iaxs[fr->callno]) {
07936 ast_mutex_unlock(&iaxsl[fr->callno]);
07937 return 1;
07938 }
07939
07940 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", iaxs[fr->callno]->owner->name);
07941 if (!strcmp(ies.called_number, ast_parking_ext())) {
07942 struct ast_channel *saved_channel = iaxs[fr->callno]->owner;
07943 ast_mutex_unlock(&iaxsl[fr->callno]);
07944 if (iax_park(bridged_chan, saved_channel)) {
07945 ast_log(LOG_WARNING, "Failed to park call on '%s'\n", bridged_chan->name);
07946 } else {
07947 ast_log(LOG_DEBUG, "Parked call on '%s'\n", bridged_chan->name);
07948 }
07949 ast_mutex_lock(&iaxsl[fr->callno]);
07950 } else {
07951 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context, ies.called_number, 1))
07952 ast_log(LOG_WARNING, "Async goto of '%s' to '%s@%s' failed\n", bridged_chan->name,
07953 ies.called_number, iaxs[fr->callno]->context);
07954 else
07955 ast_log(LOG_DEBUG, "Async goto of '%s' to '%s@%s' started\n", bridged_chan->name,
07956 ies.called_number, iaxs[fr->callno]->context);
07957 }
07958 } else
07959 ast_log(LOG_DEBUG, "Async goto not applicable on call %d\n", fr->callno);
07960
07961 break;
07962 }
07963 case IAX_COMMAND_ACCEPT:
07964
07965 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
07966 break;
07967 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
07968
07969 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
07970 iax2_destroy(fr->callno);
07971 break;
07972 }
07973 if (ies.format) {
07974 iaxs[fr->callno]->peerformat = ies.format;
07975 } else {
07976 if (iaxs[fr->callno]->owner)
07977 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
07978 else
07979 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
07980 }
07981 if (option_verbose > 2)
07982 ast_verbose(VERBOSE_PREFIX_3 "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
07983 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
07984 memset(&ied0, 0, sizeof(ied0));
07985 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
07986 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
07987 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
07988 if (!iaxs[fr->callno]) {
07989 ast_mutex_unlock(&iaxsl[fr->callno]);
07990 return 1;
07991 }
07992 if (authdebug)
07993 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);
07994 } else {
07995 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
07996 if (iaxs[fr->callno]->owner) {
07997
07998 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
07999 if (option_verbose > 2)
08000 ast_verbose(VERBOSE_PREFIX_3 "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
08001 retryowner2:
08002 if (ast_mutex_trylock(&iaxs[fr->callno]->owner->lock)) {
08003 DEADLOCK_AVOIDANCE(&iaxsl[fr->callno]);
08004 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) goto retryowner2;
08005 }
08006
08007 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
08008
08009 if (iaxs[fr->callno]->owner->writeformat)
08010 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
08011 if (iaxs[fr->callno]->owner->readformat)
08012 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
08013 ast_mutex_unlock(&iaxs[fr->callno]->owner->lock);
08014 }
08015 }
08016 }
08017 if (iaxs[fr->callno]) {
08018 ast_mutex_lock(&dpcache_lock);
08019 dp = iaxs[fr->callno]->dpentries;
08020 while(dp) {
08021 if (!(dp->flags & CACHE_FLAG_TRANSMITTED)) {
08022 iax2_dprequest(dp, fr->callno);
08023 }
08024 dp = dp->peer;
08025 }
08026 ast_mutex_unlock(&dpcache_lock);
08027 }
08028 break;
08029 case IAX_COMMAND_POKE:
08030
08031 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
08032 if (!iaxs[fr->callno]) {
08033 ast_mutex_unlock(&iaxsl[fr->callno]);
08034 return 1;
08035 }
08036 break;
08037 case IAX_COMMAND_PING:
08038 {
08039 struct iax_ie_data pingied;
08040 construct_rr(iaxs[fr->callno], &pingied);
08041
08042 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
08043 }
08044 break;
08045 case IAX_COMMAND_PONG:
08046
08047 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
08048
08049 save_rr(fr, &ies);
08050
08051 if (iaxs[fr->callno]->peerpoke) {
08052 peer = iaxs[fr->callno]->peerpoke;
08053 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
08054 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
08055 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
08056 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
08057 ast_device_state_changed("IAX2/%s", peer->name);
08058 }
08059 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
08060 if (iaxs[fr->callno]->pingtime > peer->maxms) {
08061 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
08062 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
08063 ast_device_state_changed("IAX2/%s", peer->name);
08064 }
08065 }
08066 peer->lastms = iaxs[fr->callno]->pingtime;
08067 if (peer->smoothing && (peer->lastms > -1))
08068 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
08069 else if (peer->smoothing && peer->lastms < 0)
08070 peer->historicms = (0 + peer->historicms) / 2;
08071 else
08072 peer->historicms = iaxs[fr->callno]->pingtime;
08073
08074
08075 if (peer->pokeexpire > -1) {
08076 if (!ast_sched_del(sched, peer->pokeexpire)) {
08077 peer_unref(peer);
08078 peer->pokeexpire = -1;
08079 }
08080 }
08081
08082 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
08083 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
08084 else
08085 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
08086 if (peer->pokeexpire == -1)
08087 peer_unref(peer);
08088
08089 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08090
08091 iax2_destroy(fr->callno);
08092 peer->callno = 0;
08093 if (option_debug)
08094 ast_log(LOG_DEBUG, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
08095 }
08096 break;
08097 case IAX_COMMAND_LAGRQ:
08098 case IAX_COMMAND_LAGRP:
08099 f.src = "LAGRQ";
08100 f.mallocd = 0;
08101 f.offset = 0;
08102 f.samples = 0;
08103 iax_frame_wrap(fr, &f);
08104 if(f.subclass == IAX_COMMAND_LAGRQ) {
08105
08106 fr->af.subclass = IAX_COMMAND_LAGRP;
08107 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
08108 } else {
08109
08110 unsigned int ts;
08111
08112 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
08113 iaxs[fr->callno]->lag = ts - fr->ts;
08114 if (option_debug && iaxdebug)
08115 ast_log(LOG_DEBUG, "Peer %s lag measured as %dms\n",
08116 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
08117 }
08118 break;
08119 case IAX_COMMAND_AUTHREQ:
08120 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
08121 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>");
08122 break;
08123 }
08124 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
08125 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
08126 .subclass = AST_CONTROL_HANGUP,
08127 };
08128 ast_log(LOG_WARNING,
08129 "I don't know how to authenticate %s to %s\n",
08130 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
08131 iax2_queue_frame(fr->callno, &hangup_fr);
08132 }
08133 if (!iaxs[fr->callno]) {
08134 ast_mutex_unlock(&iaxsl[fr->callno]);
08135 return 1;
08136 }
08137 break;
08138 case IAX_COMMAND_AUTHREP:
08139
08140 if (delayreject)
08141 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08142
08143 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
08144 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>");
08145 break;
08146 }
08147 if (authenticate_verify(iaxs[fr->callno], &ies)) {
08148 if (authdebug)
08149 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);
08150 memset(&ied0, 0, sizeof(ied0));
08151 auth_fail(fr->callno, IAX_COMMAND_REJECT);
08152 break;
08153 }
08154 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
08155
08156 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
08157 } else
08158 exists = 0;
08159 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
08160 if (authdebug)
08161 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);
08162 memset(&ied0, 0, sizeof(ied0));
08163 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
08164 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
08165 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08166 if (!iaxs[fr->callno]) {
08167 ast_mutex_unlock(&iaxsl[fr->callno]);
08168 return 1;
08169 }
08170 } else {
08171
08172 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
08173 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
08174 using_prefs = "reqonly";
08175 } else {
08176 using_prefs = "disabled";
08177 }
08178 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
08179 memset(&pref, 0, sizeof(pref));
08180 strcpy(caller_pref_buf, "disabled");
08181 strcpy(host_pref_buf, "disabled");
08182 } else {
08183 using_prefs = "mine";
08184 if (ies.codec_prefs)
08185 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
08186 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
08187 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
08188 pref = iaxs[fr->callno]->rprefs;
08189 using_prefs = "caller";
08190 } else {
08191 pref = iaxs[fr->callno]->prefs;
08192 }
08193 } else
08194 pref = iaxs[fr->callno]->prefs;
08195
08196 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
08197 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
08198 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
08199 }
08200 if (!format) {
08201 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
08202 if (option_debug)
08203 ast_log(LOG_DEBUG, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
08204 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
08205 }
08206 if (!format) {
08207 if (authdebug) {
08208 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
08209 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);
08210 else
08211 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);
08212 }
08213 memset(&ied0, 0, sizeof(ied0));
08214 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
08215 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
08216 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08217 if (!iaxs[fr->callno]) {
08218 ast_mutex_unlock(&iaxsl[fr->callno]);
08219 return 1;
08220 }
08221 } else {
08222
08223 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
08224 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
08225 format = 0;
08226 } else {
08227 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
08228 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
08229 memset(&pref, 0, sizeof(pref));
08230 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
08231 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
08232 strcpy(caller_pref_buf,"disabled");
08233 strcpy(host_pref_buf,"disabled");
08234 } else {
08235 using_prefs = "mine";
08236 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
08237
08238 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
08239 pref = iaxs[fr->callno]->prefs;
08240 } else {
08241 pref = iaxs[fr->callno]->rprefs;
08242 using_prefs = "caller";
08243 }
08244 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
08245 } else
08246 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
08247 }
08248 }
08249 if (!format) {
08250 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
08251 if (authdebug) {
08252 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
08253 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);
08254 else
08255 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);
08256 }
08257 memset(&ied0, 0, sizeof(ied0));
08258 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
08259 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
08260 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08261 if (!iaxs[fr->callno]) {
08262 ast_mutex_unlock(&iaxsl[fr->callno]);
08263 return 1;
08264 }
08265 }
08266 }
08267 }
08268 if (format) {
08269
08270 memset(&ied1, 0, sizeof(ied1));
08271 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
08272 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
08273 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
08274 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
08275 if (option_verbose > 2)
08276 ast_verbose(VERBOSE_PREFIX_3 "Accepting AUTHENTICATED call from %s:\n"
08277 "%srequested format = %s,\n"
08278 "%srequested prefs = %s,\n"
08279 "%sactual format = %s,\n"
08280 "%shost prefs = %s,\n"
08281 "%spriority = %s\n",
08282 ast_inet_ntoa(sin.sin_addr),
08283 VERBOSE_PREFIX_4,
08284 ast_getformatname(iaxs[fr->callno]->peerformat),
08285 VERBOSE_PREFIX_4,
08286 caller_pref_buf,
08287 VERBOSE_PREFIX_4,
08288 ast_getformatname(format),
08289 VERBOSE_PREFIX_4,
08290 host_pref_buf,
08291 VERBOSE_PREFIX_4,
08292 using_prefs);
08293
08294 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
08295 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
08296 iax2_destroy(fr->callno);
08297 } else {
08298 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
08299
08300 if (option_verbose > 2)
08301 ast_verbose(VERBOSE_PREFIX_3 "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
08302 }
08303 }
08304 }
08305 break;
08306 case IAX_COMMAND_DIAL:
08307 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
08308 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
08309 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
08310 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
08311 if (authdebug)
08312 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);
08313 memset(&ied0, 0, sizeof(ied0));
08314 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
08315 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
08316 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08317 if (!iaxs[fr->callno]) {
08318 ast_mutex_unlock(&iaxsl[fr->callno]);
08319 return 1;
08320 }
08321 } else {
08322 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
08323 if (option_verbose > 2)
08324 ast_verbose(VERBOSE_PREFIX_3 "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
08325 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
08326 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
08327 if(!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
08328 iax2_destroy(fr->callno);
08329 }
08330 }
08331 break;
08332 case IAX_COMMAND_INVAL:
08333 iaxs[fr->callno]->error = ENOTCONN;
08334 if (option_debug)
08335 ast_log(LOG_DEBUG, "Immediately destroying %d, having received INVAL\n", fr->callno);
08336 iax2_destroy(fr->callno);
08337 if (option_debug)
08338 ast_log(LOG_DEBUG, "Destroying call %d\n", fr->callno);
08339 break;
08340 case IAX_COMMAND_VNAK:
08341 if (option_debug)
08342 ast_log(LOG_DEBUG, "Received VNAK: resending outstanding frames\n");
08343
08344 vnak_retransmit(fr->callno, fr->iseqno);
08345 break;
08346 case IAX_COMMAND_REGREQ:
08347 case IAX_COMMAND_REGREL:
08348
08349 if (delayreject)
08350 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08351 if (register_verify(fr->callno, &sin, &ies)) {
08352 if (!iaxs[fr->callno]) {
08353 ast_mutex_unlock(&iaxsl[fr->callno]);
08354 return 1;
08355 }
08356
08357 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
08358 break;
08359 }
08360 if (!iaxs[fr->callno]) {
08361 ast_mutex_unlock(&iaxsl[fr->callno]);
08362 return 1;
08363 }
08364 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
08365 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED | IAX_STATE_UNCHANGED)) {
08366 if (f.subclass == IAX_COMMAND_REGREL)
08367 memset(&sin, 0, sizeof(sin));
08368 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
08369 ast_log(LOG_WARNING, "Registry error\n");
08370 if (!iaxs[fr->callno]) {
08371 ast_mutex_unlock(&iaxsl[fr->callno]);
08372 return 1;
08373 }
08374 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
08375 ast_mutex_unlock(&iaxsl[fr->callno]);
08376 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
08377 ast_mutex_lock(&iaxsl[fr->callno]);
08378 if (!iaxs[fr->callno]) {
08379 ast_mutex_unlock(&iaxsl[fr->callno]);
08380 return 1;
08381 }
08382 }
08383 break;
08384 }
08385 registry_authrequest(fr->callno);
08386 if (!iaxs[fr->callno]) {
08387 ast_mutex_unlock(&iaxsl[fr->callno]);
08388 return 1;
08389 }
08390 break;
08391 case IAX_COMMAND_REGACK:
08392 if (iax2_ack_registry(&ies, &sin, fr->callno))
08393 ast_log(LOG_WARNING, "Registration failure\n");
08394
08395 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08396 iax2_destroy(fr->callno);
08397 break;
08398 case IAX_COMMAND_REGREJ:
08399 if (iaxs[fr->callno]->reg) {
08400 if (authdebug) {
08401 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));
08402 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelDriver: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
08403 }
08404 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
08405 }
08406
08407 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08408 iax2_destroy(fr->callno);
08409 break;
08410 case IAX_COMMAND_REGAUTH:
08411
08412 if (registry_rerequest(&ies, fr->callno, &sin)) {
08413 memset(&ied0, 0, sizeof(ied0));
08414 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
08415 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
08416 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08417 if (!iaxs[fr->callno]) {
08418 ast_mutex_unlock(&iaxsl[fr->callno]);
08419 return 1;
08420 }
08421 }
08422 break;
08423 case IAX_COMMAND_TXREJ:
08424 iaxs[fr->callno]->transferring = 0;
08425 if (option_verbose > 2)
08426 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
08427 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
08428 if (iaxs[fr->callno]->bridgecallno) {
08429 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
08430 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
08431 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
08432 }
08433 }
08434 break;
08435 case IAX_COMMAND_TXREADY:
08436 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
08437 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
08438 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
08439 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
08440 else
08441 iaxs[fr->callno]->transferring = TRANSFER_READY;
08442 if (option_verbose > 2)
08443 ast_verbose(VERBOSE_PREFIX_3 "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
08444 if (iaxs[fr->callno]->bridgecallno) {
08445 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
08446 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
08447
08448 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
08449 if (option_verbose > 2)
08450 ast_verbose(VERBOSE_PREFIX_3 "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
08451 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
08452
08453 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
08454 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
08455
08456 memset(&ied0, 0, sizeof(ied0));
08457 memset(&ied1, 0, sizeof(ied1));
08458 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
08459 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
08460 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
08461 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
08462 } else {
08463 if (option_verbose > 2)
08464 ast_verbose(VERBOSE_PREFIX_3 "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
08465 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
08466
08467 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
08468 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
08469 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
08470 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
08471
08472
08473 stop_stuff(fr->callno);
08474 stop_stuff(iaxs[fr->callno]->bridgecallno);
08475
08476 memset(&ied0, 0, sizeof(ied0));
08477 memset(&ied1, 0, sizeof(ied1));
08478 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
08479 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
08480 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
08481 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
08482 }
08483
08484 }
08485 }
08486 }
08487 break;
08488 case IAX_COMMAND_TXREQ:
08489 try_transfer(iaxs[fr->callno], &ies);
08490 break;
08491 case IAX_COMMAND_TXCNT:
08492 if (iaxs[fr->callno]->transferring)
08493 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
08494 break;
08495 case IAX_COMMAND_TXREL:
08496
08497 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08498 complete_transfer(fr->callno, &ies);
08499 stop_stuff(fr->callno);
08500 break;
08501 case IAX_COMMAND_TXMEDIA:
08502 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
08503 AST_LIST_LOCK(&iaxq.queue);
08504 AST_LIST_TRAVERSE(&iaxq.queue, cur, list) {
08505
08506 if ((fr->callno == cur->callno) && (cur->transfer)) {
08507 cur->retries = -1;
08508 }
08509 }
08510 AST_LIST_UNLOCK(&iaxq.queue);
08511
08512 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
08513 }
08514 break;
08515 case IAX_COMMAND_DPREP:
08516 complete_dpreply(iaxs[fr->callno], &ies);
08517 break;
08518 case IAX_COMMAND_UNSUPPORT:
08519 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
08520 break;
08521 case IAX_COMMAND_FWDOWNL:
08522
08523 if (!ast_test_flag(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
08524 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
08525 break;
08526 }
08527 memset(&ied0, 0, sizeof(ied0));
08528 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
08529 if (res < 0)
08530 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
08531 else if (res > 0)
08532 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
08533 else
08534 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
08535 if (!iaxs[fr->callno]) {
08536 ast_mutex_unlock(&iaxsl[fr->callno]);
08537 return 1;
08538 }
08539 break;
08540 default:
08541 if (option_debug)
08542 ast_log(LOG_DEBUG, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
08543 memset(&ied0, 0, sizeof(ied0));
08544 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
08545 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
08546 }
08547
08548 if ((f.subclass != IAX_COMMAND_ACK) &&
08549 (f.subclass != IAX_COMMAND_TXCNT) &&
08550 (f.subclass != IAX_COMMAND_TXACC) &&
08551 (f.subclass != IAX_COMMAND_INVAL) &&
08552 (f.subclass != IAX_COMMAND_VNAK)) {
08553 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
08554 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08555 }
08556 ast_mutex_unlock(&iaxsl[fr->callno]);
08557 return 1;
08558 }
08559
08560 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
08561 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
08562 } else if (minivid) {
08563 f.frametype = AST_FRAME_VIDEO;
08564 if (iaxs[fr->callno]->videoformat > 0)
08565 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
08566 else {
08567 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
08568 iax2_vnak(fr->callno);
08569 ast_mutex_unlock(&iaxsl[fr->callno]);
08570 return 1;
08571 }
08572 f.datalen = res - sizeof(*vh);
08573 if (f.datalen)
08574 f.data = thread->buf + sizeof(*vh);
08575 else
08576 f.data = NULL;
08577 #ifdef IAXTESTS
08578 if (test_resync) {
08579 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
08580 } else
08581 #endif
08582 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
08583 } else {
08584
08585 f.frametype = AST_FRAME_VOICE;
08586 if (iaxs[fr->callno]->voiceformat > 0)
08587 f.subclass = iaxs[fr->callno]->voiceformat;
08588 else {
08589 if (option_debug)
08590 ast_log(LOG_DEBUG, "Received mini frame before first full voice frame\n");
08591 iax2_vnak(fr->callno);
08592 ast_mutex_unlock(&iaxsl[fr->callno]);
08593 return 1;
08594 }
08595 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
08596 if (f.datalen < 0) {
08597 ast_log(LOG_WARNING, "Datalen < 0?\n");
08598 ast_mutex_unlock(&iaxsl[fr->callno]);
08599 return 1;
08600 }
08601 if (f.datalen)
08602 f.data = thread->buf + sizeof(*mh);
08603 else
08604 f.data = NULL;
08605 #ifdef IAXTESTS
08606 if (test_resync) {
08607 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
08608 } else
08609 #endif
08610 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
08611
08612 }
08613
08614 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
08615 ast_mutex_unlock(&iaxsl[fr->callno]);
08616 return 1;
08617 }
08618
08619 f.src = "IAX2";
08620 f.mallocd = 0;
08621 f.offset = 0;
08622 f.len = 0;
08623 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
08624 f.samples = ast_codec_get_samples(&f);
08625
08626 if (f.subclass == AST_FORMAT_SLINEAR)
08627 ast_frame_byteswap_be(&f);
08628 } else
08629 f.samples = 0;
08630 iax_frame_wrap(fr, &f);
08631
08632
08633 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
08634
08635 fr->outoforder = 0;
08636 } else {
08637 if (option_debug && iaxdebug && iaxs[fr->callno])
08638 ast_log(LOG_DEBUG, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
08639 fr->outoforder = -1;
08640 }
08641 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
08642 duped_fr = iaxfrdup2(fr);
08643 if (duped_fr) {
08644 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
08645 }
08646 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
08647 iaxs[fr->callno]->last = fr->ts;
08648 #if 1
08649 if (option_debug && iaxdebug)
08650 ast_log(LOG_DEBUG, "For call=%d, set last=%d\n", fr->callno, fr->ts);
08651 #endif
08652 }
08653
08654
08655 ast_mutex_unlock(&iaxsl[fr->callno]);
08656 return 1;
08657 }
08658
08659
08660 static void iax2_process_thread_cleanup(void *data)
08661 {
08662 struct iax2_thread *thread = data;
08663 ast_mutex_destroy(&thread->lock);
08664 ast_cond_destroy(&thread->cond);
08665 free(thread);
08666 ast_atomic_dec_and_test(&iaxactivethreadcount);
08667 }
08668
08669 static void *iax2_process_thread(void *data)
08670 {
08671 struct iax2_thread *thread = data;
08672 struct timeval tv;
08673 struct timespec ts;
08674 int put_into_idle = 0;
08675
08676 ast_atomic_fetchadd_int(&iaxactivethreadcount,1);
08677 pthread_cleanup_push(iax2_process_thread_cleanup, data);
08678 for(;;) {
08679
08680 ast_mutex_lock(&thread->lock);
08681
08682
08683 thread->ready_for_signal = 1;
08684
08685
08686 if (put_into_idle)
08687 insert_idle_thread(thread);
08688
08689 if (thread->type == IAX_TYPE_DYNAMIC) {
08690 struct iax2_thread *t = NULL;
08691
08692 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
08693 ts.tv_sec = tv.tv_sec;
08694 ts.tv_nsec = tv.tv_usec * 1000;
08695 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
08696
08697
08698 if (!put_into_idle) {
08699 ast_mutex_unlock(&thread->lock);
08700 break;
08701 }
08702 AST_LIST_LOCK(&dynamic_list);
08703
08704 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
08705 iaxdynamicthreadcount--;
08706 AST_LIST_UNLOCK(&dynamic_list);
08707 if (t) {
08708
08709
08710
08711 ast_mutex_unlock(&thread->lock);
08712 break;
08713 }
08714
08715
08716
08717 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
08718 ts.tv_sec = tv.tv_sec;
08719 ts.tv_nsec = tv.tv_usec * 1000;
08720 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT)
08721 {
08722 ast_mutex_unlock(&thread->lock);
08723 break;
08724 }
08725 }
08726 } else {
08727 ast_cond_wait(&thread->cond, &thread->lock);
08728 }
08729
08730
08731 put_into_idle = 1;
08732
08733 ast_mutex_unlock(&thread->lock);
08734
08735 if (thread->iostate == IAX_IOSTATE_IDLE)
08736 continue;
08737
08738
08739 AST_LIST_LOCK(&active_list);
08740 AST_LIST_INSERT_HEAD(&active_list, thread, list);
08741 AST_LIST_UNLOCK(&active_list);
08742
08743
08744 switch(thread->iostate) {
08745 case IAX_IOSTATE_READY:
08746 thread->actions++;
08747 thread->iostate = IAX_IOSTATE_PROCESSING;
08748 socket_process(thread);
08749 handle_deferred_full_frames(thread);
08750 break;
08751 case IAX_IOSTATE_SCHEDREADY:
08752 thread->actions++;
08753 thread->iostate = IAX_IOSTATE_PROCESSING;
08754 #ifdef SCHED_MULTITHREADED
08755 thread->schedfunc(thread->scheddata);
08756 #endif
08757 break;
08758 }
08759 time(&thread->checktime);
08760 thread->iostate = IAX_IOSTATE_IDLE;
08761 #ifdef DEBUG_SCHED_MULTITHREAD
08762 thread->curfunc[0]='\0';
08763 #endif
08764
08765
08766 AST_LIST_LOCK(&active_list);
08767 AST_LIST_REMOVE(&active_list, thread, list);
08768 AST_LIST_UNLOCK(&active_list);
08769
08770
08771 handle_deferred_full_frames(thread);
08772 }
08773
08774
08775
08776
08777
08778 AST_LIST_LOCK(&idle_list);
08779 AST_LIST_REMOVE(&idle_list, thread, list);
08780 AST_LIST_UNLOCK(&idle_list);
08781
08782 AST_LIST_LOCK(&dynamic_list);
08783 AST_LIST_REMOVE(&dynamic_list, thread, list);
08784 AST_LIST_UNLOCK(&dynamic_list);
08785
08786
08787
08788
08789 pthread_cleanup_pop(1);
08790
08791 return NULL;
08792 }
08793
08794 static int iax2_do_register(struct iax2_registry *reg)
08795 {
08796 struct iax_ie_data ied;
08797 if (option_debug && iaxdebug)
08798 ast_log(LOG_DEBUG, "Sending registration request for '%s'\n", reg->username);
08799
08800 if (reg->dnsmgr &&
08801 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
08802
08803 ast_dnsmgr_refresh(reg->dnsmgr);
08804 }
08805
08806
08807
08808
08809
08810 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
08811 int callno = reg->callno;
08812 ast_mutex_lock(&iaxsl[callno]);
08813 iax2_destroy(callno);
08814 ast_mutex_unlock(&iaxsl[callno]);
08815 reg->callno = 0;
08816 }
08817 if (!reg->addr.sin_addr.s_addr) {
08818 if (option_debug && iaxdebug)
08819 ast_log(LOG_DEBUG, "Unable to send registration request for '%s' without IP address\n", reg->username);
08820
08821 AST_SCHED_DEL(sched, reg->expire);
08822 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08823 return -1;
08824 }
08825
08826 if (!reg->callno) {
08827 if (option_debug)
08828 ast_log(LOG_DEBUG, "Allocate call number\n");
08829 reg->callno = find_callno_locked(0, 0, ®->addr, NEW_FORCE, defaultsockfd, 0);
08830 if (reg->callno < 1) {
08831 ast_log(LOG_WARNING, "Unable to create call for registration\n");
08832 return -1;
08833 } else if (option_debug)
08834 ast_log(LOG_DEBUG, "Registration created on call %d\n", reg->callno);
08835 iaxs[reg->callno]->reg = reg;
08836 ast_mutex_unlock(&iaxsl[reg->callno]);
08837 }
08838
08839 AST_SCHED_DEL(sched, reg->expire);
08840
08841 reg->expire = iax2_sched_add(sched, (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08842
08843 memset(&ied, 0, sizeof(ied));
08844 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08845 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08846 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08847 reg->regstate = REG_STATE_REGSENT;
08848 return 0;
08849 }
08850
08851 static char *iax2_prov_complete_template_3rd(const char *line, const char *word, int pos, int state)
08852 {
08853 if (pos != 3)
08854 return NULL;
08855 return iax_prov_complete_template(line, word, pos, state);
08856 }
08857
08858 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
08859 {
08860
08861
08862 struct iax_ie_data provdata;
08863 struct iax_ie_data ied;
08864 unsigned int sig;
08865 struct sockaddr_in sin;
08866 int callno;
08867 struct create_addr_info cai;
08868
08869 memset(&cai, 0, sizeof(cai));
08870
08871 if (option_debug)
08872 ast_log(LOG_DEBUG, "Provisioning '%s' from template '%s'\n", dest, template);
08873
08874 if (iax_provision_build(&provdata, &sig, template, force)) {
08875 if (option_debug)
08876 ast_log(LOG_DEBUG, "No provisioning found for template '%s'\n", template);
08877 return 0;
08878 }
08879
08880 if (end) {
08881 memcpy(&sin, end, sizeof(sin));
08882 cai.sockfd = sockfd;
08883 } else if (create_addr(dest, NULL, &sin, &cai))
08884 return -1;
08885
08886
08887 memset(&ied, 0, sizeof(ied));
08888 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
08889
08890 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
08891 if (!callno)
08892 return -1;
08893
08894 if (iaxs[callno]) {
08895
08896 AST_SCHED_DEL(sched, iaxs[callno]->autoid);
08897 iaxs[callno]->autoid = iax2_sched_add(sched, 15000, auto_hangup, (void *)(long)callno);
08898 ast_set_flag(iaxs[callno], IAX_PROVISION);
08899
08900 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
08901 }
08902 ast_mutex_unlock(&iaxsl[callno]);
08903
08904 return 1;
08905 }
08906
08907 static char *papp = "IAX2Provision";
08908 static char *psyn = "Provision a calling IAXy with a given template";
08909 static char *pdescrip =
08910 " IAX2Provision([template]): Provisions the calling IAXy (assuming\n"
08911 "the calling entity is in fact an IAXy) with the given template or\n"
08912 "default if one is not specified. Returns -1 on error or 0 on success.\n";
08913
08914
08915
08916
08917 static int iax2_prov_app(struct ast_channel *chan, void *data)
08918 {
08919 int res;
08920 char *sdata;
08921 char *opts;
08922 int force =0;
08923 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
08924 if (ast_strlen_zero(data))
08925 data = "default";
08926 sdata = ast_strdupa(data);
08927 opts = strchr(sdata, '|');
08928 if (opts)
08929 *opts='\0';
08930
08931 if (chan->tech != &iax2_tech) {
08932 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
08933 return -1;
08934 }
08935 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
08936 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
08937 return -1;
08938 }
08939 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
08940 if (option_verbose > 2)
08941 ast_verbose(VERBOSE_PREFIX_3 "Provisioned IAXY at '%s' with '%s'= %d\n",
08942 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
08943 sdata, res);
08944 return res;
08945 }
08946
08947
08948 static int iax2_prov_cmd(int fd, int argc, char *argv[])
08949 {
08950 int force = 0;
08951 int res;
08952 if (argc < 4)
08953 return RESULT_SHOWUSAGE;
08954 if ((argc > 4)) {
08955 if (!strcasecmp(argv[4], "forced"))
08956 force = 1;
08957 else
08958 return RESULT_SHOWUSAGE;
08959 }
08960 res = iax2_provision(NULL, -1, argv[2], argv[3], force);
08961 if (res < 0)
08962 ast_cli(fd, "Unable to find peer/address '%s'\n", argv[2]);
08963 else if (res < 1)
08964 ast_cli(fd, "No template (including wildcard) matching '%s'\n", argv[3]);
08965 else
08966 ast_cli(fd, "Provisioning '%s' with template '%s'%s\n", argv[2], argv[3], force ? ", forced" : "");
08967 return RESULT_SUCCESS;
08968 }
08969
08970 static void __iax2_poke_noanswer(const void *data)
08971 {
08972 struct iax2_peer *peer = (struct iax2_peer *)data;
08973 int callno;
08974
08975 if (peer->lastms > -1) {
08976 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
08977 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "Peer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
08978 ast_device_state_changed("IAX2/%s", peer->name);
08979 }
08980 if ((callno = peer->callno) > 0) {
08981 ast_mutex_lock(&iaxsl[callno]);
08982 iax2_destroy(callno);
08983 ast_mutex_unlock(&iaxsl[callno]);
08984 }
08985 peer->callno = 0;
08986 peer->lastms = -1;
08987
08988 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
08989 if (peer->pokeexpire == -1)
08990 peer_unref(peer);
08991 }
08992
08993 static int iax2_poke_noanswer(const void *data)
08994 {
08995 struct iax2_peer *peer = (struct iax2_peer *)data;
08996 peer->pokeexpire = -1;
08997 #ifdef SCHED_MULTITHREADED
08998 if (schedule_action(__iax2_poke_noanswer, data))
08999 #endif
09000 __iax2_poke_noanswer(data);
09001 peer_unref(peer);
09002 return 0;
09003 }
09004
09005 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
09006 {
09007 struct iax2_peer *peer = obj;
09008
09009 iax2_poke_peer(peer, 0);
09010
09011 return 0;
09012 }
09013
09014 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
09015 {
09016 int callno;
09017 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
09018
09019
09020 peer->lastms = 0;
09021 peer->historicms = 0;
09022 peer->pokeexpire = -1;
09023 peer->callno = 0;
09024 return 0;
09025 }
09026
09027
09028 if ((callno = peer->callno) > 0) {
09029 ast_log(LOG_NOTICE, "Still have a callno...\n");
09030 ast_mutex_lock(&iaxsl[callno]);
09031 iax2_destroy(callno);
09032 ast_mutex_unlock(&iaxsl[callno]);
09033 }
09034 if (heldcall)
09035 ast_mutex_unlock(&iaxsl[heldcall]);
09036 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
09037 if (heldcall)
09038 ast_mutex_lock(&iaxsl[heldcall]);
09039 if (peer->callno < 1) {
09040 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
09041 return -1;
09042 }
09043
09044
09045 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
09046 iaxs[peer->callno]->peerpoke = peer;
09047
09048
09049 if (peer->pokeexpire > -1) {
09050 if (!ast_sched_del(sched, peer->pokeexpire)) {
09051 peer->pokeexpire = -1;
09052 peer_unref(peer);
09053 }
09054 }
09055
09056
09057
09058 if (peer->lastms < 0) {
09059 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
09060 } else
09061 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
09062
09063 if (peer->pokeexpire == -1)
09064 peer_unref(peer);
09065
09066
09067 ast_mutex_lock(&iaxsl[callno]);
09068 if (iaxs[callno]) {
09069 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, NULL, 0, -1);
09070 }
09071 ast_mutex_unlock(&iaxsl[callno]);
09072
09073 return 0;
09074 }
09075
09076 static void free_context(struct iax2_context *con)
09077 {
09078 struct iax2_context *conl;
09079 while(con) {
09080 conl = con;
09081 con = con->next;
09082 free(conl);
09083 }
09084 }
09085
09086 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
09087 {
09088 int callno;
09089 int res;
09090 int fmt, native;
09091 struct sockaddr_in sin;
09092 struct ast_channel *c;
09093 struct parsed_dial_string pds;
09094 struct create_addr_info cai;
09095 char *tmpstr;
09096
09097 memset(&pds, 0, sizeof(pds));
09098 tmpstr = ast_strdupa(data);
09099 parse_dial_string(tmpstr, &pds);
09100
09101 if (ast_strlen_zero(pds.peer)) {
09102 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
09103 return NULL;
09104 }
09105
09106 memset(&cai, 0, sizeof(cai));
09107 cai.capability = iax2_capability;
09108
09109 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
09110
09111
09112 if (create_addr(pds.peer, NULL, &sin, &cai)) {
09113 *cause = AST_CAUSE_UNREGISTERED;
09114 return NULL;
09115 }
09116
09117 if (pds.port)
09118 sin.sin_port = htons(atoi(pds.port));
09119
09120 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
09121 if (callno < 1) {
09122 ast_log(LOG_WARNING, "Unable to create call\n");
09123 *cause = AST_CAUSE_CONGESTION;
09124 return NULL;
09125 }
09126
09127
09128 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
09129 if (ast_test_flag(&cai, IAX_TRUNK)) {
09130 int new_callno;
09131 if ((new_callno = make_trunk(callno, 1)) != -1)
09132 callno = new_callno;
09133 }
09134 iaxs[callno]->maxtime = cai.maxtime;
09135 if (cai.found)
09136 ast_string_field_set(iaxs[callno], host, pds.peer);
09137
09138 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
09139
09140 ast_mutex_unlock(&iaxsl[callno]);
09141
09142 if (c) {
09143
09144 if (c->nativeformats & format)
09145 c->nativeformats &= format;
09146 else {
09147 native = c->nativeformats;
09148 fmt = format;
09149 res = ast_translator_best_choice(&fmt, &native);
09150 if (res < 0) {
09151 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
09152 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
09153 ast_hangup(c);
09154 return NULL;
09155 }
09156 c->nativeformats = native;
09157 }
09158 c->readformat = ast_best_codec(c->nativeformats);
09159 c->writeformat = c->readformat;
09160 }
09161
09162 return c;
09163 }
09164
09165 static void *sched_thread(void *ignore)
09166 {
09167 int count;
09168 int res;
09169 struct timeval tv;
09170 struct timespec ts;
09171
09172 for (;;) {
09173 pthread_testcancel();
09174 ast_mutex_lock(&sched_lock);
09175 res = ast_sched_wait(sched);
09176 if ((res > 1000) || (res < 0))
09177 res = 1000;
09178 tv = ast_tvadd(ast_tvnow(), ast_samp2tv(res, 1000));
09179 ts.tv_sec = tv.tv_sec;
09180 ts.tv_nsec = tv.tv_usec * 1000;
09181 ast_cond_timedwait(&sched_cond, &sched_lock, &ts);
09182 ast_mutex_unlock(&sched_lock);
09183 pthread_testcancel();
09184
09185 count = ast_sched_runq(sched);
09186 if (option_debug && count >= 20)
09187 ast_log(LOG_DEBUG, "chan_iax2: ast_sched_runq ran %d scheduled tasks all at once\n", count);
09188 }
09189 return NULL;
09190 }
09191
09192 static void *network_thread(void *ignore)
09193 {
09194
09195
09196 int res, count, wakeup;
09197 struct iax_frame *f;
09198
09199 if (timingfd > -1)
09200 ast_io_add(io, timingfd, timing_read, AST_IO_IN | AST_IO_PRI, NULL);
09201
09202 for(;;) {
09203 pthread_testcancel();
09204
09205
09206
09207 AST_LIST_LOCK(&iaxq.queue);
09208 count = 0;
09209 wakeup = -1;
09210 AST_LIST_TRAVERSE_SAFE_BEGIN(&iaxq.queue, f, list) {
09211 if (f->sentyet)
09212 continue;
09213
09214
09215 if (ast_mutex_trylock(&iaxsl[f->callno])) {
09216 wakeup = 1;
09217 continue;
09218 }
09219
09220 f->sentyet++;
09221
09222 if (iaxs[f->callno]) {
09223 send_packet(f);
09224 count++;
09225 }
09226
09227 ast_mutex_unlock(&iaxsl[f->callno]);
09228
09229 if (f->retries < 0) {
09230
09231 AST_LIST_REMOVE_CURRENT(&iaxq.queue, list);
09232 iaxq.count--;
09233
09234 iax_frame_free(f);
09235 } else {
09236
09237 f->retries++;
09238 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
09239 }
09240 }
09241 AST_LIST_TRAVERSE_SAFE_END
09242 AST_LIST_UNLOCK(&iaxq.queue);
09243
09244 pthread_testcancel();
09245
09246 if (option_debug && count >= 20)
09247 ast_log(LOG_DEBUG, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
09248
09249
09250 res = ast_io_wait(io, wakeup);
09251 if (res >= 0) {
09252 if (option_debug && res >= 20)
09253 ast_log(LOG_DEBUG, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
09254 }
09255 }
09256 return NULL;
09257 }
09258
09259 static int start_network_thread(void)
09260 {
09261 pthread_attr_t attr;
09262 int threadcount = 0;
09263 int x;
09264 for (x = 0; x < iaxthreadcount; x++) {
09265 struct iax2_thread *thread = ast_calloc(1, sizeof(struct iax2_thread));
09266 if (thread) {
09267 thread->type = IAX_TYPE_POOL;
09268 thread->threadnum = ++threadcount;
09269 ast_mutex_init(&thread->lock);
09270 ast_cond_init(&thread->cond, NULL);
09271 pthread_attr_init(&attr);
09272 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
09273 if (ast_pthread_create(&thread->threadid, &attr, iax2_process_thread, thread)) {
09274 ast_log(LOG_WARNING, "Failed to create new thread!\n");
09275 free(thread);
09276 thread = NULL;
09277 }
09278 AST_LIST_LOCK(&idle_list);
09279 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
09280 AST_LIST_UNLOCK(&idle_list);
09281 }
09282 }
09283 ast_pthread_create_background(&schedthreadid, NULL, sched_thread, NULL);
09284 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
09285 if (option_verbose > 1)
09286 ast_verbose(VERBOSE_PREFIX_2 "%d helper threads started\n", threadcount);
09287 return 0;
09288 }
09289
09290 static struct iax2_context *build_context(char *context)
09291 {
09292 struct iax2_context *con;
09293
09294 if ((con = ast_calloc(1, sizeof(*con))))
09295 ast_copy_string(con->context, context, sizeof(con->context));
09296
09297 return con;
09298 }
09299
09300 static int get_auth_methods(char *value)
09301 {
09302 int methods = 0;
09303 if (strstr(value, "rsa"))
09304 methods |= IAX_AUTH_RSA;
09305 if (strstr(value, "md5"))
09306 methods |= IAX_AUTH_MD5;
09307 if (strstr(value, "plaintext"))
09308 methods |= IAX_AUTH_PLAINTEXT;
09309 return methods;
09310 }
09311
09312
09313
09314
09315
09316 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
09317 {
09318 int sd;
09319 int res;
09320
09321 sd = socket(AF_INET, SOCK_DGRAM, 0);
09322 if (sd < 0) {
09323 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
09324 return -1;
09325 }
09326
09327 res = bind(sd, sa, salen);
09328 if (res < 0) {
09329 if (option_debug)
09330 ast_log(LOG_DEBUG, "Can't bind: %s\n", strerror(errno));
09331 close(sd);
09332 return 1;
09333 }
09334
09335 close(sd);
09336 return 0;
09337 }
09338
09339
09340
09341
09342 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
09343 {
09344 struct sockaddr_in sin;
09345 int nonlocal = 1;
09346 int port = IAX_DEFAULT_PORTNO;
09347 int sockfd = defaultsockfd;
09348 char *tmp;
09349 char *addr;
09350 char *portstr;
09351
09352 if (!(tmp = ast_strdupa(srcaddr)))
09353 return -1;
09354
09355 addr = strsep(&tmp, ":");
09356 portstr = tmp;
09357
09358 if (portstr) {
09359 port = atoi(portstr);
09360 if (port < 1)
09361 port = IAX_DEFAULT_PORTNO;
09362 }
09363
09364 if (!ast_get_ip(&sin, addr)) {
09365 struct ast_netsock *sock;
09366 int res;
09367
09368 sin.sin_port = 0;
09369 sin.sin_family = AF_INET;
09370 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
09371 if (res == 0) {
09372
09373 sin.sin_port = htons(port);
09374 if (!(sock = ast_netsock_find(netsock, &sin)))
09375 sock = ast_netsock_find(outsock, &sin);
09376 if (sock) {
09377 sockfd = ast_netsock_sockfd(sock);
09378 nonlocal = 0;
09379 } else {
09380 unsigned int orig_saddr = sin.sin_addr.s_addr;
09381
09382 sin.sin_addr.s_addr = INADDR_ANY;
09383 if (ast_netsock_find(netsock, &sin)) {
09384 sin.sin_addr.s_addr = orig_saddr;
09385 sock = ast_netsock_bind(outsock, io, srcaddr, port, tos, socket_read, NULL);
09386 if (sock) {
09387 sockfd = ast_netsock_sockfd(sock);
09388 ast_netsock_unref(sock);
09389 nonlocal = 0;
09390 } else {
09391 nonlocal = 2;
09392 }
09393 }
09394 }
09395 }
09396 }
09397
09398 peer->sockfd = sockfd;
09399
09400 if (nonlocal == 1) {
09401 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
09402 srcaddr, peer->name);
09403 return -1;
09404 } else if (nonlocal == 2) {
09405 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
09406 srcaddr, peer->name);
09407 return -1;
09408 } else {
09409 if (option_debug)
09410 ast_log(LOG_DEBUG, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
09411 return 0;
09412 }
09413 }
09414
09415 static void peer_destructor(void *obj)
09416 {
09417 struct iax2_peer *peer = obj;
09418 int callno = peer->callno;
09419
09420 ast_free_ha(peer->ha);
09421
09422 if (callno > 0) {
09423 ast_mutex_lock(&iaxsl[callno]);
09424 iax2_destroy(callno);
09425 ast_mutex_unlock(&iaxsl[callno]);
09426 }
09427
09428 register_peer_exten(peer, 0);
09429
09430 if (peer->dnsmgr)
09431 ast_dnsmgr_release(peer->dnsmgr);
09432
09433 ast_string_field_free_memory(peer);
09434 }
09435
09436
09437 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
09438 {
09439 struct iax2_peer *peer = NULL;
09440 struct ast_ha *oldha = NULL;
09441 int maskfound=0;
09442 int found=0;
09443 int firstpass=1;
09444 struct iax2_peer tmp_peer = {
09445 .name = name,
09446 };
09447
09448 if (!temponly) {
09449 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
09450 if (peer && !ast_test_flag(peer, IAX_DELME))
09451 firstpass = 0;
09452 }
09453
09454 if (peer) {
09455 found++;
09456 if (firstpass) {
09457 oldha = peer->ha;
09458 peer->ha = NULL;
09459 }
09460 unlink_peer(peer);
09461 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
09462 peer->expire = -1;
09463 peer->pokeexpire = -1;
09464 peer->sockfd = defaultsockfd;
09465 if (ast_string_field_init(peer, 32))
09466 peer = peer_unref(peer);
09467 }
09468
09469 if (peer) {
09470 if (firstpass) {
09471 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
09472 peer->encmethods = iax2_encryption;
09473 peer->adsi = adsi;
09474 ast_string_field_set(peer,secret,"");
09475 if (!found) {
09476 ast_string_field_set(peer, name, name);
09477 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
09478 peer->expiry = min_reg_expire;
09479 }
09480 peer->prefs = prefs;
09481 peer->capability = iax2_capability;
09482 peer->smoothing = 0;
09483 peer->pokefreqok = DEFAULT_FREQ_OK;
09484 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
09485 ast_string_field_set(peer,context,"");
09486 ast_string_field_set(peer,peercontext,"");
09487 ast_clear_flag(peer, IAX_HASCALLERID);
09488 ast_string_field_set(peer, cid_name, "");
09489 ast_string_field_set(peer, cid_num, "");
09490 }
09491
09492 if (!v) {
09493 v = alt;
09494 alt = NULL;
09495 }
09496 while(v) {
09497 if (!strcasecmp(v->name, "secret")) {
09498 ast_string_field_set(peer, secret, v->value);
09499 } else if (!strcasecmp(v->name, "mailbox")) {
09500 ast_string_field_set(peer, mailbox, v->value);
09501 } else if (!strcasecmp(v->name, "hasvoicemail")) {
09502 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
09503 ast_string_field_set(peer, mailbox, name);
09504 }
09505 } else if (!strcasecmp(v->name, "mohinterpret")) {
09506 ast_string_field_set(peer, mohinterpret, v->value);
09507 } else if (!strcasecmp(v->name, "mohsuggest")) {
09508 ast_string_field_set(peer, mohsuggest, v->value);
09509 } else if (!strcasecmp(v->name, "dbsecret")) {
09510 ast_string_field_set(peer, dbsecret, v->value);
09511 } else if (!strcasecmp(v->name, "trunk")) {
09512 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
09513 if (ast_test_flag(peer, IAX_TRUNK) && (timingfd < 0)) {
09514 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without timing\n", peer->name);
09515 ast_clear_flag(peer, IAX_TRUNK);
09516 }
09517 } else if (!strcasecmp(v->name, "auth")) {
09518 peer->authmethods = get_auth_methods(v->value);
09519 } else if (!strcasecmp(v->name, "encryption")) {
09520 peer->encmethods = get_encrypt_methods(v->value);
09521 } else if (!strcasecmp(v->name, "notransfer")) {
09522 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
09523 ast_clear_flag(peer, IAX_TRANSFERMEDIA);
09524 ast_set2_flag(peer, ast_true(v->value), IAX_NOTRANSFER);
09525 } else if (!strcasecmp(v->name, "transfer")) {
09526 if (!strcasecmp(v->value, "mediaonly")) {
09527 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
09528 } else if (ast_true(v->value)) {
09529 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
09530 } else
09531 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
09532 } else if (!strcasecmp(v->name, "jitterbuffer")) {
09533 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
09534 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
09535 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
09536 } else if (!strcasecmp(v->name, "host")) {
09537 if (!strcasecmp(v->value, "dynamic")) {
09538
09539 ast_set_flag(peer, IAX_DYNAMIC);
09540 if (!found) {
09541
09542
09543 memset(&peer->addr.sin_addr, 0, 4);
09544 if (peer->addr.sin_port) {
09545
09546 peer->defaddr.sin_port = peer->addr.sin_port;
09547 peer->addr.sin_port = 0;
09548 }
09549 }
09550 } else {
09551
09552 AST_SCHED_DEL(sched, peer->expire);
09553 ast_clear_flag(peer, IAX_DYNAMIC);
09554 if (ast_dnsmgr_lookup(v->value, &peer->addr.sin_addr, &peer->dnsmgr))
09555 return peer_unref(peer);
09556 if (!peer->addr.sin_port)
09557 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
09558 }
09559 if (!maskfound)
09560 inet_aton("255.255.255.255", &peer->mask);
09561 } else if (!strcasecmp(v->name, "defaultip")) {
09562 if (ast_get_ip(&peer->defaddr, v->value))
09563 return peer_unref(peer);
09564 } else if (!strcasecmp(v->name, "sourceaddress")) {
09565 peer_set_srcaddr(peer, v->value);
09566 } else if (!strcasecmp(v->name, "permit") ||
09567 !strcasecmp(v->name, "deny")) {
09568 peer->ha = ast_append_ha(v->name, v->value, peer->ha);
09569 } else if (!strcasecmp(v->name, "mask")) {
09570 maskfound++;
09571 inet_aton(v->value, &peer->mask);
09572 } else if (!strcasecmp(v->name, "context")) {
09573 ast_string_field_set(peer, context, v->value);
09574 } else if (!strcasecmp(v->name, "regexten")) {
09575 ast_string_field_set(peer, regexten, v->value);
09576 } else if (!strcasecmp(v->name, "peercontext")) {
09577 ast_string_field_set(peer, peercontext, v->value);
09578 } else if (!strcasecmp(v->name, "port")) {
09579 if (ast_test_flag(peer, IAX_DYNAMIC))
09580 peer->defaddr.sin_port = htons(atoi(v->value));
09581 else
09582 peer->addr.sin_port = htons(atoi(v->value));
09583 } else if (!strcasecmp(v->name, "username")) {
09584 ast_string_field_set(peer, username, v->value);
09585 } else if (!strcasecmp(v->name, "allow")) {
09586 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
09587 } else if (!strcasecmp(v->name, "disallow")) {
09588 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
09589 } else if (!strcasecmp(v->name, "callerid")) {
09590 if (!ast_strlen_zero(v->value)) {
09591 char name2[80];
09592 char num2[80];
09593 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
09594 ast_string_field_set(peer, cid_name, name2);
09595 ast_string_field_set(peer, cid_num, num2);
09596 } else {
09597 ast_string_field_set(peer, cid_name, "");
09598 ast_string_field_set(peer, cid_num, "");
09599 }
09600 ast_set_flag(peer, IAX_HASCALLERID);
09601 } else if (!strcasecmp(v->name, "fullname")) {
09602 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
09603 ast_set_flag(peer, IAX_HASCALLERID);
09604 } else if (!strcasecmp(v->name, "cid_number")) {
09605 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
09606 ast_set_flag(peer, IAX_HASCALLERID);
09607 } else if (!strcasecmp(v->name, "sendani")) {
09608 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
09609 } else if (!strcasecmp(v->name, "inkeys")) {
09610 ast_string_field_set(peer, inkeys, v->value);
09611 } else if (!strcasecmp(v->name, "outkey")) {
09612 ast_string_field_set(peer, outkey, v->value);
09613 } else if (!strcasecmp(v->name, "qualify")) {
09614 if (!strcasecmp(v->value, "no")) {
09615 peer->maxms = 0;
09616 } else if (!strcasecmp(v->value, "yes")) {
09617 peer->maxms = DEFAULT_MAXMS;
09618 } else if (sscanf(v->value, "%d", &peer->maxms) != 1) {
09619 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);
09620 peer->maxms = 0;
09621 }
09622 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
09623 peer->smoothing = ast_true(v->value);
09624 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
09625 if (sscanf(v->value, "%d", &peer->pokefreqok) != 1) {
09626 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);
09627 }
09628 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
09629 if (sscanf(v->value, "%d", &peer->pokefreqnotok) != 1) {
09630 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);
09631 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
09632 } else if (!strcasecmp(v->name, "timezone")) {
09633 ast_string_field_set(peer, zonetag, v->value);
09634 } else if (!strcasecmp(v->name, "adsi")) {
09635 peer->adsi = ast_true(v->value);
09636 }
09637
09638 v = v->next;
09639 if (!v) {
09640 v = alt;
09641 alt = NULL;
09642 }
09643 }
09644 if (!peer->authmethods)
09645 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
09646 ast_clear_flag(peer, IAX_DELME);
09647
09648 peer->addr.sin_family = AF_INET;
09649 }
09650 if (oldha)
09651 ast_free_ha(oldha);
09652 return peer;
09653 }
09654
09655 static void user_destructor(void *obj)
09656 {
09657 struct iax2_user *user = obj;
09658
09659 ast_free_ha(user->ha);
09660 free_context(user->contexts);
09661 if(user->vars) {
09662 ast_variables_destroy(user->vars);
09663 user->vars = NULL;
09664 }
09665 ast_string_field_free_memory(user);
09666 }
09667
09668
09669 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
09670 {
09671 struct iax2_user *user = NULL;
09672 struct iax2_context *con, *conl = NULL;
09673 struct ast_ha *oldha = NULL;
09674 struct iax2_context *oldcon = NULL;
09675 int format;
09676 int firstpass=1;
09677 int oldcurauthreq = 0;
09678 char *varname = NULL, *varval = NULL;
09679 struct ast_variable *tmpvar = NULL;
09680 struct iax2_user tmp_user = {
09681 .name = name,
09682 };
09683
09684 if (!temponly) {
09685 user = ao2_find(users, &tmp_user, OBJ_POINTER);
09686 if (user && !ast_test_flag(user, IAX_DELME))
09687 firstpass = 0;
09688 }
09689
09690 if (user) {
09691 if (firstpass) {
09692 oldcurauthreq = user->curauthreq;
09693 oldha = user->ha;
09694 oldcon = user->contexts;
09695 user->ha = NULL;
09696 user->contexts = NULL;
09697 }
09698
09699 ao2_unlink(users, user);
09700 } else {
09701 user = ao2_alloc(sizeof(*user), user_destructor);
09702 }
09703
09704 if (user) {
09705 if (firstpass) {
09706 ast_string_field_free_memory(user);
09707 memset(user, 0, sizeof(struct iax2_user));
09708 if (ast_string_field_init(user, 32)) {
09709 user = user_unref(user);
09710 goto cleanup;
09711 }
09712 user->maxauthreq = maxauthreq;
09713 user->curauthreq = oldcurauthreq;
09714 user->prefs = prefs;
09715 user->capability = iax2_capability;
09716 user->encmethods = iax2_encryption;
09717 user->adsi = adsi;
09718 ast_string_field_set(user, name, name);
09719 ast_string_field_set(user, language, language);
09720 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP);
09721 ast_clear_flag(user, IAX_HASCALLERID);
09722 ast_string_field_set(user, cid_name, "");
09723 ast_string_field_set(user, cid_num, "");
09724 }
09725 if (!v) {
09726 v = alt;
09727 alt = NULL;
09728 }
09729 while(v) {
09730 if (!strcasecmp(v->name, "context")) {
09731 con = build_context(v->value);
09732 if (con) {
09733 if (conl)
09734 conl->next = con;
09735 else
09736 user->contexts = con;
09737 conl = con;
09738 }
09739 } else if (!strcasecmp(v->name, "permit") ||
09740 !strcasecmp(v->name, "deny")) {
09741 user->ha = ast_append_ha(v->name, v->value, user->ha);
09742 } else if (!strcasecmp(v->name, "setvar")) {
09743 varname = ast_strdupa(v->value);
09744 if (varname && (varval = strchr(varname,'='))) {
09745 *varval = '\0';
09746 varval++;
09747 if((tmpvar = ast_variable_new(varname, varval))) {
09748 tmpvar->next = user->vars;
09749 user->vars = tmpvar;
09750 }
09751 }
09752 } else if (!strcasecmp(v->name, "allow")) {
09753 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
09754 } else if (!strcasecmp(v->name, "disallow")) {
09755 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
09756 } else if (!strcasecmp(v->name, "trunk")) {
09757 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
09758 if (ast_test_flag(user, IAX_TRUNK) && (timingfd < 0)) {
09759 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without timing\n", user->name);
09760 ast_clear_flag(user, IAX_TRUNK);
09761 }
09762 } else if (!strcasecmp(v->name, "auth")) {
09763 user->authmethods = get_auth_methods(v->value);
09764 } else if (!strcasecmp(v->name, "encryption")) {
09765 user->encmethods = get_encrypt_methods(v->value);
09766 } else if (!strcasecmp(v->name, "notransfer")) {
09767 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
09768 ast_clear_flag(user, IAX_TRANSFERMEDIA);
09769 ast_set2_flag(user, ast_true(v->value), IAX_NOTRANSFER);
09770 } else if (!strcasecmp(v->name, "transfer")) {
09771 if (!strcasecmp(v->value, "mediaonly")) {
09772 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
09773 } else if (ast_true(v->value)) {
09774 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
09775 } else
09776 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
09777 } else if (!strcasecmp(v->name, "codecpriority")) {
09778 if(!strcasecmp(v->value, "caller"))
09779 ast_set_flag(user, IAX_CODEC_USER_FIRST);
09780 else if(!strcasecmp(v->value, "disabled"))
09781 ast_set_flag(user, IAX_CODEC_NOPREFS);
09782 else if(!strcasecmp(v->value, "reqonly")) {
09783 ast_set_flag(user, IAX_CODEC_NOCAP);
09784 ast_set_flag(user, IAX_CODEC_NOPREFS);
09785 }
09786 } else if (!strcasecmp(v->name, "jitterbuffer")) {
09787 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
09788 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
09789 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
09790 } else if (!strcasecmp(v->name, "dbsecret")) {
09791 ast_string_field_set(user, dbsecret, v->value);
09792 } else if (!strcasecmp(v->name, "secret")) {
09793 if (!ast_strlen_zero(user->secret)) {
09794 char *old = ast_strdupa(user->secret);
09795
09796 ast_string_field_build(user, secret, "%s;%s", old, v->value);
09797 } else
09798 ast_string_field_set(user, secret, v->value);
09799 } else if (!strcasecmp(v->name, "callerid")) {
09800 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
09801 char name2[80];
09802 char num2[80];
09803 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
09804 ast_string_field_set(user, cid_name, name2);
09805 ast_string_field_set(user, cid_num, num2);
09806 ast_set_flag(user, IAX_HASCALLERID);
09807 } else {
09808 ast_clear_flag(user, IAX_HASCALLERID);
09809 ast_string_field_set(user, cid_name, "");
09810 ast_string_field_set(user, cid_num, "");
09811 }
09812 } else if (!strcasecmp(v->name, "fullname")) {
09813 if (!ast_strlen_zero(v->value)) {
09814 ast_string_field_set(user, cid_name, v->value);
09815 ast_set_flag(user, IAX_HASCALLERID);
09816 } else {
09817 ast_string_field_set(user, cid_name, "");
09818 if (ast_strlen_zero(user->cid_num))
09819 ast_clear_flag(user, IAX_HASCALLERID);
09820 }
09821 } else if (!strcasecmp(v->name, "cid_number")) {
09822 if (!ast_strlen_zero(v->value)) {
09823 ast_string_field_set(user, cid_num, v->value);
09824 ast_set_flag(user, IAX_HASCALLERID);
09825 } else {
09826 ast_string_field_set(user, cid_num, "");
09827 if (ast_strlen_zero(user->cid_name))
09828 ast_clear_flag(user, IAX_HASCALLERID);
09829 }
09830 } else if (!strcasecmp(v->name, "accountcode")) {
09831 ast_string_field_set(user, accountcode, v->value);
09832 } else if (!strcasecmp(v->name, "mohinterpret")) {
09833 ast_string_field_set(user, mohinterpret, v->value);
09834 } else if (!strcasecmp(v->name, "mohsuggest")) {
09835 ast_string_field_set(user, mohsuggest, v->value);
09836 } else if (!strcasecmp(v->name, "language")) {
09837 ast_string_field_set(user, language, v->value);
09838 } else if (!strcasecmp(v->name, "amaflags")) {
09839 format = ast_cdr_amaflags2int(v->value);
09840 if (format < 0) {
09841 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
09842 } else {
09843 user->amaflags = format;
09844 }
09845 } else if (!strcasecmp(v->name, "inkeys")) {
09846 ast_string_field_set(user, inkeys, v->value);
09847 } else if (!strcasecmp(v->name, "maxauthreq")) {
09848 user->maxauthreq = atoi(v->value);
09849 if (user->maxauthreq < 0)
09850 user->maxauthreq = 0;
09851 } else if (!strcasecmp(v->name, "adsi")) {
09852 user->adsi = ast_true(v->value);
09853 }
09854
09855 v = v->next;
09856 if (!v) {
09857 v = alt;
09858 alt = NULL;
09859 }
09860 }
09861 if (!user->authmethods) {
09862 if (!ast_strlen_zero(user->secret)) {
09863 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
09864 if (!ast_strlen_zero(user->inkeys))
09865 user->authmethods |= IAX_AUTH_RSA;
09866 } else if (!ast_strlen_zero(user->inkeys)) {
09867 user->authmethods = IAX_AUTH_RSA;
09868 } else {
09869 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
09870 }
09871 }
09872 ast_clear_flag(user, IAX_DELME);
09873 }
09874 cleanup:
09875 if (oldha)
09876 ast_free_ha(oldha);
09877 if (oldcon)
09878 free_context(oldcon);
09879 return user;
09880 }
09881
09882 static int peer_delme_cb(void *obj, void *arg, int flags)
09883 {
09884 struct iax2_peer *peer = obj;
09885
09886 ast_set_flag(peer, IAX_DELME);
09887
09888 return 0;
09889 }
09890
09891 static int user_delme_cb(void *obj, void *arg, int flags)
09892 {
09893 struct iax2_user *user = obj;
09894
09895 ast_set_flag(user, IAX_DELME);
09896
09897 return 0;
09898 }
09899
09900 static void delete_users(void)
09901 {
09902 struct iax2_registry *reg;
09903
09904 ao2_callback(users, 0, user_delme_cb, NULL);
09905
09906 AST_LIST_LOCK(®istrations);
09907 while ((reg = AST_LIST_REMOVE_HEAD(®istrations, entry))) {
09908 ast_sched_del(sched, reg->expire);
09909 if (reg->callno) {
09910 int callno = reg->callno;
09911 ast_mutex_lock(&iaxsl[callno]);
09912 if (iaxs[callno]) {
09913 iaxs[callno]->reg = NULL;
09914 iax2_destroy(callno);
09915 }
09916 ast_mutex_unlock(&iaxsl[callno]);
09917 }
09918 if (reg->dnsmgr)
09919 ast_dnsmgr_release(reg->dnsmgr);
09920 free(reg);
09921 }
09922 AST_LIST_UNLOCK(®istrations);
09923
09924 ao2_callback(peers, 0, peer_delme_cb, NULL);
09925 }
09926
09927 static void prune_users(void)
09928 {
09929 struct iax2_user *user;
09930 struct ao2_iterator i;
09931
09932 i = ao2_iterator_init(users, 0);
09933 while ((user = ao2_iterator_next(&i))) {
09934 if (ast_test_flag(user, IAX_DELME))
09935 ao2_unlink(users, user);
09936 user_unref(user);
09937 }
09938 }
09939
09940
09941 static void prune_peers(void)
09942 {
09943 struct iax2_peer *peer;
09944 struct ao2_iterator i;
09945
09946 i = ao2_iterator_init(peers, 0);
09947 while ((peer = ao2_iterator_next(&i))) {
09948 if (ast_test_flag(peer, IAX_DELME))
09949 unlink_peer(peer);
09950 peer_unref(peer);
09951 }
09952 }
09953
09954 static void set_timing(void)
09955 {
09956 #ifdef HAVE_DAHDI
09957 int bs = trunkfreq * 8;
09958 if (timingfd > -1) {
09959 if (
09960 #ifdef DAHDI_TIMERACK
09961 ioctl(timingfd, DAHDI_TIMERCONFIG, &bs) &&
09962 #endif
09963 ioctl(timingfd, DAHDI_SET_BLOCKSIZE, &bs))
09964 ast_log(LOG_WARNING, "Unable to set blocksize on timing source\n");
09965 }
09966 #endif
09967 }
09968
09969 static void set_config_destroy(void)
09970 {
09971 strcpy(accountcode, "");
09972 strcpy(language, "");
09973 strcpy(mohinterpret, "default");
09974 strcpy(mohsuggest, "");
09975 amaflags = 0;
09976 delayreject = 0;
09977 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
09978 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
09979 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
09980 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
09981 delete_users();
09982 }
09983
09984
09985 static int set_config(char *config_file, int reload)
09986 {
09987 struct ast_config *cfg, *ucfg;
09988 int capability=iax2_capability;
09989 struct ast_variable *v;
09990 char *cat;
09991 const char *utype;
09992 const char *tosval;
09993 int format;
09994 int portno = IAX_DEFAULT_PORTNO;
09995 int x;
09996 struct iax2_user *user;
09997 struct iax2_peer *peer;
09998 struct ast_netsock *ns;
09999 #if 0
10000 static unsigned short int last_port=0;
10001 #endif
10002
10003 cfg = ast_config_load(config_file);
10004
10005 if (!cfg) {
10006 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
10007 return -1;
10008 }
10009
10010 if (reload) {
10011 set_config_destroy();
10012 }
10013
10014
10015 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
10016
10017
10018 memset(&globalflags, 0, sizeof(globalflags));
10019 ast_set_flag(&globalflags, IAX_RTUPDATE);
10020
10021 #ifdef SO_NO_CHECK
10022 nochecksums = 0;
10023 #endif
10024
10025 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
10026 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
10027
10028 maxauthreq = 3;
10029
10030 v = ast_variable_browse(cfg, "general");
10031
10032
10033 tosval = ast_variable_retrieve(cfg, "general", "tos");
10034 if (tosval) {
10035 if (ast_str2tos(tosval, &tos))
10036 ast_log(LOG_WARNING, "Invalid tos value, see doc/ip-tos.txt for more information.\n");
10037 }
10038 while(v) {
10039 if (!strcasecmp(v->name, "bindport")){
10040 if (reload)
10041 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
10042 else
10043 portno = atoi(v->value);
10044 } else if (!strcasecmp(v->name, "pingtime"))
10045 ping_time = atoi(v->value);
10046 else if (!strcasecmp(v->name, "iaxthreadcount")) {
10047 if (reload) {
10048 if (atoi(v->value) != iaxthreadcount)
10049 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
10050 } else {
10051 iaxthreadcount = atoi(v->value);
10052 if (iaxthreadcount < 1) {
10053 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
10054 iaxthreadcount = 1;
10055 } else if (iaxthreadcount > 256) {
10056 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
10057 iaxthreadcount = 256;
10058 }
10059 }
10060 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
10061 if (reload) {
10062 AST_LIST_LOCK(&dynamic_list);
10063 iaxmaxthreadcount = atoi(v->value);
10064 AST_LIST_UNLOCK(&dynamic_list);
10065 } else {
10066 iaxmaxthreadcount = atoi(v->value);
10067 if (iaxmaxthreadcount < 0) {
10068 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
10069 iaxmaxthreadcount = 0;
10070 } else if (iaxmaxthreadcount > 256) {
10071 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
10072 iaxmaxthreadcount = 256;
10073 }
10074 }
10075 } else if (!strcasecmp(v->name, "nochecksums")) {
10076 #ifdef SO_NO_CHECK
10077 if (ast_true(v->value))
10078 nochecksums = 1;
10079 else
10080 nochecksums = 0;
10081 #else
10082 if (ast_true(v->value))
10083 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
10084 #endif
10085 }
10086 else if (!strcasecmp(v->name, "maxjitterbuffer"))
10087 maxjitterbuffer = atoi(v->value);
10088 else if (!strcasecmp(v->name, "resyncthreshold"))
10089 resyncthreshold = atoi(v->value);
10090 else if (!strcasecmp(v->name, "maxjitterinterps"))
10091 maxjitterinterps = atoi(v->value);
10092 else if (!strcasecmp(v->name, "lagrqtime"))
10093 lagrq_time = atoi(v->value);
10094 else if (!strcasecmp(v->name, "maxregexpire"))
10095 max_reg_expire = atoi(v->value);
10096 else if (!strcasecmp(v->name, "minregexpire"))
10097 min_reg_expire = atoi(v->value);
10098 else if (!strcasecmp(v->name, "bindaddr")) {
10099 if (reload) {
10100 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
10101 } else {
10102 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, tos, socket_read, NULL))) {
10103 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
10104 } else {
10105 if (option_verbose > 1) {
10106 if (strchr(v->value, ':'))
10107 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s'\n", v->value);
10108 else
10109 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to '%s:%d'\n", v->value, portno);
10110 }
10111 if (defaultsockfd < 0)
10112 defaultsockfd = ast_netsock_sockfd(ns);
10113 ast_netsock_unref(ns);
10114 }
10115 }
10116 } else if (!strcasecmp(v->name, "authdebug"))
10117 authdebug = ast_true(v->value);
10118 else if (!strcasecmp(v->name, "encryption"))
10119 iax2_encryption = get_encrypt_methods(v->value);
10120 else if (!strcasecmp(v->name, "notransfer")) {
10121 ast_log(LOG_NOTICE, "The option 'notransfer' is deprecated in favor of 'transfer' which has options 'yes', 'no', and 'mediaonly'\n");
10122 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
10123 ast_set2_flag((&globalflags), ast_true(v->value), IAX_NOTRANSFER);
10124 } else if (!strcasecmp(v->name, "transfer")) {
10125 if (!strcasecmp(v->value, "mediaonly")) {
10126 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
10127 } else if (ast_true(v->value)) {
10128 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
10129 } else
10130 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
10131 } else if (!strcasecmp(v->name, "codecpriority")) {
10132 if(!strcasecmp(v->value, "caller"))
10133 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
10134 else if(!strcasecmp(v->value, "disabled"))
10135 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
10136 else if(!strcasecmp(v->value, "reqonly")) {
10137 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
10138 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
10139 }
10140 } else if (!strcasecmp(v->name, "jitterbuffer"))
10141 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
10142 else if (!strcasecmp(v->name, "forcejitterbuffer"))
10143 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
10144 else if (!strcasecmp(v->name, "delayreject"))
10145 delayreject = ast_true(v->value);
10146 else if (!strcasecmp(v->name, "allowfwdownload"))
10147 ast_set2_flag((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
10148 else if (!strcasecmp(v->name, "rtcachefriends"))
10149 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
10150 else if (!strcasecmp(v->name, "rtignoreregexpire"))
10151 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
10152 else if (!strcasecmp(v->name, "rtupdate"))
10153 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
10154 else if (!strcasecmp(v->name, "trunktimestamps"))
10155 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
10156 else if (!strcasecmp(v->name, "rtautoclear")) {
10157 int i = atoi(v->value);
10158 if(i > 0)
10159 global_rtautoclear = i;
10160 else
10161 i = 0;
10162 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
10163 } else if (!strcasecmp(v->name, "trunkfreq")) {
10164 trunkfreq = atoi(v->value);
10165 if (trunkfreq < 10)
10166 trunkfreq = 10;
10167 } else if (!strcasecmp(v->name, "autokill")) {
10168 if (sscanf(v->value, "%d", &x) == 1) {
10169 if (x >= 0)
10170 autokill = x;
10171 else
10172 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
10173 } else if (ast_true(v->value)) {
10174 autokill = DEFAULT_MAXMS;
10175 } else {
10176 autokill = 0;
10177 }
10178 } else if (!strcasecmp(v->name, "bandwidth")) {
10179 if (!strcasecmp(v->value, "low")) {
10180 capability = IAX_CAPABILITY_LOWBANDWIDTH;
10181 } else if (!strcasecmp(v->value, "medium")) {
10182 capability = IAX_CAPABILITY_MEDBANDWIDTH;
10183 } else if (!strcasecmp(v->value, "high")) {
10184 capability = IAX_CAPABILITY_FULLBANDWIDTH;
10185 } else
10186 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
10187 } else if (!strcasecmp(v->name, "allow")) {
10188 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
10189 } else if (!strcasecmp(v->name, "disallow")) {
10190 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
10191 } else if (!strcasecmp(v->name, "register")) {
10192 iax2_register(v->value, v->lineno);
10193 } else if (!strcasecmp(v->name, "iaxcompat")) {
10194 iaxcompat = ast_true(v->value);
10195 } else if (!strcasecmp(v->name, "regcontext")) {
10196 ast_copy_string(regcontext, v->value, sizeof(regcontext));
10197
10198 if (!ast_context_find(regcontext))
10199 ast_context_create(NULL, regcontext, "IAX2");
10200 } else if (!strcasecmp(v->name, "tos")) {
10201 if (ast_str2tos(v->value, &tos))
10202 ast_log(LOG_WARNING, "Invalid tos value at line %d, see doc/ip-tos.txt for more information.'\n", v->lineno);
10203 } else if (!strcasecmp(v->name, "accountcode")) {
10204 ast_copy_string(accountcode, v->value, sizeof(accountcode));
10205 } else if (!strcasecmp(v->name, "mohinterpret")) {
10206 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
10207 } else if (!strcasecmp(v->name, "mohsuggest")) {
10208 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
10209 } else if (!strcasecmp(v->name, "amaflags")) {
10210 format = ast_cdr_amaflags2int(v->value);
10211 if (format < 0) {
10212 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
10213 } else {
10214 amaflags = format;
10215 }
10216 } else if (!strcasecmp(v->name, "language")) {
10217 ast_copy_string(language, v->value, sizeof(language));
10218 } else if (!strcasecmp(v->name, "maxauthreq")) {
10219 maxauthreq = atoi(v->value);
10220 if (maxauthreq < 0)
10221 maxauthreq = 0;
10222 } else if (!strcasecmp(v->name, "adsi")) {
10223 adsi = ast_true(v->value);
10224 }
10225
10226 v = v->next;
10227 }
10228
10229 if (defaultsockfd < 0) {
10230 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, tos, socket_read, NULL))) {
10231 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
10232 } else {
10233 if (option_verbose > 1)
10234 ast_verbose(VERBOSE_PREFIX_2 "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
10235 defaultsockfd = ast_netsock_sockfd(ns);
10236 ast_netsock_unref(ns);
10237 }
10238 }
10239 if (reload) {
10240 ast_netsock_release(outsock);
10241 outsock = ast_netsock_list_alloc();
10242 if (!outsock) {
10243 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
10244 return -1;
10245 }
10246 ast_netsock_init(outsock);
10247 }
10248
10249 if (min_reg_expire > max_reg_expire) {
10250 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
10251 min_reg_expire, max_reg_expire, max_reg_expire);
10252 min_reg_expire = max_reg_expire;
10253 }
10254 iax2_capability = capability;
10255
10256 ucfg = ast_config_load("users.conf");
10257 if (ucfg) {
10258 struct ast_variable *gen;
10259 int genhasiax;
10260 int genregisteriax;
10261 const char *hasiax, *registeriax;
10262
10263 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
10264 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
10265 gen = ast_variable_browse(ucfg, "general");
10266 cat = ast_category_browse(ucfg, NULL);
10267 while (cat) {
10268 if (strcasecmp(cat, "general")) {
10269 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
10270 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
10271 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
10272
10273 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
10274 if (user) {
10275 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10276 user = user_unref(user);
10277 }
10278 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
10279 if (peer) {
10280 if (ast_test_flag(peer, IAX_DYNAMIC))
10281 reg_source_db(peer);
10282 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10283 peer = peer_unref(peer);
10284 }
10285 }
10286 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
10287 char tmp[256];
10288 const char *host = ast_variable_retrieve(ucfg, cat, "host");
10289 const char *username = ast_variable_retrieve(ucfg, cat, "username");
10290 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
10291 if (!host)
10292 host = ast_variable_retrieve(ucfg, "general", "host");
10293 if (!username)
10294 username = ast_variable_retrieve(ucfg, "general", "username");
10295 if (!secret)
10296 secret = ast_variable_retrieve(ucfg, "general", "secret");
10297 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
10298 if (!ast_strlen_zero(secret))
10299 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
10300 else
10301 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
10302 iax2_register(tmp, 0);
10303 }
10304 }
10305 }
10306 cat = ast_category_browse(ucfg, cat);
10307 }
10308 ast_config_destroy(ucfg);
10309 }
10310
10311 cat = ast_category_browse(cfg, NULL);
10312 while(cat) {
10313 if (strcasecmp(cat, "general")) {
10314 utype = ast_variable_retrieve(cfg, cat, "type");
10315 if (utype) {
10316 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
10317 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
10318 if (user) {
10319 __ao2_link(users, user, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10320 user = user_unref(user);
10321 }
10322 }
10323 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
10324 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
10325 if (peer) {
10326 if (ast_test_flag(peer, IAX_DYNAMIC))
10327 reg_source_db(peer);
10328 __ao2_link(peers, peer, (MAX_PEER_BUCKETS == 1) ? 1 : 0);
10329 peer = peer_unref(peer);
10330 }
10331 } else if (strcasecmp(utype, "user")) {
10332 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
10333 }
10334 } else
10335 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
10336 }
10337 cat = ast_category_browse(cfg, cat);
10338 }
10339 ast_config_destroy(cfg);
10340 set_timing();
10341 return 1;
10342 }
10343
10344 static void poke_all_peers(void)
10345 {
10346 struct ao2_iterator i;
10347 struct iax2_peer *peer;
10348
10349 i = ao2_iterator_init(peers, 0);
10350 while ((peer = ao2_iterator_next(&i))) {
10351 iax2_poke_peer(peer, 0);
10352 peer_unref(peer);
10353 }
10354 }
10355 static int reload_config(void)
10356 {
10357 char *config = "iax.conf";
10358 struct iax2_registry *reg;
10359
10360 if (set_config(config, 1) > 0) {
10361 prune_peers();
10362 prune_users();
10363 AST_LIST_LOCK(®istrations);
10364 AST_LIST_TRAVERSE(®istrations, reg, entry)
10365 iax2_do_register(reg);
10366 AST_LIST_UNLOCK(®istrations);
10367
10368 poke_all_peers();
10369 }
10370 reload_firmware(0);
10371 iax_provision_reload();
10372
10373 return 0;
10374 }
10375
10376 static int iax2_reload(int fd, int argc, char *argv[])
10377 {
10378 return reload_config();
10379 }
10380
10381 static int reload(void)
10382 {
10383 return reload_config();
10384 }
10385
10386 static int cache_get_callno_locked(const char *data)
10387 {
10388 struct sockaddr_in sin;
10389 int x;
10390 int callno;
10391 struct iax_ie_data ied;
10392 struct create_addr_info cai;
10393 struct parsed_dial_string pds;
10394 char *tmpstr;
10395
10396 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
10397
10398
10399 if (!ast_mutex_trylock(&iaxsl[x])) {
10400 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
10401 return x;
10402 ast_mutex_unlock(&iaxsl[x]);
10403 }
10404 }
10405
10406
10407
10408 memset(&cai, 0, sizeof(cai));
10409 memset(&ied, 0, sizeof(ied));
10410 memset(&pds, 0, sizeof(pds));
10411
10412 tmpstr = ast_strdupa(data);
10413 parse_dial_string(tmpstr, &pds);
10414
10415 if (ast_strlen_zero(pds.peer)) {
10416 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
10417 return -1;
10418 }
10419
10420
10421 if (create_addr(pds.peer, NULL, &sin, &cai))
10422 return -1;
10423
10424 if (option_debug)
10425 ast_log(LOG_DEBUG, "peer: %s, username: %s, password: %s, context: %s\n",
10426 pds.peer, pds.username, pds.password, pds.context);
10427
10428 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
10429 if (callno < 1) {
10430 ast_log(LOG_WARNING, "Unable to create call\n");
10431 return -1;
10432 }
10433
10434 ast_string_field_set(iaxs[callno], dproot, data);
10435 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
10436
10437 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
10438 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
10439
10440
10441
10442 if (pds.exten)
10443 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
10444 if (pds.username)
10445 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
10446 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
10447 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
10448
10449 if (pds.password)
10450 ast_string_field_set(iaxs[callno], secret, pds.password);
10451 if (pds.key)
10452 ast_string_field_set(iaxs[callno], outkey, pds.key);
10453
10454 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
10455
10456 return callno;
10457 }
10458
10459 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
10460 {
10461 struct iax2_dpcache *dp, *prev = NULL, *next;
10462 struct timeval tv;
10463 int x;
10464 int com[2];
10465 int timeout;
10466 int old=0;
10467 int outfd;
10468 int abort;
10469 int callno;
10470 struct ast_channel *c;
10471 struct ast_frame *f;
10472 gettimeofday(&tv, NULL);
10473 dp = dpcache;
10474 while(dp) {
10475 next = dp->next;
10476
10477 if (ast_tvcmp(tv, dp->expiry) > 0) {
10478
10479 if (prev)
10480 prev->next = dp->next;
10481 else
10482 dpcache = dp->next;
10483 if (!dp->peer && !(dp->flags & CACHE_FLAG_PENDING) && !dp->callno) {
10484
10485 free(dp);
10486 } else {
10487 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = %p callno = %d)\n", dp->flags, dp->peer, dp->callno);
10488 }
10489 dp = next;
10490 continue;
10491 }
10492
10493 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
10494 break;
10495 prev = dp;
10496 dp = next;
10497 }
10498 if (!dp) {
10499
10500
10501 callno = cache_get_callno_locked(data);
10502 if (callno < 0) {
10503 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
10504 return NULL;
10505 }
10506 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
10507 ast_mutex_unlock(&iaxsl[callno]);
10508 return NULL;
10509 }
10510 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
10511 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
10512 gettimeofday(&dp->expiry, NULL);
10513 dp->orig = dp->expiry;
10514
10515 dp->expiry.tv_sec += iaxdefaultdpcache;
10516 dp->next = dpcache;
10517 dp->flags = CACHE_FLAG_PENDING;
10518 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++)
10519 dp->waiters[x] = -1;
10520 dpcache = dp;
10521 dp->peer = iaxs[callno]->dpentries;
10522 iaxs[callno]->dpentries = dp;
10523
10524 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
10525 iax2_dprequest(dp, callno);
10526 ast_mutex_unlock(&iaxsl[callno]);
10527 }
10528
10529 if (dp->flags & CACHE_FLAG_PENDING) {
10530
10531
10532 for (x=0;x<sizeof(dp->waiters) / sizeof(dp->waiters[0]); x++) {
10533
10534 if (dp->waiters[x] < 0)
10535 break;
10536 }
10537 if (x >= sizeof(dp->waiters) / sizeof(dp->waiters[0])) {
10538 ast_log(LOG_WARNING, "No more waiter positions available\n");
10539 return NULL;
10540 }
10541 if (pipe(com)) {
10542 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
10543 return NULL;
10544 }
10545 dp->waiters[x] = com[1];
10546
10547 timeout = iaxdefaulttimeout * 1000;
10548
10549 ast_mutex_unlock(&dpcache_lock);
10550
10551 if (chan)
10552 old = ast_channel_defer_dtmf(chan);
10553 abort = 0;
10554 while(timeout) {
10555 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
10556 if (outfd > -1) {
10557 break;
10558 }
10559 if (c) {
10560 f = ast_read(c);
10561 if (f)
10562 ast_frfree(f);
10563 else {
10564
10565 break;
10566 abort = 1;
10567 }
10568 }
10569 }
10570 if (!timeout) {
10571 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
10572 }
10573 ast_mutex_lock(&dpcache_lock);
10574 dp->waiters[x] = -1;
10575 close(com[1]);
10576 close(com[0]);
10577 if (abort) {
10578
10579
10580 if (!old && chan)
10581 ast_channel_undefer_dtmf(chan);
10582 return NULL;
10583 }
10584 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
10585
10586 if (dp->flags & CACHE_FLAG_PENDING) {
10587
10588
10589 dp->flags &= ~CACHE_FLAG_PENDING;
10590 dp->flags |= CACHE_FLAG_TIMEOUT;
10591
10592
10593 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
10594 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
10595 if (dp->waiters[x] > -1) {
10596 if (write(dp->waiters[x], "asdf", 4) < 0) {
10597 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
10598 }
10599 }
10600 }
10601 }
10602 }
10603
10604 if (!old && chan)
10605 ast_channel_undefer_dtmf(chan);
10606 }
10607 return dp;
10608 }
10609
10610
10611 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10612 {
10613 struct iax2_dpcache *dp;
10614 int res = 0;
10615 #if 0
10616 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10617 #endif
10618 if ((priority != 1) && (priority != 2))
10619 return 0;
10620 ast_mutex_lock(&dpcache_lock);
10621 dp = find_cache(chan, data, context, exten, priority);
10622 if (dp) {
10623 if (dp->flags & CACHE_FLAG_EXISTS)
10624 res= 1;
10625 }
10626 ast_mutex_unlock(&dpcache_lock);
10627 if (!dp) {
10628 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10629 }
10630 return res;
10631 }
10632
10633
10634 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10635 {
10636 int res = 0;
10637 struct iax2_dpcache *dp;
10638 #if 0
10639 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10640 #endif
10641 if ((priority != 1) && (priority != 2))
10642 return 0;
10643 ast_mutex_lock(&dpcache_lock);
10644 dp = find_cache(chan, data, context, exten, priority);
10645 if (dp) {
10646 if (dp->flags & CACHE_FLAG_CANEXIST)
10647 res= 1;
10648 }
10649 ast_mutex_unlock(&dpcache_lock);
10650 if (!dp) {
10651 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10652 }
10653 return res;
10654 }
10655
10656
10657 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10658 {
10659 int res = 0;
10660 struct iax2_dpcache *dp;
10661 #if 0
10662 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
10663 #endif
10664 if ((priority != 1) && (priority != 2))
10665 return 0;
10666 ast_mutex_lock(&dpcache_lock);
10667 dp = find_cache(chan, data, context, exten, priority);
10668 if (dp) {
10669 if (dp->flags & CACHE_FLAG_MATCHMORE)
10670 res= 1;
10671 }
10672 ast_mutex_unlock(&dpcache_lock);
10673 if (!dp) {
10674 ast_log(LOG_WARNING, "Unable to make DP cache\n");
10675 }
10676 return res;
10677 }
10678
10679
10680 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
10681 {
10682 char odata[256];
10683 char req[256];
10684 char *ncontext;
10685 struct iax2_dpcache *dp;
10686 struct ast_app *dial;
10687 #if 0
10688 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);
10689 #endif
10690 if (priority == 2) {
10691
10692 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
10693 if (dialstatus) {
10694 dial = pbx_findapp(dialstatus);
10695 if (dial)
10696 pbx_exec(chan, dial, "");
10697 }
10698 return -1;
10699 } else if (priority != 1)
10700 return -1;
10701 ast_mutex_lock(&dpcache_lock);
10702 dp = find_cache(chan, data, context, exten, priority);
10703 if (dp) {
10704 if (dp->flags & CACHE_FLAG_EXISTS) {
10705 ast_copy_string(odata, data, sizeof(odata));
10706 ncontext = strchr(odata, '/');
10707 if (ncontext) {
10708 *ncontext = '\0';
10709 ncontext++;
10710 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
10711 } else {
10712 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
10713 }
10714 if (option_verbose > 2)
10715 ast_verbose(VERBOSE_PREFIX_3 "Executing Dial('%s')\n", req);
10716 } else {
10717 ast_mutex_unlock(&dpcache_lock);
10718 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
10719 return -1;
10720 }
10721 }
10722 ast_mutex_unlock(&dpcache_lock);
10723 dial = pbx_findapp("Dial");
10724 if (dial) {
10725 return pbx_exec(chan, dial, req);
10726 } else {
10727 ast_log(LOG_WARNING, "No dial application registered\n");
10728 }
10729 return -1;
10730 }
10731
10732 static int function_iaxpeer(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
10733 {
10734 struct iax2_peer *peer;
10735 char *peername, *colname;
10736
10737 peername = ast_strdupa(data);
10738
10739
10740 if (!strcmp(peername,"CURRENTCHANNEL")) {
10741 unsigned short callno;
10742 if (chan->tech != &iax2_tech)
10743 return -1;
10744 callno = PTR_TO_CALLNO(chan->tech_pvt);
10745 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
10746 return 0;
10747 }
10748
10749 if ((colname = strchr(peername, ':')))
10750 *colname++ = '\0';
10751 else if ((colname = strchr(peername, '|')))
10752 *colname++ = '\0';
10753 else
10754 colname = "ip";
10755
10756 if (!(peer = find_peer(peername, 1)))
10757 return -1;
10758
10759 if (!strcasecmp(colname, "ip")) {
10760 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
10761 } else if (!strcasecmp(colname, "status")) {
10762 peer_status(peer, buf, len);
10763 } else if (!strcasecmp(colname, "mailbox")) {
10764 ast_copy_string(buf, peer->mailbox, len);
10765 } else if (!strcasecmp(colname, "context")) {
10766 ast_copy_string(buf, peer->context, len);
10767 } else if (!strcasecmp(colname, "expire")) {
10768 snprintf(buf, len, "%d", peer->expire);
10769 } else if (!strcasecmp(colname, "dynamic")) {
10770 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
10771 } else if (!strcasecmp(colname, "callerid_name")) {
10772 ast_copy_string(buf, peer->cid_name, len);
10773 } else if (!strcasecmp(colname, "callerid_num")) {
10774 ast_copy_string(buf, peer->cid_num, len);
10775 } else if (!strcasecmp(colname, "codecs")) {
10776 ast_getformatname_multiple(buf, len -1, peer->capability);
10777 } else if (!strncasecmp(colname, "codec[", 6)) {
10778 char *codecnum, *ptr;
10779 int index = 0, codec = 0;
10780
10781 codecnum = strchr(colname, '[');
10782 *codecnum = '\0';
10783 codecnum++;
10784 if ((ptr = strchr(codecnum, ']'))) {
10785 *ptr = '\0';
10786 }
10787 index = atoi(codecnum);
10788 if((codec = ast_codec_pref_index(&peer->prefs, index))) {
10789 ast_copy_string(buf, ast_getformatname(codec), len);
10790 } else {
10791 buf[0] = '\0';
10792 }
10793 } else {
10794 buf[0] = '\0';
10795 }
10796
10797 peer_unref(peer);
10798
10799 return 0;
10800 }
10801
10802 struct ast_custom_function iaxpeer_function = {
10803 .name = "IAXPEER",
10804 .synopsis = "Gets IAX peer information",
10805 .syntax = "IAXPEER(<peername|CURRENTCHANNEL>[|item])",
10806 .read = function_iaxpeer,
10807 .desc = "If peername specified, valid items are:\n"
10808 "- ip (default) The IP address.\n"
10809 "- status The peer's status (if qualify=yes)\n"
10810 "- mailbox The configured mailbox.\n"
10811 "- context The configured context.\n"
10812 "- expire The epoch time of the next expire.\n"
10813 "- dynamic Is it dynamic? (yes/no).\n"
10814 "- callerid_name The configured Caller ID name.\n"
10815 "- callerid_num The configured Caller ID number.\n"
10816 "- codecs The configured codecs.\n"
10817 "- codec[x] Preferred codec index number 'x' (beginning with zero).\n"
10818 "\n"
10819 "If CURRENTCHANNEL specified, returns IP address of current channel\n"
10820 "\n"
10821 };
10822
10823
10824
10825 static int iax2_devicestate(void *data)
10826 {
10827 struct parsed_dial_string pds;
10828 char *tmp = ast_strdupa(data);
10829 struct iax2_peer *p;
10830 int res = AST_DEVICE_INVALID;
10831
10832 memset(&pds, 0, sizeof(pds));
10833 parse_dial_string(tmp, &pds);
10834
10835 if (ast_strlen_zero(pds.peer)) {
10836 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
10837 return res;
10838 }
10839
10840 if (option_debug > 2)
10841 ast_log(LOG_DEBUG, "Checking device state for device %s\n", pds.peer);
10842
10843
10844 if (!(p = find_peer(pds.peer, 1)))
10845 return res;
10846
10847 res = AST_DEVICE_UNAVAILABLE;
10848 if (option_debug > 2)
10849 ast_log(LOG_DEBUG, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
10850 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
10851
10852 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
10853 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
10854
10855
10856 if (p->historicms == 0 || p->historicms <= p->maxms)
10857
10858 res = AST_DEVICE_UNKNOWN;
10859 }
10860
10861 peer_unref(p);
10862
10863 return res;
10864 }
10865
10866 static struct ast_switch iax2_switch =
10867 {
10868 name: "IAX2",
10869 description: "IAX Remote Dialplan Switch",
10870 exists: iax2_exists,
10871 canmatch: iax2_canmatch,
10872 exec: iax2_exec,
10873 matchmore: iax2_matchmore,
10874 };
10875
10876 static char show_stats_usage[] =
10877 "Usage: iax2 show stats\n"
10878 " Display statistics on IAX channel driver.\n";
10879
10880 static char show_cache_usage[] =
10881 "Usage: iax2 show cache\n"
10882 " Display currently cached IAX Dialplan results.\n";
10883
10884 static char show_peer_usage[] =
10885 "Usage: iax2 show peer <name>\n"
10886 " Display details on specific IAX peer\n";
10887
10888 static char prune_realtime_usage[] =
10889 "Usage: iax2 prune realtime [<peername>|all]\n"
10890 " Prunes object(s) from the cache\n";
10891
10892 static char iax2_reload_usage[] =
10893 "Usage: iax2 reload\n"
10894 " Reloads IAX configuration from iax.conf\n";
10895
10896 static char show_prov_usage[] =
10897 "Usage: iax2 provision <host> <template> [forced]\n"
10898 " Provisions the given peer or IP address using a template\n"
10899 " matching either 'template' or '*' if the template is not\n"
10900 " found. If 'forced' is specified, even empty provisioning\n"
10901 " fields will be provisioned as empty fields.\n";
10902
10903 static char show_users_usage[] =
10904 "Usage: iax2 show users [like <pattern>]\n"
10905 " Lists all known IAX2 users.\n"
10906 " Optional regular expression pattern is used to filter the user list.\n";
10907
10908 static char show_channels_usage[] =
10909 "Usage: iax2 show channels\n"
10910 " Lists all currently active IAX channels.\n";
10911
10912 static char show_netstats_usage[] =
10913 "Usage: iax2 show netstats\n"
10914 " Lists network status for all currently active IAX channels.\n";
10915
10916 static char show_threads_usage[] =
10917 "Usage: iax2 show threads\n"
10918 " Lists status of IAX helper threads\n";
10919
10920 static char show_peers_usage[] =
10921 "Usage: iax2 show peers [registered] [like <pattern>]\n"
10922 " Lists all known IAX2 peers.\n"
10923 " Optional 'registered' argument lists only peers with known addresses.\n"
10924 " Optional regular expression pattern is used to filter the peer list.\n";
10925
10926 static char show_firmware_usage[] =
10927 "Usage: iax2 show firmware\n"
10928 " Lists all known IAX firmware images.\n";
10929
10930 static char show_reg_usage[] =
10931 "Usage: iax2 show registry\n"
10932 " Lists all registration requests and status.\n";
10933
10934 static char debug_usage[] =
10935 "Usage: iax2 set debug\n"
10936 " Enables dumping of IAX packets for debugging purposes\n";
10937
10938 static char no_debug_usage[] =
10939 "Usage: iax2 set debug off\n"
10940 " Disables dumping of IAX packets for debugging purposes\n";
10941
10942 static char debug_trunk_usage[] =
10943 "Usage: iax2 set debug trunk\n"
10944 " Requests current status of IAX trunking\n";
10945
10946 static char no_debug_trunk_usage[] =
10947 "Usage: iax2 set debug trunk off\n"
10948 " Requests current status of IAX trunking\n";
10949
10950 static char debug_jb_usage[] =
10951 "Usage: iax2 set debug jb\n"
10952 " Enables jitterbuffer debugging information\n";
10953
10954 static char no_debug_jb_usage[] =
10955 "Usage: iax2 set debug jb off\n"
10956 " Disables jitterbuffer debugging information\n";
10957
10958 static char iax2_test_losspct_usage[] =
10959 "Usage: iax2 test losspct <percentage>\n"
10960 " For testing, throws away <percentage> percent of incoming packets\n";
10961
10962 #ifdef IAXTESTS
10963 static char iax2_test_late_usage[] =
10964 "Usage: iax2 test late <ms>\n"
10965 " For testing, count the next frame as <ms> ms late\n";
10966
10967 static char iax2_test_resync_usage[] =
10968 "Usage: iax2 test resync <ms>\n"
10969 " For testing, adjust all future frames by <ms> ms\n";
10970
10971 static char iax2_test_jitter_usage[] =
10972 "Usage: iax2 test jitter <ms> <pct>\n"
10973 " For testing, simulate maximum jitter of +/- <ms> on <pct> percentage of packets. If <pct> is not specified, adds jitter to all packets.\n";
10974 #endif
10975
10976 static struct ast_cli_entry cli_iax2_trunk_debug_deprecated = {
10977 { "iax2", "trunk", "debug", NULL },
10978 iax2_do_trunk_debug, NULL,
10979 NULL };
10980
10981 static struct ast_cli_entry cli_iax2_jb_debug_deprecated = {
10982 { "iax2", "jb", "debug", NULL },
10983 iax2_do_jb_debug, NULL,
10984 NULL };
10985
10986 static struct ast_cli_entry cli_iax2_no_debug_deprecated = {
10987 { "iax2", "no", "debug", NULL },
10988 iax2_no_debug, NULL,
10989 NULL };
10990
10991 static struct ast_cli_entry cli_iax2_no_trunk_debug_deprecated = {
10992 { "iax2", "no", "trunk", "debug", NULL },
10993 iax2_no_trunk_debug, NULL,
10994 NULL };
10995
10996 static struct ast_cli_entry cli_iax2_no_jb_debug_deprecated = {
10997 { "iax2", "no", "jb", "debug", NULL },
10998 iax2_no_jb_debug, NULL,
10999 NULL };
11000
11001 static struct ast_cli_entry cli_iax2[] = {
11002 { { "iax2", "show", "cache", NULL },
11003 iax2_show_cache, "Display IAX cached dialplan",
11004 show_cache_usage, NULL, },
11005
11006 { { "iax2", "show", "channels", NULL },
11007 iax2_show_channels, "List active IAX channels",
11008 show_channels_usage, NULL, },
11009
11010 { { "iax2", "show", "firmware", NULL },
11011 iax2_show_firmware, "List available IAX firmwares",
11012 show_firmware_usage, NULL, },
11013
11014 { { "iax2", "show", "netstats", NULL },
11015 iax2_show_netstats, "List active IAX channel netstats",
11016 show_netstats_usage, NULL, },
11017
11018 { { "iax2", "show", "peers", NULL },
11019 iax2_show_peers, "List defined IAX peers",
11020 show_peers_usage, NULL, },
11021
11022 { { "iax2", "show", "registry", NULL },
11023 iax2_show_registry, "Display IAX registration status",
11024 show_reg_usage, NULL, },
11025
11026 { { "iax2", "show", "stats", NULL },
11027 iax2_show_stats, "Display IAX statistics",
11028 show_stats_usage, NULL, },
11029
11030 { { "iax2", "show", "threads", NULL },
11031 iax2_show_threads, "Display IAX helper thread info",
11032 show_threads_usage, NULL, },
11033
11034 { { "iax2", "show", "users", NULL },
11035 iax2_show_users, "List defined IAX users",
11036 show_users_usage, NULL, },
11037
11038 { { "iax2", "prune", "realtime", NULL },
11039 iax2_prune_realtime, "Prune a cached realtime lookup",
11040 prune_realtime_usage, complete_iax2_show_peer },
11041
11042 { { "iax2", "reload", NULL },
11043 iax2_reload, "Reload IAX configuration",
11044 iax2_reload_usage },
11045
11046 { { "iax2", "show", "peer", NULL },
11047 iax2_show_peer, "Show details on specific IAX peer",
11048 show_peer_usage, complete_iax2_show_peer },
11049
11050 { { "iax2", "set", "debug", NULL },
11051 iax2_do_debug, "Enable IAX debugging",
11052 debug_usage },
11053
11054 { { "iax2", "set", "debug", "trunk", NULL },
11055 iax2_do_trunk_debug, "Enable IAX trunk debugging",
11056 debug_trunk_usage, NULL, &cli_iax2_trunk_debug_deprecated },
11057
11058 { { "iax2", "set", "debug", "jb", NULL },
11059 iax2_do_jb_debug, "Enable IAX jitterbuffer debugging",
11060 debug_jb_usage, NULL, &cli_iax2_jb_debug_deprecated },
11061
11062 { { "iax2", "set", "debug", "off", NULL },
11063 iax2_no_debug, "Disable IAX debugging",
11064 no_debug_usage, NULL, &cli_iax2_no_debug_deprecated },
11065
11066 { { "iax2", "set", "debug", "trunk", "off", NULL },
11067 iax2_no_trunk_debug, "Disable IAX trunk debugging",
11068 no_debug_trunk_usage, NULL, &cli_iax2_no_trunk_debug_deprecated },
11069
11070 { { "iax2", "set", "debug", "jb", "off", NULL },
11071 iax2_no_jb_debug, "Disable IAX jitterbuffer debugging",
11072 no_debug_jb_usage, NULL, &cli_iax2_no_jb_debug_deprecated },
11073
11074 { { "iax2", "test", "losspct", NULL },
11075 iax2_test_losspct, "Set IAX2 incoming frame loss percentage",
11076 iax2_test_losspct_usage },
11077
11078 { { "iax2", "provision", NULL },
11079 iax2_prov_cmd, "Provision an IAX device",
11080 show_prov_usage, iax2_prov_complete_template_3rd },
11081
11082 #ifdef IAXTESTS
11083 { { "iax2", "test", "late", NULL },
11084 iax2_test_late, "Test the receipt of a late frame",
11085 iax2_test_late_usage },
11086
11087 { { "iax2", "test", "resync", NULL },
11088 iax2_test_resync, "Test a resync in received timestamps",
11089 iax2_test_resync_usage },
11090
11091 { { "iax2", "test", "jitter", NULL },
11092 iax2_test_jitter, "Simulates jitter for testing",
11093 iax2_test_jitter_usage },
11094 #endif
11095 };
11096
11097 static int __unload_module(void)
11098 {
11099 struct iax2_thread *thread = NULL;
11100 int x;
11101
11102
11103
11104
11105
11106 if (netthreadid != AST_PTHREADT_NULL) {
11107 AST_LIST_LOCK(&iaxq.queue);
11108 ast_mutex_lock(&sched_lock);
11109 pthread_cancel(netthreadid);
11110 ast_cond_signal(&sched_cond);
11111 ast_mutex_unlock(&sched_lock);
11112 AST_LIST_UNLOCK(&iaxq.queue);
11113 pthread_join(netthreadid, NULL);
11114 }
11115 if (schedthreadid != AST_PTHREADT_NULL) {
11116 ast_mutex_lock(&sched_lock);
11117 pthread_cancel(schedthreadid);
11118 ast_cond_signal(&sched_cond);
11119 ast_mutex_unlock(&sched_lock);
11120 pthread_join(schedthreadid, NULL);
11121 }
11122
11123
11124 AST_LIST_LOCK(&idle_list);
11125 AST_LIST_TRAVERSE_SAFE_BEGIN(&idle_list, thread, list) {
11126 AST_LIST_REMOVE_CURRENT(&idle_list, list);
11127 pthread_cancel(thread->threadid);
11128 }
11129 AST_LIST_TRAVERSE_SAFE_END
11130 AST_LIST_UNLOCK(&idle_list);
11131
11132 AST_LIST_LOCK(&active_list);
11133 AST_LIST_TRAVERSE_SAFE_BEGIN(&active_list, thread, list) {
11134 AST_LIST_REMOVE_CURRENT(&active_list, list);
11135 pthread_cancel(thread->threadid);
11136 }
11137 AST_LIST_TRAVERSE_SAFE_END
11138 AST_LIST_UNLOCK(&active_list);
11139
11140 AST_LIST_LOCK(&dynamic_list);
11141 AST_LIST_TRAVERSE_SAFE_BEGIN(&dynamic_list, thread, list) {
11142 AST_LIST_REMOVE_CURRENT(&dynamic_list, list);
11143 pthread_cancel(thread->threadid);
11144 }
11145 AST_LIST_TRAVERSE_SAFE_END
11146 AST_LIST_UNLOCK(&dynamic_list);
11147
11148 AST_LIST_HEAD_DESTROY(&iaxq.queue);
11149
11150
11151 while(0 < iaxactivethreadcount)
11152 usleep(10000);
11153
11154 ast_netsock_release(netsock);
11155 ast_netsock_release(outsock);
11156 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
11157 if (iaxs[x]) {
11158 iax2_destroy(x);
11159 }
11160 }
11161 ast_manager_unregister( "IAXpeers" );
11162 ast_manager_unregister( "IAXnetstats" );
11163 ast_unregister_application(papp);
11164 ast_cli_unregister_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
11165 ast_unregister_switch(&iax2_switch);
11166 ast_channel_unregister(&iax2_tech);
11167 delete_users();
11168 iax_provision_unload();
11169 sched_context_destroy(sched);
11170 reload_firmware(1);
11171
11172 ast_mutex_destroy(&waresl.lock);
11173
11174 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
11175 ast_mutex_destroy(&iaxsl[x]);
11176 }
11177
11178 ao2_ref(peers, -1);
11179 ao2_ref(users, -1);
11180 ao2_ref(iax_peercallno_pvts, -1);
11181
11182 return 0;
11183 }
11184
11185 static int unload_module(void)
11186 {
11187 ast_custom_function_unregister(&iaxpeer_function);
11188 return __unload_module();
11189 }
11190
11191 static int peer_set_sock_cb(void *obj, void *arg, int flags)
11192 {
11193 struct iax2_peer *peer = obj;
11194
11195 if (peer->sockfd < 0)
11196 peer->sockfd = defaultsockfd;
11197
11198 return 0;
11199 }
11200
11201 static int pvt_hash_cb(const void *obj, const int flags)
11202 {
11203 const struct chan_iax2_pvt *pvt = obj;
11204
11205 return pvt->peercallno;
11206 }
11207
11208 static int pvt_cmp_cb(void *obj, void *arg, int flags)
11209 {
11210 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
11211
11212
11213
11214
11215 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
11216 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
11217 }
11218
11219
11220 static int load_module(void)
11221 {
11222 char *config = "iax.conf";
11223 int res = 0;
11224 int x;
11225 struct iax2_registry *reg = NULL;
11226
11227 peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb);
11228 if (!peers)
11229 return AST_MODULE_LOAD_FAILURE;
11230 users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb);
11231 if (!users) {
11232 ao2_ref(peers, -1);
11233 return AST_MODULE_LOAD_FAILURE;
11234 }
11235 iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb);
11236 if (!iax_peercallno_pvts) {
11237 ao2_ref(peers, -1);
11238 ao2_ref(users, -1);
11239 return AST_MODULE_LOAD_FAILURE;
11240 }
11241
11242 ast_custom_function_register(&iaxpeer_function);
11243
11244 iax_set_output(iax_debug_output);
11245 iax_set_error(iax_error_output);
11246 jb_setoutput(jb_error_output, jb_warning_output, NULL);
11247
11248 #ifdef HAVE_ZAPTEL
11249 #ifdef ZAPTEL_TIMERACK
11250 timingfd = open("/dev/zap/timer", O_RDWR);
11251 if (timingfd < 0)
11252 #endif
11253 timingfd = open("/dev/zap/pseudo", O_RDWR);
11254 if (timingfd < 0)
11255 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
11256 #elif defined(HAVE_DAHDI)
11257 #ifdef DAHDI_TIMERACK
11258 timingfd = open("/dev/dahdi/timer", O_RDWR);
11259 if (timingfd < 0)
11260 #endif
11261 timingfd = open("/dev/dahdi/pseudo", O_RDWR);
11262 if (timingfd < 0)
11263 ast_log(LOG_WARNING, "Unable to open IAX timing interface: %s\n", strerror(errno));
11264 #endif
11265
11266 memset(iaxs, 0, sizeof(iaxs));
11267
11268 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
11269 ast_mutex_init(&iaxsl[x]);
11270 }
11271
11272 ast_cond_init(&sched_cond, NULL);
11273
11274 io = io_context_create();
11275 sched = sched_context_create();
11276
11277 if (!io || !sched) {
11278 ast_log(LOG_ERROR, "Out of memory\n");
11279 return -1;
11280 }
11281
11282 netsock = ast_netsock_list_alloc();
11283 if (!netsock) {
11284 ast_log(LOG_ERROR, "Could not allocate netsock list.\n");
11285 return -1;
11286 }
11287 ast_netsock_init(netsock);
11288
11289 outsock = ast_netsock_list_alloc();
11290 if (!outsock) {
11291 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
11292 return -1;
11293 }
11294 ast_netsock_init(outsock);
11295
11296 ast_mutex_init(&waresl.lock);
11297
11298 AST_LIST_HEAD_INIT(&iaxq.queue);
11299
11300 ast_cli_register_multiple(cli_iax2, sizeof(cli_iax2) / sizeof(struct ast_cli_entry));
11301
11302 ast_register_application(papp, iax2_prov_app, psyn, pdescrip);
11303
11304 ast_manager_register( "IAXpeers", 0, manager_iax2_show_peers, "List IAX Peers" );
11305 ast_manager_register( "IAXnetstats", 0, manager_iax2_show_netstats, "Show IAX Netstats" );
11306
11307 if(set_config(config, 0) == -1)
11308 return AST_MODULE_LOAD_DECLINE;
11309
11310 if (ast_channel_register(&iax2_tech)) {
11311 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
11312 __unload_module();
11313 return -1;
11314 }
11315
11316 if (ast_register_switch(&iax2_switch))
11317 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
11318
11319 res = start_network_thread();
11320 if (!res) {
11321 if (option_verbose > 1)
11322 ast_verbose(VERBOSE_PREFIX_2 "IAX Ready and Listening\n");
11323 } else {
11324 ast_log(LOG_ERROR, "Unable to start network thread\n");
11325 ast_netsock_release(netsock);
11326 ast_netsock_release(outsock);
11327 }
11328
11329 AST_LIST_LOCK(®istrations);
11330 AST_LIST_TRAVERSE(®istrations, reg, entry)
11331 iax2_do_register(reg);
11332 AST_LIST_UNLOCK(®istrations);
11333
11334 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
11335 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
11336
11337 reload_firmware(0);
11338 iax_provision_reload();
11339 return res;
11340 }
11341
11342 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
11343 .load = load_module,
11344 .unload = unload_module,
11345 .reload = reload,
11346 );