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
00037
00038
00039 #include "asterisk.h"
00040
00041 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 368759 $")
00042
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 <strings.h>
00054 #include <netdb.h>
00055 #include <fcntl.h>
00056 #include <sys/stat.h>
00057 #include <regex.h>
00058
00059 #include "asterisk/paths.h"
00060
00061 #include "asterisk/lock.h"
00062 #include "asterisk/frame.h"
00063 #include "asterisk/channel.h"
00064 #include "asterisk/module.h"
00065 #include "asterisk/pbx.h"
00066 #include "asterisk/sched.h"
00067 #include "asterisk/io.h"
00068 #include "asterisk/config.h"
00069 #include "asterisk/cli.h"
00070 #include "asterisk/translate.h"
00071 #include "asterisk/md5.h"
00072 #include "asterisk/cdr.h"
00073 #include "asterisk/crypto.h"
00074 #include "asterisk/acl.h"
00075 #include "asterisk/manager.h"
00076 #include "asterisk/callerid.h"
00077 #include "asterisk/app.h"
00078 #include "asterisk/astdb.h"
00079 #include "asterisk/musiconhold.h"
00080 #include "asterisk/features.h"
00081 #include "asterisk/utils.h"
00082 #include "asterisk/causes.h"
00083 #include "asterisk/localtime.h"
00084 #include "asterisk/dnsmgr.h"
00085 #include "asterisk/devicestate.h"
00086 #include "asterisk/netsock.h"
00087 #include "asterisk/stringfields.h"
00088 #include "asterisk/linkedlists.h"
00089 #include "asterisk/event.h"
00090 #include "asterisk/astobj2.h"
00091 #include "asterisk/timing.h"
00092 #include "asterisk/taskprocessor.h"
00093 #include "asterisk/test.h"
00094 #include "asterisk/data.h"
00095 #include "asterisk/netsock2.h"
00096
00097 #include "iax2.h"
00098 #include "iax2-parser.h"
00099 #include "iax2-provision.h"
00100 #include "jitterbuf.h"
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
00151
00152
00153
00154
00155
00156
00157
00158
00159
00160
00161
00162
00163
00164
00165
00166
00167
00168
00169
00170
00171
00172
00173
00174
00175
00176
00177
00178
00179
00180
00181
00182
00183
00184
00185
00186
00187
00188
00189
00190
00191
00192
00193
00194
00195
00196
00197
00198
00199
00200
00201
00202
00203
00204
00205
00206
00207
00208
00209
00210
00211
00212
00213
00214
00215
00216
00217
00218
00219
00220
00221
00222
00223
00224
00225
00226
00227
00228
00229
00230
00231 #define SCHED_MULTITHREADED
00232
00233
00234
00235 #define DEBUG_SCHED_MULTITHREAD
00236
00237
00238 #ifdef SO_NO_CHECK
00239 static int nochecksums = 0;
00240 #endif
00241
00242 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00243 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00244
00245 #define DEFAULT_THREAD_COUNT 10
00246 #define DEFAULT_MAX_THREAD_COUNT 100
00247 #define DEFAULT_RETRY_TIME 1000
00248 #define MEMORY_SIZE 100
00249 #define DEFAULT_DROP 3
00250
00251 #define DEBUG_SUPPORT
00252
00253 #define MIN_REUSE_TIME 60
00254
00255
00256 #define GAMMA (0.01)
00257
00258 static struct ast_codec_pref prefs;
00259
00260 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00261
00262
00263
00264
00265 #define MAX_TRUNK_MTU 1240
00266
00267 static int global_max_trunk_mtu;
00268 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;
00269
00270 #define DEFAULT_CONTEXT "default"
00271
00272 static char default_parkinglot[AST_MAX_CONTEXT];
00273
00274 static char language[MAX_LANGUAGE] = "";
00275 static char regcontext[AST_MAX_CONTEXT] = "";
00276
00277 static struct ast_event_sub *network_change_event_subscription;
00278 static int network_change_event_sched_id = -1;
00279
00280 static int maxauthreq = 3;
00281 static int max_retries = 4;
00282 static int ping_time = 21;
00283 static int lagrq_time = 10;
00284 static int maxjitterbuffer=1000;
00285 static int resyncthreshold=1000;
00286 static int maxjitterinterps=10;
00287 static int jittertargetextra = 40;
00288
00289 #define MAX_TRUNKDATA 640 * 200
00290
00291 static int trunkfreq = 20;
00292 static int trunkmaxsize = MAX_TRUNKDATA;
00293
00294 static int authdebug = 1;
00295 static int autokill = 0;
00296 static int iaxcompat = 0;
00297 static int last_authmethod = 0;
00298
00299 static int iaxdefaultdpcache=10 * 60;
00300
00301 static int iaxdefaulttimeout = 5;
00302
00303 static struct {
00304 unsigned int tos;
00305 unsigned int cos;
00306 } qos = { 0, 0 };
00307
00308 static int min_reg_expire;
00309 static int max_reg_expire;
00310
00311 static int srvlookup = 0;
00312
00313 static struct ast_timer *timer;
00314
00315 static struct ast_netsock_list *netsock;
00316 static struct ast_netsock_list *outsock;
00317 static int defaultsockfd = -1;
00318
00319 static int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00320
00321
00322 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
00323
00324 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00325 ~AST_FORMAT_SLINEAR & \
00326 ~AST_FORMAT_SLINEAR16 & \
00327 ~AST_FORMAT_SIREN7 & \
00328 ~AST_FORMAT_SIREN14 & \
00329 ~AST_FORMAT_G719 & \
00330 ~AST_FORMAT_ULAW & \
00331 ~AST_FORMAT_ALAW & \
00332 ~AST_FORMAT_G722)
00333
00334 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00335 ~AST_FORMAT_G726 & \
00336 ~AST_FORMAT_G726_AAL2 & \
00337 ~AST_FORMAT_ADPCM)
00338
00339 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
00340 ~AST_FORMAT_G723_1)
00341
00342
00343 #define DEFAULT_MAXMS 2000
00344 #define DEFAULT_FREQ_OK 60 * 1000
00345 #define DEFAULT_FREQ_NOTOK 10 * 1000
00346
00347
00348 #define IAX_CALLENCRYPTED(pvt) \
00349 (ast_test_flag64(pvt, IAX_ENCRYPTED) && ast_test_flag64(pvt, IAX_KEYPOPULATED))
00350
00351 #define IAX_DEBUGDIGEST(msg, key) do { \
00352 int idx; \
00353 char digest[33] = ""; \
00354 \
00355 if (!iaxdebug) \
00356 break; \
00357 \
00358 for (idx = 0; idx < 16; idx++) \
00359 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00360 \
00361 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00362 } while(0)
00363
00364 static struct io_context *io;
00365 static struct ast_sched_thread *sched;
00366
00367 #define DONT_RESCHEDULE -2
00368
00369 static format_t iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00370
00371 static int iaxdebug = 0;
00372
00373 static int iaxtrunkdebug = 0;
00374
00375 static int test_losspct = 0;
00376 #ifdef IAXTESTS
00377 static int test_late = 0;
00378 static int test_resync = 0;
00379 static int test_jit = 0;
00380 static int test_jitpct = 0;
00381 #endif
00382
00383 static char accountcode[AST_MAX_ACCOUNT_CODE];
00384 static char mohinterpret[MAX_MUSICCLASS];
00385 static char mohsuggest[MAX_MUSICCLASS];
00386 static int amaflags = 0;
00387 static int adsi = 0;
00388 static int delayreject = 0;
00389 static int iax2_encryption = 0;
00390
00391 static struct ast_flags64 globalflags = { 0 };
00392
00393 static pthread_t netthreadid = AST_PTHREADT_NULL;
00394
00395 enum iax2_state {
00396 IAX_STATE_STARTED = (1 << 0),
00397 IAX_STATE_AUTHENTICATED = (1 << 1),
00398 IAX_STATE_TBD = (1 << 2),
00399 };
00400
00401 struct iax2_context {
00402 char context[AST_MAX_CONTEXT];
00403 struct iax2_context *next;
00404 };
00405
00406
00407 #define IAX_HASCALLERID (uint64_t)(1 << 0)
00408 #define IAX_DELME (uint64_t)(1 << 1)
00409 #define IAX_TEMPONLY (uint64_t)(1 << 2)
00410 #define IAX_TRUNK (uint64_t)(1 << 3)
00411 #define IAX_NOTRANSFER (uint64_t)(1 << 4)
00412 #define IAX_USEJITTERBUF (uint64_t)(1 << 5)
00413 #define IAX_DYNAMIC (uint64_t)(1 << 6)
00414 #define IAX_SENDANI (uint64_t)(1 << 7)
00415 #define IAX_RTSAVE_SYSNAME (uint64_t)(1 << 8)
00416 #define IAX_ALREADYGONE (uint64_t)(1 << 9)
00417 #define IAX_PROVISION (uint64_t)(1 << 10)
00418 #define IAX_QUELCH (uint64_t)(1 << 11)
00419 #define IAX_ENCRYPTED (uint64_t)(1 << 12)
00420 #define IAX_KEYPOPULATED (uint64_t)(1 << 13)
00421 #define IAX_CODEC_USER_FIRST (uint64_t)(1 << 14)
00422 #define IAX_CODEC_NOPREFS (uint64_t)(1 << 15)
00423 #define IAX_CODEC_NOCAP (uint64_t)(1 << 16)
00424 #define IAX_RTCACHEFRIENDS (uint64_t)(1 << 17)
00425 #define IAX_RTUPDATE (uint64_t)(1 << 18)
00426 #define IAX_RTAUTOCLEAR (uint64_t)(1 << 19)
00427 #define IAX_FORCEJITTERBUF (uint64_t)(1 << 20)
00428 #define IAX_RTIGNOREREGEXPIRE (uint64_t)(1 << 21)
00429 #define IAX_TRUNKTIMESTAMPS (uint64_t)(1 << 22)
00430 #define IAX_TRANSFERMEDIA (uint64_t)(1 << 23)
00431 #define IAX_MAXAUTHREQ (uint64_t)(1 << 24)
00432 #define IAX_DELAYPBXSTART (uint64_t)(1 << 25)
00433 #define IAX_ALLOWFWDOWNLOAD (uint64_t)(1 << 26)
00434 #define IAX_IMMEDIATE (uint64_t)(1 << 27)
00435 #define IAX_SENDCONNECTEDLINE (uint64_t)(1 << 28)
00436 #define IAX_RECVCONNECTEDLINE (uint64_t)(1 << 29)
00437 #define IAX_FORCE_ENCRYPT (uint64_t)(1 << 30)
00438 #define IAX_SHRINKCALLERID (uint64_t)(1 << 31)
00439 static int global_rtautoclear = 120;
00440
00441 static int reload_config(void);
00442
00443
00444
00445
00446 enum calltoken_peer_enum {
00447
00448 CALLTOKEN_DEFAULT = 0,
00449
00450 CALLTOKEN_YES = 1,
00451
00452
00453 CALLTOKEN_AUTO = 2,
00454
00455 CALLTOKEN_NO = 3,
00456 };
00457
00458 struct iax2_user {
00459 AST_DECLARE_STRING_FIELDS(
00460 AST_STRING_FIELD(name);
00461 AST_STRING_FIELD(secret);
00462 AST_STRING_FIELD(dbsecret);
00463 AST_STRING_FIELD(accountcode);
00464 AST_STRING_FIELD(mohinterpret);
00465 AST_STRING_FIELD(mohsuggest);
00466 AST_STRING_FIELD(inkeys);
00467 AST_STRING_FIELD(language);
00468 AST_STRING_FIELD(cid_num);
00469 AST_STRING_FIELD(cid_name);
00470 AST_STRING_FIELD(parkinglot);
00471 );
00472
00473 int authmethods;
00474 int encmethods;
00475 int amaflags;
00476 int adsi;
00477 uint64_t flags;
00478 format_t capability;
00479 int maxauthreq;
00480 int curauthreq;
00481 struct ast_codec_pref prefs;
00482 struct ast_ha *ha;
00483 struct iax2_context *contexts;
00484 struct ast_variable *vars;
00485 enum calltoken_peer_enum calltoken_required;
00486 };
00487
00488 struct iax2_peer {
00489 AST_DECLARE_STRING_FIELDS(
00490 AST_STRING_FIELD(name);
00491 AST_STRING_FIELD(username);
00492 AST_STRING_FIELD(secret);
00493 AST_STRING_FIELD(dbsecret);
00494 AST_STRING_FIELD(outkey);
00495
00496 AST_STRING_FIELD(regexten);
00497 AST_STRING_FIELD(context);
00498 AST_STRING_FIELD(peercontext);
00499 AST_STRING_FIELD(mailbox);
00500 AST_STRING_FIELD(mohinterpret);
00501 AST_STRING_FIELD(mohsuggest);
00502 AST_STRING_FIELD(inkeys);
00503
00504 AST_STRING_FIELD(cid_num);
00505 AST_STRING_FIELD(cid_name);
00506 AST_STRING_FIELD(zonetag);
00507 AST_STRING_FIELD(parkinglot);
00508 );
00509 struct ast_codec_pref prefs;
00510 struct ast_dnsmgr_entry *dnsmgr;
00511 struct ast_sockaddr addr;
00512 int formats;
00513 int sockfd;
00514 struct in_addr mask;
00515 int adsi;
00516 uint64_t flags;
00517
00518
00519 struct sockaddr_in defaddr;
00520 int authmethods;
00521 int encmethods;
00522
00523 int expire;
00524 int expiry;
00525 format_t capability;
00526
00527
00528 int callno;
00529 int pokeexpire;
00530 int lastms;
00531 int maxms;
00532
00533 int pokefreqok;
00534 int pokefreqnotok;
00535 int historicms;
00536 int smoothing;
00537 uint16_t maxcallno;
00538
00539 struct ast_event_sub *mwi_event_sub;
00540
00541 struct ast_ha *ha;
00542 enum calltoken_peer_enum calltoken_required;
00543 };
00544
00545 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00546
00547 struct iax2_trunk_peer {
00548 ast_mutex_t lock;
00549 int sockfd;
00550 struct sockaddr_in addr;
00551 struct timeval txtrunktime;
00552 struct timeval rxtrunktime;
00553 struct timeval lasttxtime;
00554 struct timeval trunkact;
00555 unsigned int lastsent;
00556
00557 unsigned char *trunkdata;
00558 unsigned int trunkdatalen;
00559 unsigned int trunkdataalloc;
00560 int trunkmaxmtu;
00561 int trunkerror;
00562 int calls;
00563 AST_LIST_ENTRY(iax2_trunk_peer) list;
00564 };
00565
00566 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00567
00568 struct iax_firmware {
00569 AST_LIST_ENTRY(iax_firmware) list;
00570 int fd;
00571 int mmaplen;
00572 int dead;
00573 struct ast_iax2_firmware_header *fwh;
00574 unsigned char *buf;
00575 };
00576
00577 enum iax_reg_state {
00578 REG_STATE_UNREGISTERED = 0,
00579 REG_STATE_REGSENT,
00580 REG_STATE_AUTHSENT,
00581 REG_STATE_REGISTERED,
00582 REG_STATE_REJECTED,
00583 REG_STATE_TIMEOUT,
00584 REG_STATE_NOAUTH
00585 };
00586
00587 enum iax_transfer_state {
00588 TRANSFER_NONE = 0,
00589 TRANSFER_BEGIN,
00590 TRANSFER_READY,
00591 TRANSFER_RELEASED,
00592 TRANSFER_PASSTHROUGH,
00593 TRANSFER_MBEGIN,
00594 TRANSFER_MREADY,
00595 TRANSFER_MRELEASED,
00596 TRANSFER_MPASSTHROUGH,
00597 TRANSFER_MEDIA,
00598 TRANSFER_MEDIAPASS
00599 };
00600
00601 struct iax2_registry {
00602 struct ast_sockaddr addr;
00603 char username[80];
00604 char secret[80];
00605 int expire;
00606 int refresh;
00607 enum iax_reg_state regstate;
00608 int messages;
00609 int callno;
00610 struct sockaddr_in us;
00611 struct ast_dnsmgr_entry *dnsmgr;
00612 AST_LIST_ENTRY(iax2_registry) entry;
00613 };
00614
00615 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00616
00617
00618 #define MIN_RETRY_TIME 100
00619 #define MAX_RETRY_TIME 10000
00620
00621 #define MAX_JITTER_BUFFER 50
00622 #define MIN_JITTER_BUFFER 10
00623
00624 #define DEFAULT_TRUNKDATA 640 * 10
00625
00626 #define MAX_TIMESTAMP_SKEW 160
00627
00628
00629 #define TS_GAP_FOR_JB_RESYNC 5000
00630
00631
00632 #define MARK_IAX_SUBCLASS_TX 0x8000
00633
00634 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00635 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00636 static int iaxdynamicthreadcount = 0;
00637 static int iaxdynamicthreadnum = 0;
00638 static int iaxactivethreadcount = 0;
00639
00640 struct iax_rr {
00641 int jitter;
00642 int losspct;
00643 int losscnt;
00644 int packets;
00645 int delay;
00646 int dropped;
00647 int ooo;
00648 };
00649
00650 struct iax2_pvt_ref;
00651
00652 struct chan_iax2_pvt {
00653
00654 int sockfd;
00655
00656 format_t voiceformat;
00657
00658 format_t videoformat;
00659
00660 format_t svoiceformat;
00661
00662 format_t svideoformat;
00663
00664 format_t capability;
00665
00666 unsigned int last;
00667
00668 unsigned int lastsent;
00669
00670 unsigned int lastvsent;
00671
00672 unsigned int nextpred;
00673
00674 int first_iax_message;
00675
00676 int last_iax_message;
00677
00678 unsigned int notsilenttx:1;
00679
00680 unsigned int pingtime;
00681
00682 int maxtime;
00683
00684 struct sockaddr_in addr;
00685
00686 struct ast_codec_pref prefs;
00687
00688 struct ast_codec_pref rprefs;
00689
00690 unsigned short callno;
00691
00692 struct callno_entry *callno_entry;
00693
00694 unsigned short peercallno;
00695
00696
00697
00698 format_t chosenformat;
00699
00700 format_t peerformat;
00701
00702 format_t peercapability;
00703
00704 struct timeval offset;
00705
00706 struct timeval rxcore;
00707
00708 jitterbuf *jb;
00709
00710 int jbid;
00711
00712 int lag;
00713
00714 int error;
00715
00716 struct ast_channel *owner;
00717
00718 struct ast_flags state;
00719
00720 int expiry;
00721
00722 unsigned char oseqno;
00723
00724 unsigned char rseqno;
00725
00726 unsigned char iseqno;
00727
00728 unsigned char aseqno;
00729
00730 AST_DECLARE_STRING_FIELDS(
00731
00732 AST_STRING_FIELD(peer);
00733
00734 AST_STRING_FIELD(context);
00735
00736 AST_STRING_FIELD(cid_num);
00737 AST_STRING_FIELD(cid_name);
00738
00739 AST_STRING_FIELD(ani);
00740
00741 AST_STRING_FIELD(dnid);
00742
00743 AST_STRING_FIELD(rdnis);
00744
00745 AST_STRING_FIELD(exten);
00746
00747 AST_STRING_FIELD(username);
00748
00749 AST_STRING_FIELD(secret);
00750
00751 AST_STRING_FIELD(challenge);
00752
00753 AST_STRING_FIELD(inkeys);
00754
00755 AST_STRING_FIELD(outkey);
00756
00757 AST_STRING_FIELD(language);
00758
00759 AST_STRING_FIELD(host);
00760
00761 AST_STRING_FIELD(dproot);
00762 AST_STRING_FIELD(accountcode);
00763 AST_STRING_FIELD(mohinterpret);
00764 AST_STRING_FIELD(mohsuggest);
00765
00766 AST_STRING_FIELD(osptoken);
00767
00768 AST_STRING_FIELD(parkinglot);
00769 );
00770
00771 int authrej;
00772
00773 int authmethods;
00774
00775 int encmethods;
00776
00777 ast_aes_encrypt_key ecx;
00778
00779 ast_aes_decrypt_key mydcx;
00780
00781 ast_aes_decrypt_key dcx;
00782
00783
00784 int keyrotateid;
00785
00786 unsigned char semirand[32];
00787
00788 struct iax2_registry *reg;
00789
00790 struct iax2_peer *peerpoke;
00791
00792 uint64_t flags;
00793 int adsi;
00794
00795
00796 enum iax_transfer_state transferring;
00797
00798 int transferid;
00799
00800 struct sockaddr_in transfer;
00801
00802 unsigned short transfercallno;
00803
00804 ast_aes_encrypt_key tdcx;
00805
00806
00807 int peeradsicpe;
00808
00809
00810 unsigned short bridgecallno;
00811
00812 int pingid;
00813 int lagid;
00814 int autoid;
00815 int authid;
00816 int authfail;
00817 int initid;
00818 int calling_ton;
00819 int calling_tns;
00820 int calling_pres;
00821 int amaflags;
00822 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00823
00824 struct ast_variable *vars;
00825
00826 struct ast_variable *iaxvars;
00827
00828 struct iax_rr remote_rr;
00829
00830 int min;
00831
00832 int frames_dropped;
00833
00834 int frames_received;
00835
00836 unsigned char calltoken_ie_len;
00837
00838 char hold_signaling;
00839
00840 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00841 };
00842
00843 struct signaling_queue_entry {
00844 struct ast_frame f;
00845 AST_LIST_ENTRY(signaling_queue_entry) next;
00846 };
00847
00848
00849 static struct ao2_container *callno_pool;
00850
00851
00852 static struct ao2_container *callno_pool_trunk;
00853
00854 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00855
00856
00857
00858
00859
00860
00861
00862
00863
00864
00865 static AST_LIST_HEAD_NOLOCK(, iax_frame) frame_queue[IAX_MAX_CALLS + 1];
00866
00867 static struct ast_taskprocessor *transmit_processor;
00868
00869 static int randomcalltokendata;
00870
00871 static const time_t MAX_CALLTOKEN_DELAY = 10;
00872
00873
00874
00875
00876
00877
00878
00879
00880 #ifdef LOW_MEMORY
00881 #define MAX_PEER_BUCKETS 17
00882 #else
00883 #define MAX_PEER_BUCKETS 563
00884 #endif
00885 static struct ao2_container *peers;
00886
00887 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00888 static struct ao2_container *users;
00889
00890
00891 static struct ao2_container *peercnts;
00892
00893
00894 static struct ao2_container *callno_limits;
00895
00896
00897 static struct ao2_container *calltoken_ignores;
00898
00899 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00900
00901 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00902
00903 static uint16_t global_maxcallno;
00904
00905
00906 static uint16_t global_maxcallno_nonval;
00907
00908 static uint16_t total_nonval_callno_used = 0;
00909
00910
00911
00912 struct peercnt {
00913
00914 unsigned long addr;
00915
00916 uint16_t cur;
00917
00918 uint16_t limit;
00919
00920
00921 unsigned char reg;
00922 };
00923
00924
00925 struct addr_range {
00926
00927 struct ast_ha ha;
00928
00929 uint16_t limit;
00930
00931 unsigned char delme;
00932 };
00933
00934 struct callno_entry {
00935
00936 uint16_t callno;
00937
00938 unsigned char validated;
00939 };
00940
00941 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00942
00943 enum {
00944
00945 CACHE_FLAG_EXISTS = (1 << 0),
00946
00947 CACHE_FLAG_NONEXISTENT = (1 << 1),
00948
00949 CACHE_FLAG_CANEXIST = (1 << 2),
00950
00951 CACHE_FLAG_PENDING = (1 << 3),
00952
00953 CACHE_FLAG_TIMEOUT = (1 << 4),
00954
00955 CACHE_FLAG_TRANSMITTED = (1 << 5),
00956
00957 CACHE_FLAG_UNKNOWN = (1 << 6),
00958
00959 CACHE_FLAG_MATCHMORE = (1 << 7),
00960 };
00961
00962 struct iax2_dpcache {
00963 char peercontext[AST_MAX_CONTEXT];
00964 char exten[AST_MAX_EXTENSION];
00965 struct timeval orig;
00966 struct timeval expiry;
00967 int flags;
00968 unsigned short callno;
00969 int waiters[256];
00970 AST_LIST_ENTRY(iax2_dpcache) cache_list;
00971 AST_LIST_ENTRY(iax2_dpcache) peer_list;
00972 };
00973
00974 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00975
00976 static void reg_source_db(struct iax2_peer *p);
00977 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00978 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00979
00980 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00981 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags);
00982 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00983
00984 enum iax2_thread_iostate {
00985 IAX_IOSTATE_IDLE,
00986 IAX_IOSTATE_READY,
00987 IAX_IOSTATE_PROCESSING,
00988 IAX_IOSTATE_SCHEDREADY,
00989 };
00990
00991 enum iax2_thread_type {
00992 IAX_THREAD_TYPE_POOL,
00993 IAX_THREAD_TYPE_DYNAMIC,
00994 };
00995
00996 struct iax2_pkt_buf {
00997 AST_LIST_ENTRY(iax2_pkt_buf) entry;
00998 size_t len;
00999 unsigned char buf[1];
01000 };
01001
01002 struct iax2_thread {
01003 AST_LIST_ENTRY(iax2_thread) list;
01004 enum iax2_thread_type type;
01005 enum iax2_thread_iostate iostate;
01006 #ifdef SCHED_MULTITHREADED
01007 void (*schedfunc)(const void *);
01008 const void *scheddata;
01009 #endif
01010 #ifdef DEBUG_SCHED_MULTITHREAD
01011 char curfunc[80];
01012 #endif
01013 int actions;
01014 pthread_t threadid;
01015 int threadnum;
01016 struct sockaddr_in iosin;
01017 unsigned char readbuf[4096];
01018 unsigned char *buf;
01019 ssize_t buf_len;
01020 size_t buf_size;
01021 int iofd;
01022 time_t checktime;
01023 ast_mutex_t lock;
01024 ast_cond_t cond;
01025 ast_mutex_t init_lock;
01026 ast_cond_t init_cond;
01027
01028
01029
01030
01031 struct {
01032 unsigned short callno;
01033 struct sockaddr_in sin;
01034 unsigned char type;
01035 unsigned char csub;
01036 } ffinfo;
01037
01038
01039
01040 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
01041 unsigned char stop;
01042 };
01043
01044
01045 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
01046 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
01047 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
01048
01049 static void *iax2_process_thread(void *data);
01050 static void iax2_destroy(int callno);
01051
01052 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
01053 {
01054 ast_mutex_lock(lock);
01055 ast_cond_signal(cond);
01056 ast_mutex_unlock(lock);
01057 }
01058
01059
01060
01061
01062
01063
01064
01065
01066
01067 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
01068
01069
01070
01071
01072
01073
01074
01075
01076
01077
01078 static struct ao2_container *iax_peercallno_pvts;
01079
01080
01081
01082
01083
01084
01085
01086
01087 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01088
01089
01090
01091
01092
01093
01094 static struct ao2_container *iax_transfercallno_pvts;
01095
01096
01097
01098 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
01099
01100
01101 static struct sockaddr_in debugaddr;
01102
01103 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01104 {
01105 if (iaxdebug ||
01106 (sin && debugaddr.sin_addr.s_addr &&
01107 (!ntohs(debugaddr.sin_port) ||
01108 debugaddr.sin_port == sin->sin_port) &&
01109 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01110 if (iaxdebug) {
01111 iax_showframe(f, fhi, rx, sin, datalen);
01112 } else {
01113 iaxdebug = 1;
01114 iax_showframe(f, fhi, rx, sin, datalen);
01115 iaxdebug = 0;
01116 }
01117 }
01118 }
01119
01120 static void iax_debug_output(const char *data)
01121 {
01122 if (iaxdebug)
01123 ast_verbose("%s", data);
01124 }
01125
01126 static void iax_error_output(const char *data)
01127 {
01128 ast_log(LOG_WARNING, "%s", data);
01129 }
01130
01131 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01132 {
01133 va_list args;
01134 char buf[1024];
01135
01136 va_start(args, fmt);
01137 vsnprintf(buf, sizeof(buf), fmt, args);
01138 va_end(args);
01139
01140 ast_log(LOG_ERROR, "%s", buf);
01141 }
01142
01143 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01144 {
01145 va_list args;
01146 char buf[1024];
01147
01148 va_start(args, fmt);
01149 vsnprintf(buf, sizeof(buf), fmt, args);
01150 va_end(args);
01151
01152 ast_log(LOG_WARNING, "%s", buf);
01153 }
01154
01155 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01156 {
01157 va_list args;
01158 char buf[1024];
01159
01160 va_start(args, fmt);
01161 vsnprintf(buf, sizeof(buf), fmt, args);
01162 va_end(args);
01163
01164 ast_verbose("%s", buf);
01165 }
01166
01167 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);
01168 static int expire_registry(const void *data);
01169 static int iax2_answer(struct ast_channel *c);
01170 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
01171 static int iax2_devicestate(void *data);
01172 static int iax2_digit_begin(struct ast_channel *c, char digit);
01173 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01174 static int iax2_do_register(struct iax2_registry *reg);
01175 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01176 static int iax2_hangup(struct ast_channel *c);
01177 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01178 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01179 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force);
01180 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01181 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01182 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01183 static int iax2_sendtext(struct ast_channel *c, const char *text);
01184 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01185 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen);
01186 static int iax2_transfer(struct ast_channel *c, const char *dest);
01187 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01188 static int iax2_sched_add(struct ast_sched_thread *st, int when, ast_sched_cb callback, const void *data);
01189
01190 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01191 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01192 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01193 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01194 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01195 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01196 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause);
01197 static struct ast_frame *iax2_read(struct ast_channel *c);
01198 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01199 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01200 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime);
01201 static void *iax2_dup_variable_datastore(void *);
01202 static void prune_peers(void);
01203 static void prune_users(void);
01204 static void iax2_free_variable_datastore(void *);
01205
01206 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01207 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01208 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01209 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01210 static void build_rand_pad(unsigned char *buf, ssize_t len);
01211 static struct callno_entry *get_unused_callno(int trunk, int validated);
01212 static int replace_callno(const void *obj);
01213 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01214 static void network_change_event_cb(const struct ast_event *, void *);
01215
01216 static const struct ast_channel_tech iax2_tech = {
01217 .type = "IAX2",
01218 .description = tdesc,
01219 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
01220 .properties = AST_CHAN_TP_WANTSJITTER,
01221 .requester = iax2_request,
01222 .devicestate = iax2_devicestate,
01223 .send_digit_begin = iax2_digit_begin,
01224 .send_digit_end = iax2_digit_end,
01225 .send_text = iax2_sendtext,
01226 .send_image = iax2_sendimage,
01227 .send_html = iax2_sendhtml,
01228 .call = iax2_call,
01229 .hangup = iax2_hangup,
01230 .answer = iax2_answer,
01231 .read = iax2_read,
01232 .write = iax2_write,
01233 .write_video = iax2_write,
01234 .indicate = iax2_indicate,
01235 .setoption = iax2_setoption,
01236 .queryoption = iax2_queryoption,
01237 .bridge = iax2_bridge,
01238 .transfer = iax2_transfer,
01239 .fixup = iax2_fixup,
01240 .func_channel_read = acf_channel_read,
01241 };
01242
01243
01244
01245
01246
01247
01248
01249
01250
01251
01252
01253
01254
01255
01256
01257
01258
01259
01260 static void iax2_lock_owner(int callno)
01261 {
01262 for (;;) {
01263 if (!iaxs[callno] || !iaxs[callno]->owner) {
01264
01265 break;
01266 }
01267 if (!ast_channel_trylock(iaxs[callno]->owner)) {
01268
01269 break;
01270 }
01271
01272 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01273 }
01274 }
01275
01276 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01277 {
01278
01279
01280
01281 }
01282
01283 static void network_change_event_subscribe(void)
01284 {
01285 if (!network_change_event_subscription) {
01286 network_change_event_subscription = ast_event_subscribe(AST_EVENT_NETWORK_CHANGE,
01287 network_change_event_cb, "IAX2 Network Change", NULL, AST_EVENT_IE_END);
01288 }
01289 }
01290
01291 static void network_change_event_unsubscribe(void)
01292 {
01293 if (network_change_event_subscription) {
01294 network_change_event_subscription = ast_event_unsubscribe(network_change_event_subscription);
01295 }
01296 }
01297
01298 static int network_change_event_sched_cb(const void *data)
01299 {
01300 struct iax2_registry *reg;
01301 network_change_event_sched_id = -1;
01302 AST_LIST_LOCK(®istrations);
01303 AST_LIST_TRAVERSE(®istrations, reg, entry) {
01304 iax2_do_register(reg);
01305 }
01306 AST_LIST_UNLOCK(®istrations);
01307
01308 return 0;
01309 }
01310
01311 static void network_change_event_cb(const struct ast_event *event, void *userdata)
01312 {
01313 ast_debug(1, "IAX, got a network change event, renewing all IAX registrations.\n");
01314 if (network_change_event_sched_id == -1) {
01315 network_change_event_sched_id = iax2_sched_add(sched, 1000, network_change_event_sched_cb, NULL);
01316 }
01317
01318 }
01319
01320
01321
01322
01323 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
01324 {
01325 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01326 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01327 pvt->owner ? pvt->owner->name : "",
01328 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01329 }
01330
01331 static struct ast_datastore_info iax2_variable_datastore_info = {
01332 .type = "IAX2_VARIABLE",
01333 .duplicate = iax2_dup_variable_datastore,
01334 .destroy = iax2_free_variable_datastore,
01335 };
01336
01337 static void *iax2_dup_variable_datastore(void *old)
01338 {
01339 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01340 struct ast_var_t *oldvar, *newvar;
01341
01342 newlist = ast_calloc(sizeof(*newlist), 1);
01343 if (!newlist) {
01344 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01345 return NULL;
01346 }
01347
01348 AST_LIST_HEAD_INIT(newlist);
01349 AST_LIST_LOCK(oldlist);
01350 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01351 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01352 if (newvar)
01353 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01354 else
01355 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01356 }
01357 AST_LIST_UNLOCK(oldlist);
01358 return newlist;
01359 }
01360
01361 static void iax2_free_variable_datastore(void *old)
01362 {
01363 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01364 struct ast_var_t *oldvar;
01365
01366 AST_LIST_LOCK(oldlist);
01367 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01368 ast_free(oldvar);
01369 }
01370 AST_LIST_UNLOCK(oldlist);
01371 AST_LIST_HEAD_DESTROY(oldlist);
01372 ast_free(oldlist);
01373 }
01374
01375
01376
01377
01378
01379 static void insert_idle_thread(struct iax2_thread *thread)
01380 {
01381 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01382 AST_LIST_LOCK(&dynamic_list);
01383 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01384 AST_LIST_UNLOCK(&dynamic_list);
01385 } else {
01386 AST_LIST_LOCK(&idle_list);
01387 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01388 AST_LIST_UNLOCK(&idle_list);
01389 }
01390
01391 return;
01392 }
01393
01394 static struct iax2_thread *find_idle_thread(void)
01395 {
01396 struct iax2_thread *thread = NULL;
01397
01398
01399 AST_LIST_LOCK(&idle_list);
01400 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01401 AST_LIST_UNLOCK(&idle_list);
01402
01403
01404 if (thread) {
01405 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01406 return thread;
01407 }
01408
01409
01410 AST_LIST_LOCK(&dynamic_list);
01411 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01412 AST_LIST_UNLOCK(&dynamic_list);
01413
01414
01415 if (thread) {
01416 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01417 return thread;
01418 }
01419
01420
01421 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01422 return NULL;
01423
01424
01425 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01426 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01427 thread->type = IAX_THREAD_TYPE_DYNAMIC;
01428
01429
01430 ast_mutex_init(&thread->lock);
01431 ast_cond_init(&thread->cond, NULL);
01432 ast_mutex_init(&thread->init_lock);
01433 ast_cond_init(&thread->init_cond, NULL);
01434 ast_mutex_lock(&thread->init_lock);
01435
01436
01437 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01438 ast_cond_destroy(&thread->cond);
01439 ast_mutex_destroy(&thread->lock);
01440 ast_mutex_unlock(&thread->init_lock);
01441 ast_cond_destroy(&thread->init_cond);
01442 ast_mutex_destroy(&thread->init_lock);
01443 ast_free(thread);
01444 return NULL;
01445 }
01446
01447
01448
01449 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01450
01451
01452 ast_cond_wait(&thread->init_cond, &thread->init_lock);
01453
01454
01455 ast_mutex_unlock(&thread->init_lock);
01456
01457 return thread;
01458 }
01459
01460 #ifdef SCHED_MULTITHREADED
01461 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01462 {
01463 struct iax2_thread *thread = NULL;
01464 static time_t lasterror;
01465 static time_t t;
01466
01467 thread = find_idle_thread();
01468
01469 if (thread != NULL) {
01470 thread->schedfunc = func;
01471 thread->scheddata = data;
01472 thread->iostate = IAX_IOSTATE_SCHEDREADY;
01473 #ifdef DEBUG_SCHED_MULTITHREAD
01474 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01475 #endif
01476 signal_condition(&thread->lock, &thread->cond);
01477 return 0;
01478 }
01479 time(&t);
01480 if (t != lasterror)
01481 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
01482 lasterror = t;
01483
01484 return -1;
01485 }
01486 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01487 #endif
01488
01489 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
01490 ast_sched_cb callback, const void *data)
01491 {
01492 ast_sched_thread_del(st, id);
01493
01494 return ast_sched_thread_add(st, when, callback, data);
01495 }
01496
01497 static int iax2_sched_add(struct ast_sched_thread *st, int when,
01498 ast_sched_cb callback, const void *data)
01499 {
01500 return ast_sched_thread_add(st, when, callback, data);
01501 }
01502
01503 static int send_ping(const void *data);
01504
01505 static void __send_ping(const void *data)
01506 {
01507 int callno = (long) data;
01508
01509 ast_mutex_lock(&iaxsl[callno]);
01510
01511 if (iaxs[callno]) {
01512 if (iaxs[callno]->peercallno) {
01513 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01514 if (iaxs[callno]->pingid != DONT_RESCHEDULE) {
01515 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01516 }
01517 }
01518 } else {
01519 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01520 }
01521
01522 ast_mutex_unlock(&iaxsl[callno]);
01523 }
01524
01525 static int send_ping(const void *data)
01526 {
01527 int callno = (long) data;
01528 ast_mutex_lock(&iaxsl[callno]);
01529 if (iaxs[callno] && iaxs[callno]->pingid != DONT_RESCHEDULE) {
01530 iaxs[callno]->pingid = -1;
01531 }
01532 ast_mutex_unlock(&iaxsl[callno]);
01533
01534 #ifdef SCHED_MULTITHREADED
01535 if (schedule_action(__send_ping, data))
01536 #endif
01537 __send_ping(data);
01538
01539 return 0;
01540 }
01541
01542 static void encmethods_to_str(int e, struct ast_str *buf)
01543 {
01544 ast_str_set(&buf, 0, "(");
01545 if (e & IAX_ENCRYPT_AES128) {
01546 ast_str_append(&buf, 0, "aes128");
01547 }
01548 if (e & IAX_ENCRYPT_KEYROTATE) {
01549 ast_str_append(&buf, 0, ",keyrotate");
01550 }
01551 if (ast_str_strlen(buf) > 1) {
01552 ast_str_append(&buf, 0, ")");
01553 } else {
01554 ast_str_set(&buf, 0, "No");
01555 }
01556 }
01557
01558 static int get_encrypt_methods(const char *s)
01559 {
01560 int e;
01561 if (!strcasecmp(s, "aes128"))
01562 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01563 else if (ast_true(s))
01564 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01565 else
01566 e = 0;
01567 return e;
01568 }
01569
01570 static int send_lagrq(const void *data);
01571
01572 static void __send_lagrq(const void *data)
01573 {
01574 int callno = (long) data;
01575
01576 ast_mutex_lock(&iaxsl[callno]);
01577
01578 if (iaxs[callno]) {
01579 if (iaxs[callno]->peercallno) {
01580 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01581 if (iaxs[callno]->lagid != DONT_RESCHEDULE) {
01582 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01583 }
01584 }
01585 } else {
01586 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01587 }
01588
01589 ast_mutex_unlock(&iaxsl[callno]);
01590 }
01591
01592 static int send_lagrq(const void *data)
01593 {
01594 int callno = (long) data;
01595 ast_mutex_lock(&iaxsl[callno]);
01596 if (iaxs[callno] && iaxs[callno]->lagid != DONT_RESCHEDULE) {
01597 iaxs[callno]->lagid = -1;
01598 }
01599 ast_mutex_unlock(&iaxsl[callno]);
01600
01601 #ifdef SCHED_MULTITHREADED
01602 if (schedule_action(__send_lagrq, data))
01603 #endif
01604 __send_lagrq(data);
01605 return 0;
01606 }
01607
01608 static unsigned char compress_subclass(format_t subclass)
01609 {
01610 int x;
01611 int power=-1;
01612
01613 if (subclass < IAX_FLAG_SC_LOG)
01614 return subclass;
01615
01616 for (x = 0; x < IAX_MAX_SHIFT; x++) {
01617 if (subclass & (1LL << x)) {
01618 if (power > -1) {
01619 ast_log(LOG_WARNING, "Can't compress subclass %lld\n", (long long) subclass);
01620 return 0;
01621 } else
01622 power = x;
01623 }
01624 }
01625 return power | IAX_FLAG_SC_LOG;
01626 }
01627
01628 static format_t uncompress_subclass(unsigned char csub)
01629 {
01630
01631 if (csub & IAX_FLAG_SC_LOG) {
01632
01633 if (csub == 0xff)
01634 return -1;
01635 else
01636 return 1LL << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01637 }
01638 else
01639 return csub;
01640 }
01641
01642
01643
01644
01645 static int peer_hash_cb(const void *obj, const int flags)
01646 {
01647 const struct iax2_peer *peer = obj;
01648
01649 return ast_str_hash(peer->name);
01650 }
01651
01652
01653
01654
01655 static int peer_cmp_cb(void *obj, void *arg, int flags)
01656 {
01657 struct iax2_peer *peer = obj, *peer2 = arg;
01658
01659 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01660 }
01661
01662
01663
01664
01665 static int user_hash_cb(const void *obj, const int flags)
01666 {
01667 const struct iax2_user *user = obj;
01668
01669 return ast_str_hash(user->name);
01670 }
01671
01672
01673
01674
01675 static int user_cmp_cb(void *obj, void *arg, int flags)
01676 {
01677 struct iax2_user *user = obj, *user2 = arg;
01678
01679 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01680 }
01681
01682
01683
01684
01685
01686 static struct iax2_peer *find_peer(const char *name, int realtime)
01687 {
01688 struct iax2_peer *peer = NULL;
01689 struct iax2_peer tmp_peer = {
01690 .name = name,
01691 };
01692
01693 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01694
01695
01696 if(!peer && realtime)
01697 peer = realtime_peer(name, NULL);
01698
01699 return peer;
01700 }
01701
01702 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01703 {
01704 ao2_ref(peer, +1);
01705 return peer;
01706 }
01707
01708 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01709 {
01710 ao2_ref(peer, -1);
01711 return NULL;
01712 }
01713
01714 static struct iax2_user *find_user(const char *name)
01715 {
01716 struct iax2_user tmp_user = {
01717 .name = name,
01718 };
01719
01720 return ao2_find(users, &tmp_user, OBJ_POINTER);
01721 }
01722 static inline struct iax2_user *user_ref(struct iax2_user *user)
01723 {
01724 ao2_ref(user, +1);
01725 return user;
01726 }
01727
01728 static inline struct iax2_user *user_unref(struct iax2_user *user)
01729 {
01730 ao2_ref(user, -1);
01731 return NULL;
01732 }
01733
01734 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01735 {
01736 struct iax2_peer *peer = NULL;
01737 int res = 0;
01738 struct ao2_iterator i;
01739
01740 i = ao2_iterator_init(peers, 0);
01741 while ((peer = ao2_iterator_next(&i))) {
01742 struct sockaddr_in peer_addr;
01743
01744 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
01745
01746 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01747 (peer_addr.sin_port == sin.sin_port)) {
01748 ast_copy_string(host, peer->name, len);
01749 peer_unref(peer);
01750 res = 1;
01751 break;
01752 }
01753 peer_unref(peer);
01754 }
01755 ao2_iterator_destroy(&i);
01756
01757 if (!peer) {
01758 peer = realtime_peer(NULL, &sin);
01759 if (peer) {
01760 ast_copy_string(host, peer->name, len);
01761 peer_unref(peer);
01762 res = 1;
01763 }
01764 }
01765
01766 return res;
01767 }
01768
01769
01770
01771 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01772 {
01773
01774 if (ast_test_flag64(pvt, IAX_MAXAUTHREQ)) {
01775 struct iax2_user *user;
01776 struct iax2_user tmp_user = {
01777 .name = pvt->username,
01778 };
01779
01780 user = ao2_find(users, &tmp_user, OBJ_POINTER);
01781 if (user) {
01782 ast_atomic_fetchadd_int(&user->curauthreq, -1);
01783 user_unref(user);
01784 }
01785
01786 ast_clear_flag64(pvt, IAX_MAXAUTHREQ);
01787 }
01788
01789 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
01790 pvt->pingid = DONT_RESCHEDULE;
01791 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
01792 pvt->lagid = DONT_RESCHEDULE;
01793 ast_sched_thread_del(sched, pvt->autoid);
01794 ast_sched_thread_del(sched, pvt->authid);
01795 ast_sched_thread_del(sched, pvt->initid);
01796 ast_sched_thread_del(sched, pvt->jbid);
01797 ast_sched_thread_del(sched, pvt->keyrotateid);
01798 }
01799
01800 static void iax2_frame_free(struct iax_frame *fr)
01801 {
01802 ast_sched_thread_del(sched, fr->retrans);
01803 iax_frame_free(fr);
01804 }
01805
01806 static int scheduled_destroy(const void *vid)
01807 {
01808 unsigned short callno = PTR_TO_CALLNO(vid);
01809 ast_mutex_lock(&iaxsl[callno]);
01810 if (iaxs[callno]) {
01811 if (option_debug) {
01812 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01813 }
01814 iax2_destroy(callno);
01815 }
01816 ast_mutex_unlock(&iaxsl[callno]);
01817 return 0;
01818 }
01819
01820 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
01821 {
01822 if (s->f.datalen) {
01823 ast_free(s->f.data.ptr);
01824 }
01825 ast_free(s);
01826 }
01827
01828
01829
01830 static void send_signaling(struct chan_iax2_pvt *pvt)
01831 {
01832 struct signaling_queue_entry *s = NULL;
01833
01834 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01835 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
01836 free_signaling_queue_entry(s);
01837 }
01838 pvt->hold_signaling = 0;
01839 }
01840
01841
01842
01843 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
01844 {
01845 struct signaling_queue_entry *qe;
01846
01847 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
01848 return 1;
01849 } else if (!(qe = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
01850 return -1;
01851 }
01852
01853
01854 qe->f = *f;
01855 if (qe->f.datalen) {
01856
01857 if (!(qe->f.data.ptr = ast_malloc(qe->f.datalen))) {
01858 free_signaling_queue_entry(qe);
01859 return -1;
01860 }
01861 memcpy(qe->f.data.ptr, f->data.ptr, qe->f.datalen);
01862 }
01863 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, qe, next);
01864
01865 return 0;
01866 }
01867
01868 static void pvt_destructor(void *obj)
01869 {
01870 struct chan_iax2_pvt *pvt = obj;
01871 struct iax_frame *cur = NULL;
01872 struct signaling_queue_entry *s = NULL;
01873
01874 ast_mutex_lock(&iaxsl[pvt->callno]);
01875
01876 iax2_destroy_helper(pvt);
01877
01878 sched_delay_remove(&pvt->addr, pvt->callno_entry);
01879 pvt->callno_entry = NULL;
01880
01881
01882 ast_set_flag64(pvt, IAX_ALREADYGONE);
01883
01884 AST_LIST_TRAVERSE(&frame_queue[pvt->callno], cur, list) {
01885
01886 cur->retries = -1;
01887 }
01888
01889 ast_mutex_unlock(&iaxsl[pvt->callno]);
01890
01891 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01892 free_signaling_queue_entry(s);
01893 }
01894
01895 if (pvt->reg) {
01896 pvt->reg->callno = 0;
01897 }
01898
01899 if (!pvt->owner) {
01900 jb_frame frame;
01901 if (pvt->vars) {
01902 ast_variables_destroy(pvt->vars);
01903 pvt->vars = NULL;
01904 }
01905
01906 while (jb_getall(pvt->jb, &frame) == JB_OK) {
01907 iax2_frame_free(frame.data);
01908 }
01909
01910 jb_destroy(pvt->jb);
01911 ast_string_field_free_memory(pvt);
01912 }
01913 }
01914
01915 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01916 {
01917 struct chan_iax2_pvt *tmp;
01918 jb_conf jbconf;
01919
01920 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01921 return NULL;
01922 }
01923
01924 if (ast_string_field_init(tmp, 32)) {
01925 ao2_ref(tmp, -1);
01926 tmp = NULL;
01927 return NULL;
01928 }
01929
01930 tmp->prefs = prefs;
01931 tmp->pingid = -1;
01932 tmp->lagid = -1;
01933 tmp->autoid = -1;
01934 tmp->authid = -1;
01935 tmp->initid = -1;
01936 tmp->keyrotateid = -1;
01937
01938 ast_string_field_set(tmp,exten, "s");
01939 ast_string_field_set(tmp,host, host);
01940
01941 tmp->jb = jb_new();
01942 tmp->jbid = -1;
01943 jbconf.max_jitterbuf = maxjitterbuffer;
01944 jbconf.resync_threshold = resyncthreshold;
01945 jbconf.max_contig_interp = maxjitterinterps;
01946 jbconf.target_extra = jittertargetextra;
01947 jb_setconf(tmp->jb,&jbconf);
01948
01949 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
01950
01951 tmp->hold_signaling = 1;
01952 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
01953
01954 return tmp;
01955 }
01956
01957 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01958 {
01959 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01960 if (new) {
01961 size_t afdatalen = new->afdatalen;
01962 memcpy(new, fr, sizeof(*new));
01963 iax_frame_wrap(new, &fr->af);
01964 new->afdatalen = afdatalen;
01965 new->data = NULL;
01966 new->datalen = 0;
01967 new->direction = DIRECTION_INGRESS;
01968 new->retrans = -1;
01969 }
01970 return new;
01971 }
01972
01973
01974 enum {
01975
01976 NEW_PREVENT = 0,
01977
01978 NEW_ALLOW = 1,
01979
01980 NEW_FORCE = 2,
01981
01982
01983 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
01984 };
01985
01986 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
01987 {
01988 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01989 (cur->addr.sin_port == sin->sin_port)) {
01990
01991 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01992 (check_dcallno ? dcallno == cur->callno : 1) ) {
01993
01994 return 1;
01995 }
01996 }
01997 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01998 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01999
02000 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
02001 return 1;
02002 }
02003 return 0;
02004 }
02005
02006 #ifdef IAX_OLD_FIND
02007
02008 static int maxtrunkcall = TRUNK_CALL_START;
02009 static int maxnontrunkcall = 1;
02010
02011 #define update_max_trunk() __update_max_trunk()
02012 #define update_max_nontrunk() __update_max_nontrunk()
02013
02014 static void __update_max_trunk(void)
02015 {
02016 int max = TRUNK_CALL_START;
02017 int x;
02018
02019
02020 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
02021 if (iaxs[x]) {
02022 max = x + 1;
02023 }
02024 }
02025
02026 maxtrunkcall = max;
02027 if (iaxdebug)
02028 ast_debug(1, "New max trunk callno is %d\n", max);
02029 }
02030
02031 static void __update_max_nontrunk(void)
02032 {
02033 int max = 1;
02034 int x;
02035
02036 for (x=1;x<TRUNK_CALL_START - 1; x++) {
02037 if (iaxs[x])
02038 max = x + 1;
02039 }
02040 maxnontrunkcall = max;
02041 if (iaxdebug)
02042 ast_debug(1, "New max nontrunk callno is %d\n", max);
02043 }
02044
02045 #else
02046
02047 #define update_max_trunk() do { } while (0)
02048 #define update_max_nontrunk() do { } while (0)
02049
02050 #endif
02051
02052 static int make_trunk(unsigned short callno, int locked)
02053 {
02054 int x;
02055 int res= 0;
02056 struct callno_entry *callno_entry;
02057 if (iaxs[callno]->oseqno) {
02058 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
02059 return -1;
02060 }
02061 if (callno & TRUNK_CALL_START) {
02062 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
02063 return -1;
02064 }
02065
02066 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
02067 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
02068 return -1;
02069 }
02070
02071 x = callno_entry->callno;
02072 ast_mutex_lock(&iaxsl[x]);
02073
02074
02075
02076
02077
02078 ast_sched_thread_del(sched, iaxs[callno]->pingid);
02079 ast_sched_thread_del(sched, iaxs[callno]->lagid);
02080 iaxs[callno]->lagid = iaxs[callno]->pingid = -1;
02081 iaxs[x] = iaxs[callno];
02082 iaxs[x]->callno = x;
02083
02084
02085
02086 if (iaxs[x]->callno_entry) {
02087 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
02088 }
02089 iaxs[x]->callno_entry = callno_entry;
02090
02091 iaxs[callno] = NULL;
02092
02093 iaxs[x]->pingid = iax2_sched_add(sched,
02094 ping_time * 1000, send_ping, (void *)(long)x);
02095 iaxs[x]->lagid = iax2_sched_add(sched,
02096 lagrq_time * 1000, send_lagrq, (void *)(long)x);
02097
02098 if (locked)
02099 ast_mutex_unlock(&iaxsl[callno]);
02100 res = x;
02101 if (!locked)
02102 ast_mutex_unlock(&iaxsl[x]);
02103
02104 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
02105
02106 update_max_trunk();
02107 update_max_nontrunk();
02108 return res;
02109 }
02110
02111 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
02112 {
02113 if (!pvt->transfercallno) {
02114 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02115 return;
02116 }
02117
02118 ao2_link(iax_transfercallno_pvts, pvt);
02119 }
02120
02121 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
02122 {
02123 if (!pvt->transfercallno) {
02124 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
02125 return;
02126 }
02127
02128 ao2_unlink(iax_transfercallno_pvts, pvt);
02129 }
02130 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
02131 {
02132 if (!pvt->peercallno) {
02133 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02134 return;
02135 }
02136
02137 ao2_link(iax_peercallno_pvts, pvt);
02138 }
02139
02140 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02141 {
02142 if (!pvt->peercallno) {
02143 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02144 return;
02145 }
02146
02147 ao2_unlink(iax_peercallno_pvts, pvt);
02148 }
02149
02150 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02151 {
02152 struct addr_range *lim = obj;
02153 lim->delme = 1;
02154 return 0;
02155 }
02156
02157 static int addr_range_hash_cb(const void *obj, const int flags)
02158 {
02159 const struct addr_range *lim = obj;
02160 struct sockaddr_in sin;
02161 ast_sockaddr_to_sin(&lim->ha.addr, &sin);
02162 return abs((int) sin.sin_addr.s_addr);
02163 }
02164
02165 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02166 {
02167 struct addr_range *lim1 = obj, *lim2 = arg;
02168 return (!(ast_sockaddr_cmp_addr(&lim1->ha.addr, &lim2->ha.addr)) &&
02169 !(ast_sockaddr_cmp_addr(&lim1->ha.netmask, &lim2->ha.netmask))) ?
02170 CMP_MATCH | CMP_STOP : 0;
02171 }
02172
02173 static int peercnt_hash_cb(const void *obj, const int flags)
02174 {
02175 const struct peercnt *peercnt = obj;
02176 return abs((int) peercnt->addr);
02177 }
02178
02179 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02180 {
02181 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02182 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02183 }
02184
02185 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02186 {
02187 struct addr_range *addr_range = obj;
02188 struct sockaddr_in *sin = arg;
02189 struct sockaddr_in ha_netmask_sin;
02190 struct sockaddr_in ha_addr_sin;
02191
02192 ast_sockaddr_to_sin(&addr_range->ha.netmask, &ha_netmask_sin);
02193 ast_sockaddr_to_sin(&addr_range->ha.addr, &ha_addr_sin);
02194
02195 if ((sin->sin_addr.s_addr & ha_netmask_sin.sin_addr.s_addr) == ha_addr_sin.sin_addr.s_addr) {
02196 return CMP_MATCH | CMP_STOP;
02197 }
02198 return 0;
02199 }
02200
02201
02202
02203
02204
02205
02206 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02207 {
02208 struct addr_range *addr_range;
02209 struct iax2_peer *peer = NULL;
02210 struct iax2_user *user = NULL;
02211
02212 const char *find = S_OR(name, "guest");
02213 int res = 1;
02214 int optional = 0;
02215 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02216
02217
02218
02219
02220
02221
02222
02223 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02224 ao2_ref(addr_range, -1);
02225 optional = 1;
02226 }
02227
02228
02229 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02230 calltoken_required = user->calltoken_required;
02231 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02232 calltoken_required = user->calltoken_required;
02233 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02234 calltoken_required = peer->calltoken_required;
02235 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02236 calltoken_required = peer->calltoken_required;
02237 }
02238
02239 if (peer) {
02240 peer_unref(peer);
02241 }
02242 if (user) {
02243 user_unref(user);
02244 }
02245
02246 ast_debug(1, "Determining if address %s with username %s requires calltoken validation. Optional = %d calltoken_required = %d \n", ast_inet_ntoa(sin->sin_addr), name, optional, calltoken_required);
02247 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02248 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02249 res = 0;
02250 }
02251
02252 return res;
02253 }
02254
02255
02256
02257
02258
02259
02260
02261
02262
02263
02264
02265 static void set_peercnt_limit(struct peercnt *peercnt)
02266 {
02267 uint16_t limit = global_maxcallno;
02268 struct addr_range *addr_range;
02269 struct sockaddr_in sin = {
02270 .sin_addr.s_addr = peercnt->addr,
02271 };
02272
02273
02274 if (peercnt->reg && peercnt->limit) {
02275 return;
02276 }
02277
02278 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02279 limit = addr_range->limit;
02280 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02281 ao2_ref(addr_range, -1);
02282 }
02283
02284 peercnt->limit = limit;
02285 }
02286
02287
02288
02289
02290
02291 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02292 {
02293 struct peercnt *peercnt = obj;
02294
02295 set_peercnt_limit(peercnt);
02296 ast_debug(1, "Reset limits for peercnts table\n");
02297
02298 return 0;
02299 }
02300
02301
02302
02303
02304
02305 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02306 {
02307 struct addr_range *addr_range = obj;
02308
02309 return addr_range->delme ? CMP_MATCH : 0;
02310 }
02311
02312
02313
02314
02315
02316 static void peercnt_modify(unsigned char reg, uint16_t limit, struct ast_sockaddr *sockaddr)
02317 {
02318
02319 struct peercnt *peercnt;
02320 struct peercnt tmp = {
02321 .addr = 0,
02322 };
02323 struct sockaddr_in sin;
02324
02325 ast_sockaddr_to_sin(sockaddr, &sin);
02326
02327 tmp.addr = sin.sin_addr.s_addr;
02328
02329 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02330 peercnt->reg = reg;
02331 if (limit) {
02332 peercnt->limit = limit;
02333 } else {
02334 set_peercnt_limit(peercnt);
02335 }
02336 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin.sin_addr), peercnt->limit, peercnt->reg);
02337 ao2_ref(peercnt, -1);
02338 }
02339 }
02340
02341
02342
02343
02344
02345
02346
02347
02348
02349 static int peercnt_add(struct sockaddr_in *sin)
02350 {
02351 struct peercnt *peercnt;
02352 unsigned long addr = sin->sin_addr.s_addr;
02353 int res = 0;
02354 struct peercnt tmp = {
02355 .addr = addr,
02356 };
02357
02358
02359
02360
02361
02362
02363
02364 ao2_lock(peercnts);
02365 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02366 ao2_lock(peercnt);
02367 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02368 ao2_lock(peercnt);
02369
02370 peercnt->addr = addr;
02371 set_peercnt_limit(peercnt);
02372
02373
02374 ao2_link(peercnts, peercnt);
02375 } else {
02376 ao2_unlock(peercnts);
02377 return -1;
02378 }
02379
02380
02381 if (peercnt->limit > peercnt->cur) {
02382 peercnt->cur++;
02383 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02384 } else {
02385 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02386 res = -1;
02387 }
02388
02389
02390 ao2_unlock(peercnt);
02391 ao2_unlock(peercnts);
02392 ao2_ref(peercnt, -1);
02393
02394 return res;
02395 }
02396
02397
02398
02399
02400
02401 static void peercnt_remove(struct peercnt *peercnt)
02402 {
02403 struct sockaddr_in sin = {
02404 .sin_addr.s_addr = peercnt->addr,
02405 };
02406
02407
02408
02409
02410
02411
02412
02413 ao2_lock(peercnts);
02414 peercnt->cur--;
02415 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02416
02417 if (peercnt->cur == 0) {
02418 ao2_unlink(peercnts, peercnt);
02419 }
02420 ao2_unlock(peercnts);
02421 }
02422
02423
02424
02425
02426
02427 static int peercnt_remove_cb(const void *obj)
02428 {
02429 struct peercnt *peercnt = (struct peercnt *) obj;
02430
02431 peercnt_remove(peercnt);
02432 ao2_ref(peercnt, -1);
02433
02434 return 0;
02435 }
02436
02437
02438
02439
02440
02441 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02442 {
02443 struct peercnt *peercnt;
02444 struct peercnt tmp = {
02445 .addr = sin->sin_addr.s_addr,
02446 };
02447
02448 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02449 peercnt_remove(peercnt);
02450 ao2_ref(peercnt, -1);
02451 }
02452 return 0;
02453 }
02454
02455
02456
02457
02458
02459 static void build_callno_limits(struct ast_variable *v)
02460 {
02461 struct addr_range *addr_range = NULL;
02462 struct addr_range tmp;
02463 struct ast_ha *ha;
02464 int limit;
02465 int error;
02466 int found;
02467
02468 for (; v; v = v->next) {
02469 limit = -1;
02470 error = 0;
02471 found = 0;
02472 ha = ast_append_ha("permit", v->name, NULL, &error);
02473
02474
02475 if (error) {
02476 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02477 continue;
02478 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02479 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02480 ast_free_ha(ha);
02481 continue;
02482 }
02483
02484 ast_copy_ha(ha, &tmp.ha);
02485
02486 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02487 ao2_lock(addr_range);
02488 found = 1;
02489 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02490 ast_free_ha(ha);
02491 return;
02492 }
02493
02494
02495 ast_copy_ha(ha, &addr_range->ha);
02496 ast_free_ha(ha);
02497 addr_range->limit = limit;
02498 addr_range->delme = 0;
02499
02500
02501 if (found) {
02502 ao2_unlock(addr_range);
02503 } else {
02504 ao2_link(callno_limits, addr_range);
02505 }
02506 ao2_ref(addr_range, -1);
02507 }
02508 }
02509
02510
02511
02512
02513
02514 static int add_calltoken_ignore(const char *addr)
02515 {
02516 struct addr_range tmp;
02517 struct addr_range *addr_range = NULL;
02518 struct ast_ha *ha = NULL;
02519 int error = 0;
02520
02521 if (ast_strlen_zero(addr)) {
02522 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02523 return -1;
02524 }
02525
02526 ha = ast_append_ha("permit", addr, NULL, &error);
02527
02528
02529 if (error) {
02530 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02531 return -1;
02532 }
02533
02534 ast_copy_ha(ha, &tmp.ha);
02535
02536 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02537 ao2_lock(addr_range);
02538 addr_range->delme = 0;
02539 ao2_unlock(addr_range);
02540 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02541
02542 ast_copy_ha(ha, &addr_range->ha);
02543 ao2_link(calltoken_ignores, addr_range);
02544 } else {
02545 ast_free_ha(ha);
02546 return -1;
02547 }
02548
02549 ast_free_ha(ha);
02550 ao2_ref(addr_range, -1);
02551
02552 return 0;
02553 }
02554
02555 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02556 {
02557 struct ao2_iterator i;
02558 struct peercnt *peercnt;
02559 struct sockaddr_in sin;
02560 int found = 0;
02561
02562 switch (cmd) {
02563 case CLI_INIT:
02564 e->command = "iax2 show callnumber usage";
02565 e->usage =
02566 "Usage: iax2 show callnumber usage [IP address]\n"
02567 " Shows current IP addresses which are consuming iax2 call numbers\n";
02568 return NULL;
02569 case CLI_GENERATE:
02570 return NULL;
02571 case CLI_HANDLER:
02572 if (a->argc < 4 || a->argc > 5)
02573 return CLI_SHOWUSAGE;
02574
02575 if (a->argc == 4) {
02576 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02577 }
02578
02579 i = ao2_iterator_init(peercnts, 0);
02580 while ((peercnt = ao2_iterator_next(&i))) {
02581 sin.sin_addr.s_addr = peercnt->addr;
02582 if (a->argc == 5) {
02583 if (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr))) {
02584 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02585 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02586 ao2_ref(peercnt, -1);
02587 found = 1;
02588 break;
02589 }
02590 } else {
02591 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02592 }
02593 ao2_ref(peercnt, -1);
02594 }
02595 ao2_iterator_destroy(&i);
02596
02597 if (a->argc == 4) {
02598 ast_cli(a->fd, "\nNon-CallToken Validation Callno Limit: %d\n"
02599 "Non-CallToken Validated Callno Used: %d\n",
02600 global_maxcallno_nonval,
02601 total_nonval_callno_used);
02602
02603 ast_cli(a->fd, "Total Available Callno: %d\n"
02604 "Regular Callno Available: %d\n"
02605 "Trunk Callno Available: %d\n",
02606 ao2_container_count(callno_pool) + ao2_container_count(callno_pool_trunk),
02607 ao2_container_count(callno_pool),
02608 ao2_container_count(callno_pool_trunk));
02609 } else if (a->argc == 5 && !found) {
02610 ast_cli(a->fd, "No call number table entries for %s found\n", a->argv[4] );
02611 }
02612
02613
02614 return CLI_SUCCESS;
02615 default:
02616 return NULL;
02617 }
02618 }
02619
02620 static struct callno_entry *get_unused_callno(int trunk, int validated)
02621 {
02622 struct callno_entry *callno_entry = NULL;
02623 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02624 ast_log(LOG_WARNING, "Out of CallNumbers\n");
02625
02626 return NULL;
02627 }
02628
02629
02630
02631 ao2_lock(callno_pool);
02632
02633
02634
02635
02636 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02637 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02638 ao2_unlock(callno_pool);
02639 return NULL;
02640 }
02641
02642
02643
02644 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02645
02646 if (callno_entry) {
02647 callno_entry->validated = validated;
02648 if (!validated) {
02649 total_nonval_callno_used++;
02650 }
02651 }
02652
02653 ao2_unlock(callno_pool);
02654 return callno_entry;
02655 }
02656
02657 static int replace_callno(const void *obj)
02658 {
02659 struct callno_entry *callno_entry = (struct callno_entry *) obj;
02660
02661
02662
02663 ao2_lock(callno_pool);
02664
02665 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02666 total_nonval_callno_used--;
02667 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02668 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02669 }
02670
02671 if (callno_entry->callno < TRUNK_CALL_START) {
02672 ao2_link(callno_pool, callno_entry);
02673 } else {
02674 ao2_link(callno_pool_trunk, callno_entry);
02675 }
02676 ao2_ref(callno_entry, -1);
02677
02678 ao2_unlock(callno_pool);
02679 return 0;
02680 }
02681
02682 static int callno_hash(const void *obj, const int flags)
02683 {
02684 return abs(ast_random());
02685 }
02686
02687 static int create_callno_pools(void)
02688 {
02689 uint16_t i;
02690
02691 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02692 return -1;
02693 }
02694
02695 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02696 return -1;
02697 }
02698
02699
02700 for (i = 2; i <= IAX_MAX_CALLS; i++) {
02701 struct callno_entry *callno_entry;
02702
02703 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02704 return -1;
02705 }
02706
02707 callno_entry->callno = i;
02708
02709 if (i < TRUNK_CALL_START) {
02710 ao2_link(callno_pool, callno_entry);
02711 } else {
02712 ao2_link(callno_pool_trunk, callno_entry);
02713 }
02714
02715 ao2_ref(callno_entry, -1);
02716 }
02717
02718 return 0;
02719 }
02720
02721
02722
02723
02724
02725
02726
02727
02728
02729 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02730 {
02731 int i;
02732 struct peercnt *peercnt;
02733 struct peercnt tmp = {
02734 .addr = sin->sin_addr.s_addr,
02735 };
02736
02737 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02738
02739 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02740 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02741 if (i == -1) {
02742 ao2_ref(peercnt, -1);
02743 }
02744 }
02745
02746 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02747 }
02748
02749
02750
02751
02752
02753
02754
02755
02756 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02757 {
02758 if (frametype != AST_FRAME_IAX) {
02759 return 0;
02760 }
02761 switch (subclass) {
02762 case IAX_COMMAND_NEW:
02763 case IAX_COMMAND_REGREQ:
02764 case IAX_COMMAND_FWDOWNL:
02765 case IAX_COMMAND_REGREL:
02766 return 1;
02767 case IAX_COMMAND_POKE:
02768 if (!inbound) {
02769 return 1;
02770 }
02771 break;
02772 }
02773 return 0;
02774 }
02775
02776
02777
02778
02779 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02780 {
02781 int res = 0;
02782 int x;
02783
02784
02785 int validated = (new > NEW_ALLOW) ? 1 : 0;
02786 char host[80];
02787
02788 if (new <= NEW_ALLOW) {
02789 if (callno) {
02790 struct chan_iax2_pvt *pvt;
02791 struct chan_iax2_pvt tmp_pvt = {
02792 .callno = dcallno,
02793 .peercallno = callno,
02794 .transfercallno = callno,
02795
02796 .frames_received = check_dcallno,
02797 };
02798
02799 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02800
02801 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02802 if (return_locked) {
02803 ast_mutex_lock(&iaxsl[pvt->callno]);
02804 }
02805 res = pvt->callno;
02806 ao2_ref(pvt, -1);
02807 pvt = NULL;
02808 return res;
02809 }
02810
02811 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02812 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02813 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02814 if (return_locked) {
02815 ast_mutex_lock(&iaxsl[pvt->callno]);
02816 }
02817 res = pvt->callno;
02818 ao2_ref(pvt, -1);
02819 pvt = NULL;
02820 return res;
02821 }
02822 }
02823
02824
02825 if (dcallno) {
02826 ast_mutex_lock(&iaxsl[dcallno]);
02827 }
02828 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
02829 iaxs[dcallno]->peercallno = callno;
02830 res = dcallno;
02831 store_by_peercallno(iaxs[dcallno]);
02832 if (!res || !return_locked) {
02833 ast_mutex_unlock(&iaxsl[dcallno]);
02834 }
02835 return res;
02836 }
02837 if (dcallno) {
02838 ast_mutex_unlock(&iaxsl[dcallno]);
02839 }
02840 #ifdef IAX_OLD_FIND
02841
02842
02843
02844
02845
02846
02847
02848
02849
02850
02851
02852 for (x = 1; !res && x < maxnontrunkcall; x++) {
02853 ast_mutex_lock(&iaxsl[x]);
02854 if (iaxs[x]) {
02855
02856 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02857 res = x;
02858 }
02859 }
02860 if (!res || !return_locked)
02861 ast_mutex_unlock(&iaxsl[x]);
02862 }
02863 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
02864 ast_mutex_lock(&iaxsl[x]);
02865 if (iaxs[x]) {
02866
02867 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02868 res = x;
02869 }
02870 }
02871 if (!res || !return_locked)
02872 ast_mutex_unlock(&iaxsl[x]);
02873 }
02874 #endif
02875 }
02876 if (!res && (new >= NEW_ALLOW)) {
02877 struct callno_entry *callno_entry;
02878
02879
02880
02881
02882
02883
02884 if (!iax2_getpeername(*sin, host, sizeof(host)))
02885 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
02886
02887 if (peercnt_add(sin)) {
02888
02889
02890 return 0;
02891 }
02892
02893 if (!(callno_entry = get_unused_callno(0, validated))) {
02894
02895
02896 peercnt_remove_by_addr(sin);
02897 ast_log(LOG_WARNING, "No more space\n");
02898 return 0;
02899 }
02900 x = callno_entry->callno;
02901 ast_mutex_lock(&iaxsl[x]);
02902
02903 iaxs[x] = new_iax(sin, host);
02904 update_max_nontrunk();
02905 if (iaxs[x]) {
02906 if (iaxdebug)
02907 ast_debug(1, "Creating new call structure %d\n", x);
02908 iaxs[x]->callno_entry = callno_entry;
02909 iaxs[x]->sockfd = sockfd;
02910 iaxs[x]->addr.sin_port = sin->sin_port;
02911 iaxs[x]->addr.sin_family = sin->sin_family;
02912 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
02913 iaxs[x]->peercallno = callno;
02914 iaxs[x]->callno = x;
02915 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
02916 iaxs[x]->expiry = min_reg_expire;
02917 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
02918 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
02919 iaxs[x]->amaflags = amaflags;
02920 ast_copy_flags64(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
02921 ast_string_field_set(iaxs[x], accountcode, accountcode);
02922 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
02923 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
02924 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
02925
02926 if (iaxs[x]->peercallno) {
02927 store_by_peercallno(iaxs[x]);
02928 }
02929 } else {
02930 ast_log(LOG_WARNING, "Out of resources\n");
02931 ast_mutex_unlock(&iaxsl[x]);
02932 replace_callno(callno_entry);
02933 return 0;
02934 }
02935 if (!return_locked)
02936 ast_mutex_unlock(&iaxsl[x]);
02937 res = x;
02938 }
02939 return res;
02940 }
02941
02942 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02943 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
02944 }
02945
02946 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02947
02948 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
02949 }
02950
02951
02952
02953
02954
02955
02956
02957
02958
02959
02960
02961 static int iax2_queue_frame(int callno, struct ast_frame *f)
02962 {
02963 iax2_lock_owner(callno);
02964 if (iaxs[callno] && iaxs[callno]->owner) {
02965 ast_queue_frame(iaxs[callno]->owner, f);
02966 ast_channel_unlock(iaxs[callno]->owner);
02967 }
02968 return 0;
02969 }
02970
02971
02972
02973
02974
02975
02976
02977
02978
02979
02980
02981
02982
02983
02984 static int iax2_queue_hangup(int callno)
02985 {
02986 iax2_lock_owner(callno);
02987 if (iaxs[callno] && iaxs[callno]->owner) {
02988 ast_queue_hangup(iaxs[callno]->owner);
02989 ast_channel_unlock(iaxs[callno]->owner);
02990 }
02991 return 0;
02992 }
02993
02994
02995
02996
02997
02998
02999
03000
03001
03002
03003
03004
03005
03006
03007 static int iax2_queue_control_data(int callno,
03008 enum ast_control_frame_type control, const void *data, size_t datalen)
03009 {
03010 iax2_lock_owner(callno);
03011 if (iaxs[callno] && iaxs[callno]->owner) {
03012 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
03013 ast_channel_unlock(iaxs[callno]->owner);
03014 }
03015 return 0;
03016 }
03017 static void destroy_firmware(struct iax_firmware *cur)
03018 {
03019
03020 if (cur->fwh) {
03021 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
03022 }
03023 close(cur->fd);
03024 ast_free(cur);
03025 }
03026
03027 static int try_firmware(char *s)
03028 {
03029 struct stat stbuf;
03030 struct iax_firmware *cur = NULL;
03031 int ifd, fd, res, len, chunk;
03032 struct ast_iax2_firmware_header *fwh, fwh2;
03033 struct MD5Context md5;
03034 unsigned char sum[16], buf[1024];
03035 char *s2, *last;
03036
03037 if (!(s2 = alloca(strlen(s) + 100))) {
03038 ast_log(LOG_WARNING, "Alloca failed!\n");
03039 return -1;
03040 }
03041
03042 last = strrchr(s, '/');
03043 if (last)
03044 last++;
03045 else
03046 last = s;
03047
03048 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
03049
03050 if ((res = stat(s, &stbuf) < 0)) {
03051 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
03052 return -1;
03053 }
03054
03055
03056 if (S_ISDIR(stbuf.st_mode))
03057 return -1;
03058 ifd = open(s, O_RDONLY);
03059 if (ifd < 0) {
03060 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
03061 return -1;
03062 }
03063 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
03064 if (fd < 0) {
03065 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
03066 close(ifd);
03067 return -1;
03068 }
03069
03070 unlink(s2);
03071
03072
03073 len = stbuf.st_size;
03074 while(len) {
03075 chunk = len;
03076 if (chunk > sizeof(buf))
03077 chunk = sizeof(buf);
03078 res = read(ifd, buf, chunk);
03079 if (res != chunk) {
03080 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03081 close(ifd);
03082 close(fd);
03083 return -1;
03084 }
03085 res = write(fd, buf, chunk);
03086 if (res != chunk) {
03087 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03088 close(ifd);
03089 close(fd);
03090 return -1;
03091 }
03092 len -= chunk;
03093 }
03094 close(ifd);
03095
03096 lseek(fd, 0, SEEK_SET);
03097 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
03098 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
03099 close(fd);
03100 return -1;
03101 }
03102 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
03103 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
03104 close(fd);
03105 return -1;
03106 }
03107 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
03108 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
03109 close(fd);
03110 return -1;
03111 }
03112 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
03113 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
03114 close(fd);
03115 return -1;
03116 }
03117 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
03118 if (fwh == MAP_FAILED) {
03119 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
03120 close(fd);
03121 return -1;
03122 }
03123 MD5Init(&md5);
03124 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
03125 MD5Final(sum, &md5);
03126 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
03127 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
03128 munmap((void*)fwh, stbuf.st_size);
03129 close(fd);
03130 return -1;
03131 }
03132
03133 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03134 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
03135
03136 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
03137
03138 break;
03139
03140
03141 munmap((void*)fwh, stbuf.st_size);
03142 close(fd);
03143 return 0;
03144 }
03145 }
03146
03147 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
03148 cur->fd = -1;
03149 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
03150 }
03151
03152 if (cur) {
03153 if (cur->fwh)
03154 munmap((void*)cur->fwh, cur->mmaplen);
03155 if (cur->fd > -1)
03156 close(cur->fd);
03157 cur->fwh = fwh;
03158 cur->fd = fd;
03159 cur->mmaplen = stbuf.st_size;
03160 cur->dead = 0;
03161 }
03162
03163 return 0;
03164 }
03165
03166 static int iax_check_version(char *dev)
03167 {
03168 int res = 0;
03169 struct iax_firmware *cur = NULL;
03170
03171 if (ast_strlen_zero(dev))
03172 return 0;
03173
03174 AST_LIST_LOCK(&firmwares);
03175 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03176 if (!strcmp(dev, (char *)cur->fwh->devname)) {
03177 res = ntohs(cur->fwh->version);
03178 break;
03179 }
03180 }
03181 AST_LIST_UNLOCK(&firmwares);
03182
03183 return res;
03184 }
03185
03186 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03187 {
03188 int res = -1;
03189 unsigned int bs = desc & 0xff;
03190 unsigned int start = (desc >> 8) & 0xffffff;
03191 unsigned int bytes;
03192 struct iax_firmware *cur;
03193
03194 if (ast_strlen_zero((char *)dev) || !bs)
03195 return -1;
03196
03197 start *= bs;
03198
03199 AST_LIST_LOCK(&firmwares);
03200 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03201 if (strcmp((char *)dev, (char *)cur->fwh->devname))
03202 continue;
03203 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03204 if (start < ntohl(cur->fwh->datalen)) {
03205 bytes = ntohl(cur->fwh->datalen) - start;
03206 if (bytes > bs)
03207 bytes = bs;
03208 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03209 } else {
03210 bytes = 0;
03211 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03212 }
03213 if (bytes == bs)
03214 res = 0;
03215 else
03216 res = 1;
03217 break;
03218 }
03219 AST_LIST_UNLOCK(&firmwares);
03220
03221 return res;
03222 }
03223
03224
03225 static void reload_firmware(int unload)
03226 {
03227 struct iax_firmware *cur = NULL;
03228 DIR *fwd;
03229 struct dirent *de;
03230 char dir[256], fn[256];
03231
03232 AST_LIST_LOCK(&firmwares);
03233
03234
03235 AST_LIST_TRAVERSE(&firmwares, cur, list)
03236 cur->dead = 1;
03237
03238
03239 if (!unload) {
03240 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03241 fwd = opendir(dir);
03242 if (fwd) {
03243 while((de = readdir(fwd))) {
03244 if (de->d_name[0] != '.') {
03245 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03246 if (!try_firmware(fn)) {
03247 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03248 }
03249 }
03250 }
03251 closedir(fwd);
03252 } else
03253 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03254 }
03255
03256
03257 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03258 if (!cur->dead)
03259 continue;
03260 AST_LIST_REMOVE_CURRENT(list);
03261 destroy_firmware(cur);
03262 }
03263 AST_LIST_TRAVERSE_SAFE_END;
03264
03265 AST_LIST_UNLOCK(&firmwares);
03266 }
03267
03268
03269
03270
03271
03272
03273
03274
03275
03276 static int __do_deliver(void *data)
03277 {
03278
03279
03280 struct iax_frame *fr = data;
03281 fr->retrans = -1;
03282 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03283 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
03284 iax2_queue_frame(fr->callno, &fr->af);
03285
03286 iax2_frame_free(fr);
03287
03288 return 0;
03289 }
03290
03291 static int handle_error(void)
03292 {
03293
03294
03295
03296 #if 0
03297 struct sockaddr_in *sin;
03298 int res;
03299 struct msghdr m;
03300 struct sock_extended_err e;
03301 m.msg_name = NULL;
03302 m.msg_namelen = 0;
03303 m.msg_iov = NULL;
03304 m.msg_control = &e;
03305 m.msg_controllen = sizeof(e);
03306 m.msg_flags = 0;
03307 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03308 if (res < 0)
03309 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03310 else {
03311 if (m.msg_controllen) {
03312 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03313 if (sin)
03314 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03315 else
03316 ast_log(LOG_WARNING, "No address detected??\n");
03317 } else {
03318 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03319 }
03320 }
03321 #endif
03322 return 0;
03323 }
03324
03325 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03326 {
03327 int res;
03328 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03329 sizeof(*sin));
03330 if (res < 0) {
03331 ast_debug(1, "Received error: %s\n", strerror(errno));
03332 handle_error();
03333 } else
03334 res = 0;
03335 return res;
03336 }
03337
03338 static int send_packet(struct iax_frame *f)
03339 {
03340 int res;
03341 int callno = f->callno;
03342
03343
03344 if (!callno || !iaxs[callno] || iaxs[callno]->error)
03345 return -1;
03346
03347
03348 if (iaxdebug)
03349 ast_debug(3, "Sending %d on %d/%d to %s:%d\n", f->ts, callno, iaxs[callno]->peercallno, ast_inet_ntoa(iaxs[callno]->addr.sin_addr), ntohs(iaxs[callno]->addr.sin_port));
03350
03351 if (f->transfer) {
03352 if (iaxdebug)
03353 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03354 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03355 } else {
03356 if (iaxdebug)
03357 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03358 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03359 }
03360 if (res < 0) {
03361 if (iaxdebug)
03362 ast_debug(1, "Received error: %s\n", strerror(errno));
03363 handle_error();
03364 } else
03365 res = 0;
03366
03367 return res;
03368 }
03369
03370
03371
03372
03373
03374 static int iax2_predestroy(int callno)
03375 {
03376 struct ast_channel *c = NULL;
03377 struct chan_iax2_pvt *pvt = iaxs[callno];
03378
03379 if (!pvt)
03380 return -1;
03381
03382 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
03383 iax2_destroy_helper(pvt);
03384 ast_set_flag64(pvt, IAX_ALREADYGONE);
03385 }
03386
03387 if ((c = pvt->owner)) {
03388 c->tech_pvt = NULL;
03389 iax2_queue_hangup(callno);
03390 pvt->owner = NULL;
03391 ast_module_unref(ast_module_info->self);
03392 }
03393
03394 return 0;
03395 }
03396
03397 static void iax2_destroy(int callno)
03398 {
03399 struct chan_iax2_pvt *pvt = NULL;
03400 struct ast_channel *owner = NULL;
03401
03402 retry:
03403 if ((pvt = iaxs[callno])) {
03404 #if 0
03405
03406
03407
03408
03409
03410
03411
03412 iax2_destroy_helper(pvt);
03413 #endif
03414 }
03415
03416 owner = pvt ? pvt->owner : NULL;
03417
03418 if (owner) {
03419 if (ast_channel_trylock(owner)) {
03420 ast_debug(3, "Avoiding IAX destroy deadlock\n");
03421 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03422 goto retry;
03423 }
03424 }
03425
03426 if (!owner) {
03427 iaxs[callno] = NULL;
03428 }
03429
03430 if (pvt) {
03431 if (!owner) {
03432 pvt->owner = NULL;
03433 } else {
03434
03435
03436
03437 ast_queue_hangup(owner);
03438 }
03439
03440 if (pvt->peercallno) {
03441 remove_by_peercallno(pvt);
03442 }
03443
03444 if (pvt->transfercallno) {
03445 remove_by_transfercallno(pvt);
03446 }
03447
03448 if (!owner) {
03449 ao2_ref(pvt, -1);
03450 pvt = NULL;
03451 }
03452 }
03453
03454 if (owner) {
03455 ast_channel_unlock(owner);
03456 }
03457
03458 if (callno & TRUNK_CALL_START) {
03459 update_max_trunk();
03460 }
03461 }
03462
03463 static int update_packet(struct iax_frame *f)
03464 {
03465
03466 struct ast_iax2_full_hdr *fh = f->data;
03467 struct ast_frame af;
03468
03469
03470 if (f->encmethods) {
03471 decode_frame(&f->mydcx, fh, &af, &f->datalen);
03472 }
03473
03474 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03475
03476 f->iseqno = iaxs[f->callno]->iseqno;
03477 fh->iseqno = f->iseqno;
03478
03479
03480 if (f->encmethods) {
03481
03482
03483 build_rand_pad(f->semirand, sizeof(f->semirand));
03484 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03485 }
03486 return 0;
03487 }
03488
03489 static int attempt_transmit(const void *data);
03490 static void __attempt_transmit(const void *data)
03491 {
03492
03493
03494 struct iax_frame *f = (struct iax_frame *)data;
03495 int freeme = 0;
03496 int callno = f->callno;
03497
03498 if (callno)
03499 ast_mutex_lock(&iaxsl[callno]);
03500 if (callno && iaxs[callno]) {
03501 if ((f->retries < 0) ||
03502 (f->retries >= max_retries) ) {
03503
03504 if (f->retries >= max_retries) {
03505 if (f->transfer) {
03506
03507 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03508 } else if (f->final) {
03509 iax2_destroy(callno);
03510 } else {
03511 if (iaxs[callno]->owner)
03512 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %u, 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.integer, f->ts, f->oseqno);
03513 iaxs[callno]->error = ETIMEDOUT;
03514 if (iaxs[callno]->owner) {
03515 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03516
03517 iax2_queue_frame(callno, &fr);
03518
03519 if (iaxs[callno] && iaxs[callno]->owner)
03520 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03521 } else {
03522 if (iaxs[callno]->reg) {
03523 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03524 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03525 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03526 }
03527 iax2_destroy(callno);
03528 }
03529 }
03530
03531 }
03532 freeme = 1;
03533 } else {
03534
03535 update_packet(f);
03536
03537 send_packet(f);
03538 f->retries++;
03539
03540 f->retrytime *= 10;
03541 if (f->retrytime > MAX_RETRY_TIME)
03542 f->retrytime = MAX_RETRY_TIME;
03543
03544 if (f->transfer && (f->retrytime > 1000))
03545 f->retrytime = 1000;
03546 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03547 }
03548 } else {
03549
03550 f->retries = -1;
03551 freeme = 1;
03552 }
03553
03554 if (freeme) {
03555
03556 AST_LIST_REMOVE(&frame_queue[callno], f, list);
03557 ast_mutex_unlock(&iaxsl[callno]);
03558 f->retrans = -1;
03559
03560 iax2_frame_free(f);
03561 } else if (callno) {
03562 ast_mutex_unlock(&iaxsl[callno]);
03563 }
03564 }
03565
03566 static int attempt_transmit(const void *data)
03567 {
03568 #ifdef SCHED_MULTITHREADED
03569 if (schedule_action(__attempt_transmit, data))
03570 #endif
03571 __attempt_transmit(data);
03572 return 0;
03573 }
03574
03575 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03576 {
03577 struct iax2_peer *peer = NULL;
03578 struct iax2_user *user = NULL;
03579 static const char * const choices[] = { "all", NULL };
03580 char *cmplt;
03581
03582 switch (cmd) {
03583 case CLI_INIT:
03584 e->command = "iax2 prune realtime";
03585 e->usage =
03586 "Usage: iax2 prune realtime [<peername>|all]\n"
03587 " Prunes object(s) from the cache\n";
03588 return NULL;
03589 case CLI_GENERATE:
03590 if (a->pos == 3) {
03591 cmplt = ast_cli_complete(a->word, choices, a->n);
03592 if (!cmplt)
03593 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03594 return cmplt;
03595 }
03596 return NULL;
03597 }
03598 if (a->argc != 4)
03599 return CLI_SHOWUSAGE;
03600 if (!strcmp(a->argv[3], "all")) {
03601 prune_users();
03602 prune_peers();
03603 ast_cli(a->fd, "Cache flushed successfully.\n");
03604 return CLI_SUCCESS;
03605 }
03606 peer = find_peer(a->argv[3], 0);
03607 user = find_user(a->argv[3]);
03608 if (peer || user) {
03609 if (peer) {
03610 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
03611 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
03612 expire_registry(peer_ref(peer));
03613 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03614 } else {
03615 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03616 }
03617 peer_unref(peer);
03618 }
03619 if (user) {
03620 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
03621 ast_set_flag64(user, IAX_RTAUTOCLEAR);
03622 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03623 } else {
03624 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03625 }
03626 ao2_unlink(users,user);
03627 user_unref(user);
03628 }
03629 } else {
03630 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03631 }
03632
03633 return CLI_SUCCESS;
03634 }
03635
03636 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03637 {
03638 switch (cmd) {
03639 case CLI_INIT:
03640 e->command = "iax2 test losspct";
03641 e->usage =
03642 "Usage: iax2 test losspct <percentage>\n"
03643 " For testing, throws away <percentage> percent of incoming packets\n";
03644 return NULL;
03645 case CLI_GENERATE:
03646 return NULL;
03647 }
03648 if (a->argc != 4)
03649 return CLI_SHOWUSAGE;
03650
03651 test_losspct = atoi(a->argv[3]);
03652
03653 return CLI_SUCCESS;
03654 }
03655
03656 #ifdef IAXTESTS
03657 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03658 {
03659 switch (cmd) {
03660 case CLI_INIT:
03661 e->command = "iax2 test late";
03662 e->usage =
03663 "Usage: iax2 test late <ms>\n"
03664 " For testing, count the next frame as <ms> ms late\n";
03665 return NULL;
03666 case CLI_GENERATE:
03667 return NULL;
03668 }
03669
03670 if (a->argc != 4)
03671 return CLI_SHOWUSAGE;
03672
03673 test_late = atoi(a->argv[3]);
03674
03675 return CLI_SUCCESS;
03676 }
03677
03678 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03679 {
03680 switch (cmd) {
03681 case CLI_INIT:
03682 e->command = "iax2 test resync";
03683 e->usage =
03684 "Usage: iax2 test resync <ms>\n"
03685 " For testing, adjust all future frames by <ms> ms\n";
03686 return NULL;
03687 case CLI_GENERATE:
03688 return NULL;
03689 }
03690
03691 if (a->argc != 4)
03692 return CLI_SHOWUSAGE;
03693
03694 test_resync = atoi(a->argv[3]);
03695
03696 return CLI_SUCCESS;
03697 }
03698
03699 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03700 {
03701 switch (cmd) {
03702 case CLI_INIT:
03703 e->command = "iax2 test jitter";
03704 e->usage =
03705 "Usage: iax2 test jitter <ms> <pct>\n"
03706 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03707 " percentage of packets. If <pct> is not specified, adds\n"
03708 " jitter to all packets.\n";
03709 return NULL;
03710 case CLI_GENERATE:
03711 return NULL;
03712 }
03713
03714 if (a->argc < 4 || a->argc > 5)
03715 return CLI_SHOWUSAGE;
03716
03717 test_jit = atoi(a->argv[3]);
03718 if (a->argc == 5)
03719 test_jitpct = atoi(a->argv[4]);
03720
03721 return CLI_SUCCESS;
03722 }
03723 #endif
03724
03725
03726
03727 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03728 {
03729 int res = 0;
03730 if (peer->maxms) {
03731 if (peer->lastms < 0) {
03732 ast_copy_string(status, "UNREACHABLE", statuslen);
03733 } else if (peer->lastms > peer->maxms) {
03734 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03735 res = 1;
03736 } else if (peer->lastms) {
03737 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03738 res = 1;
03739 } else {
03740 ast_copy_string(status, "UNKNOWN", statuslen);
03741 }
03742 } else {
03743 ast_copy_string(status, "Unmonitored", statuslen);
03744 res = -1;
03745 }
03746 return res;
03747 }
03748
03749
03750 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03751 {
03752 char status[30];
03753 char cbuf[256];
03754 struct iax2_peer *peer;
03755 char codec_buf[512];
03756 struct ast_str *encmethods = ast_str_alloca(256);
03757 int x = 0, codec = 0, load_realtime = 0;
03758
03759 switch (cmd) {
03760 case CLI_INIT:
03761 e->command = "iax2 show peer";
03762 e->usage =
03763 "Usage: iax2 show peer <name>\n"
03764 " Display details on specific IAX peer\n";
03765 return NULL;
03766 case CLI_GENERATE:
03767 if (a->pos == 3)
03768 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03769 return NULL;
03770 }
03771
03772 if (a->argc < 4)
03773 return CLI_SHOWUSAGE;
03774
03775 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03776
03777 peer = find_peer(a->argv[3], load_realtime);
03778 if (peer) {
03779 struct sockaddr_in peer_addr;
03780
03781 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
03782
03783 encmethods_to_str(peer->encmethods, encmethods);
03784 ast_cli(a->fd, "\n\n");
03785 ast_cli(a->fd, " * Name : %s\n", peer->name);
03786 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03787 ast_cli(a->fd, " Context : %s\n", peer->context);
03788 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
03789 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
03790 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
03791 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
03792 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03793 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
03794 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03795 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03796 ast_cli(a->fd, " Expire : %d\n", peer->expire);
03797 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
03798 ast_cli(a->fd, " Addr->IP : %s Port %d\n", peer_addr.sin_addr.s_addr ? ast_inet_ntoa(peer_addr.sin_addr) : "(Unspecified)", ntohs(peer_addr.sin_port));
03799 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03800 ast_cli(a->fd, " Username : %s\n", peer->username);
03801 ast_cli(a->fd, " Codecs : ");
03802 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03803 ast_cli(a->fd, "%s\n", codec_buf);
03804
03805 ast_cli(a->fd, " Codec Order : (");
03806 for(x = 0; x < 32 ; x++) {
03807 codec = ast_codec_pref_index(&peer->prefs,x);
03808 if(!codec)
03809 break;
03810 ast_cli(a->fd, "%s", ast_getformatname(codec));
03811 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03812 ast_cli(a->fd, "|");
03813 }
03814
03815 if (!x)
03816 ast_cli(a->fd, "none");
03817 ast_cli(a->fd, ")\n");
03818
03819 ast_cli(a->fd, " Status : ");
03820 peer_status(peer, status, sizeof(status));
03821 ast_cli(a->fd, "%s\n",status);
03822 ast_cli(a->fd, " Qualify : every %dms when OK, every %dms when UNREACHABLE (sample smoothing %s)\n", peer->pokefreqok, peer->pokefreqnotok, peer->smoothing ? "On" : "Off");
03823 ast_cli(a->fd, "\n");
03824 peer_unref(peer);
03825 } else {
03826 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03827 ast_cli(a->fd, "\n");
03828 }
03829
03830 return CLI_SUCCESS;
03831 }
03832
03833 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
03834 {
03835 int which = 0;
03836 struct iax2_peer *peer;
03837 char *res = NULL;
03838 int wordlen = strlen(word);
03839 struct ao2_iterator i;
03840
03841 i = ao2_iterator_init(peers, 0);
03842 while ((peer = ao2_iterator_next(&i))) {
03843 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03844 && (!flags || ast_test_flag64(peer, flags))) {
03845 res = ast_strdup(peer->name);
03846 peer_unref(peer);
03847 break;
03848 }
03849 peer_unref(peer);
03850 }
03851 ao2_iterator_destroy(&i);
03852
03853 return res;
03854 }
03855
03856 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03857 {
03858 struct iax_frame *cur;
03859 int cnt = 0, dead = 0, final = 0, i = 0;
03860
03861 switch (cmd) {
03862 case CLI_INIT:
03863 e->command = "iax2 show stats";
03864 e->usage =
03865 "Usage: iax2 show stats\n"
03866 " Display statistics on IAX channel driver.\n";
03867 return NULL;
03868 case CLI_GENERATE:
03869 return NULL;
03870 }
03871
03872 if (a->argc != 3)
03873 return CLI_SHOWUSAGE;
03874
03875 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
03876 ast_mutex_lock(&iaxsl[i]);
03877 AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
03878 if (cur->retries < 0)
03879 dead++;
03880 if (cur->final)
03881 final++;
03882 cnt++;
03883 }
03884 ast_mutex_unlock(&iaxsl[i]);
03885 }
03886
03887 ast_cli(a->fd, " IAX Statistics\n");
03888 ast_cli(a->fd, "---------------------\n");
03889 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03890 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03891 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03892 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03893
03894 trunk_timed = trunk_untimed = 0;
03895 if (trunk_maxmtu > trunk_nmaxmtu)
03896 trunk_nmaxmtu = trunk_maxmtu;
03897
03898 return CLI_SUCCESS;
03899 }
03900
03901
03902 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03903 {
03904 int mtuv;
03905
03906 switch (cmd) {
03907 case CLI_INIT:
03908 e->command = "iax2 set mtu";
03909 e->usage =
03910 "Usage: iax2 set mtu <value>\n"
03911 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
03912 " zero to disable. Disabling means that the operating system\n"
03913 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
03914 " packet exceeds the UDP payload size. This is substantially\n"
03915 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03916 " greater for G.711 samples.\n";
03917 return NULL;
03918 case CLI_GENERATE:
03919 return NULL;
03920 }
03921
03922 if (a->argc != 4)
03923 return CLI_SHOWUSAGE;
03924 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03925 mtuv = MAX_TRUNK_MTU;
03926 else
03927 mtuv = atoi(a->argv[3]);
03928
03929 if (mtuv == 0) {
03930 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
03931 global_max_trunk_mtu = 0;
03932 return CLI_SUCCESS;
03933 }
03934 if (mtuv < 172 || mtuv > 4000) {
03935 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
03936 return CLI_SHOWUSAGE;
03937 }
03938 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
03939 global_max_trunk_mtu = mtuv;
03940 return CLI_SUCCESS;
03941 }
03942
03943 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03944 {
03945 struct iax2_dpcache *dp = NULL;
03946 char tmp[1024], *pc = NULL;
03947 int s, x, y;
03948 struct timeval now = ast_tvnow();
03949
03950 switch (cmd) {
03951 case CLI_INIT:
03952 e->command = "iax2 show cache";
03953 e->usage =
03954 "Usage: iax2 show cache\n"
03955 " Display currently cached IAX Dialplan results.\n";
03956 return NULL;
03957 case CLI_GENERATE:
03958 return NULL;
03959 }
03960
03961 AST_LIST_LOCK(&dpcache);
03962
03963 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03964
03965 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03966 s = dp->expiry.tv_sec - now.tv_sec;
03967 tmp[0] = '\0';
03968 if (dp->flags & CACHE_FLAG_EXISTS)
03969 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03970 if (dp->flags & CACHE_FLAG_NONEXISTENT)
03971 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03972 if (dp->flags & CACHE_FLAG_CANEXIST)
03973 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03974 if (dp->flags & CACHE_FLAG_PENDING)
03975 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03976 if (dp->flags & CACHE_FLAG_TIMEOUT)
03977 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03978 if (dp->flags & CACHE_FLAG_TRANSMITTED)
03979 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03980 if (dp->flags & CACHE_FLAG_MATCHMORE)
03981 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03982 if (dp->flags & CACHE_FLAG_UNKNOWN)
03983 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03984
03985 if (!ast_strlen_zero(tmp)) {
03986 tmp[strlen(tmp) - 1] = '\0';
03987 } else {
03988 ast_copy_string(tmp, "(none)", sizeof(tmp));
03989 }
03990 y = 0;
03991 pc = strchr(dp->peercontext, '@');
03992 if (!pc) {
03993 pc = dp->peercontext;
03994 } else {
03995 pc++;
03996 }
03997 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03998 if (dp->waiters[x] > -1)
03999 y++;
04000 }
04001 if (s > 0) {
04002 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
04003 } else {
04004 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
04005 }
04006 }
04007
04008 AST_LIST_UNLOCK(&dpcache);
04009
04010 return CLI_SUCCESS;
04011 }
04012
04013 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
04014
04015 static void unwrap_timestamp(struct iax_frame *fr)
04016 {
04017
04018
04019 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
04020 const int lower_mask = (1 << ts_shift) - 1;
04021 const int upper_mask = ~lower_mask;
04022 const int last_upper = iaxs[fr->callno]->last & upper_mask;
04023
04024 if ( (fr->ts & upper_mask) == last_upper ) {
04025 const int x = fr->ts - iaxs[fr->callno]->last;
04026 const int threshold = (ts_shift == 15) ? 25000 : 50000;
04027
04028 if (x < -threshold) {
04029
04030
04031
04032
04033 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
04034 if (iaxdebug)
04035 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
04036 } else if (x > threshold) {
04037
04038
04039
04040
04041 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
04042 if (iaxdebug)
04043 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
04044 }
04045 }
04046 }
04047
04048 static int get_from_jb(const void *p);
04049
04050 static void update_jbsched(struct chan_iax2_pvt *pvt)
04051 {
04052 int when;
04053
04054 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
04055
04056 when = jb_next(pvt->jb) - when;
04057
04058 if (when <= 0) {
04059
04060 when = 1;
04061 }
04062
04063 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
04064 CALLNO_TO_PTR(pvt->callno));
04065 }
04066
04067 static void __get_from_jb(const void *p)
04068 {
04069 int callno = PTR_TO_CALLNO(p);
04070 struct chan_iax2_pvt *pvt = NULL;
04071 struct iax_frame *fr;
04072 jb_frame frame;
04073 int ret;
04074 long ms;
04075 long next;
04076 struct timeval now = ast_tvnow();
04077
04078
04079 ast_mutex_lock(&iaxsl[callno]);
04080 pvt = iaxs[callno];
04081 if (!pvt) {
04082
04083 ast_mutex_unlock(&iaxsl[callno]);
04084 return;
04085 }
04086
04087 pvt->jbid = -1;
04088
04089
04090
04091
04092 now.tv_usec += 1000;
04093
04094 ms = ast_tvdiff_ms(now, pvt->rxcore);
04095
04096 if(ms >= (next = jb_next(pvt->jb))) {
04097 ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
04098 switch(ret) {
04099 case JB_OK:
04100 fr = frame.data;
04101 __do_deliver(fr);
04102
04103 pvt = iaxs[callno];
04104 break;
04105 case JB_INTERP:
04106 {
04107 struct ast_frame af = { 0, };
04108
04109
04110 af.frametype = AST_FRAME_VOICE;
04111 af.subclass.codec = pvt->voiceformat;
04112 af.samples = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
04113 af.src = "IAX2 JB interpolation";
04114 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
04115 af.offset = AST_FRIENDLY_OFFSET;
04116
04117
04118
04119 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
04120 iax2_queue_frame(callno, &af);
04121
04122 pvt = iaxs[callno];
04123 }
04124 }
04125 break;
04126 case JB_DROP:
04127 iax2_frame_free(frame.data);
04128 break;
04129 case JB_NOFRAME:
04130 case JB_EMPTY:
04131
04132 break;
04133 default:
04134
04135 break;
04136 }
04137 }
04138 if (pvt)
04139 update_jbsched(pvt);
04140 ast_mutex_unlock(&iaxsl[callno]);
04141 }
04142
04143 static int get_from_jb(const void *data)
04144 {
04145 #ifdef SCHED_MULTITHREADED
04146 if (schedule_action(__get_from_jb, data))
04147 #endif
04148 __get_from_jb(data);
04149 return 0;
04150 }
04151
04152
04153
04154
04155
04156
04157
04158 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
04159 {
04160 int type, len;
04161 int ret;
04162 int needfree = 0;
04163 struct ast_channel *owner = NULL;
04164 struct ast_channel *bridge = NULL;
04165
04166
04167
04168
04169
04170
04171 if (!fr->af.datalen) {
04172 memset(&fr->af.data, 0, sizeof(fr->af.data));
04173 }
04174
04175
04176 unwrap_timestamp(fr);
04177
04178
04179 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04180 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04181 else {
04182 #if 0
04183 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04184 #endif
04185 fr->af.delivery = ast_tv(0,0);
04186 }
04187
04188 type = JB_TYPE_CONTROL;
04189 len = 0;
04190
04191 if(fr->af.frametype == AST_FRAME_VOICE) {
04192 type = JB_TYPE_VOICE;
04193 len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass.codec) / 1000);
04194 } else if(fr->af.frametype == AST_FRAME_CNG) {
04195 type = JB_TYPE_SILENCE;
04196 }
04197
04198 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04199 if (tsout)
04200 *tsout = fr->ts;
04201 __do_deliver(fr);
04202 return -1;
04203 }
04204
04205 iax2_lock_owner(fr->callno);
04206 if (!iaxs[fr->callno]) {
04207
04208 iax2_frame_free(fr);
04209 return -1;
04210 }
04211 if ((owner = iaxs[fr->callno]->owner))
04212 bridge = ast_bridged_channel(owner);
04213
04214
04215
04216 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04217 jb_frame frame;
04218
04219 ast_channel_unlock(owner);
04220
04221
04222 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04223 __do_deliver(frame.data);
04224
04225 if (!iaxs[fr->callno])
04226 return -1;
04227 }
04228
04229 jb_reset(iaxs[fr->callno]->jb);
04230
04231 ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04232
04233
04234 if (tsout)
04235 *tsout = fr->ts;
04236 __do_deliver(fr);
04237 return -1;
04238 }
04239 if (owner) {
04240 ast_channel_unlock(owner);
04241 }
04242
04243
04244
04245 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04246 calc_rxstamp(iaxs[fr->callno],fr->ts));
04247 if (ret == JB_DROP) {
04248 needfree++;
04249 } else if (ret == JB_SCHED) {
04250 update_jbsched(iaxs[fr->callno]);
04251 }
04252 if (tsout)
04253 *tsout = fr->ts;
04254 if (needfree) {
04255
04256 iax2_frame_free(fr);
04257 return -1;
04258 }
04259 return 0;
04260 }
04261
04262 static int transmit_frame(void *data)
04263 {
04264 struct iax_frame *fr = data;
04265
04266 ast_mutex_lock(&iaxsl[fr->callno]);
04267
04268 fr->sentyet = 1;
04269
04270 if (iaxs[fr->callno]) {
04271 send_packet(fr);
04272 }
04273
04274 if (fr->retries < 0) {
04275 ast_mutex_unlock(&iaxsl[fr->callno]);
04276
04277 iax_frame_free(fr);
04278 } else {
04279
04280 AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
04281 fr->retries++;
04282 fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
04283 ast_mutex_unlock(&iaxsl[fr->callno]);
04284 }
04285
04286 return 0;
04287 }
04288
04289 static int iax2_transmit(struct iax_frame *fr)
04290 {
04291 fr->sentyet = 0;
04292
04293 return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
04294 }
04295
04296 static int iax2_digit_begin(struct ast_channel *c, char digit)
04297 {
04298 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04299 }
04300
04301 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04302 {
04303 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04304 }
04305
04306 static int iax2_sendtext(struct ast_channel *c, const char *text)
04307 {
04308
04309 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04310 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04311 }
04312
04313 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04314 {
04315 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
04316 }
04317
04318 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04319 {
04320 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04321 }
04322
04323 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04324 {
04325 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04326 ast_mutex_lock(&iaxsl[callno]);
04327 if (iaxs[callno])
04328 iaxs[callno]->owner = newchan;
04329 else
04330 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04331 ast_mutex_unlock(&iaxsl[callno]);
04332 return 0;
04333 }
04334
04335
04336
04337
04338
04339 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04340 {
04341 struct ast_variable *var = NULL;
04342 struct ast_variable *tmp;
04343 struct iax2_peer *peer=NULL;
04344 time_t regseconds = 0, nowtime;
04345 int dynamic=0;
04346
04347 if (peername) {
04348 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04349 if (!var && sin)
04350 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04351 } else if (sin) {
04352 char porta[25];
04353 sprintf(porta, "%d", ntohs(sin->sin_port));
04354 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04355 if (var) {
04356
04357 for (tmp = var; tmp; tmp = tmp->next) {
04358 if (!strcasecmp(tmp->name, "name"))
04359 peername = tmp->value;
04360 }
04361 }
04362 }
04363 if (!var && peername) {
04364 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04365
04366
04367
04368
04369
04370
04371 if (var && sin) {
04372 for (tmp = var; tmp; tmp = tmp->next) {
04373 if (!strcasecmp(tmp->name, "host")) {
04374 struct ast_hostent ahp;
04375 struct hostent *hp;
04376 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04377
04378 ast_variables_destroy(var);
04379 var = NULL;
04380 }
04381 break;
04382 }
04383 }
04384 }
04385 }
04386 if (!var)
04387 return NULL;
04388
04389 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04390
04391 if (!peer) {
04392 ast_variables_destroy(var);
04393 return NULL;
04394 }
04395
04396 for (tmp = var; tmp; tmp = tmp->next) {
04397
04398 if (!strcasecmp(tmp->name, "type")) {
04399 if (strcasecmp(tmp->value, "friend") &&
04400 strcasecmp(tmp->value, "peer")) {
04401
04402 peer = peer_unref(peer);
04403 break;
04404 }
04405 } else if (!strcasecmp(tmp->name, "regseconds")) {
04406 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
04407 } else if (!strcasecmp(tmp->name, "ipaddr")) {
04408 if (!ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE)) {
04409 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
04410 }
04411 } else if (!strcasecmp(tmp->name, "port")) {
04412 ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
04413 } else if (!strcasecmp(tmp->name, "host")) {
04414 if (!strcasecmp(tmp->value, "dynamic"))
04415 dynamic = 1;
04416 }
04417 }
04418
04419 ast_variables_destroy(var);
04420
04421 if (!peer)
04422 return NULL;
04423
04424 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04425 ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04426 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
04427 if (peer->expire > -1) {
04428 if (!ast_sched_thread_del(sched, peer->expire)) {
04429 peer->expire = -1;
04430 peer_unref(peer);
04431 }
04432 }
04433 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04434 if (peer->expire == -1)
04435 peer_unref(peer);
04436 }
04437 ao2_link(peers, peer);
04438 if (ast_test_flag64(peer, IAX_DYNAMIC))
04439 reg_source_db(peer);
04440 } else {
04441 ast_set_flag64(peer, IAX_TEMPONLY);
04442 }
04443
04444 if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04445 time(&nowtime);
04446 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04447 memset(&peer->addr, 0, sizeof(peer->addr));
04448 realtime_update_peer(peer->name, &peer->addr, 0);
04449 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04450 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04451 }
04452 else {
04453 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04454 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04455 }
04456 }
04457
04458 return peer;
04459 }
04460
04461 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04462 {
04463 struct ast_variable *var;
04464 struct ast_variable *tmp;
04465 struct iax2_user *user=NULL;
04466
04467 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04468 if (!var)
04469 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04470 if (!var && sin) {
04471 char porta[6];
04472 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04473 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04474 if (!var)
04475 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04476 }
04477 if (!var) {
04478 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04479
04480
04481
04482
04483
04484
04485 if (var) {
04486 for (tmp = var; tmp; tmp = tmp->next) {
04487 if (!strcasecmp(tmp->name, "host")) {
04488 struct ast_hostent ahp;
04489 struct hostent *hp;
04490 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04491
04492 ast_variables_destroy(var);
04493 var = NULL;
04494 }
04495 break;
04496 }
04497 }
04498 }
04499 }
04500 if (!var)
04501 return NULL;
04502
04503 tmp = var;
04504 while(tmp) {
04505
04506 if (!strcasecmp(tmp->name, "type")) {
04507 if (strcasecmp(tmp->value, "friend") &&
04508 strcasecmp(tmp->value, "user")) {
04509 return NULL;
04510 }
04511 }
04512 tmp = tmp->next;
04513 }
04514
04515 user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
04516
04517 ast_variables_destroy(var);
04518
04519 if (!user)
04520 return NULL;
04521
04522 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04523 ast_set_flag64(user, IAX_RTCACHEFRIENDS);
04524 ao2_link(users, user);
04525 } else {
04526 ast_set_flag64(user, IAX_TEMPONLY);
04527 }
04528
04529 return user;
04530 }
04531
04532 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
04533 {
04534 char port[10];
04535 char regseconds[20];
04536 const char *sysname = ast_config_AST_SYSTEM_NAME;
04537 char *syslabel = NULL;
04538
04539 if (ast_strlen_zero(sysname))
04540 sysname = NULL;
04541 else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
04542 syslabel = "regserver";
04543
04544 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04545 snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
04546 ast_update_realtime("iaxpeers", "name", peername,
04547 "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port,
04548 "regseconds", regseconds, syslabel, sysname, SENTINEL);
04549 }
04550
04551 struct create_addr_info {
04552 format_t capability;
04553 uint64_t flags;
04554 int maxtime;
04555 int encmethods;
04556 int found;
04557 int sockfd;
04558 int adsi;
04559 char username[80];
04560 char secret[80];
04561 char outkey[80];
04562 char timezone[80];
04563 char prefs[32];
04564 char cid_num[80];
04565 char cid_name[80];
04566 char context[AST_MAX_CONTEXT];
04567 char peercontext[AST_MAX_CONTEXT];
04568 char mohinterpret[MAX_MUSICCLASS];
04569 char mohsuggest[MAX_MUSICCLASS];
04570 };
04571
04572 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04573 {
04574 struct iax2_peer *peer;
04575 int res = -1;
04576 struct ast_codec_pref ourprefs;
04577 struct sockaddr_in peer_addr;
04578
04579 ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
04580 cai->sockfd = defaultsockfd;
04581 cai->maxtime = 0;
04582 sin->sin_family = AF_INET;
04583
04584 if (!(peer = find_peer(peername, 1))) {
04585 struct ast_sockaddr sin_tmp;
04586
04587 cai->found = 0;
04588 sin_tmp.ss.ss_family = AF_INET;
04589 if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
04590 ast_log(LOG_WARNING, "No such host: %s\n", peername);
04591 return -1;
04592 }
04593 ast_sockaddr_to_sin(&sin_tmp, sin);
04594 if (sin->sin_port == 0) {
04595 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04596 }
04597
04598
04599 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04600 if (c)
04601 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04602 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04603 return 0;
04604 }
04605
04606 cai->found = 1;
04607
04608 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
04609
04610
04611 if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
04612 goto return_unref;
04613 }
04614
04615
04616 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04617 goto return_unref;
04618
04619 ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
04620 cai->maxtime = peer->maxms;
04621 cai->capability = peer->capability;
04622 cai->encmethods = peer->encmethods;
04623 cai->sockfd = peer->sockfd;
04624 cai->adsi = peer->adsi;
04625 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04626
04627 if (c) {
04628 ast_debug(1, "prepending %llx to prefs\n", (unsigned long long) c->nativeformats);
04629 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04630 }
04631 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04632 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04633 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04634 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04635 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04636 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04637 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
04638 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
04639 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04640 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04641 if (ast_strlen_zero(peer->dbsecret)) {
04642 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04643 } else {
04644 char *family;
04645 char *key = NULL;
04646
04647 family = ast_strdupa(peer->dbsecret);
04648 key = strchr(family, '/');
04649 if (key)
04650 *key++ = '\0';
04651 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04652 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04653 goto return_unref;
04654 }
04655 }
04656
04657 if (peer_addr.sin_addr.s_addr) {
04658 sin->sin_addr = peer_addr.sin_addr;
04659 sin->sin_port = peer_addr.sin_port;
04660 } else {
04661 sin->sin_addr = peer->defaddr.sin_addr;
04662 sin->sin_port = peer->defaddr.sin_port;
04663 }
04664
04665 res = 0;
04666
04667 return_unref:
04668 peer_unref(peer);
04669
04670 return res;
04671 }
04672
04673 static void __auto_congest(const void *nothing)
04674 {
04675 int callno = PTR_TO_CALLNO(nothing);
04676 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
04677 ast_mutex_lock(&iaxsl[callno]);
04678 if (iaxs[callno]) {
04679 iaxs[callno]->initid = -1;
04680 iax2_queue_frame(callno, &f);
04681 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04682 }
04683 ast_mutex_unlock(&iaxsl[callno]);
04684 }
04685
04686 static int auto_congest(const void *data)
04687 {
04688 #ifdef SCHED_MULTITHREADED
04689 if (schedule_action(__auto_congest, data))
04690 #endif
04691 __auto_congest(data);
04692 return 0;
04693 }
04694
04695 static unsigned int iax2_datetime(const char *tz)
04696 {
04697 struct timeval t = ast_tvnow();
04698 struct ast_tm tm;
04699 unsigned int tmp;
04700 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04701 tmp = (tm.tm_sec >> 1) & 0x1f;
04702 tmp |= (tm.tm_min & 0x3f) << 5;
04703 tmp |= (tm.tm_hour & 0x1f) << 11;
04704 tmp |= (tm.tm_mday & 0x1f) << 16;
04705 tmp |= ((tm.tm_mon + 1) & 0xf) << 21;
04706 tmp |= ((tm.tm_year - 100) & 0x7f) << 25;
04707 return tmp;
04708 }
04709
04710 struct parsed_dial_string {
04711 char *username;
04712 char *password;
04713 char *key;
04714 char *peer;
04715 char *port;
04716 char *exten;
04717 char *context;
04718 char *options;
04719 };
04720
04721 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04722 struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04723 int sockfd, struct iax_ie_data *ied)
04724 {
04725 struct {
04726 struct ast_iax2_full_hdr f;
04727 struct iax_ie_data ied;
04728 } data;
04729 size_t size = sizeof(struct ast_iax2_full_hdr);
04730
04731 if (ied) {
04732 size += ied->pos;
04733 memcpy(&data.ied, ied->buf, ied->pos);
04734 }
04735
04736 data.f.scallno = htons(0x8000 | callno);
04737 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
04738 data.f.ts = htonl(ts);
04739 data.f.iseqno = seqno;
04740 data.f.oseqno = 0;
04741 data.f.type = AST_FRAME_IAX;
04742 data.f.csub = compress_subclass(command);
04743
04744 if (iaxdebug) {
04745 iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
04746 }
04747
04748 return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04749 }
04750
04751 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04752 {
04753
04754 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04755 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;
04756 ied->buf[ied->pos++] = 0;
04757 pvt->calltoken_ie_len = 2;
04758 }
04759 }
04760
04761 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04762 {
04763 struct chan_iax2_pvt *pvt = iaxs[callno];
04764 int frametype = f->af.frametype;
04765 int subclass = f->af.subclass.integer;
04766 struct {
04767 struct ast_iax2_full_hdr fh;
04768 struct iax_ie_data ied;
04769 } data = {
04770 .ied.buf = { 0 },
04771 .ied.pos = 0,
04772 };
04773
04774 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04775
04776 if (!pvt) {
04777 return;
04778 }
04779
04780
04781
04782
04783
04784
04785
04786
04787
04788
04789
04790
04791 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04792 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04793 (f->datalen > sizeof(data))) {
04794
04795 return;
04796 }
04797
04798
04799
04800
04801
04802
04803
04804
04805
04806
04807
04808
04809
04810
04811
04812 memcpy(&data, f->data, f->datalen);
04813 data.ied.pos = ie_data_pos;
04814
04815
04816
04817 data.ied.pos -= pvt->calltoken_ie_len;
04818 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04819
04820
04821 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos;
04822
04823
04824 AST_LIST_REMOVE(&frame_queue[callno], f, list);
04825
04826
04827 iax2_frame_free(f);
04828
04829
04830 pvt->oseqno = 0;
04831 pvt->rseqno = 0;
04832 pvt->iseqno = 0;
04833 pvt->aseqno = 0;
04834 if (pvt->peercallno) {
04835 remove_by_peercallno(pvt);
04836 pvt->peercallno = 0;
04837 }
04838
04839
04840 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04841 }
04842
04843 static void requirecalltoken_mark_auto(const char *name, int subclass)
04844 {
04845 struct iax2_user *user = NULL;
04846 struct iax2_peer *peer = NULL;
04847
04848 if (ast_strlen_zero(name)) {
04849 return;
04850 }
04851
04852 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04853 user->calltoken_required = CALLTOKEN_YES;
04854 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04855 peer->calltoken_required = CALLTOKEN_YES;
04856 }
04857
04858 if (peer) {
04859 peer_unref(peer);
04860 }
04861 if (user) {
04862 user_unref(user);
04863 }
04864 }
04865
04866
04867
04868
04869
04870
04871
04872
04873
04874
04875
04876
04877
04878
04879
04880
04881
04882
04883 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04884 struct sockaddr_in *sin, int fd)
04885 {
04886 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"
04887 #define CALLTOKEN_IE_FORMAT "%u?%s"
04888 struct ast_str *buf = ast_str_alloca(256);
04889 time_t t = time(NULL);
04890 char hash[41];
04891 int subclass = uncompress_subclass(fh->csub);
04892
04893
04894 if (ies->calltoken && !ies->calltokendata) {
04895 struct iax_ie_data ied = {
04896 .buf = { 0 },
04897 .pos = 0,
04898 };
04899
04900
04901 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04902 ast_sha1_hash(hash, ast_str_buffer(buf));
04903
04904 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04905 iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04906 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04907
04908 return 1;
04909
04910
04911 } else if (ies->calltoken && ies->calltokendata) {
04912 char *rec_hash = NULL;
04913 char *rec_ts = NULL;
04914 unsigned int rec_time;
04915
04916
04917 rec_hash = strchr((char *) ies->calltokendata, '?');
04918 if (rec_hash) {
04919 *rec_hash++ = '\0';
04920 rec_ts = (char *) ies->calltokendata;
04921 }
04922
04923
04924 if (!rec_hash || !rec_ts) {
04925 goto reject;
04926 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04927 goto reject;
04928 }
04929
04930
04931 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04932 ast_sha1_hash(hash, ast_str_buffer(buf));
04933
04934
04935 if (strcmp(hash, rec_hash)) {
04936 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04937 goto reject;
04938 } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04939 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04940 goto reject;
04941 }
04942
04943
04944
04945 requirecalltoken_mark_auto(ies->username, subclass);
04946 return 0;
04947
04948
04949 } else {
04950 if (calltoken_required(sin, ies->username, subclass)) {
04951 ast_log(LOG_ERROR, "Call rejected, CallToken Support required. If unexpected, resolve by placing address %s in the calltokenoptional list or setting user %s requirecalltoken=no\n", ast_inet_ntoa(sin->sin_addr), S_OR(ies->username, "guest"));
04952 goto reject;
04953 }
04954 return 0;
04955 }
04956
04957 reject:
04958
04959 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04960 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04961 } else {
04962 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04963 }
04964
04965 return 1;
04966 }
04967
04968
04969
04970
04971
04972
04973
04974
04975
04976
04977
04978
04979
04980
04981
04982
04983
04984
04985
04986 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04987 {
04988 if (ast_strlen_zero(data))
04989 return;
04990
04991 pds->peer = strsep(&data, "/");
04992 pds->exten = strsep(&data, "/");
04993 pds->options = data;
04994
04995 if (pds->exten) {
04996 data = pds->exten;
04997 pds->exten = strsep(&data, "@");
04998 pds->context = data;
04999 }
05000
05001 if (strchr(pds->peer, '@')) {
05002 data = pds->peer;
05003 pds->username = strsep(&data, "@");
05004 pds->peer = data;
05005 }
05006
05007 if (pds->username) {
05008 data = pds->username;
05009 pds->username = strsep(&data, ":");
05010 pds->password = data;
05011 }
05012
05013 data = pds->peer;
05014 pds->peer = strsep(&data, ":");
05015 pds->port = data;
05016
05017
05018
05019
05020 if (pds->password && (pds->password[0] == '[')) {
05021 pds->key = ast_strip_quoted(pds->password, "[", "]");
05022 pds->password = NULL;
05023 }
05024 }
05025
05026 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
05027 {
05028 struct sockaddr_in sin;
05029 char *l=NULL, *n=NULL, *tmpstr;
05030 struct iax_ie_data ied;
05031 char *defaultrdest = "s";
05032 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05033 struct parsed_dial_string pds;
05034 struct create_addr_info cai;
05035 struct ast_var_t *var;
05036 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
05037 const char* osp_token_ptr;
05038 unsigned int osp_token_length;
05039 unsigned char osp_block_index;
05040 unsigned int osp_block_length;
05041 unsigned char osp_buffer[256];
05042
05043 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
05044 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
05045 return -1;
05046 }
05047
05048 memset(&cai, 0, sizeof(cai));
05049 cai.encmethods = iax2_encryption;
05050
05051 memset(&pds, 0, sizeof(pds));
05052 tmpstr = ast_strdupa(dest);
05053 parse_dial_string(tmpstr, &pds);
05054
05055 if (ast_strlen_zero(pds.peer)) {
05056 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
05057 return -1;
05058 }
05059 if (!pds.exten) {
05060 pds.exten = defaultrdest;
05061 }
05062 if (create_addr(pds.peer, c, &sin, &cai)) {
05063 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
05064 return -1;
05065 }
05066 if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
05067 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
05068 c->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05069 return -1;
05070 }
05071 if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
05072 ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
05073 return -1;
05074 }
05075 if (!pds.username && !ast_strlen_zero(cai.username))
05076 pds.username = cai.username;
05077 if (!pds.password && !ast_strlen_zero(cai.secret))
05078 pds.password = cai.secret;
05079 if (!pds.key && !ast_strlen_zero(cai.outkey))
05080 pds.key = cai.outkey;
05081 if (!pds.context && !ast_strlen_zero(cai.peercontext))
05082 pds.context = cai.peercontext;
05083
05084
05085 ast_copy_string(c->context, cai.context, sizeof(c->context));
05086
05087 if (pds.port)
05088 sin.sin_port = htons(atoi(pds.port));
05089
05090 l = c->connected.id.number.valid ? c->connected.id.number.str : NULL;
05091 n = c->connected.id.name.valid ? c->connected.id.name.str : NULL;
05092
05093
05094 memset(&ied, 0, sizeof(ied));
05095
05096
05097 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
05098 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
05099 if (pds.options && strchr(pds.options, 'a')) {
05100
05101 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
05102 }
05103
05104
05105 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
05106
05107 if (l) {
05108 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
05109 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05110 ast_party_id_presentation(&c->connected.id));
05111 } else if (n) {
05112 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05113 ast_party_id_presentation(&c->connected.id));
05114 } else {
05115 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
05116 }
05117
05118 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->connected.id.number.plan);
05119 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->dialed.transit_network_select);
05120
05121 if (n)
05122 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
05123 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
05124 && c->connected.ani.number.valid
05125 && c->connected.ani.number.str) {
05126 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->connected.ani.number.str);
05127 }
05128
05129 if (!ast_strlen_zero(c->language))
05130 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
05131 if (!ast_strlen_zero(c->dialed.number.str)) {
05132 iax_ie_append_str(&ied, IAX_IE_DNID, c->dialed.number.str);
05133 }
05134 if (c->redirecting.from.number.valid
05135 && !ast_strlen_zero(c->redirecting.from.number.str)) {
05136 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->redirecting.from.number.str);
05137 }
05138
05139 if (pds.context)
05140 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
05141
05142 if (pds.username)
05143 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
05144
05145 if (cai.encmethods)
05146 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
05147
05148 ast_mutex_lock(&iaxsl[callno]);
05149
05150 if (!ast_strlen_zero(c->context))
05151 ast_string_field_set(iaxs[callno], context, c->context);
05152
05153 if (pds.username)
05154 ast_string_field_set(iaxs[callno], username, pds.username);
05155
05156 iaxs[callno]->encmethods = cai.encmethods;
05157
05158 iaxs[callno]->adsi = cai.adsi;
05159
05160 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
05161 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
05162
05163 if (pds.key)
05164 ast_string_field_set(iaxs[callno], outkey, pds.key);
05165 if (pds.password)
05166 ast_string_field_set(iaxs[callno], secret, pds.password);
05167
05168 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) c->nativeformats);
05169 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, c->nativeformats);
05170 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
05171 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
05172 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
05173 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
05174
05175 if (iaxs[callno]->maxtime) {
05176
05177 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
05178 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
05179 } else if (autokill) {
05180 iaxs[callno]->pingtime = autokill / 2;
05181 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
05182 }
05183
05184
05185 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
05186 if (!ast_strlen_zero(osp_token_ptr)) {
05187 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
05188 osp_block_index = 0;
05189 while (osp_token_length > 0) {
05190 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
05191 osp_buffer[0] = osp_block_index;
05192 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
05193 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
05194 osp_block_index++;
05195 osp_token_ptr += osp_block_length;
05196 osp_token_length -= osp_block_length;
05197 }
05198 } else
05199 ast_log(LOG_WARNING, "OSP token is too long\n");
05200 } else if (iaxdebug)
05201 ast_debug(1, "OSP token is undefined\n");
05202
05203
05204 iaxs[callno]->sockfd = cai.sockfd;
05205
05206
05207 if (variablestore) {
05208 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
05209 ast_debug(1, "Found an IAX variable store on this channel\n");
05210 AST_LIST_LOCK(variablelist);
05211 AST_LIST_TRAVERSE(variablelist, var, entries) {
05212 char tmp[256];
05213 int i;
05214 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
05215
05216 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
05217 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
05218 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
05219 }
05220 }
05221 AST_LIST_UNLOCK(variablelist);
05222 }
05223
05224
05225 add_empty_calltoken_ie(iaxs[callno], &ied);
05226 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
05227
05228 ast_mutex_unlock(&iaxsl[callno]);
05229 ast_setstate(c, AST_STATE_RINGING);
05230
05231 return 0;
05232 }
05233
05234 static int iax2_hangup(struct ast_channel *c)
05235 {
05236 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05237 struct iax_ie_data ied;
05238 int alreadygone;
05239 memset(&ied, 0, sizeof(ied));
05240 ast_mutex_lock(&iaxsl[callno]);
05241 if (callno && iaxs[callno]) {
05242 ast_debug(1, "We're hanging up %s now...\n", c->name);
05243 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
05244
05245 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05246 if (!iaxs[callno]->error && !alreadygone) {
05247 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05248 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05249 }
05250 if (!iaxs[callno]) {
05251 ast_mutex_unlock(&iaxsl[callno]);
05252 return 0;
05253 }
05254 }
05255
05256 iax2_predestroy(callno);
05257
05258 if (iaxs[callno] && alreadygone) {
05259 ast_debug(1, "Really destroying %s now...\n", c->name);
05260 iax2_destroy(callno);
05261 } else if (iaxs[callno]) {
05262 if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05263 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
05264 iax2_destroy(callno);
05265 }
05266 }
05267 } else if (c->tech_pvt) {
05268
05269
05270
05271
05272 c->tech_pvt = NULL;
05273 }
05274 ast_mutex_unlock(&iaxsl[callno]);
05275 ast_verb(3, "Hungup '%s'\n", c->name);
05276 return 0;
05277 }
05278
05279
05280
05281
05282 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05283 {
05284 unsigned short callno = pvt->callno;
05285
05286 if (!pvt->peercallno) {
05287
05288 int count = 10;
05289 while (count-- && pvt && !pvt->peercallno) {
05290 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05291 pvt = iaxs[callno];
05292 }
05293 if (!pvt || !pvt->peercallno) {
05294 return -1;
05295 }
05296 }
05297
05298 return 0;
05299 }
05300
05301 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05302 {
05303 struct ast_option_header *h;
05304 int res;
05305
05306 switch (option) {
05307 case AST_OPTION_TXGAIN:
05308 case AST_OPTION_RXGAIN:
05309
05310 errno = ENOSYS;
05311 return -1;
05312 case AST_OPTION_OPRMODE:
05313 errno = EINVAL;
05314 return -1;
05315 case AST_OPTION_SECURE_SIGNALING:
05316 case AST_OPTION_SECURE_MEDIA:
05317 {
05318 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05319 ast_mutex_lock(&iaxsl[callno]);
05320 if ((*(int *) data)) {
05321 ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05322 } else {
05323 ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05324 }
05325 ast_mutex_unlock(&iaxsl[callno]);
05326 return 0;
05327 }
05328
05329
05330
05331
05332 case AST_OPTION_TONE_VERIFY:
05333 case AST_OPTION_TDD:
05334 case AST_OPTION_RELAXDTMF:
05335 case AST_OPTION_AUDIO_MODE:
05336 case AST_OPTION_DIGIT_DETECT:
05337 case AST_OPTION_FAX_DETECT:
05338 {
05339 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05340 struct chan_iax2_pvt *pvt;
05341
05342 ast_mutex_lock(&iaxsl[callno]);
05343 pvt = iaxs[callno];
05344
05345 if (wait_for_peercallno(pvt)) {
05346 ast_mutex_unlock(&iaxsl[callno]);
05347 return -1;
05348 }
05349
05350 ast_mutex_unlock(&iaxsl[callno]);
05351
05352 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05353 return -1;
05354 }
05355
05356 h->flag = AST_OPTION_FLAG_REQUEST;
05357 h->option = htons(option);
05358 memcpy(h->data, data, datalen);
05359 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05360 AST_CONTROL_OPTION, 0, (unsigned char *) h,
05361 datalen + sizeof(*h), -1);
05362 ast_free(h);
05363 return res;
05364 }
05365 default:
05366 return -1;
05367 }
05368
05369
05370 return -1;
05371 }
05372
05373 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
05374 {
05375 switch (option) {
05376 case AST_OPTION_SECURE_SIGNALING:
05377 case AST_OPTION_SECURE_MEDIA:
05378 {
05379 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05380 ast_mutex_lock(&iaxsl[callno]);
05381 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
05382 ast_mutex_unlock(&iaxsl[callno]);
05383 return 0;
05384 }
05385 default:
05386 return -1;
05387 }
05388 }
05389
05390 static struct ast_frame *iax2_read(struct ast_channel *c)
05391 {
05392 ast_debug(1, "I should never be called!\n");
05393 return &ast_null_frame;
05394 }
05395
05396 static int iax2_key_rotate(const void *vpvt)
05397 {
05398 int res = 0;
05399 struct chan_iax2_pvt *pvt = (void *) vpvt;
05400 struct MD5Context md5;
05401 char key[17] = "";
05402 struct iax_ie_data ied = {
05403 .pos = 0,
05404 };
05405
05406 ast_mutex_lock(&iaxsl[pvt->callno]);
05407 pvt->keyrotateid =
05408 ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05409
05410 snprintf(key, sizeof(key), "%lX", ast_random());
05411
05412 MD5Init(&md5);
05413 MD5Update(&md5, (unsigned char *) key, strlen(key));
05414 MD5Final((unsigned char *) key, &md5);
05415
05416 IAX_DEBUGDIGEST("Sending", key);
05417
05418 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05419
05420 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05421
05422 build_ecx_key((unsigned char *) key, pvt);
05423
05424 ast_mutex_unlock(&iaxsl[pvt->callno]);
05425
05426 return res;
05427 }
05428
05429 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05430 {
05431 int res;
05432 struct iax_ie_data ied0;
05433 struct iax_ie_data ied1;
05434 unsigned int transferid = (unsigned int)ast_random();
05435
05436 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05437 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
05438 ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
05439 ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
05440 return 0;
05441 }
05442
05443 memset(&ied0, 0, sizeof(ied0));
05444 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05445 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05446 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05447
05448 memset(&ied1, 0, sizeof(ied1));
05449 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05450 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05451 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05452
05453 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05454 if (res)
05455 return -1;
05456 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05457 if (res)
05458 return -1;
05459 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05460 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05461 return 0;
05462 }
05463
05464 static void lock_both(unsigned short callno0, unsigned short callno1)
05465 {
05466 ast_mutex_lock(&iaxsl[callno0]);
05467 while (ast_mutex_trylock(&iaxsl[callno1])) {
05468 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05469 }
05470 }
05471
05472 static void unlock_both(unsigned short callno0, unsigned short callno1)
05473 {
05474 ast_mutex_unlock(&iaxsl[callno1]);
05475 ast_mutex_unlock(&iaxsl[callno0]);
05476 }
05477
05478 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)
05479 {
05480 struct ast_channel *cs[3];
05481 struct ast_channel *who, *other;
05482 int to = -1;
05483 int res = -1;
05484 int transferstarted=0;
05485 struct ast_frame *f;
05486 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05487 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05488 struct timeval waittimer = {0, 0};
05489
05490
05491 if (timeoutms > 0) {
05492 return AST_BRIDGE_FAILED;
05493 }
05494
05495 timeoutms = -1;
05496
05497 lock_both(callno0, callno1);
05498 if (!iaxs[callno0] || !iaxs[callno1]) {
05499 unlock_both(callno0, callno1);
05500 return AST_BRIDGE_FAILED;
05501 }
05502
05503 if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05504 iaxs[callno0]->bridgecallno = callno1;
05505 iaxs[callno1]->bridgecallno = callno0;
05506 }
05507 unlock_both(callno0, callno1);
05508
05509
05510 cs[0] = c0;
05511 cs[1] = c1;
05512 for (;;) {
05513
05514 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05515 ast_verb(3, "Can't masquerade, we're different...\n");
05516
05517 if (c0->tech == &iax2_tech) {
05518 ast_mutex_lock(&iaxsl[callno0]);
05519 iaxs[callno0]->bridgecallno = 0;
05520 ast_mutex_unlock(&iaxsl[callno0]);
05521 }
05522 if (c1->tech == &iax2_tech) {
05523 ast_mutex_lock(&iaxsl[callno1]);
05524 iaxs[callno1]->bridgecallno = 0;
05525 ast_mutex_unlock(&iaxsl[callno1]);
05526 }
05527 return AST_BRIDGE_FAILED_NOWARN;
05528 }
05529 if (c0->nativeformats != c1->nativeformats) {
05530 char buf0[256];
05531 char buf1[256];
05532 ast_getformatname_multiple(buf0, sizeof(buf0), c0->nativeformats);
05533 ast_getformatname_multiple(buf1, sizeof(buf1), c1->nativeformats);
05534 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
05535
05536 lock_both(callno0, callno1);
05537 if (iaxs[callno0])
05538 iaxs[callno0]->bridgecallno = 0;
05539 if (iaxs[callno1])
05540 iaxs[callno1]->bridgecallno = 0;
05541 unlock_both(callno0, callno1);
05542 return AST_BRIDGE_FAILED_NOWARN;
05543 }
05544
05545 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
05546
05547 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05548 ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
05549 ast_log(LOG_WARNING, "Unable to start the transfer\n");
05550 transferstarted = 1;
05551 }
05552 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05553
05554 struct timeval now = ast_tvnow();
05555 if (ast_tvzero(waittimer)) {
05556 waittimer = now;
05557 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05558 c0->_softhangup |= AST_SOFTHANGUP_DEV;
05559 c1->_softhangup |= AST_SOFTHANGUP_DEV;
05560 *fo = NULL;
05561 *rc = c0;
05562 res = AST_BRIDGE_COMPLETE;
05563 break;
05564 }
05565 }
05566 to = 1000;
05567 who = ast_waitfor_n(cs, 2, &to);
05568 if (timeoutms > -1) {
05569 timeoutms -= (1000 - to);
05570 if (timeoutms < 0)
05571 timeoutms = 0;
05572 }
05573 if (!who) {
05574 if (!timeoutms) {
05575 res = AST_BRIDGE_RETRY;
05576 break;
05577 }
05578 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05579 res = AST_BRIDGE_FAILED;
05580 break;
05581 }
05582 continue;
05583 }
05584 f = ast_read(who);
05585 if (!f) {
05586 *fo = NULL;
05587 *rc = who;
05588 res = AST_BRIDGE_COMPLETE;
05589 break;
05590 }
05591 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass.integer != AST_CONTROL_SRCUPDATE)) {
05592 *fo = f;
05593 *rc = who;
05594 res = AST_BRIDGE_COMPLETE;
05595 break;
05596 }
05597 other = (who == c0) ? c1 : c0;
05598 if ((f->frametype == AST_FRAME_VOICE) ||
05599 (f->frametype == AST_FRAME_TEXT) ||
05600 (f->frametype == AST_FRAME_VIDEO) ||
05601 (f->frametype == AST_FRAME_IMAGE) ||
05602 (f->frametype == AST_FRAME_DTMF) ||
05603 (f->frametype == AST_FRAME_CONTROL)) {
05604
05605
05606
05607 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05608 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05609 *rc = who;
05610 *fo = f;
05611 res = AST_BRIDGE_COMPLETE;
05612
05613 break;
05614 }
05615
05616 ast_write(other, f);
05617 }
05618 ast_frfree(f);
05619
05620 cs[2] = cs[0];
05621 cs[0] = cs[1];
05622 cs[1] = cs[2];
05623 }
05624 lock_both(callno0, callno1);
05625 if(iaxs[callno0])
05626 iaxs[callno0]->bridgecallno = 0;
05627 if(iaxs[callno1])
05628 iaxs[callno1]->bridgecallno = 0;
05629 unlock_both(callno0, callno1);
05630 return res;
05631 }
05632
05633 static int iax2_answer(struct ast_channel *c)
05634 {
05635 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05636 ast_debug(1, "Answering IAX2 call\n");
05637 ast_mutex_lock(&iaxsl[callno]);
05638 if (iaxs[callno])
05639 iax2_ami_channelupdate(iaxs[callno]);
05640 ast_mutex_unlock(&iaxsl[callno]);
05641 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05642 }
05643
05644 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05645 {
05646 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05647 struct chan_iax2_pvt *pvt;
05648 int res = 0;
05649
05650 if (iaxdebug)
05651 ast_debug(1, "Indicating condition %d\n", condition);
05652
05653 ast_mutex_lock(&iaxsl[callno]);
05654 pvt = iaxs[callno];
05655
05656 if (wait_for_peercallno(pvt)) {
05657 res = -1;
05658 goto done;
05659 }
05660
05661 switch (condition) {
05662 case AST_CONTROL_HOLD:
05663 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05664 ast_moh_start(c, data, pvt->mohinterpret);
05665 goto done;
05666 }
05667 break;
05668 case AST_CONTROL_UNHOLD:
05669 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05670 ast_moh_stop(c);
05671 goto done;
05672 }
05673 break;
05674 case AST_CONTROL_CONNECTED_LINE:
05675 if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE))
05676 goto done;
05677 break;
05678 }
05679
05680 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05681
05682 done:
05683 ast_mutex_unlock(&iaxsl[callno]);
05684
05685 return res;
05686 }
05687
05688 static int iax2_transfer(struct ast_channel *c, const char *dest)
05689 {
05690 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05691 struct iax_ie_data ied = { "", };
05692 char tmp[256], *context;
05693 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
05694 ast_copy_string(tmp, dest, sizeof(tmp));
05695 context = strchr(tmp, '@');
05696 if (context) {
05697 *context = '\0';
05698 context++;
05699 }
05700 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05701 if (context)
05702 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05703 ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05704 ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
05705 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05706 }
05707
05708 static int iax2_getpeertrunk(struct sockaddr_in sin)
05709 {
05710 struct iax2_peer *peer;
05711 int res = 0;
05712 struct ao2_iterator i;
05713
05714 i = ao2_iterator_init(peers, 0);
05715 while ((peer = ao2_iterator_next(&i))) {
05716 struct sockaddr_in peer_addr;
05717
05718 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
05719
05720 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05721 (peer_addr.sin_port == sin.sin_port)) {
05722 res = ast_test_flag64(peer, IAX_TRUNK);
05723 peer_unref(peer);
05724 break;
05725 }
05726 peer_unref(peer);
05727 }
05728 ao2_iterator_destroy(&i);
05729
05730 return res;
05731 }
05732
05733
05734 static struct ast_channel *ast_iax2_new(int callno, int state, format_t capability, const char *linkedid)
05735 {
05736 struct ast_channel *tmp;
05737 struct chan_iax2_pvt *i;
05738 struct ast_variable *v = NULL;
05739
05740 if (!(i = iaxs[callno])) {
05741 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05742 return NULL;
05743 }
05744
05745
05746 ast_mutex_unlock(&iaxsl[callno]);
05747 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, linkedid, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
05748 ast_mutex_lock(&iaxsl[callno]);
05749 if (i != iaxs[callno]) {
05750 if (tmp) {
05751
05752 ast_mutex_unlock(&iaxsl[callno]);
05753 tmp = ast_channel_release(tmp);
05754 ast_mutex_lock(&iaxsl[callno]);
05755 }
05756 return NULL;
05757 }
05758 iax2_ami_channelupdate(i);
05759 if (!tmp)
05760 return NULL;
05761 tmp->tech = &iax2_tech;
05762
05763 tmp->nativeformats = capability;
05764 tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05765 tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05766 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05767
05768 if (!ast_strlen_zero(i->parkinglot))
05769 ast_string_field_set(tmp, parkinglot, i->parkinglot);
05770
05771
05772 if (!ast_strlen_zero(i->ani)) {
05773 tmp->caller.ani.number.valid = 1;
05774 tmp->caller.ani.number.str = ast_strdup(i->ani);
05775 } else if (!ast_strlen_zero(i->cid_num)) {
05776 tmp->caller.ani.number.valid = 1;
05777 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
05778 }
05779 tmp->dialed.number.str = ast_strdup(i->dnid);
05780 if (!ast_strlen_zero(i->rdnis)) {
05781 tmp->redirecting.from.number.valid = 1;
05782 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
05783 }
05784 tmp->caller.id.name.presentation = i->calling_pres;
05785 tmp->caller.id.number.presentation = i->calling_pres;
05786 tmp->caller.id.number.plan = i->calling_ton;
05787 tmp->dialed.transit_network_select = i->calling_tns;
05788 if (!ast_strlen_zero(i->language))
05789 ast_string_field_set(tmp, language, i->language);
05790 if (!ast_strlen_zero(i->accountcode))
05791 ast_string_field_set(tmp, accountcode, i->accountcode);
05792 if (i->amaflags)
05793 tmp->amaflags = i->amaflags;
05794 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05795 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05796 if (i->adsi)
05797 tmp->adsicpe = i->peeradsicpe;
05798 else
05799 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05800 i->owner = tmp;
05801 i->capability = capability;
05802
05803
05804 if (i->vars) {
05805 for (v = i->vars ; v ; v = v->next)
05806 pbx_builtin_setvar_helper(tmp, v->name, v->value);
05807 }
05808 if (i->iaxvars) {
05809 struct ast_datastore *variablestore;
05810 struct ast_variable *var, *prev = NULL;
05811 AST_LIST_HEAD(, ast_var_t) *varlist;
05812 ast_debug(1, "Loading up the channel with IAXVARs\n");
05813 varlist = ast_calloc(1, sizeof(*varlist));
05814 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05815 if (variablestore && varlist) {
05816 variablestore->data = varlist;
05817 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05818 AST_LIST_HEAD_INIT(varlist);
05819 for (var = i->iaxvars; var; var = var->next) {
05820 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05821 if (prev)
05822 ast_free(prev);
05823 prev = var;
05824 if (!newvar) {
05825
05826 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05827 } else {
05828 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05829 }
05830 }
05831 if (prev)
05832 ast_free(prev);
05833 i->iaxvars = NULL;
05834 ast_channel_datastore_add(i->owner, variablestore);
05835 } else {
05836 if (variablestore) {
05837 ast_datastore_free(variablestore);
05838 }
05839 if (varlist) {
05840 ast_free(varlist);
05841 }
05842 }
05843 }
05844
05845 if (state != AST_STATE_DOWN) {
05846 if (ast_pbx_start(tmp)) {
05847 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05848 ast_hangup(tmp);
05849 i->owner = NULL;
05850 return NULL;
05851 }
05852 }
05853
05854 ast_module_ref(ast_module_info->self);
05855 return tmp;
05856 }
05857
05858 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05859 {
05860 unsigned long int mssincetx;
05861 long int ms, pred;
05862
05863 tpeer->trunkact = *now;
05864 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05865 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05866
05867 tpeer->txtrunktime = *now;
05868 tpeer->lastsent = 999999;
05869 }
05870
05871 tpeer->lasttxtime = *now;
05872
05873
05874 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05875
05876 pred = tpeer->lastsent + sampms;
05877 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05878 ms = pred;
05879
05880
05881 if (ms == tpeer->lastsent)
05882 ms = tpeer->lastsent + 1;
05883 tpeer->lastsent = ms;
05884 return ms;
05885 }
05886
05887 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05888 {
05889 long ms;
05890 if (ast_tvzero(iaxs[callno]->rxcore)) {
05891
05892 iaxs[callno]->rxcore = ast_tvnow();
05893
05894 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05895 }
05896
05897 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05898
05899 return ms + ts;
05900 }
05901
05902 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05903 {
05904 int ms;
05905 int voice = 0;
05906 int genuine = 0;
05907 int adjust;
05908 int rate = ast_format_rate(f->subclass.codec) / 1000;
05909 struct timeval *delivery = NULL;
05910
05911
05912
05913
05914
05915
05916
05917
05918 if (f->frametype == AST_FRAME_VOICE) {
05919 voice = 1;
05920 delivery = &f->delivery;
05921 } else if (f->frametype == AST_FRAME_IAX) {
05922 genuine = 1;
05923 } else if (f->frametype == AST_FRAME_CNG) {
05924 p->notsilenttx = 0;
05925 }
05926
05927 if (ast_tvzero(p->offset)) {
05928 p->offset = ast_tvnow();
05929
05930 p->offset.tv_usec -= p->offset.tv_usec % 20000;
05931 }
05932
05933 if (ts)
05934 return ts;
05935
05936 if (delivery && !ast_tvzero(*delivery)) {
05937 ms = ast_tvdiff_ms(*delivery, p->offset);
05938 if (ms < 0) {
05939 ms = 0;
05940 }
05941 if (iaxdebug)
05942 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05943 } else {
05944 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05945 if (ms < 0)
05946 ms = 0;
05947 if (voice) {
05948
05949 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05950
05951
05952
05953
05954
05955
05956
05957
05958
05959
05960
05961
05962
05963
05964
05965
05966
05967
05968 adjust = (ms - p->nextpred);
05969 if (adjust < 0)
05970 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05971 else if (adjust > 0)
05972 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05973
05974 if (!p->nextpred) {
05975 p->nextpred = ms;
05976 if (p->nextpred <= p->lastsent)
05977 p->nextpred = p->lastsent + 3;
05978 }
05979 ms = p->nextpred;
05980 } else {
05981
05982
05983
05984
05985
05986
05987
05988
05989
05990 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05991 ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05992 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05993
05994 if (f->samples >= rate)
05995 {
05996 int diff = ms % (f->samples / rate);
05997 if (diff)
05998 ms += f->samples/rate - diff;
05999 }
06000
06001 p->nextpred = ms;
06002 p->notsilenttx = 1;
06003 }
06004 } else if ( f->frametype == AST_FRAME_VIDEO ) {
06005
06006
06007
06008
06009
06010
06011
06012
06013 if ( (unsigned int)ms < p->lastsent )
06014 ms = p->lastsent;
06015 } else {
06016
06017
06018 if (genuine) {
06019
06020 if (ms <= p->lastsent)
06021 ms = p->lastsent + 3;
06022 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
06023
06024 ms = p->lastsent + 3;
06025 }
06026 }
06027 }
06028 p->lastsent = ms;
06029 if (voice)
06030 p->nextpred = p->nextpred + f->samples / rate;
06031 return ms;
06032 }
06033
06034 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
06035 {
06036
06037
06038 int ms;
06039 #ifdef IAXTESTS
06040 int jit;
06041 #endif
06042
06043 if (ast_tvzero(p->rxcore)) {
06044 p->rxcore = ast_tvnow();
06045 if (iaxdebug)
06046 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
06047 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
06048 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
06049 #if 1
06050 if (iaxdebug)
06051 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
06052 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
06053 #endif
06054 }
06055
06056 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
06057 #ifdef IAXTESTS
06058 if (test_jit) {
06059 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
06060 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
06061 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
06062 jit = -jit;
06063 ms += jit;
06064 }
06065 }
06066 if (test_late) {
06067 ms += test_late;
06068 test_late = 0;
06069 }
06070 #endif
06071 return ms;
06072 }
06073
06074 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
06075 {
06076 struct iax2_trunk_peer *tpeer = NULL;
06077
06078
06079 AST_LIST_LOCK(&tpeers);
06080
06081 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
06082 if (!inaddrcmp(&tpeer->addr, sin)) {
06083 ast_mutex_lock(&tpeer->lock);
06084 break;
06085 }
06086 }
06087
06088 if (!tpeer) {
06089 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
06090 ast_mutex_init(&tpeer->lock);
06091 tpeer->lastsent = 9999;
06092 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
06093 tpeer->trunkact = ast_tvnow();
06094 ast_mutex_lock(&tpeer->lock);
06095 tpeer->sockfd = fd;
06096 #ifdef SO_NO_CHECK
06097 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
06098 #endif
06099 ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
06100 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
06101 }
06102 }
06103
06104 AST_LIST_UNLOCK(&tpeers);
06105
06106 return tpeer;
06107 }
06108
06109 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
06110 {
06111 struct ast_frame *f;
06112 struct iax2_trunk_peer *tpeer;
06113 void *tmp, *ptr;
06114 struct timeval now;
06115 struct ast_iax2_meta_trunk_entry *met;
06116 struct ast_iax2_meta_trunk_mini *mtm;
06117
06118 f = &fr->af;
06119 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
06120 if (tpeer) {
06121 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
06122
06123 if (tpeer->trunkdataalloc < trunkmaxsize) {
06124 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
06125 ast_mutex_unlock(&tpeer->lock);
06126 return -1;
06127 }
06128
06129 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
06130 tpeer->trunkdata = tmp;
06131 ast_debug(1, "Expanded trunk '%s:%d' to %d bytes\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), tpeer->trunkdataalloc);
06132 } else {
06133 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));
06134 ast_mutex_unlock(&tpeer->lock);
06135 return -1;
06136 }
06137 }
06138
06139
06140 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
06141 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
06142 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
06143 mtm->len = htons(f->datalen);
06144 mtm->mini.callno = htons(pvt->callno);
06145 mtm->mini.ts = htons(0xffff & fr->ts);
06146 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
06147 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
06148 } else {
06149 met = (struct ast_iax2_meta_trunk_entry *)ptr;
06150
06151 met->callno = htons(pvt->callno);
06152 met->len = htons(f->datalen);
06153
06154 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
06155 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
06156 }
06157
06158 memcpy(ptr, f->data.ptr, f->datalen);
06159 tpeer->trunkdatalen += f->datalen;
06160
06161 tpeer->calls++;
06162
06163
06164 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
06165 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
06166
06167
06168 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
06169 now = ast_tvnow();
06170 send_trunk(tpeer, &now);
06171 trunk_untimed ++;
06172 }
06173
06174 ast_mutex_unlock(&tpeer->lock);
06175 }
06176 return 0;
06177 }
06178
06179
06180
06181 static void build_rand_pad(unsigned char *buf, ssize_t len)
06182 {
06183 long tmp;
06184 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
06185 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
06186 buf += sizeof(tmp);
06187 len -= sizeof(tmp);
06188 }
06189 }
06190
06191 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06192 {
06193 build_ecx_key(digest, pvt);
06194 ast_aes_set_decrypt_key(digest, &pvt->dcx);
06195 }
06196
06197 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06198 {
06199
06200
06201
06202 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
06203 ast_aes_set_encrypt_key(digest, &pvt->ecx);
06204 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
06205 }
06206
06207 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
06208 {
06209 #if 0
06210
06211 int x;
06212 if (len % 16)
06213 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06214 for (x=0;x<len;x++)
06215 dst[x] = src[x] ^ 0xff;
06216 #else
06217 unsigned char lastblock[16] = { 0 };
06218 int x;
06219 while(len > 0) {
06220 ast_aes_decrypt(src, dst, dcx);
06221 for (x=0;x<16;x++)
06222 dst[x] ^= lastblock[x];
06223 memcpy(lastblock, src, sizeof(lastblock));
06224 dst += 16;
06225 src += 16;
06226 len -= 16;
06227 }
06228 #endif
06229 }
06230
06231 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
06232 {
06233 #if 0
06234
06235 int x;
06236 if (len % 16)
06237 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06238 for (x=0;x<len;x++)
06239 dst[x] = src[x] ^ 0xff;
06240 #else
06241 unsigned char curblock[16] = { 0 };
06242 int x;
06243 while(len > 0) {
06244 for (x=0;x<16;x++)
06245 curblock[x] ^= src[x];
06246 ast_aes_encrypt(curblock, dst, ecx);
06247 memcpy(curblock, dst, sizeof(curblock));
06248 dst += 16;
06249 src += 16;
06250 len -= 16;
06251 }
06252 #endif
06253 }
06254
06255 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06256 {
06257 int padding;
06258 unsigned char *workspace;
06259
06260 workspace = alloca(*datalen);
06261 memset(f, 0, sizeof(*f));
06262 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06263 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06264 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
06265 return -1;
06266
06267 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
06268
06269 padding = 16 + (workspace[15] & 0x0f);
06270 if (iaxdebug)
06271 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
06272 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
06273 return -1;
06274
06275 *datalen -= padding;
06276 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06277 f->frametype = fh->type;
06278 if (f->frametype == AST_FRAME_VIDEO) {
06279 f->subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
06280 } else if (f->frametype == AST_FRAME_VOICE) {
06281 f->subclass.codec = uncompress_subclass(fh->csub);
06282 } else {
06283 f->subclass.integer = uncompress_subclass(fh->csub);
06284 }
06285 } else {
06286 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06287 if (iaxdebug)
06288 ast_debug(1, "Decoding mini with length %d\n", *datalen);
06289 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06290 return -1;
06291
06292 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06293 padding = 16 + (workspace[15] & 0x0f);
06294 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06295 return -1;
06296 *datalen -= padding;
06297 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06298 }
06299 return 0;
06300 }
06301
06302 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06303 {
06304 int padding;
06305 unsigned char *workspace;
06306 workspace = alloca(*datalen + 32);
06307 if (!workspace)
06308 return -1;
06309 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06310 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06311 if (iaxdebug)
06312 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06313 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06314 padding = 16 + (padding & 0xf);
06315 memcpy(workspace, poo, padding);
06316 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06317 workspace[15] &= 0xf0;
06318 workspace[15] |= (padding & 0xf);
06319 if (iaxdebug)
06320 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06321 *datalen += padding;
06322 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06323 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06324 memcpy(poo, workspace + *datalen - 32, 32);
06325 } else {
06326 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06327 if (iaxdebug)
06328 ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06329 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06330 padding = 16 + (padding & 0xf);
06331 memcpy(workspace, poo, padding);
06332 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06333 workspace[15] &= 0xf0;
06334 workspace[15] |= (padding & 0x0f);
06335 *datalen += padding;
06336 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06337 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06338 memcpy(poo, workspace + *datalen - 32, 32);
06339 }
06340 return 0;
06341 }
06342
06343 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06344 {
06345 int res=-1;
06346 if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
06347
06348 struct MD5Context md5;
06349 unsigned char digest[16];
06350 char *tmppw, *stringp;
06351
06352 tmppw = ast_strdupa(iaxs[callno]->secret);
06353 stringp = tmppw;
06354 while ((tmppw = strsep(&stringp, ";"))) {
06355 MD5Init(&md5);
06356 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06357 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06358 MD5Final(digest, &md5);
06359 build_encryption_keys(digest, iaxs[callno]);
06360 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06361 if (!res) {
06362 ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
06363 break;
06364 }
06365 }
06366 } else
06367 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06368 return res;
06369 }
06370
06371 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06372 {
06373
06374
06375
06376 struct ast_iax2_full_hdr *fh;
06377 struct ast_iax2_mini_hdr *mh;
06378 struct ast_iax2_video_hdr *vh;
06379 struct {
06380 struct iax_frame fr2;
06381 unsigned char buffer[4096];
06382 } frb;
06383 struct iax_frame *fr;
06384 int res;
06385 int sendmini=0;
06386 unsigned int lastsent;
06387 unsigned int fts;
06388
06389 frb.fr2.afdatalen = sizeof(frb.buffer);
06390
06391 if (!pvt) {
06392 ast_log(LOG_WARNING, "No private structure for packet?\n");
06393 return -1;
06394 }
06395
06396 lastsent = pvt->lastsent;
06397
06398
06399 fts = calc_timestamp(pvt, ts, f);
06400
06401
06402
06403
06404 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06405 return 0;
06406 #if 0
06407 ast_log(LOG_NOTICE,
06408 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06409 *("=!" + (f->frametype == AST_FRAME_VOICE)),
06410 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06411 pvt->keyrotateid != -1 ? "" : "no "
06412 );
06413 #endif
06414 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06415 iax2_key_rotate(pvt);
06416 }
06417
06418 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
06419 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06420 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06421 &&
06422 (f->frametype == AST_FRAME_VOICE)
06423 &&
06424 (f->subclass.codec == pvt->svoiceformat)
06425 ) {
06426
06427 now = 1;
06428
06429 sendmini = 1;
06430 }
06431 if ( f->frametype == AST_FRAME_VIDEO ) {
06432
06433
06434
06435
06436
06437 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06438 ((f->subclass.codec & ~0x1LL) == pvt->svideoformat)
06439 ) {
06440 now = 1;
06441 sendmini = 1;
06442 } else {
06443 now = 0;
06444 sendmini = 0;
06445 }
06446 pvt->lastvsent = fts;
06447 }
06448 if (f->frametype == AST_FRAME_IAX) {
06449
06450 pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
06451 if (!pvt->first_iax_message) {
06452 pvt->first_iax_message = pvt->last_iax_message;
06453 }
06454 }
06455
06456 if (now) {
06457 fr = &frb.fr2;
06458 } else
06459 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag64(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
06460 if (!fr) {
06461 ast_log(LOG_WARNING, "Out of memory\n");
06462 return -1;
06463 }
06464
06465 iax_frame_wrap(fr, f);
06466
06467 fr->ts = fts;
06468 fr->callno = pvt->callno;
06469 fr->transfer = transfer;
06470 fr->final = final;
06471 fr->encmethods = 0;
06472 if (!sendmini) {
06473
06474 if (seqno > -1)
06475 fr->oseqno = seqno;
06476 else
06477 fr->oseqno = pvt->oseqno++;
06478 fr->iseqno = pvt->iseqno;
06479 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06480 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06481 fh->ts = htonl(fr->ts);
06482 fh->oseqno = fr->oseqno;
06483 if (transfer) {
06484 fh->iseqno = 0;
06485 } else
06486 fh->iseqno = fr->iseqno;
06487
06488 if (!transfer)
06489 pvt->aseqno = fr->iseqno;
06490 fh->type = fr->af.frametype & 0xFF;
06491
06492 if (fr->af.frametype == AST_FRAME_VIDEO) {
06493 fh->csub = compress_subclass(fr->af.subclass.codec & ~0x1LL) | ((fr->af.subclass.codec & 0x1LL) << 6);
06494 } else if (fr->af.frametype == AST_FRAME_VOICE) {
06495 fh->csub = compress_subclass(fr->af.subclass.codec);
06496 } else {
06497 fh->csub = compress_subclass(fr->af.subclass.integer);
06498 }
06499
06500 if (transfer) {
06501 fr->dcallno = pvt->transfercallno;
06502 } else
06503 fr->dcallno = pvt->peercallno;
06504 fh->dcallno = htons(fr->dcallno);
06505 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06506 fr->data = fh;
06507 fr->retries = 0;
06508
06509 fr->retrytime = pvt->pingtime * 2;
06510 if (fr->retrytime < MIN_RETRY_TIME)
06511 fr->retrytime = MIN_RETRY_TIME;
06512 if (fr->retrytime > MAX_RETRY_TIME)
06513 fr->retrytime = MAX_RETRY_TIME;
06514
06515 if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
06516 fr->retries = -1;
06517 else if (f->frametype == AST_FRAME_VOICE)
06518 pvt->svoiceformat = f->subclass.codec;
06519 else if (f->frametype == AST_FRAME_VIDEO)
06520 pvt->svideoformat = f->subclass.codec & ~0x1LL;
06521 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06522 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06523 if (fr->transfer)
06524 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06525 else
06526 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06527 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06528 fr->encmethods = pvt->encmethods;
06529 fr->ecx = pvt->ecx;
06530 fr->mydcx = pvt->mydcx;
06531 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06532 } else
06533 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06534 }
06535
06536 if (now) {
06537 res = send_packet(fr);
06538 } else
06539 res = iax2_transmit(fr);
06540 } else {
06541 if (ast_test_flag64(pvt, IAX_TRUNK)) {
06542 iax2_trunk_queue(pvt, fr);
06543 res = 0;
06544 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06545
06546 fr->oseqno = -1;
06547 fr->iseqno = -1;
06548 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06549 vh->zeros = 0;
06550 vh->callno = htons(0x8000 | fr->callno);
06551 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.codec & 0x1LL ? 0x8000 : 0));
06552 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06553 fr->data = vh;
06554 fr->retries = -1;
06555 res = send_packet(fr);
06556 } else {
06557
06558 fr->oseqno = -1;
06559 fr->iseqno = -1;
06560
06561 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06562 mh->callno = htons(fr->callno);
06563 mh->ts = htons(fr->ts & 0xFFFF);
06564 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06565 fr->data = mh;
06566 fr->retries = -1;
06567 if (pvt->transferring == TRANSFER_MEDIAPASS)
06568 fr->transfer = 1;
06569 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06570 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06571 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06572 } else
06573 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06574 }
06575 res = send_packet(fr);
06576 }
06577 }
06578 return res;
06579 }
06580
06581 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06582 {
06583 regex_t regexbuf;
06584 int havepattern = 0;
06585
06586 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
06587 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
06588
06589 struct iax2_user *user = NULL;
06590 char auth[90];
06591 char *pstr = "";
06592 struct ao2_iterator i;
06593
06594 switch (cmd) {
06595 case CLI_INIT:
06596 e->command = "iax2 show users [like]";
06597 e->usage =
06598 "Usage: iax2 show users [like <pattern>]\n"
06599 " Lists all known IAX2 users.\n"
06600 " Optional regular expression pattern is used to filter the user list.\n";
06601 return NULL;
06602 case CLI_GENERATE:
06603 return NULL;
06604 }
06605
06606 switch (a->argc) {
06607 case 5:
06608 if (!strcasecmp(a->argv[3], "like")) {
06609 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06610 return CLI_SHOWUSAGE;
06611 havepattern = 1;
06612 } else
06613 return CLI_SHOWUSAGE;
06614 case 3:
06615 break;
06616 default:
06617 return CLI_SHOWUSAGE;
06618 }
06619
06620 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06621 i = ao2_iterator_init(users, 0);
06622 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
06623 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0))
06624 continue;
06625
06626 if (!ast_strlen_zero(user->secret)) {
06627 ast_copy_string(auth,user->secret, sizeof(auth));
06628 } else if (!ast_strlen_zero(user->inkeys)) {
06629 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06630 } else
06631 ast_copy_string(auth, "-no secret-", sizeof(auth));
06632
06633 if(ast_test_flag64(user, IAX_CODEC_NOCAP))
06634 pstr = "REQ Only";
06635 else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
06636 pstr = "Disabled";
06637 else
06638 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06639
06640 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
06641 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06642 user->ha ? "Yes" : "No", pstr);
06643 }
06644 ao2_iterator_destroy(&i);
06645
06646 if (havepattern)
06647 regfree(®exbuf);
06648
06649 return CLI_SUCCESS;
06650 #undef FORMAT
06651 #undef FORMAT2
06652 }
06653
06654 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
06655 {
06656 regex_t regexbuf;
06657 int havepattern = 0;
06658 int total_peers = 0;
06659 int online_peers = 0;
06660 int offline_peers = 0;
06661 int unmonitored_peers = 0;
06662 struct ao2_iterator i;
06663
06664 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s\n"
06665 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s\n"
06666
06667 struct iax2_peer *peer = NULL;
06668 char name[256];
06669 struct ast_str *encmethods = ast_str_alloca(256);
06670 int registeredonly=0;
06671 char idtext[256] = "";
06672 switch (argc) {
06673 case 6:
06674 if (!strcasecmp(argv[3], "registered"))
06675 registeredonly = 1;
06676 else
06677 return RESULT_SHOWUSAGE;
06678 if (!strcasecmp(argv[4], "like")) {
06679 if (regcomp(®exbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06680 return RESULT_SHOWUSAGE;
06681 havepattern = 1;
06682 } else
06683 return RESULT_SHOWUSAGE;
06684 break;
06685 case 5:
06686 if (!strcasecmp(argv[3], "like")) {
06687 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06688 return RESULT_SHOWUSAGE;
06689 havepattern = 1;
06690 } else
06691 return RESULT_SHOWUSAGE;
06692 break;
06693 case 4:
06694 if (!strcasecmp(argv[3], "registered"))
06695 registeredonly = 1;
06696 else
06697 return RESULT_SHOWUSAGE;
06698 break;
06699 case 3:
06700 break;
06701 default:
06702 return RESULT_SHOWUSAGE;
06703 }
06704
06705
06706 if (!s)
06707 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status");
06708
06709 i = ao2_iterator_init(peers, 0);
06710 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
06711 char nm[20];
06712 char status[20];
06713 int retstatus;
06714 struct sockaddr_in peer_addr;
06715
06716 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
06717
06718 if (registeredonly && !peer_addr.sin_addr.s_addr) {
06719 continue;
06720 }
06721 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
06722 continue;
06723 }
06724
06725 if (!ast_strlen_zero(peer->username))
06726 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06727 else
06728 ast_copy_string(name, peer->name, sizeof(name));
06729
06730 encmethods_to_str(peer->encmethods, encmethods);
06731 retstatus = peer_status(peer, status, sizeof(status));
06732 if (retstatus > 0)
06733 online_peers++;
06734 else if (!retstatus)
06735 offline_peers++;
06736 else
06737 unmonitored_peers++;
06738
06739 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06740
06741 if (s) {
06742 astman_append(s,
06743 "Event: PeerEntry\r\n%s"
06744 "Channeltype: IAX2\r\n"
06745 "ObjectName: %s\r\n"
06746 "ChanObjectType: peer\r\n"
06747 "IPaddress: %s\r\n"
06748 "IPport: %d\r\n"
06749 "Dynamic: %s\r\n"
06750 "Trunk: %s\r\n"
06751 "Encryption: %s\r\n"
06752 "Status: %s\r\n\r\n",
06753 idtext,
06754 name,
06755 ast_sockaddr_stringify_addr(&peer->addr),
06756 ast_sockaddr_port(&peer->addr),
06757 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
06758 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
06759 peer->encmethods ? ast_str_buffer(encmethods) : "no",
06760 status);
06761 } else {
06762 ast_cli(fd, FORMAT, name,
06763 ast_sockaddr_stringify_addr(&peer->addr),
06764 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06765 nm,
06766 ast_sockaddr_port(&peer->addr),
06767 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
06768 peer->encmethods ? "(E)" : " ",
06769 status);
06770 }
06771 total_peers++;
06772 }
06773 ao2_iterator_destroy(&i);
06774
06775 if (!s)
06776 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
06777 total_peers, online_peers, offline_peers, unmonitored_peers);
06778
06779 if (havepattern)
06780 regfree(®exbuf);
06781
06782 if (total)
06783 *total = total_peers;
06784
06785 return RESULT_SUCCESS;
06786 #undef FORMAT
06787 #undef FORMAT2
06788 }
06789
06790 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06791 {
06792 struct iax2_thread *thread = NULL;
06793 time_t t;
06794 int threadcount = 0, dynamiccount = 0;
06795 char type;
06796
06797 switch (cmd) {
06798 case CLI_INIT:
06799 e->command = "iax2 show threads";
06800 e->usage =
06801 "Usage: iax2 show threads\n"
06802 " Lists status of IAX helper threads\n";
06803 return NULL;
06804 case CLI_GENERATE:
06805 return NULL;
06806 }
06807 if (a->argc != 3)
06808 return CLI_SHOWUSAGE;
06809
06810 ast_cli(a->fd, "IAX2 Thread Information\n");
06811 time(&t);
06812 ast_cli(a->fd, "Idle Threads:\n");
06813 AST_LIST_LOCK(&idle_list);
06814 AST_LIST_TRAVERSE(&idle_list, thread, list) {
06815 #ifdef DEBUG_SCHED_MULTITHREAD
06816 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06817 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06818 #else
06819 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06820 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06821 #endif
06822 threadcount++;
06823 }
06824 AST_LIST_UNLOCK(&idle_list);
06825 ast_cli(a->fd, "Active Threads:\n");
06826 AST_LIST_LOCK(&active_list);
06827 AST_LIST_TRAVERSE(&active_list, thread, list) {
06828 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06829 type = 'D';
06830 else
06831 type = 'P';
06832 #ifdef DEBUG_SCHED_MULTITHREAD
06833 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
06834 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06835 #else
06836 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
06837 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06838 #endif
06839 threadcount++;
06840 }
06841 AST_LIST_UNLOCK(&active_list);
06842 ast_cli(a->fd, "Dynamic Threads:\n");
06843 AST_LIST_LOCK(&dynamic_list);
06844 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06845 #ifdef DEBUG_SCHED_MULTITHREAD
06846 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06847 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06848 #else
06849 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06850 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06851 #endif
06852 dynamiccount++;
06853 }
06854 AST_LIST_UNLOCK(&dynamic_list);
06855 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06856 return CLI_SUCCESS;
06857 }
06858
06859 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06860 {
06861 struct iax2_peer *p;
06862
06863 switch (cmd) {
06864 case CLI_INIT:
06865 e->command = "iax2 unregister";
06866 e->usage =
06867 "Usage: iax2 unregister <peername>\n"
06868 " Unregister (force expiration) an IAX2 peer from the registry.\n";
06869 return NULL;
06870 case CLI_GENERATE:
06871 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06872 }
06873
06874 if (a->argc != 3)
06875 return CLI_SHOWUSAGE;
06876
06877 p = find_peer(a->argv[2], 1);
06878 if (p) {
06879 if (p->expire > 0) {
06880 struct iax2_peer tmp_peer = {
06881 .name = a->argv[2],
06882 };
06883 struct iax2_peer *peer;
06884
06885 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06886 if (peer) {
06887 expire_registry(peer_ref(peer));
06888 peer_unref(peer);
06889 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06890 } else {
06891 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06892 }
06893 } else {
06894 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06895 }
06896 peer_unref(p);
06897 } else {
06898 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06899 }
06900 return CLI_SUCCESS;
06901 }
06902
06903 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06904 {
06905 int which = 0;
06906 struct iax2_peer *p = NULL;
06907 char *res = NULL;
06908 int wordlen = strlen(word);
06909
06910
06911 if (pos == 2) {
06912 struct ao2_iterator i = ao2_iterator_init(peers, 0);
06913 while ((p = ao2_iterator_next(&i))) {
06914 if (!strncasecmp(p->name, word, wordlen) &&
06915 ++which > state && p->expire > 0) {
06916 res = ast_strdup(p->name);
06917 peer_unref(p);
06918 break;
06919 }
06920 peer_unref(p);
06921 }
06922 ao2_iterator_destroy(&i);
06923 }
06924
06925 return res;
06926 }
06927
06928 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06929 {
06930 switch (cmd) {
06931 case CLI_INIT:
06932 e->command = "iax2 show peers";
06933 e->usage =
06934 "Usage: iax2 show peers [registered] [like <pattern>]\n"
06935 " Lists all known IAX2 peers.\n"
06936 " Optional 'registered' argument lists only peers with known addresses.\n"
06937 " Optional regular expression pattern is used to filter the peer list.\n";
06938 return NULL;
06939 case CLI_GENERATE:
06940 return NULL;
06941 }
06942
06943 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
06944 case RESULT_SHOWUSAGE:
06945 return CLI_SHOWUSAGE;
06946 case RESULT_FAILURE:
06947 return CLI_FAILURE;
06948 default:
06949 return CLI_SUCCESS;
06950 }
06951 }
06952
06953 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06954 {
06955 ast_cli_netstats(s, -1, 0);
06956 astman_append(s, "\r\n");
06957 return RESULT_SUCCESS;
06958 }
06959
06960 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06961 {
06962 struct iax_firmware *cur = NULL;
06963
06964 switch (cmd) {
06965 case CLI_INIT:
06966 e->command = "iax2 show firmware";
06967 e->usage =
06968 "Usage: iax2 show firmware\n"
06969 " Lists all known IAX firmware images.\n";
06970 return NULL;
06971 case CLI_GENERATE:
06972 return NULL;
06973 }
06974
06975 if (a->argc != 3 && a->argc != 4)
06976 return CLI_SHOWUSAGE;
06977
06978 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
06979 AST_LIST_LOCK(&firmwares);
06980 AST_LIST_TRAVERSE(&firmwares, cur, list) {
06981 if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
06982 ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
06983 ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06984 }
06985 }
06986 AST_LIST_UNLOCK(&firmwares);
06987
06988 return CLI_SUCCESS;
06989 }
06990
06991
06992 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06993 {
06994 static const char * const a[] = { "iax2", "show", "peers" };
06995 const char *id = astman_get_header(m,"ActionID");
06996 char idtext[256] = "";
06997 int total = 0;
06998
06999 if (!ast_strlen_zero(id))
07000 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07001
07002 astman_send_listack(s, m, "Peer status list will follow", "start");
07003
07004 __iax2_show_peers(-1, &total, s, 3, a);
07005
07006 astman_append(s,
07007 "Event: PeerlistComplete\r\n"
07008 "EventList: Complete\r\n"
07009 "ListItems: %d\r\n"
07010 "%s"
07011 "\r\n", total, idtext);
07012 return 0;
07013 }
07014
07015
07016 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
07017 {
07018 struct iax2_peer *peer = NULL;
07019 int peer_count = 0;
07020 char nm[20];
07021 char status[20];
07022 const char *id = astman_get_header(m,"ActionID");
07023 char idtext[256] = "";
07024 struct ast_str *encmethods = ast_str_alloca(256);
07025 struct ao2_iterator i;
07026
07027 if (!ast_strlen_zero(id))
07028 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07029
07030 astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
07031
07032
07033 i = ao2_iterator_init(peers, 0);
07034 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
07035 encmethods_to_str(peer->encmethods, encmethods);
07036 astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
07037 if (!ast_strlen_zero(peer->username)) {
07038 astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
07039 } else {
07040 astman_append(s, "ObjectName: %s\r\n", peer->name);
07041 }
07042 astman_append(s, "ChanObjectType: peer\r\n");
07043 astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
07044 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
07045 astman_append(s, "Mask: %s\r\n", nm);
07046 astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
07047 astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
07048 astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
07049 astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
07050 peer_status(peer, status, sizeof(status));
07051 astman_append(s, "Status: %s\r\n\r\n", status);
07052 peer_count++;
07053 }
07054 ao2_iterator_destroy(&i);
07055
07056 astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
07057 return RESULT_SUCCESS;
07058 }
07059
07060
07061 static char *regstate2str(int regstate)
07062 {
07063 switch(regstate) {
07064 case REG_STATE_UNREGISTERED:
07065 return "Unregistered";
07066 case REG_STATE_REGSENT:
07067 return "Request Sent";
07068 case REG_STATE_AUTHSENT:
07069 return "Auth. Sent";
07070 case REG_STATE_REGISTERED:
07071 return "Registered";
07072 case REG_STATE_REJECTED:
07073 return "Rejected";
07074 case REG_STATE_TIMEOUT:
07075 return "Timeout";
07076 case REG_STATE_NOAUTH:
07077 return "No Authentication";
07078 default:
07079 return "Unknown";
07080 }
07081 }
07082
07083 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07084 {
07085 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
07086 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
07087 struct iax2_registry *reg = NULL;
07088 char host[80];
07089 char perceived[80];
07090 int counter = 0;
07091
07092 switch (cmd) {
07093 case CLI_INIT:
07094 e->command = "iax2 show registry";
07095 e->usage =
07096 "Usage: iax2 show registry\n"
07097 " Lists all registration requests and status.\n";
07098 return NULL;
07099 case CLI_GENERATE:
07100 return NULL;
07101 }
07102 if (a->argc != 3)
07103 return CLI_SHOWUSAGE;
07104 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
07105 AST_LIST_LOCK(®istrations);
07106 AST_LIST_TRAVERSE(®istrations, reg, entry) {
07107 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(®->addr));
07108 if (reg->us.sin_addr.s_addr)
07109 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07110 else
07111 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07112 ast_cli(a->fd, FORMAT, host,
07113 (reg->dnsmgr) ? "Y" : "N",
07114 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
07115 counter++;
07116 }
07117 AST_LIST_UNLOCK(®istrations);
07118 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
07119 return CLI_SUCCESS;
07120 #undef FORMAT
07121 #undef FORMAT2
07122 }
07123
07124 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
07125 {
07126 const char *id = astman_get_header(m, "ActionID");
07127 struct iax2_registry *reg = NULL;
07128 char idtext[256] = "";
07129 char host[80] = "";
07130 char perceived[80] = "";
07131 int total = 0;
07132
07133 if (!ast_strlen_zero(id))
07134 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07135
07136 astman_send_listack(s, m, "Registrations will follow", "start");
07137
07138 AST_LIST_LOCK(®istrations);
07139 AST_LIST_TRAVERSE(®istrations, reg, entry) {
07140 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(®->addr));
07141
07142 if (reg->us.sin_addr.s_addr) {
07143 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07144 } else {
07145 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07146 }
07147
07148 astman_append(s,
07149 "Event: RegistryEntry\r\n"
07150 "%s"
07151 "Host: %s\r\n"
07152 "DNSmanager: %s\r\n"
07153 "Username: %s\r\n"
07154 "Perceived: %s\r\n"
07155 "Refresh: %d\r\n"
07156 "State: %s\r\n"
07157 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
07158 reg->refresh, regstate2str(reg->regstate));
07159
07160 total++;
07161 }
07162 AST_LIST_UNLOCK(®istrations);
07163
07164 astman_append(s,
07165 "Event: RegistrationsComplete\r\n"
07166 "EventList: Complete\r\n"
07167 "ListItems: %d\r\n"
07168 "%s"
07169 "\r\n", total, idtext);
07170
07171 return 0;
07172 }
07173
07174 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07175 {
07176 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
07177 #define FORMAT "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d %-5.5dms %-4.4dms %-4.4dms %-6.6s %s%s %3s%s\n"
07178 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
07179 int x;
07180 int numchans = 0;
07181 char first_message[10] = { 0, };
07182 char last_message[10] = { 0, };
07183
07184 switch (cmd) {
07185 case CLI_INIT:
07186 e->command = "iax2 show channels";
07187 e->usage =
07188 "Usage: iax2 show channels\n"
07189 " Lists all currently active IAX channels.\n";
07190 return NULL;
07191 case CLI_GENERATE:
07192 return NULL;
07193 }
07194
07195 if (a->argc != 3)
07196 return CLI_SHOWUSAGE;
07197 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
07198 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07199 ast_mutex_lock(&iaxsl[x]);
07200 if (iaxs[x]) {
07201 int lag, jitter, localdelay;
07202 jb_info jbinfo;
07203 if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07204 jb_getinfo(iaxs[x]->jb, &jbinfo);
07205 jitter = jbinfo.jitter;
07206 localdelay = jbinfo.current - jbinfo.min;
07207 } else {
07208 jitter = -1;
07209 localdelay = 0;
07210 }
07211
07212 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07213 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07214 lag = iaxs[x]->remote_rr.delay;
07215 ast_cli(a->fd, FORMAT,
07216 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07217 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
07218 S_OR(iaxs[x]->username, "(None)"),
07219 iaxs[x]->callno, iaxs[x]->peercallno,
07220 iaxs[x]->oseqno, iaxs[x]->iseqno,
07221 lag,
07222 jitter,
07223 localdelay,
07224 ast_getformatname(iaxs[x]->voiceformat),
07225 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07226 first_message,
07227 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07228 last_message);
07229 numchans++;
07230 }
07231 ast_mutex_unlock(&iaxsl[x]);
07232 }
07233 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07234 return CLI_SUCCESS;
07235 #undef FORMAT
07236 #undef FORMAT2
07237 #undef FORMATB
07238 }
07239
07240 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
07241 {
07242 int x;
07243 int numchans = 0;
07244 char first_message[10] = { 0, };
07245 char last_message[10] = { 0, };
07246 #define ACN_FORMAT1 "%-20.25s %4d %4d %4d %5d %3d %5d %4d %6d %4d %4d %5d %3d %5d %4d %6d %s%s %4s%s\n"
07247 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
07248 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07249 ast_mutex_lock(&iaxsl[x]);
07250 if (iaxs[x]) {
07251 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
07252 jb_info jbinfo;
07253 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07254 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07255
07256 if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07257 jb_getinfo(iaxs[x]->jb, &jbinfo);
07258 localjitter = jbinfo.jitter;
07259 localdelay = jbinfo.current - jbinfo.min;
07260 locallost = jbinfo.frames_lost;
07261 locallosspct = jbinfo.losspct/1000;
07262 localdropped = jbinfo.frames_dropped;
07263 localooo = jbinfo.frames_ooo;
07264 } else {
07265 localjitter = -1;
07266 localdelay = 0;
07267 locallost = -1;
07268 locallosspct = -1;
07269 localdropped = 0;
07270 localooo = -1;
07271 }
07272 if (s)
07273 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07274 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07275 iaxs[x]->pingtime,
07276 localjitter,
07277 localdelay,
07278 locallost,
07279 locallosspct,
07280 localdropped,
07281 localooo,
07282 iaxs[x]->frames_received/1000,
07283 iaxs[x]->remote_rr.jitter,
07284 iaxs[x]->remote_rr.delay,
07285 iaxs[x]->remote_rr.losscnt,
07286 iaxs[x]->remote_rr.losspct,
07287 iaxs[x]->remote_rr.dropped,
07288 iaxs[x]->remote_rr.ooo,
07289 iaxs[x]->remote_rr.packets/1000,
07290 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07291 first_message,
07292 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07293 last_message);
07294 else
07295 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07296 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07297 iaxs[x]->pingtime,
07298 localjitter,
07299 localdelay,
07300 locallost,
07301 locallosspct,
07302 localdropped,
07303 localooo,
07304 iaxs[x]->frames_received/1000,
07305 iaxs[x]->remote_rr.jitter,
07306 iaxs[x]->remote_rr.delay,
07307 iaxs[x]->remote_rr.losscnt,
07308 iaxs[x]->remote_rr.losspct,
07309 iaxs[x]->remote_rr.dropped,
07310 iaxs[x]->remote_rr.ooo,
07311 iaxs[x]->remote_rr.packets/1000,
07312 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07313 first_message,
07314 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07315 last_message);
07316 numchans++;
07317 }
07318 ast_mutex_unlock(&iaxsl[x]);
07319 }
07320
07321 return numchans;
07322 }
07323
07324 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07325 {
07326 int numchans = 0;
07327
07328 switch (cmd) {
07329 case CLI_INIT:
07330 e->command = "iax2 show netstats";
07331 e->usage =
07332 "Usage: iax2 show netstats\n"
07333 " Lists network status for all currently active IAX channels.\n";
07334 return NULL;
07335 case CLI_GENERATE:
07336 return NULL;
07337 }
07338 if (a->argc != 3)
07339 return CLI_SHOWUSAGE;
07340 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
07341 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
07342 numchans = ast_cli_netstats(NULL, a->fd, 1);
07343 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07344 return CLI_SUCCESS;
07345 }
07346
07347 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07348 {
07349 switch (cmd) {
07350 case CLI_INIT:
07351 e->command = "iax2 set debug {on|off|peer}";
07352 e->usage =
07353 "Usage: iax2 set debug {on|off|peer peername}\n"
07354 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
07355 return NULL;
07356 case CLI_GENERATE:
07357 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07358 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07359 return NULL;
07360 }
07361
07362 if (a->argc < e->args || a->argc > e->args + 1)
07363 return CLI_SHOWUSAGE;
07364
07365 if (!strcasecmp(a->argv[3], "peer")) {
07366 struct iax2_peer *peer;
07367 struct sockaddr_in peer_addr;
07368
07369
07370 if (a->argc != e->args + 1)
07371 return CLI_SHOWUSAGE;
07372
07373 peer = find_peer(a->argv[4], 1);
07374
07375 if (!peer) {
07376 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07377 return CLI_FAILURE;
07378 }
07379
07380 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
07381
07382 debugaddr.sin_addr = peer_addr.sin_addr;
07383 debugaddr.sin_port = peer_addr.sin_port;
07384
07385 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07386 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07387
07388 ao2_ref(peer, -1);
07389 } else if (!strncasecmp(a->argv[3], "on", 2)) {
07390 iaxdebug = 1;
07391 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07392 } else {
07393 iaxdebug = 0;
07394 memset(&debugaddr, 0, sizeof(debugaddr));
07395 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07396 }
07397 return CLI_SUCCESS;
07398 }
07399
07400 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07401 {
07402 switch (cmd) {
07403 case CLI_INIT:
07404 e->command = "iax2 set debug trunk {on|off}";
07405 e->usage =
07406 "Usage: iax2 set debug trunk {on|off}\n"
07407 " Enables/Disables debugging of IAX trunking\n";
07408 return NULL;
07409 case CLI_GENERATE:
07410 return NULL;
07411 }
07412
07413 if (a->argc != e->args)
07414 return CLI_SHOWUSAGE;
07415
07416 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07417 iaxtrunkdebug = 1;
07418 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07419 } else {
07420 iaxtrunkdebug = 0;
07421 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07422 }
07423 return CLI_SUCCESS;
07424 }
07425
07426 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07427 {
07428 switch (cmd) {
07429 case CLI_INIT:
07430 e->command = "iax2 set debug jb {on|off}";
07431 e->usage =
07432 "Usage: iax2 set debug jb {on|off}\n"
07433 " Enables/Disables jitterbuffer debugging information\n";
07434 return NULL;
07435 case CLI_GENERATE:
07436 return NULL;
07437 }
07438
07439 if (a->argc != e->args)
07440 return CLI_SHOWUSAGE;
07441
07442 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07443 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07444 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07445 } else {
07446 jb_setoutput(jb_error_output, jb_warning_output, NULL);
07447 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07448 }
07449 return CLI_SUCCESS;
07450 }
07451
07452 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07453 {
07454 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
07455 int res = -1;
07456 ast_mutex_lock(&iaxsl[callno]);
07457 if (iaxs[callno]) {
07458
07459 if (!iaxs[callno]->error) {
07460 if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
07461 res = 0;
07462
07463 else if (f->frametype == AST_FRAME_NULL)
07464 res = 0;
07465 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
07466 res = 0;
07467 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07468 res = 0;
07469 else
07470
07471 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07472 } else {
07473 ast_debug(1, "Write error: %s\n", strerror(errno));
07474 }
07475 }
07476
07477 ast_mutex_unlock(&iaxsl[callno]);
07478 return res;
07479 }
07480
07481 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
07482 int now, int transfer, int final)
07483 {
07484 struct ast_frame f = { 0, };
07485 int res = 0;
07486
07487 f.frametype = type;
07488 f.subclass.integer = command;
07489 f.datalen = datalen;
07490 f.src = __FUNCTION__;
07491 f.data.ptr = (void *) data;
07492
07493 if ((res = queue_signalling(i, &f)) <= 0) {
07494 return res;
07495 }
07496
07497 return iax2_send(i, &f, ts, seqno, now, transfer, final);
07498 }
07499
07500 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07501 {
07502 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07503 }
07504
07505 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07506 {
07507 int res;
07508 ast_mutex_lock(&iaxsl[callno]);
07509 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07510 ast_mutex_unlock(&iaxsl[callno]);
07511 return res;
07512 }
07513
07514
07515
07516
07517
07518
07519 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)
07520 {
07521 int call_num = i->callno;
07522
07523 iax2_predestroy(i->callno);
07524 if (!iaxs[call_num])
07525 return -1;
07526 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07527 }
07528
07529 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)
07530 {
07531 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07532 }
07533
07534 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07535 {
07536 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07537 }
07538
07539 static int apply_context(struct iax2_context *con, const char *context)
07540 {
07541 while(con) {
07542 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07543 return -1;
07544 con = con->next;
07545 }
07546 return 0;
07547 }
07548
07549
07550 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07551 {
07552
07553 int res = -1;
07554 int version = 2;
07555 struct iax2_user *user = NULL, *best = NULL;
07556 int bestscore = 0;
07557 int gotcapability = 0;
07558 struct ast_variable *v = NULL, *tmpvar = NULL;
07559 struct ao2_iterator i;
07560 struct ast_sockaddr addr;
07561
07562 if (!iaxs[callno])
07563 return res;
07564 if (ies->called_number)
07565 ast_string_field_set(iaxs[callno], exten, ies->called_number);
07566 if (ies->calling_number) {
07567 if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
07568 ast_shrink_phone_number(ies->calling_number);
07569 }
07570 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07571 }
07572 if (ies->calling_name)
07573 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07574 if (ies->calling_ani)
07575 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07576 if (ies->dnid)
07577 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07578 if (ies->rdnis)
07579 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07580 if (ies->called_context)
07581 ast_string_field_set(iaxs[callno], context, ies->called_context);
07582 if (ies->language)
07583 ast_string_field_set(iaxs[callno], language, ies->language);
07584 if (ies->username)
07585 ast_string_field_set(iaxs[callno], username, ies->username);
07586 if (ies->calling_ton > -1)
07587 iaxs[callno]->calling_ton = ies->calling_ton;
07588 if (ies->calling_tns > -1)
07589 iaxs[callno]->calling_tns = ies->calling_tns;
07590 if (ies->calling_pres > -1)
07591 iaxs[callno]->calling_pres = ies->calling_pres;
07592 if (ies->format)
07593 iaxs[callno]->peerformat = ies->format;
07594 if (ies->adsicpe)
07595 iaxs[callno]->peeradsicpe = ies->adsicpe;
07596 if (ies->capability) {
07597 gotcapability = 1;
07598 iaxs[callno]->peercapability = ies->capability;
07599 }
07600 if (ies->version)
07601 version = ies->version;
07602
07603
07604 if (ies->codec_prefs) {
07605 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07606 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07607 }
07608
07609 if (!gotcapability)
07610 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07611 if (version > IAX_PROTO_VERSION) {
07612 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
07613 ast_inet_ntoa(sin->sin_addr), version);
07614 return res;
07615 }
07616
07617 ast_sockaddr_from_sin(&addr, sin);
07618 i = ao2_iterator_init(users, 0);
07619 while ((user = ao2_iterator_next(&i))) {
07620 if ((ast_strlen_zero(iaxs[callno]->username) ||
07621 !strcmp(iaxs[callno]->username, user->name))
07622 && ast_apply_ha(user->ha, &addr)
07623 && (ast_strlen_zero(iaxs[callno]->context) ||
07624 apply_context(user->contexts, iaxs[callno]->context))) {
07625 if (!ast_strlen_zero(iaxs[callno]->username)) {
07626
07627 if (best)
07628 user_unref(best);
07629 best = user;
07630 break;
07631 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07632
07633 if (user->ha) {
07634
07635 if (bestscore < 4) {
07636 bestscore = 4;
07637 if (best)
07638 user_unref(best);
07639 best = user;
07640 continue;
07641 }
07642 } else {
07643
07644 if (bestscore < 3) {
07645 bestscore = 3;
07646 if (best)
07647 user_unref(best);
07648 best = user;
07649 continue;
07650 }
07651 }
07652 } else {
07653 if (user->ha) {
07654
07655 if (bestscore < 2) {
07656 bestscore = 2;
07657 if (best)
07658 user_unref(best);
07659 best = user;
07660 continue;
07661 }
07662 } else {
07663
07664 if (bestscore < 1) {
07665 bestscore = 1;
07666 if (best)
07667 user_unref(best);
07668 best = user;
07669 continue;
07670 }
07671 }
07672 }
07673 }
07674 user_unref(user);
07675 }
07676 ao2_iterator_destroy(&i);
07677 user = best;
07678 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07679 user = realtime_user(iaxs[callno]->username, sin);
07680 if (user && !ast_strlen_zero(iaxs[callno]->context) &&
07681 !apply_context(user->contexts, iaxs[callno]->context)) {
07682 user = user_unref(user);
07683 }
07684 }
07685 if (user) {
07686
07687
07688 for (v = user->vars ; v ; v = v->next) {
07689 if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07690 tmpvar->next = iaxs[callno]->vars;
07691 iaxs[callno]->vars = tmpvar;
07692 }
07693 }
07694
07695 if (user->maxauthreq > 0)
07696 ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
07697 iaxs[callno]->prefs = user->prefs;
07698 ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07699 iaxs[callno]->encmethods = user->encmethods;
07700
07701 if (ast_strlen_zero(iaxs[callno]->username))
07702 ast_string_field_set(iaxs[callno], username, user->name);
07703
07704 ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
07705 iaxs[callno]->capability = user->capability;
07706
07707 if (ast_strlen_zero(iaxs[callno]->context)) {
07708 if (user->contexts)
07709 ast_string_field_set(iaxs[callno], context, user->contexts->context);
07710 else
07711 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07712 }
07713
07714 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07715
07716 iaxs[callno]->authmethods = user->authmethods;
07717 iaxs[callno]->adsi = user->adsi;
07718
07719 if (ast_test_flag64(user, IAX_HASCALLERID)) {
07720 iaxs[callno]->calling_tns = 0;
07721 iaxs[callno]->calling_ton = 0;
07722 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07723 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07724 ast_string_field_set(iaxs[callno], ani, user->cid_num);
07725 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07726 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07727 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07728 }
07729 if (!ast_strlen_zero(user->accountcode))
07730 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07731 if (!ast_strlen_zero(user->mohinterpret))
07732 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07733 if (!ast_strlen_zero(user->mohsuggest))
07734 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07735 if (!ast_strlen_zero(user->parkinglot))
07736 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07737 if (user->amaflags)
07738 iaxs[callno]->amaflags = user->amaflags;
07739 if (!ast_strlen_zero(user->language))
07740 ast_string_field_set(iaxs[callno], language, user->language);
07741 ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
07742
07743 if (!ast_strlen_zero(user->dbsecret)) {
07744 char *family, *key=NULL;
07745 char buf[80];
07746 family = ast_strdupa(user->dbsecret);
07747 key = strchr(family, '/');
07748 if (key) {
07749 *key = '\0';
07750 key++;
07751 }
07752 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07753 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07754 else
07755 ast_string_field_set(iaxs[callno], secret, buf);
07756 } else
07757 ast_string_field_set(iaxs[callno], secret, user->secret);
07758 res = 0;
07759 user = user_unref(user);
07760 } else {
07761
07762
07763
07764
07765 iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07766 ast_string_field_set(iaxs[callno], secret, "badsecret");
07767 iaxs[callno]->authrej = 1;
07768 if (!ast_strlen_zero(iaxs[callno]->username)) {
07769
07770 res = 0;
07771 }
07772 }
07773 ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07774 return res;
07775 }
07776
07777 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07778 {
07779 struct ast_iax2_full_hdr fh;
07780 fh.scallno = htons(src | IAX_FLAG_FULL);
07781 fh.dcallno = htons(dst);
07782 fh.ts = 0;
07783 fh.oseqno = 0;
07784 fh.iseqno = 0;
07785 fh.type = AST_FRAME_IAX;
07786 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07787 iax_outputframe(NULL, &fh, 0, sin, 0);
07788 #if 0
07789 if (option_debug)
07790 #endif
07791 ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07792 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07793 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07794 }
07795
07796 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07797 {
07798
07799 p->encmethods &= enc;
07800 if (p->encmethods) {
07801 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){
07802 p->keyrotateid = -2;
07803 }
07804 if (p->encmethods & IAX_ENCRYPT_AES128)
07805 p->encmethods = IAX_ENCRYPT_AES128;
07806 else
07807 p->encmethods = 0;
07808 }
07809 }
07810
07811
07812
07813
07814
07815
07816
07817 static int authenticate_request(int call_num)
07818 {
07819 struct iax_ie_data ied;
07820 int res = -1, authreq_restrict = 0;
07821 char challenge[10];
07822 struct chan_iax2_pvt *p = iaxs[call_num];
07823
07824 memset(&ied, 0, sizeof(ied));
07825
07826
07827 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07828 struct iax2_user *user, tmp_user = {
07829 .name = p->username,
07830 };
07831
07832 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07833 if (user) {
07834 if (user->curauthreq == user->maxauthreq)
07835 authreq_restrict = 1;
07836 else
07837 user->curauthreq++;
07838 user = user_unref(user);
07839 }
07840 }
07841
07842
07843 if (authreq_restrict) {
07844 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
07845 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
07846 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
07847 return 0;
07848 }
07849
07850 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
07851 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
07852 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
07853 ast_string_field_set(p, challenge, challenge);
07854
07855 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
07856 }
07857 if (p->encmethods)
07858 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
07859
07860 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
07861
07862 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
07863
07864 if (p->encmethods)
07865 ast_set_flag64(p, IAX_ENCRYPTED);
07866
07867 return res;
07868 }
07869
07870 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
07871 {
07872 char requeststr[256];
07873 char md5secret[256] = "";
07874 char secret[256] = "";
07875 char rsasecret[256] = "";
07876 int res = -1;
07877 int x;
07878 struct iax2_user *user, tmp_user = {
07879 .name = p->username,
07880 };
07881
07882 if (p->authrej) {
07883 return res;
07884 }
07885 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07886 if (user) {
07887 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07888 ast_atomic_fetchadd_int(&user->curauthreq, -1);
07889 ast_clear_flag64(p, IAX_MAXAUTHREQ);
07890 }
07891 ast_string_field_set(p, host, user->name);
07892 user = user_unref(user);
07893 }
07894 if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
07895 ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
07896 return res;
07897 }
07898 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
07899 return res;
07900 if (ies->password)
07901 ast_copy_string(secret, ies->password, sizeof(secret));
07902 if (ies->md5_result)
07903 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07904 if (ies->rsa_result)
07905 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07906 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
07907 struct ast_key *key;
07908 char *keyn;
07909 char tmpkey[256];
07910 char *stringp=NULL;
07911 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
07912 stringp=tmpkey;
07913 keyn = strsep(&stringp, ":");
07914 while(keyn) {
07915 key = ast_key_get(keyn, AST_KEY_PUBLIC);
07916 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
07917 res = 0;
07918 break;
07919 } else if (!key)
07920 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
07921 keyn = strsep(&stringp, ":");
07922 }
07923 } else if (p->authmethods & IAX_AUTH_MD5) {
07924 struct MD5Context md5;
07925 unsigned char digest[16];
07926 char *tmppw, *stringp;
07927
07928 tmppw = ast_strdupa(p->secret);
07929 stringp = tmppw;
07930 while((tmppw = strsep(&stringp, ";"))) {
07931 MD5Init(&md5);
07932 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
07933 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07934 MD5Final(digest, &md5);
07935
07936 for (x=0;x<16;x++)
07937 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
07938 if (!strcasecmp(requeststr, md5secret)) {
07939 res = 0;
07940 break;
07941 }
07942 }
07943 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
07944 if (!strcmp(secret, p->secret))
07945 res = 0;
07946 }
07947 return res;
07948 }
07949
07950
07951 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07952 {
07953 char requeststr[256] = "";
07954 char peer[256] = "";
07955 char md5secret[256] = "";
07956 char rsasecret[256] = "";
07957 char secret[256] = "";
07958 struct iax2_peer *p = NULL;
07959 struct ast_key *key;
07960 char *keyn;
07961 int x;
07962 int expire = 0;
07963 int res = -1;
07964 struct ast_sockaddr addr;
07965
07966 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07967
07968 if (ies->username)
07969 ast_copy_string(peer, ies->username, sizeof(peer));
07970 if (ies->password)
07971 ast_copy_string(secret, ies->password, sizeof(secret));
07972 if (ies->md5_result)
07973 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07974 if (ies->rsa_result)
07975 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07976 if (ies->refresh)
07977 expire = ies->refresh;
07978
07979 if (ast_strlen_zero(peer)) {
07980 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
07981 return -1;
07982 }
07983
07984
07985 ast_mutex_unlock(&iaxsl[callno]);
07986 p = find_peer(peer, 1);
07987 ast_mutex_lock(&iaxsl[callno]);
07988 if (!p || !iaxs[callno]) {
07989 if (iaxs[callno]) {
07990 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
07991
07992 ast_string_field_set(iaxs[callno], secret, "badsecret");
07993
07994
07995
07996
07997
07998
07999
08000
08001
08002 if (ast_strlen_zero(iaxs[callno]->challenge) &&
08003 !(!ast_strlen_zero(secret) && plaintext)) {
08004
08005 res = 0;
08006 }
08007 }
08008 if (authdebug && !p)
08009 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08010 goto return_unref;
08011 }
08012
08013 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
08014 if (authdebug)
08015 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08016 goto return_unref;
08017 }
08018
08019 ast_sockaddr_from_sin(&addr, sin);
08020 if (!ast_apply_ha(p->ha, &addr)) {
08021 if (authdebug)
08022 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08023 goto return_unref;
08024 }
08025 ast_string_field_set(iaxs[callno], secret, p->secret);
08026 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
08027
08028 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08029 if (!ast_strlen_zero(p->inkeys)) {
08030 char tmpkeys[256];
08031 char *stringp=NULL;
08032 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
08033 stringp=tmpkeys;
08034 keyn = strsep(&stringp, ":");
08035 while(keyn) {
08036 key = ast_key_get(keyn, AST_KEY_PUBLIC);
08037 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
08038 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08039 break;
08040 } else if (!key)
08041 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
08042 keyn = strsep(&stringp, ":");
08043 }
08044 if (!keyn) {
08045 if (authdebug)
08046 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
08047 goto return_unref;
08048 }
08049 } else {
08050 if (authdebug)
08051 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
08052 goto return_unref;
08053 }
08054 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08055 struct MD5Context md5;
08056 unsigned char digest[16];
08057 char *tmppw, *stringp;
08058
08059 tmppw = ast_strdupa(p->secret);
08060 stringp = tmppw;
08061 while((tmppw = strsep(&stringp, ";"))) {
08062 MD5Init(&md5);
08063 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
08064 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08065 MD5Final(digest, &md5);
08066 for (x=0;x<16;x++)
08067 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
08068 if (!strcasecmp(requeststr, md5secret))
08069 break;
08070 }
08071 if (tmppw) {
08072 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08073 } else {
08074 if (authdebug)
08075 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
08076 goto return_unref;
08077 }
08078 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
08079
08080 if (strcmp(secret, p->secret)) {
08081 if (authdebug)
08082 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08083 goto return_unref;
08084 } else
08085 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08086 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
08087
08088 goto return_unref;
08089 }
08090 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08091
08092
08093 res = 0;
08094
08095 return_unref:
08096 if (iaxs[callno]) {
08097 ast_string_field_set(iaxs[callno], peer, peer);
08098
08099
08100 if (expire && (expire < iaxs[callno]->expiry)) {
08101 iaxs[callno]->expiry = expire;
08102 }
08103 }
08104
08105 if (p) {
08106 peer_unref(p);
08107 }
08108 return res;
08109 }
08110
08111 static int authenticate(const char *challenge, const char *secret, const char *keyn, int authmethods, struct iax_ie_data *ied, struct sockaddr_in *sin, struct chan_iax2_pvt *pvt)
08112 {
08113 int res = -1;
08114 int x;
08115 if (!ast_strlen_zero(keyn)) {
08116 if (!(authmethods & IAX_AUTH_RSA)) {
08117 if (ast_strlen_zero(secret))
08118 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));
08119 } else if (ast_strlen_zero(challenge)) {
08120 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
08121 } else {
08122 char sig[256];
08123 struct ast_key *key;
08124 key = ast_key_get(keyn, AST_KEY_PRIVATE);
08125 if (!key) {
08126 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
08127 } else {
08128 if (ast_sign(key, (char*)challenge, sig)) {
08129 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
08130 res = -1;
08131 } else {
08132 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
08133 res = 0;
08134 }
08135 }
08136 }
08137 }
08138
08139 if (res && !ast_strlen_zero(secret)) {
08140 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
08141 struct MD5Context md5;
08142 unsigned char digest[16];
08143 char digres[128];
08144 MD5Init(&md5);
08145 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
08146 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
08147 MD5Final(digest, &md5);
08148
08149 for (x=0;x<16;x++)
08150 sprintf(digres + (x << 1), "%2.2x", digest[x]);
08151 if (pvt) {
08152 build_encryption_keys(digest, pvt);
08153 }
08154 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
08155 res = 0;
08156 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
08157 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
08158 res = 0;
08159 } else
08160 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
08161 }
08162 return res;
08163 }
08164
08165
08166
08167
08168
08169 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
08170 {
08171 struct iax2_peer *peer = NULL;
08172
08173 int res = -1;
08174 int authmethods = 0;
08175 struct iax_ie_data ied;
08176 uint16_t callno = p->callno;
08177
08178 memset(&ied, 0, sizeof(ied));
08179
08180 if (ies->username)
08181 ast_string_field_set(p, username, ies->username);
08182 if (ies->challenge)
08183 ast_string_field_set(p, challenge, ies->challenge);
08184 if (ies->authmethods)
08185 authmethods = ies->authmethods;
08186 if (authmethods & IAX_AUTH_MD5)
08187 merge_encryption(p, ies->encmethods);
08188 else
08189 p->encmethods = 0;
08190
08191
08192 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
08193
08194 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
08195 } else {
08196 struct ao2_iterator i = ao2_iterator_init(peers, 0);
08197 while ((peer = ao2_iterator_next(&i))) {
08198 struct sockaddr_in peer_addr;
08199
08200 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
08201
08202 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
08203
08204 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
08205
08206 && (!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)))
08207
08208 ) {
08209 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
08210 if (!res) {
08211 peer_unref(peer);
08212 break;
08213 }
08214 }
08215 peer_unref(peer);
08216 }
08217 ao2_iterator_destroy(&i);
08218 if (!peer) {
08219
08220
08221 const char *peer_name = ast_strdupa(p->peer);
08222 ast_mutex_unlock(&iaxsl[callno]);
08223 if ((peer = realtime_peer(peer_name, NULL))) {
08224 ast_mutex_lock(&iaxsl[callno]);
08225 if (!(p = iaxs[callno])) {
08226 peer_unref(peer);
08227 return -1;
08228 }
08229 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
08230 peer_unref(peer);
08231 }
08232 if (!peer) {
08233 ast_mutex_lock(&iaxsl[callno]);
08234 if (!(p = iaxs[callno]))
08235 return -1;
08236 }
08237 }
08238 }
08239
08240 if (ies->encmethods) {
08241 ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
08242 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
08243 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
08244 return -1;
08245 }
08246 if (!res) {
08247 struct ast_datastore *variablestore;
08248 struct ast_variable *var, *prev = NULL;
08249 AST_LIST_HEAD(, ast_var_t) *varlist;
08250 varlist = ast_calloc(1, sizeof(*varlist));
08251 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
08252 if (variablestore && varlist && p->owner) {
08253 variablestore->data = varlist;
08254 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
08255 AST_LIST_HEAD_INIT(varlist);
08256 for (var = ies->vars; var; var = var->next) {
08257 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
08258 if (prev)
08259 ast_free(prev);
08260 prev = var;
08261 if (!newvar) {
08262
08263 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08264 } else {
08265 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
08266 }
08267 }
08268 if (prev)
08269 ast_free(prev);
08270 ies->vars = NULL;
08271 ast_channel_datastore_add(p->owner, variablestore);
08272 } else {
08273 if (p->owner)
08274 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08275 if (variablestore)
08276 ast_datastore_free(variablestore);
08277 if (varlist)
08278 ast_free(varlist);
08279 }
08280 }
08281
08282 if (!res)
08283 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
08284 return res;
08285 }
08286
08287 static int iax2_do_register(struct iax2_registry *reg);
08288
08289 static void __iax2_do_register_s(const void *data)
08290 {
08291 struct iax2_registry *reg = (struct iax2_registry *)data;
08292 reg->expire = -1;
08293 iax2_do_register(reg);
08294 }
08295
08296 static int iax2_do_register_s(const void *data)
08297 {
08298 #ifdef SCHED_MULTITHREADED
08299 if (schedule_action(__iax2_do_register_s, data))
08300 #endif
08301 __iax2_do_register_s(data);
08302 return 0;
08303 }
08304
08305 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08306 {
08307 int newcall = 0;
08308 char newip[256];
08309 struct iax_ie_data ied;
08310 struct sockaddr_in new = { 0, };
08311
08312 memset(&ied, 0, sizeof(ied));
08313 if (ies->apparent_addr)
08314 memmove(&new, ies->apparent_addr, sizeof(new));
08315 if (ies->callno)
08316 newcall = ies->callno;
08317 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
08318 ast_log(LOG_WARNING, "Invalid transfer request\n");
08319 return -1;
08320 }
08321 pvt->transfercallno = newcall;
08322 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
08323 inet_aton(newip, &pvt->transfer.sin_addr);
08324 pvt->transfer.sin_family = AF_INET;
08325 pvt->transferid = ies->transferid;
08326
08327
08328 if (pvt->transferring == TRANSFER_NONE) {
08329 store_by_transfercallno(pvt);
08330 }
08331 pvt->transferring = TRANSFER_BEGIN;
08332
08333 if (ies->transferid)
08334 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08335 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08336 return 0;
08337 }
08338
08339 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08340 {
08341 char exten[256] = "";
08342 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08343 struct iax2_dpcache *dp = NULL;
08344
08345 if (ies->called_number)
08346 ast_copy_string(exten, ies->called_number, sizeof(exten));
08347
08348 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08349 status = CACHE_FLAG_EXISTS;
08350 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08351 status = CACHE_FLAG_CANEXIST;
08352 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08353 status = CACHE_FLAG_NONEXISTENT;
08354
08355 if (ies->refresh)
08356 expiry = ies->refresh;
08357 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08358 matchmore = CACHE_FLAG_MATCHMORE;
08359
08360 AST_LIST_LOCK(&dpcache);
08361 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08362 if (strcmp(dp->exten, exten))
08363 continue;
08364 AST_LIST_REMOVE_CURRENT(peer_list);
08365 dp->callno = 0;
08366 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08367 if (dp->flags & CACHE_FLAG_PENDING) {
08368 dp->flags &= ~CACHE_FLAG_PENDING;
08369 dp->flags |= status;
08370 dp->flags |= matchmore;
08371 }
08372
08373 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08374 if (dp->waiters[x] > -1) {
08375 if (write(dp->waiters[x], "asdf", 4) < 0) {
08376 }
08377 }
08378 }
08379 }
08380 AST_LIST_TRAVERSE_SAFE_END;
08381 AST_LIST_UNLOCK(&dpcache);
08382
08383 return 0;
08384 }
08385
08386 static int complete_transfer(int callno, struct iax_ies *ies)
08387 {
08388 int peercallno = 0;
08389 struct chan_iax2_pvt *pvt = iaxs[callno];
08390 struct iax_frame *cur;
08391 jb_frame frame;
08392
08393 if (ies->callno)
08394 peercallno = ies->callno;
08395
08396 if (peercallno < 1) {
08397 ast_log(LOG_WARNING, "Invalid transfer request\n");
08398 return -1;
08399 }
08400 remove_by_transfercallno(pvt);
08401
08402
08403
08404 peercnt_remove_by_addr(&pvt->addr);
08405 peercnt_add(&pvt->transfer);
08406
08407 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08408 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08409
08410 pvt->oseqno = 0;
08411 pvt->rseqno = 0;
08412 pvt->iseqno = 0;
08413 pvt->aseqno = 0;
08414
08415 if (pvt->peercallno) {
08416 remove_by_peercallno(pvt);
08417 }
08418 pvt->peercallno = peercallno;
08419
08420 store_by_peercallno(pvt);
08421 pvt->transferring = TRANSFER_NONE;
08422 pvt->svoiceformat = -1;
08423 pvt->voiceformat = 0;
08424 pvt->svideoformat = -1;
08425 pvt->videoformat = 0;
08426 pvt->transfercallno = 0;
08427 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08428 memset(&pvt->offset, 0, sizeof(pvt->offset));
08429
08430 while(jb_getall(pvt->jb,&frame) == JB_OK)
08431 iax2_frame_free(frame.data);
08432 jb_reset(pvt->jb);
08433 pvt->lag = 0;
08434 pvt->last = 0;
08435 pvt->lastsent = 0;
08436 pvt->nextpred = 0;
08437 pvt->pingtime = DEFAULT_RETRY_TIME;
08438 AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
08439
08440
08441
08442 cur->retries = -1;
08443 }
08444 return 0;
08445 }
08446
08447
08448 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08449 {
08450 struct iax2_registry *reg;
08451
08452 char peer[256] = "";
08453 char msgstatus[60];
08454 int refresh = 60;
08455 char ourip[256] = "<Unspecified>";
08456 struct sockaddr_in oldus;
08457 struct sockaddr_in us;
08458 int oldmsgs;
08459 struct sockaddr_in reg_addr;
08460
08461 memset(&us, 0, sizeof(us));
08462 if (ies->apparent_addr) {
08463 memmove(&us, ies->apparent_addr, sizeof(us));
08464 }
08465 if (ies->username) {
08466 ast_copy_string(peer, ies->username, sizeof(peer));
08467 }
08468 if (ies->refresh) {
08469 refresh = ies->refresh;
08470 }
08471 if (ies->calling_number) {
08472
08473 }
08474 reg = iaxs[callno]->reg;
08475 if (!reg) {
08476 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08477 return -1;
08478 }
08479 memcpy(&oldus, ®->us, sizeof(oldus));
08480 oldmsgs = reg->messages;
08481 ast_sockaddr_to_sin(®->addr, ®_addr);
08482 if (inaddrcmp(®_addr, sin)) {
08483 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08484 return -1;
08485 }
08486 memcpy(®->us, &us, sizeof(reg->us));
08487 if (ies->msgcount >= 0) {
08488 reg->messages = ies->msgcount & 0xffff;
08489 }
08490
08491
08492
08493 reg->refresh = refresh;
08494 reg->expire = iax2_sched_replace(reg->expire, sched,
08495 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08496 if (inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) {
08497 if (reg->messages > 255) {
08498 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08499 } else if (reg->messages > 1) {
08500 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
08501 } else if (reg->messages > 0) {
08502 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
08503 } else {
08504 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
08505 }
08506 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08507 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08508 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08509 }
08510 reg->regstate = REG_STATE_REGISTERED;
08511 return 0;
08512 }
08513
08514 static int iax2_append_register(const char *hostname, const char *username,
08515 const char *secret, const char *porta)
08516 {
08517 struct iax2_registry *reg;
08518
08519 if (!(reg = ast_calloc(1, sizeof(*reg))))
08520 return -1;
08521
08522 reg->addr.ss.ss_family = AF_INET;
08523 if (ast_dnsmgr_lookup(hostname, ®->addr, ®->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08524 ast_free(reg);
08525 return -1;
08526 }
08527
08528 ast_copy_string(reg->username, username, sizeof(reg->username));
08529
08530 if (secret)
08531 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08532
08533 reg->expire = -1;
08534 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08535 ast_sockaddr_set_port(®->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
08536
08537 AST_LIST_LOCK(®istrations);
08538 AST_LIST_INSERT_HEAD(®istrations, reg, entry);
08539 AST_LIST_UNLOCK(®istrations);
08540
08541 return 0;
08542 }
08543
08544 static int iax2_register(const char *value, int lineno)
08545 {
08546 char copy[256];
08547 char *username, *hostname, *secret;
08548 char *porta;
08549 char *stringp=NULL;
08550
08551 if (!value)
08552 return -1;
08553
08554 ast_copy_string(copy, value, sizeof(copy));
08555 stringp = copy;
08556 username = strsep(&stringp, "@");
08557 hostname = strsep(&stringp, "@");
08558
08559 if (!hostname) {
08560 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08561 return -1;
08562 }
08563
08564 stringp = username;
08565 username = strsep(&stringp, ":");
08566 secret = strsep(&stringp, ":");
08567 stringp = hostname;
08568 hostname = strsep(&stringp, ":");
08569 porta = strsep(&stringp, ":");
08570
08571 if (porta && !atoi(porta)) {
08572 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08573 return -1;
08574 }
08575
08576 return iax2_append_register(hostname, username, secret, porta);
08577 }
08578
08579
08580 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08581 {
08582 char multi[256];
08583 char *stringp, *ext;
08584 if (!ast_strlen_zero(regcontext)) {
08585 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08586 stringp = multi;
08587 while((ext = strsep(&stringp, "&"))) {
08588 if (onoff) {
08589 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08590 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08591 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08592 } else
08593 ast_context_remove_extension(regcontext, ext, 1, NULL);
08594 }
08595 }
08596 }
08597 static void prune_peers(void);
08598
08599 static void unlink_peer(struct iax2_peer *peer)
08600 {
08601 if (peer->expire > -1) {
08602 if (!ast_sched_thread_del(sched, peer->expire)) {
08603 peer->expire = -1;
08604 peer_unref(peer);
08605 }
08606 }
08607
08608 if (peer->pokeexpire > -1) {
08609 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
08610 peer->pokeexpire = -1;
08611 peer_unref(peer);
08612 }
08613 }
08614
08615 ao2_unlink(peers, peer);
08616 }
08617
08618 static void __expire_registry(const void *data)
08619 {
08620 struct iax2_peer *peer = (struct iax2_peer *) data;
08621
08622 if (!peer)
08623 return;
08624 if (peer->expire == -1) {
08625
08626 return;
08627 }
08628
08629 peer->expire = -1;
08630
08631 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08632 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08633 realtime_update_peer(peer->name, &peer->addr, 0);
08634 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08635
08636 peercnt_modify(0, 0, &peer->addr);
08637
08638 memset(&peer->addr, 0, sizeof(peer->addr));
08639
08640 peer->expiry = min_reg_expire;
08641 if (!ast_test_flag64(peer, IAX_TEMPONLY))
08642 ast_db_del("IAX/Registry", peer->name);
08643 register_peer_exten(peer, 0);
08644 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
08645 if (iax2_regfunk)
08646 iax2_regfunk(peer->name, 0);
08647
08648 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
08649 unlink_peer(peer);
08650
08651 peer_unref(peer);
08652 }
08653
08654 static int expire_registry(const void *data)
08655 {
08656 #ifdef SCHED_MULTITHREADED
08657 if (schedule_action(__expire_registry, data))
08658 #endif
08659 __expire_registry(data);
08660 return 0;
08661 }
08662
08663 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
08664
08665 static void reg_source_db(struct iax2_peer *p)
08666 {
08667 char data[80];
08668 char *expiry;
08669
08670 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
08671 return;
08672 }
08673
08674 expiry = strrchr(data, ':');
08675 if (!expiry) {
08676 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
08677 return;
08678 }
08679 *expiry++ = '\0';
08680
08681 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
08682 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
08683 return;
08684 }
08685
08686 p->expiry = atoi(expiry);
08687
08688 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
08689 ast_sockaddr_stringify(&p->addr), p->expiry);
08690
08691 iax2_poke_peer(p, 0);
08692 if (p->expire > -1) {
08693 if (!ast_sched_thread_del(sched, p->expire)) {
08694 p->expire = -1;
08695 peer_unref(p);
08696 }
08697 }
08698
08699 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08700
08701 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08702 if (p->expire == -1) {
08703 peer_unref(p);
08704 }
08705
08706 if (iax2_regfunk) {
08707 iax2_regfunk(p->name, 1);
08708 }
08709
08710 register_peer_exten(p, 1);
08711 }
08712
08713
08714
08715
08716
08717
08718
08719 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08720 {
08721
08722 struct iax_ie_data ied = {
08723 .pos = 0,
08724 };
08725 struct iax2_peer *p;
08726 int msgcount;
08727 char data[80];
08728 int version;
08729 const char *peer_name;
08730 int res = -1;
08731 struct ast_sockaddr sockaddr;
08732
08733 ast_sockaddr_from_sin(&sockaddr, sin);
08734
08735 peer_name = ast_strdupa(iaxs[callno]->peer);
08736
08737
08738 ast_mutex_unlock(&iaxsl[callno]);
08739 if (!(p = find_peer(peer_name, 1))) {
08740 ast_mutex_lock(&iaxsl[callno]);
08741 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08742 return -1;
08743 }
08744 ast_mutex_lock(&iaxsl[callno]);
08745 if (!iaxs[callno])
08746 goto return_unref;
08747
08748 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08749 if (sin->sin_addr.s_addr) {
08750 time_t nowtime;
08751 time(&nowtime);
08752 realtime_update_peer(peer_name, &sockaddr, nowtime);
08753 } else {
08754 realtime_update_peer(peer_name, &sockaddr, 0);
08755 }
08756 }
08757
08758 if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
08759 if (iax2_regfunk) {
08760 iax2_regfunk(p->name, 1);
08761 }
08762
08763
08764 peercnt_modify(0, 0, &p->addr);
08765
08766
08767 ast_sockaddr_from_sin(&p->addr, sin);
08768
08769 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08770 if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08771 ast_db_put("IAX/Registry", p->name, data);
08772 ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08773 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08774 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
08775 register_peer_exten(p, 1);
08776 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08777 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
08778 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08779 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08780 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08781 register_peer_exten(p, 0);
08782 ast_db_del("IAX/Registry", p->name);
08783 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name);
08784 }
08785
08786
08787 iax2_poke_peer(p, callno);
08788 }
08789
08790
08791 if (p->maxcallno) {
08792 peercnt_modify(1, p->maxcallno, &p->addr);
08793 }
08794
08795
08796 if (!iaxs[callno]) {
08797 res = -1;
08798 goto return_unref;
08799 }
08800
08801
08802 p->sockfd = fd;
08803
08804 if (p->expire > -1) {
08805 if (!ast_sched_thread_del(sched, p->expire)) {
08806 p->expire = -1;
08807 peer_unref(p);
08808 }
08809 }
08810
08811 if (!refresh)
08812 refresh = min_reg_expire;
08813 if (refresh > max_reg_expire) {
08814 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08815 p->name, max_reg_expire, refresh);
08816 p->expiry = max_reg_expire;
08817 } else if (refresh < min_reg_expire) {
08818 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08819 p->name, min_reg_expire, refresh);
08820 p->expiry = min_reg_expire;
08821 } else {
08822 p->expiry = refresh;
08823 }
08824 if (p->expiry && sin->sin_addr.s_addr) {
08825 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08826 if (p->expire == -1)
08827 peer_unref(p);
08828 }
08829 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
08830 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
08831 if (sin->sin_addr.s_addr) {
08832 struct sockaddr_in peer_addr;
08833
08834 ast_sockaddr_to_sin(&p->addr, &peer_addr);
08835
08836 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
08837 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
08838 if (!ast_strlen_zero(p->mailbox)) {
08839 struct ast_event *event;
08840 int new, old;
08841 char *mailbox, *context;
08842
08843 context = mailbox = ast_strdupa(p->mailbox);
08844 strsep(&context, "@");
08845 if (ast_strlen_zero(context))
08846 context = "default";
08847
08848 event = ast_event_get_cached(AST_EVENT_MWI,
08849 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
08850 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
08851 AST_EVENT_IE_END);
08852 if (event) {
08853 new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
08854 old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
08855 ast_event_destroy(event);
08856 } else {
08857 ast_app_inboxcount(p->mailbox, &new, &old);
08858 }
08859
08860 if (new > 255) {
08861 new = 255;
08862 }
08863 if (old > 255) {
08864 old = 255;
08865 }
08866 msgcount = (old << 8) | new;
08867
08868 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
08869 }
08870 if (ast_test_flag64(p, IAX_HASCALLERID)) {
08871 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
08872 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
08873 }
08874 }
08875 version = iax_check_version(devtype);
08876 if (version)
08877 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
08878
08879 res = 0;
08880
08881 return_unref:
08882 peer_unref(p);
08883
08884 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
08885 }
08886
08887 static int registry_authrequest(int callno)
08888 {
08889 struct iax_ie_data ied;
08890 struct iax2_peer *p;
08891 char challenge[10];
08892 const char *peer_name;
08893 int sentauthmethod;
08894
08895 peer_name = ast_strdupa(iaxs[callno]->peer);
08896
08897
08898 ast_mutex_unlock(&iaxsl[callno]);
08899 if ((p = find_peer(peer_name, 1))) {
08900 last_authmethod = p->authmethods;
08901 }
08902
08903 ast_mutex_lock(&iaxsl[callno]);
08904 if (!iaxs[callno])
08905 goto return_unref;
08906
08907 memset(&ied, 0, sizeof(ied));
08908
08909
08910
08911
08912
08913
08914 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
08915 if (!p) {
08916 iaxs[callno]->authmethods = sentauthmethod;
08917 }
08918 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
08919 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
08920
08921 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08922 ast_string_field_set(iaxs[callno], challenge, challenge);
08923 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
08924 }
08925 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
08926
08927 return_unref:
08928 if (p) {
08929 peer_unref(p);
08930 }
08931
08932 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
08933 }
08934
08935 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
08936 {
08937 struct iax2_registry *reg;
08938
08939 struct iax_ie_data ied;
08940 char peer[256] = "";
08941 char challenge[256] = "";
08942 int res;
08943 int authmethods = 0;
08944 if (ies->authmethods)
08945 authmethods = ies->authmethods;
08946 if (ies->username)
08947 ast_copy_string(peer, ies->username, sizeof(peer));
08948 if (ies->challenge)
08949 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
08950 memset(&ied, 0, sizeof(ied));
08951 reg = iaxs[callno]->reg;
08952 if (reg) {
08953 struct sockaddr_in reg_addr;
08954
08955 ast_sockaddr_to_sin(®->addr, ®_addr);
08956
08957 if (inaddrcmp(®_addr, sin)) {
08958 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08959 return -1;
08960 }
08961 if (ast_strlen_zero(reg->secret)) {
08962 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
08963 reg->regstate = REG_STATE_NOAUTH;
08964 return -1;
08965 }
08966 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08967 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08968 if (reg->secret[0] == '[') {
08969 char tmpkey[256];
08970 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
08971 tmpkey[strlen(tmpkey) - 1] = '\0';
08972 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
08973 } else
08974 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
08975 if (!res) {
08976 reg->regstate = REG_STATE_AUTHSENT;
08977 add_empty_calltoken_ie(iaxs[callno], &ied);
08978 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08979 } else
08980 return -1;
08981 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
08982 } else
08983 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
08984 return -1;
08985 }
08986
08987 static void stop_stuff(int callno)
08988 {
08989 iax2_destroy_helper(iaxs[callno]);
08990 }
08991
08992 static void __auth_reject(const void *nothing)
08993 {
08994
08995 int callno = (int)(long)(nothing);
08996 struct iax_ie_data ied;
08997 ast_mutex_lock(&iaxsl[callno]);
08998 if (iaxs[callno]) {
08999 memset(&ied, 0, sizeof(ied));
09000 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
09001 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
09002 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
09003 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
09004 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
09005 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
09006 }
09007 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
09008 }
09009 ast_mutex_unlock(&iaxsl[callno]);
09010 }
09011
09012 static int auth_reject(const void *data)
09013 {
09014 int callno = (int)(long)(data);
09015 ast_mutex_lock(&iaxsl[callno]);
09016 if (iaxs[callno])
09017 iaxs[callno]->authid = -1;
09018 ast_mutex_unlock(&iaxsl[callno]);
09019 #ifdef SCHED_MULTITHREADED
09020 if (schedule_action(__auth_reject, data))
09021 #endif
09022 __auth_reject(data);
09023 return 0;
09024 }
09025
09026 static int auth_fail(int callno, int failcode)
09027 {
09028
09029
09030 if (iaxs[callno]) {
09031 iaxs[callno]->authfail = failcode;
09032 if (delayreject) {
09033 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
09034 sched, 1000, auth_reject, (void *)(long)callno);
09035 } else
09036 auth_reject((void *)(long)callno);
09037 }
09038 return 0;
09039 }
09040
09041 static void __auto_hangup(const void *nothing)
09042 {
09043
09044 int callno = (int)(long)(nothing);
09045 struct iax_ie_data ied;
09046 ast_mutex_lock(&iaxsl[callno]);
09047 if (iaxs[callno]) {
09048 memset(&ied, 0, sizeof(ied));
09049 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
09050 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
09051 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
09052 }
09053 ast_mutex_unlock(&iaxsl[callno]);
09054 }
09055
09056 static int auto_hangup(const void *data)
09057 {
09058 int callno = (int)(long)(data);
09059 ast_mutex_lock(&iaxsl[callno]);
09060 if (iaxs[callno]) {
09061 iaxs[callno]->autoid = -1;
09062 }
09063 ast_mutex_unlock(&iaxsl[callno]);
09064 #ifdef SCHED_MULTITHREADED
09065 if (schedule_action(__auto_hangup, data))
09066 #endif
09067 __auto_hangup(data);
09068 return 0;
09069 }
09070
09071 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
09072 {
09073 struct iax_ie_data ied;
09074
09075 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
09076 sched, 30000, auto_hangup, (void *)(long)callno);
09077 memset(&ied, 0, sizeof(ied));
09078 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
09079 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
09080 dp->flags |= CACHE_FLAG_TRANSMITTED;
09081 }
09082
09083 static int iax2_vnak(int callno)
09084 {
09085 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
09086 }
09087
09088 static void vnak_retransmit(int callno, int last)
09089 {
09090 struct iax_frame *f;
09091
09092 AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
09093
09094 if (((unsigned char) (f->oseqno - last) < 128) &&
09095 (f->retries >= 0)) {
09096 send_packet(f);
09097 }
09098 }
09099 }
09100
09101 static void __iax2_poke_peer_s(const void *data)
09102 {
09103 struct iax2_peer *peer = (struct iax2_peer *)data;
09104 iax2_poke_peer(peer, 0);
09105 peer_unref(peer);
09106 }
09107
09108 static int iax2_poke_peer_s(const void *data)
09109 {
09110 struct iax2_peer *peer = (struct iax2_peer *)data;
09111 peer->pokeexpire = -1;
09112 #ifdef SCHED_MULTITHREADED
09113 if (schedule_action(__iax2_poke_peer_s, data))
09114 #endif
09115 __iax2_poke_peer_s(data);
09116 return 0;
09117 }
09118
09119 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
09120 {
09121 int res = 0;
09122 struct iax_frame *fr;
09123 struct ast_iax2_meta_hdr *meta;
09124 struct ast_iax2_meta_trunk_hdr *mth;
09125 int calls = 0;
09126
09127
09128 fr = (struct iax_frame *)tpeer->trunkdata;
09129
09130 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
09131 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
09132 if (tpeer->trunkdatalen) {
09133
09134 meta->zeros = 0;
09135 meta->metacmd = IAX_META_TRUNK;
09136 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
09137 meta->cmddata = IAX_META_TRUNK_MINI;
09138 else
09139 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
09140 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
09141
09142 fr->direction = DIRECTION_OUTGRESS;
09143 fr->retrans = -1;
09144 fr->transfer = 0;
09145
09146 fr->data = fr->afdata;
09147 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
09148 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
09149 calls = tpeer->calls;
09150 #if 0
09151 ast_debug(1, "Trunking %d call chunks in %d bytes to %s:%d, ts=%d\n", calls, fr->datalen, ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port), ntohl(mth->ts));
09152 #endif
09153
09154 tpeer->trunkdatalen = 0;
09155 tpeer->calls = 0;
09156 }
09157 if (res < 0)
09158 return res;
09159 return calls;
09160 }
09161
09162 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
09163 {
09164
09165 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
09166 return 1;
09167 return 0;
09168 }
09169
09170 static int timing_read(int *id, int fd, short events, void *cbdata)
09171 {
09172 int res, processed = 0, totalcalls = 0;
09173 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
09174 struct timeval now = ast_tvnow();
09175
09176 if (iaxtrunkdebug)
09177 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
09178
09179 if (timer) {
09180 ast_timer_ack(timer, 1);
09181 }
09182
09183
09184 AST_LIST_LOCK(&tpeers);
09185 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
09186 processed++;
09187 res = 0;
09188 ast_mutex_lock(&tpeer->lock);
09189
09190
09191 if (!drop && iax2_trunk_expired(tpeer, &now)) {
09192
09193
09194 AST_LIST_REMOVE_CURRENT(list);
09195 drop = tpeer;
09196 } else {
09197 res = send_trunk(tpeer, &now);
09198 trunk_timed++;
09199 if (iaxtrunkdebug)
09200 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);
09201 }
09202 totalcalls += res;
09203 res = 0;
09204 ast_mutex_unlock(&tpeer->lock);
09205 }
09206 AST_LIST_TRAVERSE_SAFE_END;
09207 AST_LIST_UNLOCK(&tpeers);
09208
09209 if (drop) {
09210 ast_mutex_lock(&drop->lock);
09211
09212
09213 ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
09214 if (drop->trunkdata) {
09215 ast_free(drop->trunkdata);
09216 drop->trunkdata = NULL;
09217 }
09218 ast_mutex_unlock(&drop->lock);
09219 ast_mutex_destroy(&drop->lock);
09220 ast_free(drop);
09221
09222 }
09223
09224 if (iaxtrunkdebug)
09225 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
09226 iaxtrunkdebug = 0;
09227
09228 return 1;
09229 }
09230
09231 struct dpreq_data {
09232 int callno;
09233 char context[AST_MAX_EXTENSION];
09234 char callednum[AST_MAX_EXTENSION];
09235 char *callerid;
09236 };
09237
09238 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
09239 {
09240 unsigned short dpstatus = 0;
09241 struct iax_ie_data ied1;
09242 int mm;
09243
09244 memset(&ied1, 0, sizeof(ied1));
09245 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
09246
09247 if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
09248 dpstatus = IAX_DPSTATUS_EXISTS;
09249 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
09250 dpstatus = IAX_DPSTATUS_CANEXIST;
09251 } else {
09252 dpstatus = IAX_DPSTATUS_NONEXISTENT;
09253 }
09254 if (ast_ignore_pattern(context, callednum))
09255 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
09256 if (mm)
09257 dpstatus |= IAX_DPSTATUS_MATCHMORE;
09258 if (!skiplock)
09259 ast_mutex_lock(&iaxsl[callno]);
09260 if (iaxs[callno]) {
09261 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
09262 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
09263 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
09264 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
09265 }
09266 if (!skiplock)
09267 ast_mutex_unlock(&iaxsl[callno]);
09268 }
09269
09270 static void *dp_lookup_thread(void *data)
09271 {
09272
09273 struct dpreq_data *dpr = data;
09274 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
09275 if (dpr->callerid)
09276 ast_free(dpr->callerid);
09277 ast_free(dpr);
09278 return NULL;
09279 }
09280
09281 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
09282 {
09283 pthread_t newthread;
09284 struct dpreq_data *dpr;
09285
09286 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
09287 return;
09288
09289 dpr->callno = callno;
09290 ast_copy_string(dpr->context, context, sizeof(dpr->context));
09291 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
09292 if (callerid)
09293 dpr->callerid = ast_strdup(callerid);
09294 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
09295 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
09296 }
09297 }
09298
09299 struct iax_dual {
09300 struct ast_channel *chan1;
09301 struct ast_channel *chan2;
09302 char *park_exten;
09303 char *park_context;
09304 };
09305
09306 static void *iax_park_thread(void *stuff)
09307 {
09308 struct iax_dual *d;
09309 int res;
09310 int ext = 0;
09311
09312 d = stuff;
09313
09314 ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
09315 d->chan2->name, d->chan1->name);
09316
09317 res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
09318 if (res) {
09319
09320 ast_hangup(d->chan1);
09321 } else {
09322 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
09323 }
09324 ast_hangup(d->chan2);
09325
09326 ast_free(d->park_exten);
09327 ast_free(d->park_context);
09328 ast_free(d);
09329 return NULL;
09330 }
09331
09332
09333 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
09334 {
09335 struct iax_dual *d;
09336 struct ast_channel *chan1m, *chan2m;
09337 pthread_t th;
09338
09339 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
09340 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "IAXPeer/%s", chan2->name);
09341 d = ast_calloc(1, sizeof(*d));
09342 if (!chan1m || !chan2m || !d) {
09343 if (chan1m) {
09344 ast_hangup(chan1m);
09345 }
09346 if (chan2m) {
09347 ast_hangup(chan2m);
09348 }
09349 ast_free(d);
09350 return -1;
09351 }
09352 d->park_exten = ast_strdup(park_exten);
09353 d->park_context = ast_strdup(park_context);
09354 if (!d->park_exten || !d->park_context) {
09355 ast_hangup(chan1m);
09356 ast_hangup(chan2m);
09357 ast_free(d->park_exten);
09358 ast_free(d->park_context);
09359 ast_free(d);
09360 return -1;
09361 }
09362
09363
09364 chan1m->readformat = chan1->readformat;
09365 chan1m->writeformat = chan1->writeformat;
09366
09367
09368 if (ast_channel_masquerade(chan1m, chan1)) {
09369 ast_hangup(chan1m);
09370 ast_hangup(chan2m);
09371 ast_free(d->park_exten);
09372 ast_free(d->park_context);
09373 ast_free(d);
09374 return -1;
09375 }
09376
09377
09378 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
09379 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
09380 chan1m->priority = chan1->priority;
09381
09382 ast_do_masquerade(chan1m);
09383
09384
09385
09386
09387
09388 chan2m->readformat = chan2->readformat;
09389 chan2m->writeformat = chan2->writeformat;
09390 ast_string_field_set(chan2m, parkinglot, chan2->parkinglot);
09391
09392
09393 if (ast_channel_masquerade(chan2m, chan2)) {
09394 ast_hangup(chan1m);
09395 ast_hangup(chan2m);
09396 ast_free(d->park_exten);
09397 ast_free(d->park_context);
09398 ast_free(d);
09399 return -1;
09400 }
09401
09402
09403 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
09404 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
09405 chan2m->priority = chan2->priority;
09406
09407 ast_do_masquerade(chan2m);
09408
09409 d->chan1 = chan1m;
09410 d->chan2 = chan2m;
09411 if (ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d) < 0) {
09412
09413 ast_hangup(chan1m);
09414 ast_hangup(chan2m);
09415 ast_free(d->park_exten);
09416 ast_free(d->park_context);
09417 ast_free(d);
09418 return -1;
09419 }
09420 return 0;
09421 }
09422
09423 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09424 {
09425 unsigned int ourver;
09426 char rsi[80];
09427 snprintf(rsi, sizeof(rsi), "si-%s", si);
09428 if (iax_provision_version(&ourver, rsi, 1))
09429 return 0;
09430 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09431 if (ourver != ver)
09432 iax2_provision(sin, sockfd, NULL, rsi, 1);
09433 return 0;
09434 }
09435
09436 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
09437 {
09438 jb_info stats;
09439 jb_getinfo(pvt->jb, &stats);
09440
09441 memset(iep, 0, sizeof(*iep));
09442
09443 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09444 if(stats.frames_in == 0) stats.frames_in = 1;
09445 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09446 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09447 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09448 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09449 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09450 }
09451
09452 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
09453 {
09454 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09455 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09456 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09457 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09458 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09459 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09460 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09461 }
09462
09463 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
09464 {
09465 int i;
09466 unsigned int length, offset = 0;
09467 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09468
09469 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09470 length = ies->ospblocklength[i];
09471 if (length != 0) {
09472 if (length > IAX_MAX_OSPBLOCK_SIZE) {
09473
09474 offset = 0;
09475 break;
09476 } else {
09477 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09478 offset += length;
09479 }
09480 } else {
09481 break;
09482 }
09483 }
09484 *(full_osptoken + offset) = '\0';
09485 if (strlen(full_osptoken) != offset) {
09486
09487 *full_osptoken = '\0';
09488 }
09489
09490 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09491 }
09492
09493 static void log_jitterstats(unsigned short callno)
09494 {
09495 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09496 jb_info jbinfo;
09497
09498 ast_mutex_lock(&iaxsl[callno]);
09499 if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
09500 if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
09501 jb_getinfo(iaxs[callno]->jb, &jbinfo);
09502 localjitter = jbinfo.jitter;
09503 localdelay = jbinfo.current - jbinfo.min;
09504 locallost = jbinfo.frames_lost;
09505 locallosspct = jbinfo.losspct/1000;
09506 localdropped = jbinfo.frames_dropped;
09507 localooo = jbinfo.frames_ooo;
09508 localpackets = jbinfo.frames_in;
09509 }
09510 ast_debug(3, "JB STATS:%s ping=%d ljitterms=%d ljbdelayms=%d ltotlost=%d lrecentlosspct=%d ldropped=%d looo=%d lrecvd=%d rjitterms=%d rjbdelayms=%d rtotlost=%d rrecentlosspct=%d rdropped=%d rooo=%d rrecvd=%d\n",
09511 iaxs[callno]->owner->name,
09512 iaxs[callno]->pingtime,
09513 localjitter,
09514 localdelay,
09515 locallost,
09516 locallosspct,
09517 localdropped,
09518 localooo,
09519 localpackets,
09520 iaxs[callno]->remote_rr.jitter,
09521 iaxs[callno]->remote_rr.delay,
09522 iaxs[callno]->remote_rr.losscnt,
09523 iaxs[callno]->remote_rr.losspct/1000,
09524 iaxs[callno]->remote_rr.dropped,
09525 iaxs[callno]->remote_rr.ooo,
09526 iaxs[callno]->remote_rr.packets);
09527 manager_event(EVENT_FLAG_REPORTING, "JitterBufStats", "Owner: %s\r\nPing: %d\r\nLocalJitter: %d\r\nLocalJBDelay: %d\r\nLocalTotalLost: %d\r\nLocalLossPercent: %d\r\nLocalDropped: %d\r\nLocalooo: %d\r\nLocalReceived: %d\r\nRemoteJitter: %d\r\nRemoteJBDelay: %d\r\nRemoteTotalLost: %d\r\nRemoteLossPercent: %d\r\nRemoteDropped: %d\r\nRemoteooo: %d\r\nRemoteReceived: %d\r\n",
09528 iaxs[callno]->owner->name,
09529 iaxs[callno]->pingtime,
09530 localjitter,
09531 localdelay,
09532 locallost,
09533 locallosspct,
09534 localdropped,
09535 localooo,
09536 localpackets,
09537 iaxs[callno]->remote_rr.jitter,
09538 iaxs[callno]->remote_rr.delay,
09539 iaxs[callno]->remote_rr.losscnt,
09540 iaxs[callno]->remote_rr.losspct/1000,
09541 iaxs[callno]->remote_rr.dropped,
09542 iaxs[callno]->remote_rr.ooo,
09543 iaxs[callno]->remote_rr.packets);
09544 }
09545 ast_mutex_unlock(&iaxsl[callno]);
09546 }
09547
09548 static int socket_process(struct iax2_thread *thread);
09549
09550
09551
09552
09553 static void handle_deferred_full_frames(struct iax2_thread *thread)
09554 {
09555 struct iax2_pkt_buf *pkt_buf;
09556
09557 ast_mutex_lock(&thread->lock);
09558
09559 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09560 ast_mutex_unlock(&thread->lock);
09561
09562 thread->buf = pkt_buf->buf;
09563 thread->buf_len = pkt_buf->len;
09564 thread->buf_size = pkt_buf->len + 1;
09565
09566 socket_process(thread);
09567
09568 thread->buf = NULL;
09569 ast_free(pkt_buf);
09570
09571 ast_mutex_lock(&thread->lock);
09572 }
09573
09574 ast_mutex_unlock(&thread->lock);
09575 }
09576
09577
09578
09579
09580
09581
09582
09583 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09584 {
09585 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09586 struct ast_iax2_full_hdr *fh, *cur_fh;
09587
09588 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09589 return;
09590
09591 pkt_buf->len = from_here->buf_len;
09592 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09593
09594 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09595 ast_mutex_lock(&to_here->lock);
09596 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09597 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09598 if (fh->oseqno < cur_fh->oseqno) {
09599 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09600 break;
09601 }
09602 }
09603 AST_LIST_TRAVERSE_SAFE_END
09604
09605 if (!cur_pkt_buf)
09606 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09607
09608 ast_mutex_unlock(&to_here->lock);
09609 }
09610
09611 static int socket_read(int *id, int fd, short events, void *cbdata)
09612 {
09613 struct iax2_thread *thread;
09614 socklen_t len;
09615 time_t t;
09616 static time_t last_errtime = 0;
09617 struct ast_iax2_full_hdr *fh;
09618
09619 if (!(thread = find_idle_thread())) {
09620 time(&t);
09621 if (t != last_errtime)
09622 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09623 last_errtime = t;
09624 usleep(1);
09625 return 1;
09626 }
09627
09628 len = sizeof(thread->iosin);
09629 thread->iofd = fd;
09630 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09631 thread->buf_size = sizeof(thread->readbuf);
09632 thread->buf = thread->readbuf;
09633 if (thread->buf_len < 0) {
09634 if (errno != ECONNREFUSED && errno != EAGAIN)
09635 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09636 handle_error();
09637 thread->iostate = IAX_IOSTATE_IDLE;
09638 signal_condition(&thread->lock, &thread->cond);
09639 return 1;
09640 }
09641 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) {
09642 thread->iostate = IAX_IOSTATE_IDLE;
09643 signal_condition(&thread->lock, &thread->cond);
09644 return 1;
09645 }
09646
09647
09648
09649
09650 fh = (struct ast_iax2_full_hdr *) thread->buf;
09651 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09652 struct iax2_thread *cur = NULL;
09653 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09654
09655 AST_LIST_LOCK(&active_list);
09656 AST_LIST_TRAVERSE(&active_list, cur, list) {
09657 if ((cur->ffinfo.callno == callno) &&
09658 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09659 break;
09660 }
09661 if (cur) {
09662
09663
09664 defer_full_frame(thread, cur);
09665 AST_LIST_UNLOCK(&active_list);
09666 thread->iostate = IAX_IOSTATE_IDLE;
09667 signal_condition(&thread->lock, &thread->cond);
09668 return 1;
09669 } else {
09670
09671 thread->ffinfo.callno = callno;
09672 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09673 thread->ffinfo.type = fh->type;
09674 thread->ffinfo.csub = fh->csub;
09675 AST_LIST_INSERT_HEAD(&active_list, thread, list);
09676 }
09677 AST_LIST_UNLOCK(&active_list);
09678 }
09679
09680
09681 thread->iostate = IAX_IOSTATE_READY;
09682 #ifdef DEBUG_SCHED_MULTITHREAD
09683 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09684 #endif
09685 signal_condition(&thread->lock, &thread->cond);
09686
09687 return 1;
09688 }
09689
09690 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09691 struct iax_frame *fr)
09692 {
09693 unsigned char metatype;
09694 struct ast_iax2_meta_trunk_mini *mtm;
09695 struct ast_iax2_meta_trunk_hdr *mth;
09696 struct ast_iax2_meta_trunk_entry *mte;
09697 struct iax2_trunk_peer *tpeer;
09698 unsigned int ts;
09699 void *ptr;
09700 struct timeval rxtrunktime;
09701 struct ast_frame f = { 0, };
09702
09703 if (packet_len < sizeof(*meta)) {
09704 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
09705 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09706 return 1;
09707 }
09708
09709 if (meta->metacmd != IAX_META_TRUNK)
09710 return 1;
09711
09712 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09713 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09714 (int) (sizeof(*meta) + sizeof(*mth)));
09715 return 1;
09716 }
09717 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09718 ts = ntohl(mth->ts);
09719 metatype = meta->cmddata;
09720 packet_len -= (sizeof(*meta) + sizeof(*mth));
09721 ptr = mth->data;
09722 tpeer = find_tpeer(sin, sockfd);
09723 if (!tpeer) {
09724 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
09725 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09726 return 1;
09727 }
09728 tpeer->trunkact = ast_tvnow();
09729 if (!ts || ast_tvzero(tpeer->rxtrunktime))
09730 tpeer->rxtrunktime = tpeer->trunkact;
09731 rxtrunktime = tpeer->rxtrunktime;
09732 ast_mutex_unlock(&tpeer->lock);
09733 while (packet_len >= sizeof(*mte)) {
09734
09735 unsigned short callno, trunked_ts, len;
09736
09737 if (metatype == IAX_META_TRUNK_MINI) {
09738 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09739 ptr += sizeof(*mtm);
09740 packet_len -= sizeof(*mtm);
09741 len = ntohs(mtm->len);
09742 callno = ntohs(mtm->mini.callno);
09743 trunked_ts = ntohs(mtm->mini.ts);
09744 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09745 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09746 ptr += sizeof(*mte);
09747 packet_len -= sizeof(*mte);
09748 len = ntohs(mte->len);
09749 callno = ntohs(mte->callno);
09750 trunked_ts = 0;
09751 } else {
09752 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09753 break;
09754 }
09755
09756 if (len > packet_len)
09757 break;
09758 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09759 if (!fr->callno)
09760 continue;
09761
09762
09763
09764
09765 memset(&f, 0, sizeof(f));
09766 f.frametype = AST_FRAME_VOICE;
09767 if (!iaxs[fr->callno]) {
09768
09769 } else if (iaxs[fr->callno]->voiceformat == 0) {
09770 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09771 iax2_vnak(fr->callno);
09772 } else {
09773 f.subclass.codec = iaxs[fr->callno]->voiceformat;
09774 f.datalen = len;
09775 if (f.datalen >= 0) {
09776 if (f.datalen)
09777 f.data.ptr = ptr;
09778 else
09779 f.data.ptr = NULL;
09780 if (trunked_ts)
09781 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09782 else
09783 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09784
09785 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09786 struct iax_frame *duped_fr;
09787
09788
09789 f.src = "IAX2";
09790 f.mallocd = 0;
09791 f.offset = 0;
09792 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
09793 f.samples = ast_codec_get_samples(&f);
09794 else
09795 f.samples = 0;
09796 fr->outoforder = 0;
09797 iax_frame_wrap(fr, &f);
09798 duped_fr = iaxfrdup2(fr);
09799 if (duped_fr)
09800 schedule_delivery(duped_fr, 1, 1, &fr->ts);
09801 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
09802 iaxs[fr->callno]->last = fr->ts;
09803 }
09804 } else {
09805 ast_log(LOG_WARNING, "Datalen < 0?\n");
09806 }
09807 }
09808 ast_mutex_unlock(&iaxsl[fr->callno]);
09809 ptr += len;
09810 packet_len -= len;
09811 }
09812
09813 return 1;
09814 }
09815
09816 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
09817 {
09818 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09819 AST_LIST_HEAD(, ast_var_t) *varlist;
09820 struct ast_var_t *var;
09821
09822 if (!variablestore) {
09823 *buf = '\0';
09824 return 0;
09825 }
09826 varlist = variablestore->data;
09827
09828 AST_LIST_LOCK(varlist);
09829 AST_LIST_TRAVERSE(varlist, var, entries) {
09830 if (strcmp(var->name, data) == 0) {
09831 ast_copy_string(buf, var->value, len);
09832 break;
09833 }
09834 }
09835 AST_LIST_UNLOCK(varlist);
09836 return 0;
09837 }
09838
09839 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
09840 {
09841 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09842 AST_LIST_HEAD(, ast_var_t) *varlist;
09843 struct ast_var_t *var;
09844
09845 if (!variablestore) {
09846 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09847 if (!variablestore) {
09848 ast_log(LOG_ERROR, "Memory allocation error\n");
09849 return -1;
09850 }
09851 varlist = ast_calloc(1, sizeof(*varlist));
09852 if (!varlist) {
09853 ast_datastore_free(variablestore);
09854 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09855 return -1;
09856 }
09857
09858 AST_LIST_HEAD_INIT(varlist);
09859 variablestore->data = varlist;
09860 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09861 ast_channel_datastore_add(chan, variablestore);
09862 } else
09863 varlist = variablestore->data;
09864
09865 AST_LIST_LOCK(varlist);
09866 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
09867 if (strcmp(var->name, data) == 0) {
09868 AST_LIST_REMOVE_CURRENT(entries);
09869 ast_var_delete(var);
09870 break;
09871 }
09872 }
09873 AST_LIST_TRAVERSE_SAFE_END;
09874 var = ast_var_assign(data, value);
09875 if (var)
09876 AST_LIST_INSERT_TAIL(varlist, var, entries);
09877 else
09878 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09879 AST_LIST_UNLOCK(varlist);
09880 return 0;
09881 }
09882
09883 static struct ast_custom_function iaxvar_function = {
09884 .name = "IAXVAR",
09885 .read = acf_iaxvar_read,
09886 .write = acf_iaxvar_write,
09887 };
09888
09889 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
09890 {
09891 iax2_lock_owner(callno);
09892 if (iaxs[callno] && iaxs[callno]->owner) {
09893 struct ast_channel *owner;
09894 const char *name;
09895
09896 owner = iaxs[callno]->owner;
09897 if (causecode) {
09898 owner->hangupcause = causecode;
09899 }
09900 name = ast_strdupa(owner->name);
09901 ast_channel_ref(owner);
09902 ast_channel_unlock(owner);
09903 ast_mutex_unlock(&iaxsl[callno]);
09904 ast_set_hangupsource(owner, name, 0);
09905 ast_channel_unref(owner);
09906 ast_mutex_lock(&iaxsl[callno]);
09907 }
09908 }
09909
09910 static int socket_process(struct iax2_thread *thread)
09911 {
09912 struct sockaddr_in sin;
09913 int res;
09914 int updatehistory=1;
09915 int new = NEW_PREVENT;
09916 int dcallno = 0;
09917 char decrypted = 0;
09918 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
09919 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
09920 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
09921 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
09922 struct iax_frame *fr;
09923 struct iax_frame *cur;
09924 struct ast_frame f = { 0, };
09925 struct ast_channel *c = NULL;
09926 struct iax2_dpcache *dp;
09927 struct iax2_peer *peer;
09928 struct iax_ies ies;
09929 struct iax_ie_data ied0, ied1;
09930 format_t format;
09931 int fd;
09932 int exists;
09933 int minivid = 0;
09934 char empty[32]="";
09935 struct iax_frame *duped_fr;
09936 char host_pref_buf[128];
09937 char caller_pref_buf[128];
09938 struct ast_codec_pref pref;
09939 char *using_prefs = "mine";
09940
09941
09942 fr = alloca(sizeof(*fr) + 4096);
09943 memset(fr, 0, sizeof(*fr));
09944 fr->afdatalen = 4096;
09945
09946
09947 res = thread->buf_len;
09948 fd = thread->iofd;
09949 memcpy(&sin, &thread->iosin, sizeof(sin));
09950
09951 if (res < sizeof(*mh)) {
09952 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
09953 return 1;
09954 }
09955 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
09956 if (res < sizeof(*vh)) {
09957 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));
09958 return 1;
09959 }
09960
09961
09962 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
09963 minivid = 1;
09964 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
09965 return socket_process_meta(res, meta, &sin, fd, fr);
09966
09967 #ifdef DEBUG_SUPPORT
09968 if (res >= sizeof(*fh))
09969 iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
09970 #endif
09971 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09972 if (res < sizeof(*fh)) {
09973 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));
09974 return 1;
09975 }
09976
09977
09978 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
09979
09980
09981
09982
09983
09984
09985 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
09986 ast_mutex_lock(&iaxsl[fr->callno]);
09987 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
09988 if (decrypt_frame(fr->callno, fh, &f, &res)) {
09989 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09990 ast_mutex_unlock(&iaxsl[fr->callno]);
09991 return 1;
09992 }
09993 decrypted = 1;
09994 }
09995 ast_mutex_unlock(&iaxsl[fr->callno]);
09996 }
09997
09998
09999 f.frametype = fh->type;
10000 if (f.frametype == AST_FRAME_VIDEO) {
10001 f.subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
10002 } else if (f.frametype == AST_FRAME_VOICE) {
10003 f.subclass.codec = uncompress_subclass(fh->csub);
10004 } else {
10005 f.subclass.integer = uncompress_subclass(fh->csub);
10006 }
10007
10008
10009 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
10010
10011 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10012 return 1;
10013 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10014
10015 return 1;
10016 }
10017
10018 f.datalen = res - sizeof(*fh);
10019 if (f.datalen) {
10020 if (f.frametype == AST_FRAME_IAX) {
10021 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10022 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
10023 ast_variables_destroy(ies.vars);
10024 return 1;
10025 }
10026 f.data.ptr = NULL;
10027 f.datalen = 0;
10028 } else {
10029 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10030 memset(&ies, 0, sizeof(ies));
10031 }
10032 } else {
10033 if (f.frametype == AST_FRAME_IAX)
10034 f.data.ptr = NULL;
10035 else
10036 f.data.ptr = empty;
10037 memset(&ies, 0, sizeof(ies));
10038 }
10039
10040 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10041
10042 if (handle_call_token(fh, &ies, &sin, fd)) {
10043 ast_variables_destroy(ies.vars);
10044 return 1;
10045 }
10046
10047 if (ies.calltoken && ies.calltokendata) {
10048
10049
10050
10051
10052 new = NEW_ALLOW_CALLTOKEN_VALIDATED;
10053 } else {
10054 new = NEW_ALLOW;
10055 }
10056 }
10057 } else {
10058
10059 f.frametype = AST_FRAME_NULL;
10060 f.subclass.integer = 0;
10061 memset(&ies, 0, sizeof(ies));
10062 }
10063
10064 if (!fr->callno) {
10065 int check_dcallno = 0;
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10076 check_dcallno = 1;
10077 }
10078
10079 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
10080 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
10081 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10082 } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
10083 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10084 }
10085 ast_variables_destroy(ies.vars);
10086 return 1;
10087 }
10088 }
10089
10090 if (fr->callno > 0)
10091 ast_mutex_lock(&iaxsl[fr->callno]);
10092
10093 if (!fr->callno || !iaxs[fr->callno]) {
10094
10095
10096 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10097
10098 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10099 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10100 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10101 (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
10102 (f.frametype != AST_FRAME_IAX))
10103 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10104 fd);
10105 }
10106 if (fr->callno > 0)
10107 ast_mutex_unlock(&iaxsl[fr->callno]);
10108 ast_variables_destroy(ies.vars);
10109 return 1;
10110 }
10111 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10112 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10113 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10114 ast_variables_destroy(ies.vars);
10115 ast_mutex_unlock(&iaxsl[fr->callno]);
10116 return 1;
10117 }
10118 decrypted = 1;
10119 }
10120
10121 #ifdef DEBUG_SUPPORT
10122 if (decrypted) {
10123 iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10124 }
10125 #endif
10126
10127
10128
10129 iaxs[fr->callno]->frames_received++;
10130
10131 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10132 f.subclass.integer != IAX_COMMAND_TXCNT &&
10133 f.subclass.integer != IAX_COMMAND_TXACC) {
10134 unsigned short new_peercallno;
10135
10136 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10137 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10138 if (iaxs[fr->callno]->peercallno) {
10139 remove_by_peercallno(iaxs[fr->callno]);
10140 }
10141 iaxs[fr->callno]->peercallno = new_peercallno;
10142 store_by_peercallno(iaxs[fr->callno]);
10143 }
10144 }
10145 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10146 if (iaxdebug)
10147 ast_debug(1, "Received packet %d, (%d, %u)\n", fh->oseqno, f.frametype, f.subclass.integer);
10148
10149 fr->oseqno = fh->oseqno;
10150 fr->iseqno = fh->iseqno;
10151 fr->ts = ntohl(fh->ts);
10152 #ifdef IAXTESTS
10153 if (test_resync) {
10154 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10155 fr->ts += test_resync;
10156 }
10157 #endif
10158 #if 0
10159 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10160 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10161 (f.subclass == IAX_COMMAND_NEW ||
10162 f.subclass == IAX_COMMAND_AUTHREQ ||
10163 f.subclass == IAX_COMMAND_ACCEPT ||
10164 f.subclass == IAX_COMMAND_REJECT)) ) )
10165 #endif
10166 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10167 updatehistory = 0;
10168 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10169 (iaxs[fr->callno]->iseqno ||
10170 ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10171 (f.subclass.integer != IAX_COMMAND_TXREADY) &&
10172 (f.subclass.integer != IAX_COMMAND_TXREL) &&
10173 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&
10174 (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10175 (f.frametype != AST_FRAME_IAX))) {
10176 if (
10177 ((f.subclass.integer != IAX_COMMAND_ACK) &&
10178 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10179 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10180 (f.subclass.integer != IAX_COMMAND_TXREADY) &&
10181 (f.subclass.integer != IAX_COMMAND_TXREL) &&
10182 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&
10183 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10184 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10185 (f.frametype != AST_FRAME_IAX)) {
10186
10187 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
10188 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10189
10190
10191 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10192
10193 if ((f.frametype != AST_FRAME_IAX) ||
10194 ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10195 ast_debug(1, "Acking anyway\n");
10196
10197
10198 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10199 }
10200 } else {
10201
10202 iax2_vnak(fr->callno);
10203 }
10204 ast_variables_destroy(ies.vars);
10205 ast_mutex_unlock(&iaxsl[fr->callno]);
10206 return 1;
10207 }
10208 } else {
10209
10210 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10211 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10212 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10213 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10214 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10215 (f.frametype != AST_FRAME_IAX))
10216 iaxs[fr->callno]->iseqno++;
10217 }
10218
10219 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10220 if (res < thread->buf_size)
10221 thread->buf[res++] = '\0';
10222 else
10223 thread->buf[res - 1] = '\0';
10224 }
10225
10226
10227
10228 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10229 ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10230 (f.frametype != AST_FRAME_IAX))) {
10231 unsigned char x;
10232 int call_to_destroy;
10233
10234 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10235 x = fr->iseqno;
10236 else
10237 x = iaxs[fr->callno]->oseqno;
10238 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10239
10240
10241 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10242
10243 if (iaxdebug)
10244 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10245 call_to_destroy = 0;
10246 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10247
10248 if (x == cur->oseqno) {
10249 cur->retries = -1;
10250
10251 if (cur->final)
10252 call_to_destroy = fr->callno;
10253 }
10254 }
10255 if (call_to_destroy) {
10256 if (iaxdebug)
10257 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10258 ast_mutex_lock(&iaxsl[call_to_destroy]);
10259 iax2_destroy(call_to_destroy);
10260 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10261 }
10262 }
10263
10264 if (iaxs[fr->callno])
10265 iaxs[fr->callno]->rseqno = fr->iseqno;
10266 else {
10267
10268 ast_variables_destroy(ies.vars);
10269 ast_mutex_unlock(&iaxsl[fr->callno]);
10270 return 1;
10271 }
10272 } else {
10273 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10274 }
10275 }
10276 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10277 ((f.frametype != AST_FRAME_IAX) ||
10278 ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10279 (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10280
10281 ast_variables_destroy(ies.vars);
10282 ast_mutex_unlock(&iaxsl[fr->callno]);
10283 return 1;
10284 }
10285
10286
10287
10288
10289 if ((f.frametype == AST_FRAME_VOICE) ||
10290 (f.frametype == AST_FRAME_VIDEO) ||
10291 (f.frametype == AST_FRAME_IAX)) {
10292 if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10293 ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10294 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL)) {
10295 ast_variables_destroy(ies.vars);
10296 ast_mutex_unlock(&iaxsl[fr->callno]);
10297 return 1;
10298 }
10299 }
10300
10301 if (ies.vars) {
10302 struct ast_datastore *variablestore = NULL;
10303 struct ast_variable *var, *prev = NULL;
10304 AST_LIST_HEAD(, ast_var_t) *varlist;
10305
10306 iax2_lock_owner(fr->callno);
10307 if (!iaxs[fr->callno]) {
10308 ast_variables_destroy(ies.vars);
10309 ast_mutex_unlock(&iaxsl[fr->callno]);
10310 return 1;
10311 }
10312 if ((c = iaxs[fr->callno]->owner)) {
10313 varlist = ast_calloc(1, sizeof(*varlist));
10314 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10315
10316 if (variablestore && varlist) {
10317 variablestore->data = varlist;
10318 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10319 AST_LIST_HEAD_INIT(varlist);
10320 ast_debug(1, "I can haz IAX vars?\n");
10321 for (var = ies.vars; var; var = var->next) {
10322 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10323 if (prev) {
10324 ast_free(prev);
10325 }
10326 prev = var;
10327 if (!newvar) {
10328
10329 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10330 } else {
10331 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10332 }
10333 }
10334 if (prev) {
10335 ast_free(prev);
10336 }
10337 ies.vars = NULL;
10338 ast_channel_datastore_add(c, variablestore);
10339 } else {
10340 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10341 if (variablestore) {
10342 ast_datastore_free(variablestore);
10343 }
10344 if (varlist) {
10345 ast_free(varlist);
10346 }
10347 }
10348 ast_channel_unlock(c);
10349 } else {
10350
10351
10352 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10353 for (var = ies.vars; var && var->next; var = var->next);
10354 if (var) {
10355 var->next = iaxs[fr->callno]->iaxvars;
10356 iaxs[fr->callno]->iaxvars = ies.vars;
10357 ies.vars = NULL;
10358 }
10359 }
10360 }
10361
10362 if (ies.vars) {
10363 ast_debug(1, "I have IAX variables, but they were not processed\n");
10364 }
10365 }
10366
10367
10368
10369 if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10370 send_signaling(iaxs[fr->callno]);
10371 }
10372
10373 if (f.frametype == AST_FRAME_VOICE) {
10374 if (f.subclass.codec != iaxs[fr->callno]->voiceformat) {
10375 iaxs[fr->callno]->voiceformat = f.subclass.codec;
10376 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(f.subclass.codec));
10377 if (iaxs[fr->callno]->owner) {
10378 iax2_lock_owner(fr->callno);
10379 if (iaxs[fr->callno]) {
10380 if (iaxs[fr->callno]->owner) {
10381 format_t orignative;
10382
10383 orignative = iaxs[fr->callno]->owner->nativeformats;
10384 iaxs[fr->callno]->owner->nativeformats = f.subclass.codec;
10385 if (iaxs[fr->callno]->owner->readformat)
10386 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10387 iaxs[fr->callno]->owner->nativeformats = orignative;
10388 ast_channel_unlock(iaxs[fr->callno]->owner);
10389 }
10390 } else {
10391 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10392
10393 if (ies.vars) {
10394 ast_variables_destroy(ies.vars);
10395 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10396 ies.vars = NULL;
10397 }
10398 ast_mutex_unlock(&iaxsl[fr->callno]);
10399 return 1;
10400 }
10401 }
10402 }
10403 }
10404 if (f.frametype == AST_FRAME_VIDEO) {
10405 if (f.subclass.codec != iaxs[fr->callno]->videoformat) {
10406 ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(f.subclass.codec & ~0x1LL));
10407 iaxs[fr->callno]->videoformat = f.subclass.codec & ~0x1LL;
10408 }
10409 }
10410 if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
10411 if (f.subclass.integer == AST_CONTROL_BUSY) {
10412 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
10413 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
10414 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
10415 }
10416 }
10417 if (f.frametype == AST_FRAME_IAX) {
10418 ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
10419
10420 if (iaxdebug)
10421 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10422
10423
10424 if (iaxs[fr->callno]->last < fr->ts &&
10425 f.subclass.integer != IAX_COMMAND_ACK &&
10426 f.subclass.integer != IAX_COMMAND_PONG &&
10427 f.subclass.integer != IAX_COMMAND_LAGRP) {
10428 iaxs[fr->callno]->last = fr->ts;
10429 if (iaxdebug)
10430 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10431 }
10432 iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10433 if (!iaxs[fr->callno]->first_iax_message) {
10434 iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10435 }
10436 switch(f.subclass.integer) {
10437 case IAX_COMMAND_ACK:
10438
10439 break;
10440 case IAX_COMMAND_QUELCH:
10441 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10442
10443 if (iaxs[fr->callno]->owner) {
10444 ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10445 "Status: On\r\n"
10446 "Channel: %s\r\n"
10447 "Uniqueid: %s\r\n",
10448 iaxs[fr->callno]->owner->name,
10449 iaxs[fr->callno]->owner->uniqueid);
10450 }
10451
10452 ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10453 if (ies.musiconhold) {
10454 iax2_lock_owner(fr->callno);
10455 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10456 break;
10457 }
10458 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10459 const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10460
10461
10462
10463
10464
10465 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
10466 S_OR(moh_suggest, NULL),
10467 !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10468 }
10469 ast_channel_unlock(iaxs[fr->callno]->owner);
10470 }
10471 }
10472 break;
10473 case IAX_COMMAND_UNQUELCH:
10474 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10475 iax2_lock_owner(fr->callno);
10476 if (!iaxs[fr->callno]) {
10477 break;
10478 }
10479
10480 if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10481 ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10482 "Status: Off\r\n"
10483 "Channel: %s\r\n"
10484 "Uniqueid: %s\r\n",
10485 iaxs[fr->callno]->owner->name,
10486 iaxs[fr->callno]->owner->uniqueid);
10487 }
10488
10489 ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10490 if (!iaxs[fr->callno]->owner) {
10491 break;
10492 }
10493 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10494
10495
10496
10497
10498 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10499 }
10500 ast_channel_unlock(iaxs[fr->callno]->owner);
10501 }
10502 break;
10503 case IAX_COMMAND_TXACC:
10504 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10505
10506 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10507
10508 if (cur->transfer) {
10509 cur->retries = -1;
10510 }
10511 }
10512 memset(&ied1, 0, sizeof(ied1));
10513 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10514 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10515 iaxs[fr->callno]->transferring = TRANSFER_READY;
10516 }
10517 break;
10518 case IAX_COMMAND_NEW:
10519
10520 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10521 break;
10522 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10523 ast_mutex_unlock(&iaxsl[fr->callno]);
10524 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10525 ast_mutex_lock(&iaxsl[fr->callno]);
10526 if (!iaxs[fr->callno]) {
10527 break;
10528 }
10529 }
10530
10531 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10532 int new_callno;
10533 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10534 fr->callno = new_callno;
10535 }
10536
10537 if (delayreject)
10538 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10539 if (check_access(fr->callno, &sin, &ies)) {
10540
10541 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10542 if (authdebug)
10543 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);
10544 break;
10545 }
10546 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10547 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10548 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10549 break;
10550 }
10551 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10552 const char *context, *exten, *cid_num;
10553
10554 context = ast_strdupa(iaxs[fr->callno]->context);
10555 exten = ast_strdupa(iaxs[fr->callno]->exten);
10556 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10557
10558
10559 ast_mutex_unlock(&iaxsl[fr->callno]);
10560 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10561 ast_mutex_lock(&iaxsl[fr->callno]);
10562
10563 if (!iaxs[fr->callno]) {
10564 break;
10565 }
10566 } else
10567 exists = 0;
10568
10569 save_osptoken(fr, &ies);
10570 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10571 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10572 memset(&ied0, 0, sizeof(ied0));
10573 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10574 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10575 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10576 if (!iaxs[fr->callno]) {
10577 break;
10578 }
10579 if (authdebug)
10580 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);
10581 } else {
10582
10583
10584 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10585 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10586 using_prefs = "reqonly";
10587 } else {
10588 using_prefs = "disabled";
10589 }
10590 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10591 memset(&pref, 0, sizeof(pref));
10592 strcpy(caller_pref_buf, "disabled");
10593 strcpy(host_pref_buf, "disabled");
10594 } else {
10595 using_prefs = "mine";
10596
10597 if (ies.codec_prefs)
10598 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10599 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10600
10601 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10602 pref = iaxs[fr->callno]->rprefs;
10603 using_prefs = "caller";
10604 } else {
10605 pref = iaxs[fr->callno]->prefs;
10606 }
10607 } else
10608 pref = iaxs[fr->callno]->prefs;
10609
10610 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10611 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10612 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10613 }
10614 if (!format) {
10615 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10616 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10617 if (!format) {
10618 memset(&ied0, 0, sizeof(ied0));
10619 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10620 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10621 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10622 if (!iaxs[fr->callno]) {
10623 break;
10624 }
10625 if (authdebug) {
10626 char tmp[256], tmp2[256], tmp3[256];
10627 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10628 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10629 ast_inet_ntoa(sin.sin_addr),
10630 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10631 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10632 } else {
10633 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10634 ast_inet_ntoa(sin.sin_addr),
10635 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10636 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10637 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10638 }
10639 }
10640 } else {
10641
10642 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10643 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10644 format = 0;
10645 } else {
10646 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10647 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10648 memset(&pref, 0, sizeof(pref));
10649 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10650 strcpy(caller_pref_buf,"disabled");
10651 strcpy(host_pref_buf,"disabled");
10652 } else {
10653 using_prefs = "mine";
10654 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10655
10656 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10657 pref = iaxs[fr->callno]->prefs;
10658 } else {
10659 pref = iaxs[fr->callno]->rprefs;
10660 using_prefs = "caller";
10661 }
10662 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10663 } else
10664 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10665 }
10666 }
10667
10668 if (!format) {
10669 char tmp[256], tmp2[256], tmp3[256];
10670 memset(&ied0, 0, sizeof(ied0));
10671 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10672 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10673 ast_log(LOG_ERROR, "No best format in '%s'???\n", ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10674 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10675 if (!iaxs[fr->callno]) {
10676 break;
10677 }
10678 if (authdebug) {
10679 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10680 ast_inet_ntoa(sin.sin_addr),
10681 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10682 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10683 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10684 }
10685 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10686 break;
10687 }
10688 }
10689 }
10690 if (format) {
10691
10692 memset(&ied1, 0, sizeof(ied1));
10693 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10694 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
10695 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10696 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10697 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10698 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10699 "%srequested format = %s,\n"
10700 "%srequested prefs = %s,\n"
10701 "%sactual format = %s,\n"
10702 "%shost prefs = %s,\n"
10703 "%spriority = %s\n",
10704 ast_inet_ntoa(sin.sin_addr),
10705 VERBOSE_PREFIX_4,
10706 ast_getformatname(iaxs[fr->callno]->peerformat),
10707 VERBOSE_PREFIX_4,
10708 caller_pref_buf,
10709 VERBOSE_PREFIX_4,
10710 ast_getformatname(format),
10711 VERBOSE_PREFIX_4,
10712 host_pref_buf,
10713 VERBOSE_PREFIX_4,
10714 using_prefs);
10715
10716 iaxs[fr->callno]->chosenformat = format;
10717 ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10718 } else {
10719 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10720
10721 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10722 }
10723 }
10724 }
10725 break;
10726 }
10727 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10728 merge_encryption(iaxs[fr->callno],ies.encmethods);
10729 else
10730 iaxs[fr->callno]->encmethods = 0;
10731 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10732 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10733 break;
10734 case IAX_COMMAND_DPREQ:
10735
10736 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10737 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10738 if (iaxcompat) {
10739
10740 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10741 } else {
10742
10743 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10744 }
10745 }
10746 break;
10747 case IAX_COMMAND_HANGUP:
10748 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10749 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10750
10751 if (iaxs[fr->callno]->owner) {
10752 set_hangup_source_and_cause(fr->callno, ies.causecode);
10753 if (!iaxs[fr->callno]) {
10754 break;
10755 }
10756 }
10757
10758
10759 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10760 iax2_destroy(fr->callno);
10761 break;
10762 case IAX_COMMAND_REJECT:
10763
10764 if (iaxs[fr->callno]->owner) {
10765 set_hangup_source_and_cause(fr->callno, ies.causecode);
10766 if (!iaxs[fr->callno]) {
10767 break;
10768 }
10769 }
10770
10771 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10772 if (iaxs[fr->callno]->owner && authdebug)
10773 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10774 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10775 ies.cause ? ies.cause : "<Unknown>");
10776 ast_debug(1, "Immediately destroying %d, having received reject\n",
10777 fr->callno);
10778 }
10779
10780 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
10781 fr->ts, NULL, 0, fr->iseqno);
10782 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
10783 iaxs[fr->callno]->error = EPERM;
10784 iax2_destroy(fr->callno);
10785 break;
10786 case IAX_COMMAND_TRANSFER:
10787 {
10788 struct ast_channel *bridged_chan;
10789 struct ast_channel *owner;
10790
10791 iax2_lock_owner(fr->callno);
10792 if (!iaxs[fr->callno]) {
10793
10794 break;
10795 }
10796 owner = iaxs[fr->callno]->owner;
10797 bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10798 if (bridged_chan && ies.called_number) {
10799 const char *context;
10800
10801 context = ast_strdupa(iaxs[fr->callno]->context);
10802
10803 ast_channel_ref(owner);
10804 ast_channel_ref(bridged_chan);
10805 ast_channel_unlock(owner);
10806 ast_mutex_unlock(&iaxsl[fr->callno]);
10807
10808
10809 pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10810 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10811
10812
10813 if (ast_parking_ext_valid(ies.called_number, owner, context)) {
10814 ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10815 if (iax_park(bridged_chan, owner, ies.called_number, context)) {
10816 ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10817 bridged_chan->name);
10818 }
10819 } else {
10820 if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
10821 ast_log(LOG_WARNING,
10822 "Async goto of '%s' to '%s@%s' failed\n",
10823 bridged_chan->name, ies.called_number, context);
10824 } else {
10825 ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10826 bridged_chan->name, ies.called_number, context);
10827 }
10828 }
10829 ast_channel_unref(owner);
10830 ast_channel_unref(bridged_chan);
10831
10832 ast_mutex_lock(&iaxsl[fr->callno]);
10833 } else {
10834 ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10835 if (owner) {
10836 ast_channel_unlock(owner);
10837 }
10838 }
10839
10840 break;
10841 }
10842 case IAX_COMMAND_ACCEPT:
10843
10844 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
10845 break;
10846 if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10847
10848 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10849 iax2_destroy(fr->callno);
10850 break;
10851 }
10852 if (ies.format) {
10853 iaxs[fr->callno]->peerformat = ies.format;
10854 } else {
10855 if (iaxs[fr->callno]->owner)
10856 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10857 else
10858 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10859 }
10860 ast_verb(3, "Call accepted by %s (format %s)\n", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), ast_getformatname(iaxs[fr->callno]->peerformat));
10861 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10862 memset(&ied0, 0, sizeof(ied0));
10863 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10864 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10865 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10866 if (!iaxs[fr->callno]) {
10867 break;
10868 }
10869 if (authdebug) {
10870 char tmp1[256], tmp2[256];
10871 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
10872 ast_inet_ntoa(sin.sin_addr),
10873 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10874 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10875 }
10876 } else {
10877 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10878 iax2_lock_owner(fr->callno);
10879 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10880
10881 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
10882 ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
10883
10884
10885 if (iaxs[fr->callno]->owner->writeformat)
10886 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
10887 if (iaxs[fr->callno]->owner->readformat)
10888 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10889 ast_channel_unlock(iaxs[fr->callno]->owner);
10890 }
10891 }
10892 if (iaxs[fr->callno]) {
10893 AST_LIST_LOCK(&dpcache);
10894 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
10895 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
10896 iax2_dprequest(dp, fr->callno);
10897 AST_LIST_UNLOCK(&dpcache);
10898 }
10899 break;
10900 case IAX_COMMAND_POKE:
10901
10902 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
10903 break;
10904 case IAX_COMMAND_PING:
10905 {
10906 struct iax_ie_data pingied;
10907 construct_rr(iaxs[fr->callno], &pingied);
10908
10909 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
10910 }
10911 break;
10912 case IAX_COMMAND_PONG:
10913
10914 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
10915
10916 save_rr(fr, &ies);
10917
10918
10919 log_jitterstats(fr->callno);
10920
10921 if (iaxs[fr->callno]->peerpoke) {
10922 peer = iaxs[fr->callno]->peerpoke;
10923 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
10924 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
10925 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
10926 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Reachable\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
10927 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name);
10928 }
10929 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
10930 if (iaxs[fr->callno]->pingtime > peer->maxms) {
10931 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
10932 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Lagged\r\nTime: %d\r\n", peer->name, iaxs[fr->callno]->pingtime);
10933 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
10934 }
10935 }
10936 peer->lastms = iaxs[fr->callno]->pingtime;
10937 if (peer->smoothing && (peer->lastms > -1))
10938 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
10939 else if (peer->smoothing && peer->lastms < 0)
10940 peer->historicms = (0 + peer->historicms) / 2;
10941 else
10942 peer->historicms = iaxs[fr->callno]->pingtime;
10943
10944
10945 if (peer->pokeexpire > -1) {
10946 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
10947 peer_unref(peer);
10948 peer->pokeexpire = -1;
10949 }
10950 }
10951
10952 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
10953 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
10954 else
10955 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
10956 if (peer->pokeexpire == -1)
10957 peer_unref(peer);
10958
10959 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10960
10961 iax2_destroy(fr->callno);
10962 peer->callno = 0;
10963 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
10964 }
10965 break;
10966 case IAX_COMMAND_LAGRQ:
10967 case IAX_COMMAND_LAGRP:
10968 f.src = "LAGRQ";
10969 f.mallocd = 0;
10970 f.offset = 0;
10971 f.samples = 0;
10972 iax_frame_wrap(fr, &f);
10973 if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
10974
10975 fr->af.subclass.integer = IAX_COMMAND_LAGRP;
10976 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
10977 } else {
10978
10979 unsigned int ts;
10980
10981 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
10982 iaxs[fr->callno]->lag = ts - fr->ts;
10983 if (iaxdebug)
10984 ast_debug(1, "Peer %s lag measured as %dms\n",
10985 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
10986 }
10987 break;
10988 case IAX_COMMAND_AUTHREQ:
10989 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10990 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>");
10991 break;
10992 }
10993 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
10994 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
10995 .subclass.integer = AST_CONTROL_HANGUP,
10996 };
10997 ast_log(LOG_WARNING,
10998 "I don't know how to authenticate %s to %s\n",
10999 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
11000 iax2_queue_frame(fr->callno, &hangup_fr);
11001 }
11002 break;
11003 case IAX_COMMAND_AUTHREP:
11004
11005 if (delayreject)
11006 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11007
11008 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11009 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>");
11010 break;
11011 }
11012 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11013 if (authdebug)
11014 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);
11015 memset(&ied0, 0, sizeof(ied0));
11016 auth_fail(fr->callno, IAX_COMMAND_REJECT);
11017 break;
11018 }
11019 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11020
11021 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11022 } else
11023 exists = 0;
11024 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11025 if (authdebug)
11026 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);
11027 memset(&ied0, 0, sizeof(ied0));
11028 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11029 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11030 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11031 if (!iaxs[fr->callno]) {
11032 break;
11033 }
11034 } else {
11035
11036 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11037 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11038 using_prefs = "reqonly";
11039 } else {
11040 using_prefs = "disabled";
11041 }
11042 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11043 memset(&pref, 0, sizeof(pref));
11044 strcpy(caller_pref_buf, "disabled");
11045 strcpy(host_pref_buf, "disabled");
11046 } else {
11047 using_prefs = "mine";
11048 if (ies.codec_prefs)
11049 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11050 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11051 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11052 pref = iaxs[fr->callno]->rprefs;
11053 using_prefs = "caller";
11054 } else {
11055 pref = iaxs[fr->callno]->prefs;
11056 }
11057 } else
11058 pref = iaxs[fr->callno]->prefs;
11059 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
11060 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11061 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11062 }
11063 if (!format) {
11064 char tmp1[256], tmp2[256], tmp3[256];
11065 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11066 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11067 ast_getformatname(iaxs[fr->callno]->peerformat),
11068 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
11069 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11070 }
11071 if (!format) {
11072 if (authdebug) {
11073 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11074 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
11075 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11076 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11077 } else {
11078 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11079 ast_inet_ntoa(sin.sin_addr),
11080 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11081 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11082 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11083 }
11084 }
11085 memset(&ied0, 0, sizeof(ied0));
11086 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11087 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11088 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11089 if (!iaxs[fr->callno]) {
11090 break;
11091 }
11092 } else {
11093
11094 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11095 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11096 format = 0;
11097 } else {
11098 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11099 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11100 memset(&pref, 0, sizeof(pref));
11101 format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
11102 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11103 strcpy(caller_pref_buf,"disabled");
11104 strcpy(host_pref_buf,"disabled");
11105 } else {
11106 using_prefs = "mine";
11107 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11108
11109 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11110 pref = iaxs[fr->callno]->prefs;
11111 } else {
11112 pref = iaxs[fr->callno]->rprefs;
11113 using_prefs = "caller";
11114 }
11115 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
11116 } else
11117 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11118 }
11119 }
11120 if (!format) {
11121 char tmp1[256], tmp2[256], tmp3[256];
11122 ast_log(LOG_ERROR, "No best format in %s???\n",
11123 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11124 if (authdebug) {
11125 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11126 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11127 ast_inet_ntoa(sin.sin_addr),
11128 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11129 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11130 } else {
11131 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11132 ast_inet_ntoa(sin.sin_addr),
11133 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11134 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11135 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11136 }
11137 }
11138 memset(&ied0, 0, sizeof(ied0));
11139 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11140 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11141 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11142 if (!iaxs[fr->callno]) {
11143 break;
11144 }
11145 }
11146 }
11147 }
11148 if (format) {
11149
11150 memset(&ied1, 0, sizeof(ied1));
11151 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11152 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11153 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11154 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11155 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11156 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11157 "%srequested format = %s,\n"
11158 "%srequested prefs = %s,\n"
11159 "%sactual format = %s,\n"
11160 "%shost prefs = %s,\n"
11161 "%spriority = %s\n",
11162 ast_inet_ntoa(sin.sin_addr),
11163 VERBOSE_PREFIX_4,
11164 ast_getformatname(iaxs[fr->callno]->peerformat),
11165 VERBOSE_PREFIX_4,
11166 caller_pref_buf,
11167 VERBOSE_PREFIX_4,
11168 ast_getformatname(format),
11169 VERBOSE_PREFIX_4,
11170 host_pref_buf,
11171 VERBOSE_PREFIX_4,
11172 using_prefs);
11173
11174 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11175 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL)))
11176 iax2_destroy(fr->callno);
11177 else if (ies.vars) {
11178 struct ast_datastore *variablestore;
11179 struct ast_variable *var, *prev = NULL;
11180 AST_LIST_HEAD(, ast_var_t) *varlist;
11181 varlist = ast_calloc(1, sizeof(*varlist));
11182 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11183 if (variablestore && varlist) {
11184 variablestore->data = varlist;
11185 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11186 AST_LIST_HEAD_INIT(varlist);
11187 ast_debug(1, "I can haz IAX vars? w00t\n");
11188 for (var = ies.vars; var; var = var->next) {
11189 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11190 if (prev)
11191 ast_free(prev);
11192 prev = var;
11193 if (!newvar) {
11194
11195 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11196 } else {
11197 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11198 }
11199 }
11200 if (prev)
11201 ast_free(prev);
11202 ies.vars = NULL;
11203 ast_channel_datastore_add(c, variablestore);
11204 } else {
11205 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11206 if (variablestore)
11207 ast_datastore_free(variablestore);
11208 if (varlist)
11209 ast_free(varlist);
11210 }
11211 }
11212 } else {
11213 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11214
11215 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11216 if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11217 goto immediatedial;
11218 }
11219 }
11220 }
11221 }
11222 break;
11223 case IAX_COMMAND_DIAL:
11224 immediatedial:
11225 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11226 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11227 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11228 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11229 if (authdebug)
11230 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);
11231 memset(&ied0, 0, sizeof(ied0));
11232 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11233 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11234 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11235 if (!iaxs[fr->callno]) {
11236 break;
11237 }
11238 } else {
11239 char tmp[256];
11240 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11241 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11242 ast_inet_ntoa(sin.sin_addr),
11243 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11244 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11245 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11246 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL)))
11247 iax2_destroy(fr->callno);
11248 else if (ies.vars) {
11249 struct ast_datastore *variablestore;
11250 struct ast_variable *var, *prev = NULL;
11251 AST_LIST_HEAD(, ast_var_t) *varlist;
11252 varlist = ast_calloc(1, sizeof(*varlist));
11253 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11254 ast_debug(1, "I can haz IAX vars? w00t\n");
11255 if (variablestore && varlist) {
11256 variablestore->data = varlist;
11257 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11258 AST_LIST_HEAD_INIT(varlist);
11259 for (var = ies.vars; var; var = var->next) {
11260 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11261 if (prev)
11262 ast_free(prev);
11263 prev = var;
11264 if (!newvar) {
11265
11266 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11267 } else {
11268 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11269 }
11270 }
11271 if (prev)
11272 ast_free(prev);
11273 ies.vars = NULL;
11274 ast_channel_datastore_add(c, variablestore);
11275 } else {
11276 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11277 if (variablestore)
11278 ast_datastore_free(variablestore);
11279 if (varlist)
11280 ast_free(varlist);
11281 }
11282 }
11283 }
11284 }
11285 break;
11286 case IAX_COMMAND_INVAL:
11287 iaxs[fr->callno]->error = ENOTCONN;
11288 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11289 iax2_destroy(fr->callno);
11290 ast_debug(1, "Destroying call %d\n", fr->callno);
11291 break;
11292 case IAX_COMMAND_VNAK:
11293 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11294
11295 vnak_retransmit(fr->callno, fr->iseqno);
11296 break;
11297 case IAX_COMMAND_REGREQ:
11298 case IAX_COMMAND_REGREL:
11299
11300 if (delayreject)
11301 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11302 if (register_verify(fr->callno, &sin, &ies)) {
11303 if (!iaxs[fr->callno]) {
11304 break;
11305 }
11306
11307 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11308 break;
11309 }
11310 if (!iaxs[fr->callno]) {
11311 break;
11312 }
11313 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11314 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11315
11316 if (f.subclass.integer == IAX_COMMAND_REGREL) {
11317 memset(&sin, 0, sizeof(sin));
11318 sin.sin_family = AF_INET;
11319 }
11320 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
11321 ast_log(LOG_WARNING, "Registry error\n");
11322 }
11323 if (!iaxs[fr->callno]) {
11324 break;
11325 }
11326 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11327 ast_mutex_unlock(&iaxsl[fr->callno]);
11328 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11329 ast_mutex_lock(&iaxsl[fr->callno]);
11330 }
11331 break;
11332 }
11333 registry_authrequest(fr->callno);
11334 break;
11335 case IAX_COMMAND_REGACK:
11336 if (iax2_ack_registry(&ies, &sin, fr->callno))
11337 ast_log(LOG_WARNING, "Registration failure\n");
11338
11339 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11340 iax2_destroy(fr->callno);
11341 break;
11342 case IAX_COMMAND_REGREJ:
11343 if (iaxs[fr->callno]->reg) {
11344 if (authdebug) {
11345 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));
11346 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nUsername: %s\r\nStatus: Rejected\r\nCause: %s\r\n", iaxs[fr->callno]->reg->username, ies.cause ? ies.cause : "<unknown>");
11347 }
11348 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11349 }
11350
11351 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11352 iax2_destroy(fr->callno);
11353 break;
11354 case IAX_COMMAND_REGAUTH:
11355
11356 if (registry_rerequest(&ies, fr->callno, &sin)) {
11357 memset(&ied0, 0, sizeof(ied0));
11358 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11359 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11360 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11361 }
11362 break;
11363 case IAX_COMMAND_TXREJ:
11364 iaxs[fr->callno]->transferring = 0;
11365 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11366 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11367 if (iaxs[fr->callno]->bridgecallno) {
11368 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11369 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
11370 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11371 }
11372 }
11373 break;
11374 case IAX_COMMAND_TXREADY:
11375 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
11376 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
11377 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
11378 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11379 else
11380 iaxs[fr->callno]->transferring = TRANSFER_READY;
11381 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11382 if (iaxs[fr->callno]->bridgecallno) {
11383 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
11384 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
11385
11386 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11387 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11388 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11389
11390 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11391 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11392
11393 memset(&ied0, 0, sizeof(ied0));
11394 memset(&ied1, 0, sizeof(ied1));
11395 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11396 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11397 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11398 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11399 } else {
11400 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11401 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11402
11403 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11404 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11405 ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11406 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11407
11408
11409 stop_stuff(fr->callno);
11410 stop_stuff(iaxs[fr->callno]->bridgecallno);
11411
11412 memset(&ied0, 0, sizeof(ied0));
11413 memset(&ied1, 0, sizeof(ied1));
11414 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11415 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11416 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11417 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11418 }
11419
11420 }
11421 }
11422 }
11423 break;
11424 case IAX_COMMAND_TXREQ:
11425 try_transfer(iaxs[fr->callno], &ies);
11426 break;
11427 case IAX_COMMAND_TXCNT:
11428 if (iaxs[fr->callno]->transferring)
11429 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11430 break;
11431 case IAX_COMMAND_TXREL:
11432
11433 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11434 complete_transfer(fr->callno, &ies);
11435 stop_stuff(fr->callno);
11436 break;
11437 case IAX_COMMAND_TXMEDIA:
11438 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11439 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11440
11441 if (cur->transfer) {
11442 cur->retries = -1;
11443 }
11444 }
11445
11446 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11447 }
11448 break;
11449 case IAX_COMMAND_RTKEY:
11450 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11451 ast_log(LOG_WARNING,
11452 "we've been told to rotate our encryption key, "
11453 "but this isn't an encrypted call. bad things will happen.\n"
11454 );
11455 break;
11456 }
11457
11458 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11459
11460 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11461 break;
11462 case IAX_COMMAND_DPREP:
11463 complete_dpreply(iaxs[fr->callno], &ies);
11464 break;
11465 case IAX_COMMAND_UNSUPPORT:
11466 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11467 break;
11468 case IAX_COMMAND_FWDOWNL:
11469
11470 if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11471 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11472 break;
11473 }
11474 memset(&ied0, 0, sizeof(ied0));
11475 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11476 if (res < 0)
11477 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11478 else if (res > 0)
11479 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11480 else
11481 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11482 break;
11483 case IAX_COMMAND_CALLTOKEN:
11484 {
11485 struct iax_frame *cur;
11486
11487 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11488 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11489 }
11490 break;
11491 }
11492 default:
11493 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11494 memset(&ied0, 0, sizeof(ied0));
11495 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11496 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11497 }
11498
11499 if (ies.vars) {
11500 ast_variables_destroy(ies.vars);
11501 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11502 ies.vars = NULL;
11503 }
11504
11505
11506 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11507 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
11508 (f.subclass.integer != IAX_COMMAND_TXACC) &&
11509 (f.subclass.integer != IAX_COMMAND_INVAL) &&
11510 (f.subclass.integer != IAX_COMMAND_VNAK)) {
11511 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11512 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11513 }
11514 ast_mutex_unlock(&iaxsl[fr->callno]);
11515 return 1;
11516 }
11517
11518 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11519 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11520 } else if (minivid) {
11521 f.frametype = AST_FRAME_VIDEO;
11522 if (iaxs[fr->callno]->videoformat > 0)
11523 f.subclass.codec = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000LL ? 1 : 0);
11524 else {
11525 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11526 iax2_vnak(fr->callno);
11527 ast_variables_destroy(ies.vars);
11528 ast_mutex_unlock(&iaxsl[fr->callno]);
11529 return 1;
11530 }
11531 f.datalen = res - sizeof(*vh);
11532 if (f.datalen)
11533 f.data.ptr = thread->buf + sizeof(*vh);
11534 else
11535 f.data.ptr = NULL;
11536 #ifdef IAXTESTS
11537 if (test_resync) {
11538 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11539 } else
11540 #endif
11541 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11542 } else {
11543
11544 f.frametype = AST_FRAME_VOICE;
11545 if (iaxs[fr->callno]->voiceformat > 0)
11546 f.subclass.codec = iaxs[fr->callno]->voiceformat;
11547 else {
11548 ast_debug(1, "Received mini frame before first full voice frame\n");
11549 iax2_vnak(fr->callno);
11550 ast_variables_destroy(ies.vars);
11551 ast_mutex_unlock(&iaxsl[fr->callno]);
11552 return 1;
11553 }
11554 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11555 if (f.datalen < 0) {
11556 ast_log(LOG_WARNING, "Datalen < 0?\n");
11557 ast_variables_destroy(ies.vars);
11558 ast_mutex_unlock(&iaxsl[fr->callno]);
11559 return 1;
11560 }
11561 if (f.datalen)
11562 f.data.ptr = thread->buf + sizeof(*mh);
11563 else
11564 f.data.ptr = NULL;
11565 #ifdef IAXTESTS
11566 if (test_resync) {
11567 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11568 } else
11569 #endif
11570 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11571
11572 }
11573
11574 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11575 ast_variables_destroy(ies.vars);
11576 ast_mutex_unlock(&iaxsl[fr->callno]);
11577 return 1;
11578 }
11579
11580 if (f.frametype == AST_FRAME_CONTROL && f.subclass.integer == AST_CONTROL_CONNECTED_LINE) {
11581 struct ast_party_connected_line connected;
11582
11583 if (!ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11584 ast_variables_destroy(ies.vars);
11585 ast_mutex_unlock(&iaxsl[fr->callno]);
11586 return 1;
11587 }
11588
11589
11590 ast_party_connected_line_init(&connected);
11591 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11592 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11593
11594 if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11595 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11596 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11597 iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11598
11599 if (iaxs[fr->callno]->owner) {
11600 ast_set_callerid(iaxs[fr->callno]->owner,
11601 S_COR(connected.id.number.valid, connected.id.number.str, ""),
11602 S_COR(connected.id.name.valid, connected.id.name.str, ""),
11603 NULL);
11604 iaxs[fr->callno]->owner->caller.id.number.presentation = connected.id.number.presentation;
11605 iaxs[fr->callno]->owner->caller.id.name.presentation = connected.id.name.presentation;
11606 }
11607 }
11608 ast_party_connected_line_free(&connected);
11609 }
11610
11611 f.src = "IAX2";
11612 f.mallocd = 0;
11613 f.offset = 0;
11614 f.len = 0;
11615 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11616 f.samples = ast_codec_get_samples(&f);
11617
11618 if (f.subclass.codec == AST_FORMAT_SLINEAR)
11619 ast_frame_byteswap_be(&f);
11620 } else
11621 f.samples = 0;
11622 iax_frame_wrap(fr, &f);
11623
11624
11625 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11626
11627 fr->outoforder = 0;
11628 } else {
11629 if (iaxdebug && iaxs[fr->callno])
11630 ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass.integer, fr->ts, iaxs[fr->callno]->last);
11631 fr->outoforder = -1;
11632 }
11633 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11634 duped_fr = iaxfrdup2(fr);
11635 if (duped_fr) {
11636 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11637 }
11638 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11639 iaxs[fr->callno]->last = fr->ts;
11640 #if 1
11641 if (iaxdebug)
11642 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11643 #endif
11644 }
11645
11646
11647 ast_variables_destroy(ies.vars);
11648 ast_mutex_unlock(&iaxsl[fr->callno]);
11649 return 1;
11650 }
11651
11652
11653 static void iax2_process_thread_cleanup(void *data)
11654 {
11655 struct iax2_thread *thread = data;
11656 ast_mutex_destroy(&thread->lock);
11657 ast_cond_destroy(&thread->cond);
11658 ast_mutex_destroy(&thread->init_lock);
11659 ast_cond_destroy(&thread->init_cond);
11660 ast_free(thread);
11661
11662 ast_atomic_dec_and_test(&iaxactivethreadcount);
11663 }
11664
11665 static void *iax2_process_thread(void *data)
11666 {
11667 struct iax2_thread *thread = data;
11668 struct timeval wait;
11669 struct timespec ts;
11670 int put_into_idle = 0;
11671 int first_time = 1;
11672 int old_state;
11673
11674 ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
11675
11676 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11677 pthread_cleanup_push(iax2_process_thread_cleanup, data);
11678
11679 for (;;) {
11680
11681 ast_mutex_lock(&thread->lock);
11682
11683 if (thread->stop) {
11684 ast_mutex_unlock(&thread->lock);
11685 break;
11686 }
11687
11688
11689 if (first_time) {
11690 signal_condition(&thread->init_lock, &thread->init_cond);
11691 first_time = 0;
11692 }
11693
11694
11695 if (put_into_idle) {
11696 insert_idle_thread(thread);
11697 }
11698
11699 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11700 struct iax2_thread *t = NULL;
11701
11702 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11703 ts.tv_sec = wait.tv_sec;
11704 ts.tv_nsec = wait.tv_usec * 1000;
11705 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11706
11707
11708 if (!put_into_idle || thread->stop) {
11709 ast_mutex_unlock(&thread->lock);
11710 break;
11711 }
11712 AST_LIST_LOCK(&dynamic_list);
11713
11714 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11715 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
11716 AST_LIST_UNLOCK(&dynamic_list);
11717 if (t) {
11718
11719
11720
11721 ast_mutex_unlock(&thread->lock);
11722 break;
11723 }
11724
11725
11726
11727 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11728 ts.tv_sec = wait.tv_sec;
11729 ts.tv_nsec = wait.tv_usec * 1000;
11730 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11731 ast_mutex_unlock(&thread->lock);
11732 break;
11733 }
11734 }
11735 } else {
11736 ast_cond_wait(&thread->cond, &thread->lock);
11737 }
11738
11739
11740 put_into_idle = 1;
11741
11742 ast_mutex_unlock(&thread->lock);
11743
11744 if (thread->stop) {
11745 break;
11746 }
11747
11748 if (thread->iostate == IAX_IOSTATE_IDLE)
11749 continue;
11750
11751
11752 switch (thread->iostate) {
11753 case IAX_IOSTATE_READY:
11754 thread->actions++;
11755 thread->iostate = IAX_IOSTATE_PROCESSING;
11756 socket_process(thread);
11757 handle_deferred_full_frames(thread);
11758 break;
11759 case IAX_IOSTATE_SCHEDREADY:
11760 thread->actions++;
11761 thread->iostate = IAX_IOSTATE_PROCESSING;
11762 #ifdef SCHED_MULTITHREADED
11763 thread->schedfunc(thread->scheddata);
11764 #endif
11765 default:
11766 break;
11767 }
11768 time(&thread->checktime);
11769 thread->iostate = IAX_IOSTATE_IDLE;
11770 #ifdef DEBUG_SCHED_MULTITHREAD
11771 thread->curfunc[0]='\0';
11772 #endif
11773
11774
11775
11776
11777 AST_LIST_LOCK(&active_list);
11778 AST_LIST_REMOVE(&active_list, thread, list);
11779 AST_LIST_UNLOCK(&active_list);
11780
11781
11782 handle_deferred_full_frames(thread);
11783 }
11784
11785
11786
11787
11788
11789
11790 AST_LIST_LOCK(&idle_list);
11791 AST_LIST_REMOVE(&idle_list, thread, list);
11792 AST_LIST_UNLOCK(&idle_list);
11793
11794 AST_LIST_LOCK(&dynamic_list);
11795 AST_LIST_REMOVE(&dynamic_list, thread, list);
11796 AST_LIST_UNLOCK(&dynamic_list);
11797
11798 if (!thread->stop) {
11799
11800 pthread_detach(pthread_self());
11801 }
11802
11803
11804
11805
11806 pthread_cleanup_pop(1);
11807 return NULL;
11808 }
11809
11810 static int iax2_do_register(struct iax2_registry *reg)
11811 {
11812 struct iax_ie_data ied;
11813 if (iaxdebug)
11814 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
11815
11816 if (reg->dnsmgr &&
11817 ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(®->addr))) {
11818
11819 ast_dnsmgr_refresh(reg->dnsmgr);
11820 }
11821
11822
11823
11824
11825
11826 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
11827 int callno = reg->callno;
11828 ast_mutex_lock(&iaxsl[callno]);
11829 iax2_destroy(callno);
11830 ast_mutex_unlock(&iaxsl[callno]);
11831 reg->callno = 0;
11832 }
11833 if (!ast_sockaddr_ipv4(®->addr)) {
11834 if (iaxdebug)
11835 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
11836
11837 reg->expire = iax2_sched_replace(reg->expire, sched,
11838 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11839 return -1;
11840 }
11841
11842 if (!reg->callno) {
11843 struct sockaddr_in reg_addr;
11844
11845 ast_debug(3, "Allocate call number\n");
11846
11847 ast_sockaddr_to_sin(®->addr, ®_addr);
11848
11849 reg->callno = find_callno_locked(0, 0, ®_addr, NEW_FORCE, defaultsockfd, 0);
11850 if (reg->callno < 1) {
11851 ast_log(LOG_WARNING, "Unable to create call for registration\n");
11852 return -1;
11853 } else
11854 ast_debug(3, "Registration created on call %d\n", reg->callno);
11855 iaxs[reg->callno]->reg = reg;
11856 ast_mutex_unlock(&iaxsl[reg->callno]);
11857 }
11858
11859 reg->expire = iax2_sched_replace(reg->expire, sched,
11860 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11861
11862 memset(&ied, 0, sizeof(ied));
11863 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
11864 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
11865 add_empty_calltoken_ie(iaxs[reg->callno], &ied);
11866 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
11867 reg->regstate = REG_STATE_REGSENT;
11868 return 0;
11869 }
11870
11871 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
11872 {
11873
11874
11875 struct iax_ie_data provdata;
11876 struct iax_ie_data ied;
11877 unsigned int sig;
11878 struct sockaddr_in sin;
11879 int callno;
11880 struct create_addr_info cai;
11881
11882 memset(&cai, 0, sizeof(cai));
11883
11884 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
11885
11886 if (iax_provision_build(&provdata, &sig, template, force)) {
11887 ast_debug(1, "No provisioning found for template '%s'\n", template);
11888 return 0;
11889 }
11890
11891 if (end) {
11892 memcpy(&sin, end, sizeof(sin));
11893 cai.sockfd = sockfd;
11894 } else if (create_addr(dest, NULL, &sin, &cai))
11895 return -1;
11896
11897
11898 memset(&ied, 0, sizeof(ied));
11899 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
11900
11901 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11902 if (!callno)
11903 return -1;
11904
11905 if (iaxs[callno]) {
11906
11907 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
11908 sched, 15000, auto_hangup, (void *)(long)callno);
11909 ast_set_flag64(iaxs[callno], IAX_PROVISION);
11910
11911 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
11912 }
11913 ast_mutex_unlock(&iaxsl[callno]);
11914
11915 return 1;
11916 }
11917
11918 static char *papp = "IAX2Provision";
11919
11920
11921
11922
11923 static int iax2_prov_app(struct ast_channel *chan, const char *data)
11924 {
11925 int res;
11926 char *sdata;
11927 char *opts;
11928 int force =0;
11929 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
11930 if (ast_strlen_zero(data))
11931 data = "default";
11932 sdata = ast_strdupa(data);
11933 opts = strchr(sdata, '|');
11934 if (opts)
11935 *opts='\0';
11936
11937 if (chan->tech != &iax2_tech) {
11938 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
11939 return -1;
11940 }
11941 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
11942 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
11943 return -1;
11944 }
11945 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
11946 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
11947 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
11948 sdata, res);
11949 return res;
11950 }
11951
11952 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11953 {
11954 int force = 0;
11955 int res;
11956
11957 switch (cmd) {
11958 case CLI_INIT:
11959 e->command = "iax2 provision";
11960 e->usage =
11961 "Usage: iax2 provision <host> <template> [forced]\n"
11962 " Provisions the given peer or IP address using a template\n"
11963 " matching either 'template' or '*' if the template is not\n"
11964 " found. If 'forced' is specified, even empty provisioning\n"
11965 " fields will be provisioned as empty fields.\n";
11966 return NULL;
11967 case CLI_GENERATE:
11968 if (a->pos == 3)
11969 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
11970 return NULL;
11971 }
11972
11973 if (a->argc < 4)
11974 return CLI_SHOWUSAGE;
11975 if (a->argc > 4) {
11976 if (!strcasecmp(a->argv[4], "forced"))
11977 force = 1;
11978 else
11979 return CLI_SHOWUSAGE;
11980 }
11981 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
11982 if (res < 0)
11983 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
11984 else if (res < 1)
11985 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
11986 else
11987 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
11988 return CLI_SUCCESS;
11989 }
11990
11991 static void __iax2_poke_noanswer(const void *data)
11992 {
11993 struct iax2_peer *peer = (struct iax2_peer *)data;
11994 int callno;
11995
11996 if (peer->lastms > -1) {
11997 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
11998 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
11999 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
12000 }
12001 if ((callno = peer->callno) > 0) {
12002 ast_mutex_lock(&iaxsl[callno]);
12003 iax2_destroy(callno);
12004 ast_mutex_unlock(&iaxsl[callno]);
12005 }
12006 peer->callno = 0;
12007 peer->lastms = -1;
12008
12009 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12010 if (peer->pokeexpire == -1)
12011 peer_unref(peer);
12012 }
12013
12014 static int iax2_poke_noanswer(const void *data)
12015 {
12016 struct iax2_peer *peer = (struct iax2_peer *)data;
12017 peer->pokeexpire = -1;
12018 #ifdef SCHED_MULTITHREADED
12019 if (schedule_action(__iax2_poke_noanswer, data))
12020 #endif
12021 __iax2_poke_noanswer(data);
12022 peer_unref(peer);
12023 return 0;
12024 }
12025
12026 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12027 {
12028 struct iax2_peer *peer = obj;
12029
12030 iax2_poke_peer(peer, 0);
12031
12032 return 0;
12033 }
12034
12035 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12036 {
12037 int callno;
12038 struct sockaddr_in peer_addr;
12039
12040 if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
12041
12042
12043 peer->lastms = 0;
12044 peer->historicms = 0;
12045 peer->pokeexpire = -1;
12046 peer->callno = 0;
12047 return 0;
12048 }
12049
12050 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
12051
12052
12053 if ((callno = peer->callno) > 0) {
12054 ast_log(LOG_NOTICE, "Still have a callno...\n");
12055 ast_mutex_lock(&iaxsl[callno]);
12056 iax2_destroy(callno);
12057 ast_mutex_unlock(&iaxsl[callno]);
12058 }
12059 if (heldcall)
12060 ast_mutex_unlock(&iaxsl[heldcall]);
12061 callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
12062 if (heldcall)
12063 ast_mutex_lock(&iaxsl[heldcall]);
12064 if (peer->callno < 1) {
12065 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12066 return -1;
12067 }
12068
12069
12070 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
12071 iaxs[peer->callno]->peerpoke = peer;
12072
12073 if (peer->pokeexpire > -1) {
12074 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
12075 peer->pokeexpire = -1;
12076 peer_unref(peer);
12077 }
12078 }
12079
12080
12081
12082 if (peer->lastms < 0)
12083 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
12084 else
12085 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
12086
12087 if (peer->pokeexpire == -1)
12088 peer_unref(peer);
12089
12090
12091 ast_mutex_lock(&iaxsl[callno]);
12092 if (iaxs[callno]) {
12093 struct iax_ie_data ied = {
12094 .buf = { 0 },
12095 .pos = 0,
12096 };
12097 add_empty_calltoken_ie(iaxs[callno], &ied);
12098 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12099 }
12100 ast_mutex_unlock(&iaxsl[callno]);
12101
12102 return 0;
12103 }
12104
12105 static void free_context(struct iax2_context *con)
12106 {
12107 struct iax2_context *conl;
12108 while(con) {
12109 conl = con;
12110 con = con->next;
12111 ast_free(conl);
12112 }
12113 }
12114
12115 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
12116 {
12117 int callno;
12118 int res;
12119 format_t fmt, native;
12120 struct sockaddr_in sin;
12121 struct ast_channel *c;
12122 struct parsed_dial_string pds;
12123 struct create_addr_info cai;
12124 char *tmpstr;
12125
12126 memset(&pds, 0, sizeof(pds));
12127 tmpstr = ast_strdupa(data);
12128 parse_dial_string(tmpstr, &pds);
12129
12130 if (ast_strlen_zero(pds.peer)) {
12131 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
12132 return NULL;
12133 }
12134
12135 memset(&cai, 0, sizeof(cai));
12136 cai.capability = iax2_capability;
12137
12138 ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12139
12140
12141 if (create_addr(pds.peer, NULL, &sin, &cai)) {
12142 *cause = AST_CAUSE_UNREGISTERED;
12143 return NULL;
12144 }
12145
12146 if (pds.port)
12147 sin.sin_port = htons(atoi(pds.port));
12148
12149 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12150 if (callno < 1) {
12151 ast_log(LOG_WARNING, "Unable to create call\n");
12152 *cause = AST_CAUSE_CONGESTION;
12153 return NULL;
12154 }
12155
12156
12157 ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12158 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12159 int new_callno;
12160 if ((new_callno = make_trunk(callno, 1)) != -1)
12161 callno = new_callno;
12162 }
12163 iaxs[callno]->maxtime = cai.maxtime;
12164 if (cai.found)
12165 ast_string_field_set(iaxs[callno], host, pds.peer);
12166
12167 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? requestor->linkedid : NULL);
12168
12169 ast_mutex_unlock(&iaxsl[callno]);
12170
12171 if (c) {
12172
12173 if (c->nativeformats & format)
12174 c->nativeformats &= format;
12175 else {
12176 native = c->nativeformats;
12177 fmt = format;
12178 res = ast_translator_best_choice(&fmt, &native);
12179 if (res < 0) {
12180 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12181 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
12182 ast_hangup(c);
12183 return NULL;
12184 }
12185 c->nativeformats = native;
12186 }
12187 c->readformat = ast_best_codec(c->nativeformats);
12188 c->writeformat = c->readformat;
12189 }
12190
12191 return c;
12192 }
12193
12194 static void *network_thread(void *ignore)
12195 {
12196 if (timer) {
12197 ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12198 }
12199
12200 for (;;) {
12201 pthread_testcancel();
12202
12203
12204
12205 ast_io_wait(io, 1000);
12206 }
12207
12208 return NULL;
12209 }
12210
12211 static int start_network_thread(void)
12212 {
12213 struct iax2_thread *thread;
12214 int threadcount = 0;
12215 int x;
12216 for (x = 0; x < iaxthreadcount; x++) {
12217 thread = ast_calloc(1, sizeof(*thread));
12218 if (thread) {
12219 thread->type = IAX_THREAD_TYPE_POOL;
12220 thread->threadnum = ++threadcount;
12221 ast_mutex_init(&thread->lock);
12222 ast_cond_init(&thread->cond, NULL);
12223 ast_mutex_init(&thread->init_lock);
12224 ast_cond_init(&thread->init_cond, NULL);
12225 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12226 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12227 ast_mutex_destroy(&thread->lock);
12228 ast_cond_destroy(&thread->cond);
12229 ast_mutex_destroy(&thread->init_lock);
12230 ast_cond_destroy(&thread->init_cond);
12231 ast_free(thread);
12232 thread = NULL;
12233 continue;
12234 }
12235 AST_LIST_LOCK(&idle_list);
12236 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12237 AST_LIST_UNLOCK(&idle_list);
12238 }
12239 }
12240 if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
12241 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12242 return -1;
12243 }
12244 ast_verb(2, "%d helper threads started\n", threadcount);
12245 return 0;
12246 }
12247
12248 static struct iax2_context *build_context(const char *context)
12249 {
12250 struct iax2_context *con;
12251
12252 if ((con = ast_calloc(1, sizeof(*con))))
12253 ast_copy_string(con->context, context, sizeof(con->context));
12254
12255 return con;
12256 }
12257
12258 static int get_auth_methods(const char *value)
12259 {
12260 int methods = 0;
12261 if (strstr(value, "rsa"))
12262 methods |= IAX_AUTH_RSA;
12263 if (strstr(value, "md5"))
12264 methods |= IAX_AUTH_MD5;
12265 if (strstr(value, "plaintext"))
12266 methods |= IAX_AUTH_PLAINTEXT;
12267 return methods;
12268 }
12269
12270
12271
12272
12273
12274 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
12275 {
12276 int sd;
12277 int res;
12278
12279 sd = socket(AF_INET, SOCK_DGRAM, 0);
12280 if (sd < 0) {
12281 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12282 return -1;
12283 }
12284
12285 res = bind(sd, sa, salen);
12286 if (res < 0) {
12287 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12288 close(sd);
12289 return 1;
12290 }
12291
12292 close(sd);
12293 return 0;
12294 }
12295
12296
12297
12298
12299 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12300 {
12301 struct sockaddr_in sin;
12302 struct ast_sockaddr sin_tmp;
12303 int nonlocal = 1;
12304 int port = IAX_DEFAULT_PORTNO;
12305 int sockfd = defaultsockfd;
12306 char *tmp;
12307 char *addr;
12308 char *portstr;
12309
12310 if (!(tmp = ast_strdupa(srcaddr)))
12311 return -1;
12312
12313 addr = strsep(&tmp, ":");
12314 portstr = tmp;
12315
12316 if (portstr) {
12317 port = atoi(portstr);
12318 if (port < 1)
12319 port = IAX_DEFAULT_PORTNO;
12320 }
12321
12322 sin_tmp.ss.ss_family = AF_INET;
12323 if (!ast_get_ip(&sin_tmp, addr)) {
12324 struct ast_netsock *sock;
12325 int res;
12326
12327 ast_sockaddr_to_sin(&sin_tmp, &sin);
12328 sin.sin_port = 0;
12329 sin.sin_family = AF_INET;
12330 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
12331 if (res == 0) {
12332
12333 sin.sin_port = htons(port);
12334 if (!(sock = ast_netsock_find(netsock, &sin)))
12335 sock = ast_netsock_find(outsock, &sin);
12336 if (sock) {
12337 sockfd = ast_netsock_sockfd(sock);
12338 nonlocal = 0;
12339 } else {
12340 unsigned int orig_saddr = sin.sin_addr.s_addr;
12341
12342 sin.sin_addr.s_addr = INADDR_ANY;
12343 if (ast_netsock_find(netsock, &sin)) {
12344 sin.sin_addr.s_addr = orig_saddr;
12345 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12346 if (sock) {
12347 sockfd = ast_netsock_sockfd(sock);
12348 ast_netsock_unref(sock);
12349 nonlocal = 0;
12350 } else {
12351 nonlocal = 2;
12352 }
12353 }
12354 }
12355 }
12356 }
12357
12358 peer->sockfd = sockfd;
12359
12360 if (nonlocal == 1) {
12361 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12362 srcaddr, peer->name);
12363 return -1;
12364 } else if (nonlocal == 2) {
12365 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12366 srcaddr, peer->name);
12367 return -1;
12368 } else {
12369 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12370 return 0;
12371 }
12372 }
12373
12374 static void peer_destructor(void *obj)
12375 {
12376 struct iax2_peer *peer = obj;
12377 int callno = peer->callno;
12378
12379 ast_free_ha(peer->ha);
12380
12381 if (callno > 0) {
12382 ast_mutex_lock(&iaxsl[callno]);
12383 iax2_destroy(callno);
12384 ast_mutex_unlock(&iaxsl[callno]);
12385 }
12386
12387 register_peer_exten(peer, 0);
12388
12389 if (peer->dnsmgr)
12390 ast_dnsmgr_release(peer->dnsmgr);
12391
12392 if (peer->mwi_event_sub)
12393 ast_event_unsubscribe(peer->mwi_event_sub);
12394
12395 ast_string_field_free_memory(peer);
12396 }
12397
12398
12399 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12400 {
12401 struct iax2_peer *peer = NULL;
12402 struct ast_ha *oldha = NULL;
12403 int maskfound = 0;
12404 int found = 0;
12405 int firstpass = 1;
12406 struct iax2_peer tmp_peer = {
12407 .name = name,
12408 };
12409
12410 if (!temponly) {
12411 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
12412 if (peer && !ast_test_flag64(peer, IAX_DELME))
12413 firstpass = 0;
12414 }
12415
12416 if (peer) {
12417 found++;
12418 if (firstpass) {
12419 oldha = peer->ha;
12420 peer->ha = NULL;
12421 }
12422 unlink_peer(peer);
12423 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12424 peer->expire = -1;
12425 peer->pokeexpire = -1;
12426 peer->sockfd = defaultsockfd;
12427 peer->addr.ss.ss_family = AF_INET;
12428 peer->addr.len = sizeof(struct sockaddr_in);
12429 if (ast_string_field_init(peer, 32))
12430 peer = peer_unref(peer);
12431 }
12432
12433 if (peer) {
12434 if (firstpass) {
12435 ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12436 peer->encmethods = iax2_encryption;
12437 peer->adsi = adsi;
12438 ast_string_field_set(peer,secret,"");
12439 if (!found) {
12440 ast_string_field_set(peer, name, name);
12441 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12442 peer->expiry = min_reg_expire;
12443 }
12444 peer->prefs = prefs;
12445 peer->capability = iax2_capability;
12446 peer->smoothing = 0;
12447 peer->pokefreqok = DEFAULT_FREQ_OK;
12448 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
12449 peer->maxcallno = 0;
12450 peercnt_modify(0, 0, &peer->addr);
12451 peer->calltoken_required = CALLTOKEN_DEFAULT;
12452 ast_string_field_set(peer,context,"");
12453 ast_string_field_set(peer,peercontext,"");
12454 ast_clear_flag64(peer, IAX_HASCALLERID);
12455 ast_string_field_set(peer, cid_name, "");
12456 ast_string_field_set(peer, cid_num, "");
12457 ast_string_field_set(peer, mohinterpret, mohinterpret);
12458 ast_string_field_set(peer, mohsuggest, mohsuggest);
12459 }
12460
12461 if (!v) {
12462 v = alt;
12463 alt = NULL;
12464 }
12465 while(v) {
12466 if (!strcasecmp(v->name, "secret")) {
12467 ast_string_field_set(peer, secret, v->value);
12468 } else if (!strcasecmp(v->name, "mailbox")) {
12469 ast_string_field_set(peer, mailbox, v->value);
12470 } else if (!strcasecmp(v->name, "hasvoicemail")) {
12471 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12472 ast_string_field_set(peer, mailbox, name);
12473 }
12474 } else if (!strcasecmp(v->name, "mohinterpret")) {
12475 ast_string_field_set(peer, mohinterpret, v->value);
12476 } else if (!strcasecmp(v->name, "mohsuggest")) {
12477 ast_string_field_set(peer, mohsuggest, v->value);
12478 } else if (!strcasecmp(v->name, "dbsecret")) {
12479 ast_string_field_set(peer, dbsecret, v->value);
12480 } else if (!strcasecmp(v->name, "trunk")) {
12481 ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK);
12482 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12483 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12484 ast_clear_flag64(peer, IAX_TRUNK);
12485 }
12486 } else if (!strcasecmp(v->name, "auth")) {
12487 peer->authmethods = get_auth_methods(v->value);
12488 } else if (!strcasecmp(v->name, "encryption")) {
12489 peer->encmethods |= get_encrypt_methods(v->value);
12490 if (!peer->encmethods) {
12491 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12492 }
12493 } else if (!strcasecmp(v->name, "forceencryption")) {
12494 if (ast_false(v->value)) {
12495 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12496 } else {
12497 peer->encmethods |= get_encrypt_methods(v->value);
12498 if (peer->encmethods) {
12499 ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
12500 }
12501 }
12502 } else if (!strcasecmp(v->name, "transfer")) {
12503 if (!strcasecmp(v->value, "mediaonly")) {
12504 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12505 } else if (ast_true(v->value)) {
12506 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12507 } else
12508 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12509 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12510 ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
12511 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12512 ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12513 } else if (!strcasecmp(v->name, "host")) {
12514 if (!strcasecmp(v->value, "dynamic")) {
12515
12516 ast_set_flag64(peer, IAX_DYNAMIC);
12517 if (!found) {
12518
12519
12520 if (ast_sockaddr_port(&peer->addr)) {
12521 peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12522 }
12523 ast_sockaddr_setnull(&peer->addr);
12524 }
12525 } else {
12526
12527 ast_sched_thread_del(sched, peer->expire);
12528 ast_clear_flag64(peer, IAX_DYNAMIC);
12529 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12530 return peer_unref(peer);
12531 if (!ast_sockaddr_port(&peer->addr)) {
12532 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12533 }
12534 }
12535 if (!maskfound)
12536 inet_aton("255.255.255.255", &peer->mask);
12537 } else if (!strcasecmp(v->name, "defaultip")) {
12538 struct ast_sockaddr peer_defaddr_tmp;
12539
12540 peer_defaddr_tmp.ss.ss_family = AF_INET;
12541 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12542 return peer_unref(peer);
12543 }
12544 ast_sockaddr_to_sin(&peer_defaddr_tmp,
12545 &peer->defaddr);
12546 } else if (!strcasecmp(v->name, "sourceaddress")) {
12547 peer_set_srcaddr(peer, v->value);
12548 } else if (!strcasecmp(v->name, "permit") ||
12549 !strcasecmp(v->name, "deny")) {
12550 peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12551 } else if (!strcasecmp(v->name, "mask")) {
12552 maskfound++;
12553 inet_aton(v->value, &peer->mask);
12554 } else if (!strcasecmp(v->name, "context")) {
12555 ast_string_field_set(peer, context, v->value);
12556 } else if (!strcasecmp(v->name, "regexten")) {
12557 ast_string_field_set(peer, regexten, v->value);
12558 } else if (!strcasecmp(v->name, "peercontext")) {
12559 ast_string_field_set(peer, peercontext, v->value);
12560 } else if (!strcasecmp(v->name, "port")) {
12561 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12562 peer->defaddr.sin_port = htons(atoi(v->value));
12563 } else {
12564 ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12565 }
12566 } else if (!strcasecmp(v->name, "username")) {
12567 ast_string_field_set(peer, username, v->value);
12568 } else if (!strcasecmp(v->name, "allow")) {
12569 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12570 } else if (!strcasecmp(v->name, "disallow")) {
12571 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12572 } else if (!strcasecmp(v->name, "callerid")) {
12573 if (!ast_strlen_zero(v->value)) {
12574 char name2[80];
12575 char num2[80];
12576 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12577 ast_string_field_set(peer, cid_name, name2);
12578 ast_string_field_set(peer, cid_num, num2);
12579 } else {
12580 ast_string_field_set(peer, cid_name, "");
12581 ast_string_field_set(peer, cid_num, "");
12582 }
12583 ast_set_flag64(peer, IAX_HASCALLERID);
12584 } else if (!strcasecmp(v->name, "fullname")) {
12585 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12586 ast_set_flag64(peer, IAX_HASCALLERID);
12587 } else if (!strcasecmp(v->name, "cid_number")) {
12588 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12589 ast_set_flag64(peer, IAX_HASCALLERID);
12590 } else if (!strcasecmp(v->name, "sendani")) {
12591 ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
12592 } else if (!strcasecmp(v->name, "inkeys")) {
12593 ast_string_field_set(peer, inkeys, v->value);
12594 } else if (!strcasecmp(v->name, "outkey")) {
12595 ast_string_field_set(peer, outkey, v->value);
12596 } else if (!strcasecmp(v->name, "qualify")) {
12597 if (!strcasecmp(v->value, "no")) {
12598 peer->maxms = 0;
12599 } else if (!strcasecmp(v->value, "yes")) {
12600 peer->maxms = DEFAULT_MAXMS;
12601 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12602 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);
12603 peer->maxms = 0;
12604 }
12605 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12606 peer->smoothing = ast_true(v->value);
12607 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12608 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12609 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);
12610 }
12611 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12612 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12613 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);
12614 }
12615 } else if (!strcasecmp(v->name, "timezone")) {
12616 ast_string_field_set(peer, zonetag, v->value);
12617 } else if (!strcasecmp(v->name, "adsi")) {
12618 peer->adsi = ast_true(v->value);
12619 } else if (!strcasecmp(v->name, "connectedline")) {
12620 if (ast_true(v->value)) {
12621 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12622 } else if (!strcasecmp(v->value, "send")) {
12623 ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
12624 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
12625 } else if (!strcasecmp(v->value, "receive")) {
12626 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
12627 ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
12628 } else {
12629 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12630 }
12631 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12632 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12633 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12634 } else {
12635 peercnt_modify(1, peer->maxcallno, &peer->addr);
12636 }
12637 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12638
12639 if (ast_false(v->value)) {
12640 peer->calltoken_required = CALLTOKEN_NO;
12641 } else if (!strcasecmp(v->value, "auto")) {
12642 peer->calltoken_required = CALLTOKEN_AUTO;
12643 } else if (ast_true(v->value)) {
12644 peer->calltoken_required = CALLTOKEN_YES;
12645 } else {
12646 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12647 }
12648 }
12649
12650 v = v->next;
12651 if (!v) {
12652 v = alt;
12653 alt = NULL;
12654 }
12655 }
12656 if (!peer->authmethods)
12657 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12658 ast_clear_flag64(peer, IAX_DELME);
12659 }
12660
12661 if (oldha)
12662 ast_free_ha(oldha);
12663
12664 if (!ast_strlen_zero(peer->mailbox)) {
12665 char *mailbox, *context;
12666 context = mailbox = ast_strdupa(peer->mailbox);
12667 strsep(&context, "@");
12668 if (ast_strlen_zero(context))
12669 context = "default";
12670 peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
12671 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12672 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12673 AST_EVENT_IE_END);
12674 }
12675
12676 return peer;
12677 }
12678
12679 static void user_destructor(void *obj)
12680 {
12681 struct iax2_user *user = obj;
12682
12683 ast_free_ha(user->ha);
12684 free_context(user->contexts);
12685 if(user->vars) {
12686 ast_variables_destroy(user->vars);
12687 user->vars = NULL;
12688 }
12689 ast_string_field_free_memory(user);
12690 }
12691
12692
12693 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12694 {
12695 struct iax2_user *user = NULL;
12696 struct iax2_context *con, *conl = NULL;
12697 struct ast_ha *oldha = NULL;
12698 struct iax2_context *oldcon = NULL;
12699 int format;
12700 int firstpass=1;
12701 int oldcurauthreq = 0;
12702 char *varname = NULL, *varval = NULL;
12703 struct ast_variable *tmpvar = NULL;
12704 struct iax2_user tmp_user = {
12705 .name = name,
12706 };
12707
12708 if (!temponly) {
12709 user = ao2_find(users, &tmp_user, OBJ_POINTER);
12710 if (user && !ast_test_flag64(user, IAX_DELME))
12711 firstpass = 0;
12712 }
12713
12714 if (user) {
12715 if (firstpass) {
12716 oldcurauthreq = user->curauthreq;
12717 oldha = user->ha;
12718 oldcon = user->contexts;
12719 user->ha = NULL;
12720 user->contexts = NULL;
12721 }
12722
12723 ao2_unlink(users, user);
12724 } else {
12725 user = ao2_alloc(sizeof(*user), user_destructor);
12726 }
12727
12728 if (user) {
12729 if (firstpass) {
12730 ast_string_field_free_memory(user);
12731 memset(user, 0, sizeof(struct iax2_user));
12732 if (ast_string_field_init(user, 32)) {
12733 user = user_unref(user);
12734 goto cleanup;
12735 }
12736 user->maxauthreq = maxauthreq;
12737 user->curauthreq = oldcurauthreq;
12738 user->prefs = prefs;
12739 user->capability = iax2_capability;
12740 user->encmethods = iax2_encryption;
12741 user->adsi = adsi;
12742 user->calltoken_required = CALLTOKEN_DEFAULT;
12743 ast_string_field_set(user, name, name);
12744 ast_string_field_set(user, language, language);
12745 ast_copy_flags64(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12746 ast_clear_flag64(user, IAX_HASCALLERID);
12747 ast_string_field_set(user, cid_name, "");
12748 ast_string_field_set(user, cid_num, "");
12749 ast_string_field_set(user, accountcode, accountcode);
12750 ast_string_field_set(user, mohinterpret, mohinterpret);
12751 ast_string_field_set(user, mohsuggest, mohsuggest);
12752 }
12753 if (!v) {
12754 v = alt;
12755 alt = NULL;
12756 }
12757 while(v) {
12758 if (!strcasecmp(v->name, "context")) {
12759 con = build_context(v->value);
12760 if (con) {
12761 if (conl)
12762 conl->next = con;
12763 else
12764 user->contexts = con;
12765 conl = con;
12766 }
12767 } else if (!strcasecmp(v->name, "permit") ||
12768 !strcasecmp(v->name, "deny")) {
12769 user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12770 } else if (!strcasecmp(v->name, "setvar")) {
12771 varname = ast_strdupa(v->value);
12772 if (varname && (varval = strchr(varname,'='))) {
12773 *varval = '\0';
12774 varval++;
12775 if((tmpvar = ast_variable_new(varname, varval, ""))) {
12776 tmpvar->next = user->vars;
12777 user->vars = tmpvar;
12778 }
12779 }
12780 } else if (!strcasecmp(v->name, "allow")) {
12781 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
12782 } else if (!strcasecmp(v->name, "disallow")) {
12783 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
12784 } else if (!strcasecmp(v->name, "trunk")) {
12785 ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK);
12786 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
12787 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
12788 ast_clear_flag64(user, IAX_TRUNK);
12789 }
12790 } else if (!strcasecmp(v->name, "auth")) {
12791 user->authmethods = get_auth_methods(v->value);
12792 } else if (!strcasecmp(v->name, "encryption")) {
12793 user->encmethods |= get_encrypt_methods(v->value);
12794 if (!user->encmethods) {
12795 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12796 }
12797 } else if (!strcasecmp(v->name, "forceencryption")) {
12798 if (ast_false(v->value)) {
12799 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12800 } else {
12801 user->encmethods |= get_encrypt_methods(v->value);
12802 if (user->encmethods) {
12803 ast_set_flag64(user, IAX_FORCE_ENCRYPT);
12804 }
12805 }
12806 } else if (!strcasecmp(v->name, "transfer")) {
12807 if (!strcasecmp(v->value, "mediaonly")) {
12808 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12809 } else if (ast_true(v->value)) {
12810 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12811 } else
12812 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12813 } else if (!strcasecmp(v->name, "codecpriority")) {
12814 if(!strcasecmp(v->value, "caller"))
12815 ast_set_flag64(user, IAX_CODEC_USER_FIRST);
12816 else if(!strcasecmp(v->value, "disabled"))
12817 ast_set_flag64(user, IAX_CODEC_NOPREFS);
12818 else if(!strcasecmp(v->value, "reqonly")) {
12819 ast_set_flag64(user, IAX_CODEC_NOCAP);
12820 ast_set_flag64(user, IAX_CODEC_NOPREFS);
12821 }
12822 } else if (!strcasecmp(v->name, "immediate")) {
12823 ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
12824 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12825 ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
12826 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12827 ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
12828 } else if (!strcasecmp(v->name, "dbsecret")) {
12829 ast_string_field_set(user, dbsecret, v->value);
12830 } else if (!strcasecmp(v->name, "secret")) {
12831 if (!ast_strlen_zero(user->secret)) {
12832 char *old = ast_strdupa(user->secret);
12833
12834 ast_string_field_build(user, secret, "%s;%s", old, v->value);
12835 } else
12836 ast_string_field_set(user, secret, v->value);
12837 } else if (!strcasecmp(v->name, "callerid")) {
12838 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
12839 char name2[80];
12840 char num2[80];
12841 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12842 ast_string_field_set(user, cid_name, name2);
12843 ast_string_field_set(user, cid_num, num2);
12844 ast_set_flag64(user, IAX_HASCALLERID);
12845 } else {
12846 ast_clear_flag64(user, IAX_HASCALLERID);
12847 ast_string_field_set(user, cid_name, "");
12848 ast_string_field_set(user, cid_num, "");
12849 }
12850 } else if (!strcasecmp(v->name, "fullname")) {
12851 if (!ast_strlen_zero(v->value)) {
12852 ast_string_field_set(user, cid_name, v->value);
12853 ast_set_flag64(user, IAX_HASCALLERID);
12854 } else {
12855 ast_string_field_set(user, cid_name, "");
12856 if (ast_strlen_zero(user->cid_num))
12857 ast_clear_flag64(user, IAX_HASCALLERID);
12858 }
12859 } else if (!strcasecmp(v->name, "cid_number")) {
12860 if (!ast_strlen_zero(v->value)) {
12861 ast_string_field_set(user, cid_num, v->value);
12862 ast_set_flag64(user, IAX_HASCALLERID);
12863 } else {
12864 ast_string_field_set(user, cid_num, "");
12865 if (ast_strlen_zero(user->cid_name))
12866 ast_clear_flag64(user, IAX_HASCALLERID);
12867 }
12868 } else if (!strcasecmp(v->name, "accountcode")) {
12869 ast_string_field_set(user, accountcode, v->value);
12870 } else if (!strcasecmp(v->name, "mohinterpret")) {
12871 ast_string_field_set(user, mohinterpret, v->value);
12872 } else if (!strcasecmp(v->name, "mohsuggest")) {
12873 ast_string_field_set(user, mohsuggest, v->value);
12874 } else if (!strcasecmp(v->name, "parkinglot")) {
12875 ast_string_field_set(user, parkinglot, v->value);
12876 } else if (!strcasecmp(v->name, "language")) {
12877 ast_string_field_set(user, language, v->value);
12878 } else if (!strcasecmp(v->name, "amaflags")) {
12879 format = ast_cdr_amaflags2int(v->value);
12880 if (format < 0) {
12881 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12882 } else {
12883 user->amaflags = format;
12884 }
12885 } else if (!strcasecmp(v->name, "inkeys")) {
12886 ast_string_field_set(user, inkeys, v->value);
12887 } else if (!strcasecmp(v->name, "maxauthreq")) {
12888 user->maxauthreq = atoi(v->value);
12889 if (user->maxauthreq < 0)
12890 user->maxauthreq = 0;
12891 } else if (!strcasecmp(v->name, "adsi")) {
12892 user->adsi = ast_true(v->value);
12893 } else if (!strcasecmp(v->name, "connectedline")) {
12894 if (ast_true(v->value)) {
12895 ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12896 } else if (!strcasecmp(v->value, "send")) {
12897 ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
12898 ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
12899 } else if (!strcasecmp(v->value, "receive")) {
12900 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
12901 ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
12902 } else {
12903 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12904 }
12905 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12906
12907 if (ast_false(v->value)) {
12908 user->calltoken_required = CALLTOKEN_NO;
12909 } else if (!strcasecmp(v->value, "auto")) {
12910 user->calltoken_required = CALLTOKEN_AUTO;
12911 } else if (ast_true(v->value)) {
12912 user->calltoken_required = CALLTOKEN_YES;
12913 } else {
12914 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12915 }
12916 }
12917
12918 v = v->next;
12919 if (!v) {
12920 v = alt;
12921 alt = NULL;
12922 }
12923 }
12924 if (!user->authmethods) {
12925 if (!ast_strlen_zero(user->secret)) {
12926 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12927 if (!ast_strlen_zero(user->inkeys))
12928 user->authmethods |= IAX_AUTH_RSA;
12929 } else if (!ast_strlen_zero(user->inkeys)) {
12930 user->authmethods = IAX_AUTH_RSA;
12931 } else {
12932 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12933 }
12934 }
12935 ast_clear_flag64(user, IAX_DELME);
12936 }
12937 cleanup:
12938 if (oldha)
12939 ast_free_ha(oldha);
12940 if (oldcon)
12941 free_context(oldcon);
12942 return user;
12943 }
12944
12945 static int peer_delme_cb(void *obj, void *arg, int flags)
12946 {
12947 struct iax2_peer *peer = obj;
12948
12949 ast_set_flag64(peer, IAX_DELME);
12950
12951 return 0;
12952 }
12953
12954 static int user_delme_cb(void *obj, void *arg, int flags)
12955 {
12956 struct iax2_user *user = obj;
12957
12958 ast_set_flag64(user, IAX_DELME);
12959
12960 return 0;
12961 }
12962
12963 static void delete_users(void)
12964 {
12965 struct iax2_registry *reg;
12966
12967 ao2_callback(users, 0, user_delme_cb, NULL);
12968
12969 AST_LIST_LOCK(®istrations);
12970 while ((reg = AST_LIST_REMOVE_HEAD(®istrations, entry))) {
12971 if (sched) {
12972 ast_sched_thread_del(sched, reg->expire);
12973 }
12974 if (reg->callno) {
12975 int callno = reg->callno;
12976 ast_mutex_lock(&iaxsl[callno]);
12977 if (iaxs[callno]) {
12978 iaxs[callno]->reg = NULL;
12979 iax2_destroy(callno);
12980 }
12981 ast_mutex_unlock(&iaxsl[callno]);
12982 }
12983 if (reg->dnsmgr)
12984 ast_dnsmgr_release(reg->dnsmgr);
12985 ast_free(reg);
12986 }
12987 AST_LIST_UNLOCK(®istrations);
12988
12989 ao2_callback(peers, 0, peer_delme_cb, NULL);
12990 }
12991
12992 static void prune_users(void)
12993 {
12994 struct iax2_user *user;
12995 struct ao2_iterator i;
12996
12997 i = ao2_iterator_init(users, 0);
12998 while ((user = ao2_iterator_next(&i))) {
12999 if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
13000 ao2_unlink(users, user);
13001 }
13002 user_unref(user);
13003 }
13004 ao2_iterator_destroy(&i);
13005 }
13006
13007
13008 static void prune_peers(void)
13009 {
13010 struct iax2_peer *peer;
13011 struct ao2_iterator i;
13012
13013 i = ao2_iterator_init(peers, 0);
13014 while ((peer = ao2_iterator_next(&i))) {
13015 if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
13016 unlink_peer(peer);
13017 }
13018 peer_unref(peer);
13019 }
13020 ao2_iterator_destroy(&i);
13021 }
13022
13023 static void set_config_destroy(void)
13024 {
13025 strcpy(accountcode, "");
13026 strcpy(language, "");
13027 strcpy(mohinterpret, "");
13028 strcpy(mohsuggest, "");
13029 trunkmaxsize = MAX_TRUNKDATA;
13030 amaflags = 0;
13031 delayreject = 0;
13032 ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
13033 IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13034 delete_users();
13035 ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13036 ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13037 }
13038
13039
13040 static int set_config(const char *config_file, int reload)
13041 {
13042 struct ast_config *cfg, *ucfg;
13043 format_t capability = iax2_capability;
13044 struct ast_variable *v;
13045 char *cat;
13046 const char *utype;
13047 const char *tosval;
13048 int format;
13049 int portno = IAX_DEFAULT_PORTNO;
13050 int x;
13051 int mtuv;
13052 int subscribe_network_change = 1;
13053 struct iax2_user *user;
13054 struct iax2_peer *peer;
13055 struct ast_netsock *ns;
13056 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13057 #if 0
13058 static unsigned short int last_port=0;
13059 #endif
13060
13061 cfg = ast_config_load(config_file, config_flags);
13062
13063 if (!cfg) {
13064 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13065 return -1;
13066 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13067 ucfg = ast_config_load("users.conf", config_flags);
13068 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13069 return 0;
13070
13071 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13072 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13073 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13074 ast_config_destroy(ucfg);
13075 return 0;
13076 }
13077 if (!cfg) {
13078
13079 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13080 return -1;
13081 }
13082 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13083 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13084 return 0;
13085 } else {
13086 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13087 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13088 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13089 ast_config_destroy(cfg);
13090 return 0;
13091 }
13092 }
13093
13094 if (reload) {
13095 set_config_destroy();
13096 }
13097
13098
13099 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
13100
13101
13102 memset(&globalflags, 0, sizeof(globalflags));
13103 ast_set_flag64(&globalflags, IAX_RTUPDATE);
13104 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13105
13106 #ifdef SO_NO_CHECK
13107 nochecksums = 0;
13108 #endif
13109
13110 default_parkinglot[0] = '\0';
13111
13112 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13113 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13114 global_max_trunk_mtu = MAX_TRUNK_MTU;
13115 global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13116 global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13117
13118 maxauthreq = 3;
13119
13120 srvlookup = 0;
13121
13122 v = ast_variable_browse(cfg, "general");
13123
13124
13125 tosval = ast_variable_retrieve(cfg, "general", "tos");
13126 if (tosval) {
13127 if (ast_str2tos(tosval, &qos.tos))
13128 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13129 }
13130
13131 tosval = ast_variable_retrieve(cfg, "general", "cos");
13132 if (tosval) {
13133 if (ast_str2cos(tosval, &qos.cos))
13134 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13135 }
13136 while(v) {
13137 if (!strcasecmp(v->name, "bindport")){
13138 if (reload)
13139 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13140 else
13141 portno = atoi(v->value);
13142 } else if (!strcasecmp(v->name, "pingtime"))
13143 ping_time = atoi(v->value);
13144 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13145 if (reload) {
13146 if (atoi(v->value) != iaxthreadcount)
13147 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13148 } else {
13149 iaxthreadcount = atoi(v->value);
13150 if (iaxthreadcount < 1) {
13151 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13152 iaxthreadcount = 1;
13153 } else if (iaxthreadcount > 256) {
13154 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13155 iaxthreadcount = 256;
13156 }
13157 }
13158 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13159 if (reload) {
13160 AST_LIST_LOCK(&dynamic_list);
13161 iaxmaxthreadcount = atoi(v->value);
13162 AST_LIST_UNLOCK(&dynamic_list);
13163 } else {
13164 iaxmaxthreadcount = atoi(v->value);
13165 if (iaxmaxthreadcount < 0) {
13166 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13167 iaxmaxthreadcount = 0;
13168 } else if (iaxmaxthreadcount > 256) {
13169 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13170 iaxmaxthreadcount = 256;
13171 }
13172 }
13173 } else if (!strcasecmp(v->name, "nochecksums")) {
13174 #ifdef SO_NO_CHECK
13175 if (ast_true(v->value))
13176 nochecksums = 1;
13177 else
13178 nochecksums = 0;
13179 #else
13180 if (ast_true(v->value))
13181 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13182 #endif
13183 }
13184 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13185 maxjitterbuffer = atoi(v->value);
13186 else if (!strcasecmp(v->name, "resyncthreshold"))
13187 resyncthreshold = atoi(v->value);
13188 else if (!strcasecmp(v->name, "maxjitterinterps"))
13189 maxjitterinterps = atoi(v->value);
13190 else if (!strcasecmp(v->name, "jittertargetextra"))
13191 jittertargetextra = atoi(v->value);
13192 else if (!strcasecmp(v->name, "lagrqtime"))
13193 lagrq_time = atoi(v->value);
13194 else if (!strcasecmp(v->name, "maxregexpire"))
13195 max_reg_expire = atoi(v->value);
13196 else if (!strcasecmp(v->name, "minregexpire"))
13197 min_reg_expire = atoi(v->value);
13198 else if (!strcasecmp(v->name, "bindaddr")) {
13199 if (reload) {
13200 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13201 } else {
13202 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13203 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13204 } else {
13205 if (strchr(v->value, ':'))
13206 ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13207 else
13208 ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13209 if (defaultsockfd < 0)
13210 defaultsockfd = ast_netsock_sockfd(ns);
13211 ast_netsock_unref(ns);
13212 }
13213 }
13214 } else if (!strcasecmp(v->name, "authdebug")) {
13215 authdebug = ast_true(v->value);
13216 } else if (!strcasecmp(v->name, "encryption")) {
13217 iax2_encryption |= get_encrypt_methods(v->value);
13218 if (!iax2_encryption) {
13219 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13220 }
13221 } else if (!strcasecmp(v->name, "forceencryption")) {
13222 if (ast_false(v->value)) {
13223 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13224 } else {
13225 iax2_encryption |= get_encrypt_methods(v->value);
13226 if (iax2_encryption) {
13227 ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13228 }
13229 }
13230 } else if (!strcasecmp(v->name, "transfer")) {
13231 if (!strcasecmp(v->value, "mediaonly")) {
13232 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13233 } else if (ast_true(v->value)) {
13234 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13235 } else
13236 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13237 } else if (!strcasecmp(v->name, "codecpriority")) {
13238 if(!strcasecmp(v->value, "caller"))
13239 ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13240 else if(!strcasecmp(v->value, "disabled"))
13241 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13242 else if(!strcasecmp(v->value, "reqonly")) {
13243 ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13244 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13245 }
13246 } else if (!strcasecmp(v->name, "jitterbuffer"))
13247 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13248 else if (!strcasecmp(v->name, "forcejitterbuffer"))
13249 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13250 else if (!strcasecmp(v->name, "delayreject"))
13251 delayreject = ast_true(v->value);
13252 else if (!strcasecmp(v->name, "allowfwdownload"))
13253 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13254 else if (!strcasecmp(v->name, "rtcachefriends"))
13255 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13256 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13257 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13258 else if (!strcasecmp(v->name, "rtupdate"))
13259 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13260 else if (!strcasecmp(v->name, "rtsavesysname"))
13261 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13262 else if (!strcasecmp(v->name, "trunktimestamps"))
13263 ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13264 else if (!strcasecmp(v->name, "rtautoclear")) {
13265 int i = atoi(v->value);
13266 if(i > 0)
13267 global_rtautoclear = i;
13268 else
13269 i = 0;
13270 ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13271 } else if (!strcasecmp(v->name, "trunkfreq")) {
13272 trunkfreq = atoi(v->value);
13273 if (trunkfreq < 10) {
13274 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13275 trunkfreq = 10;
13276 } else if (trunkfreq > 1000) {
13277 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13278 trunkfreq = 1000;
13279 }
13280 if (timer) {
13281 ast_timer_set_rate(timer, 1000 / trunkfreq);
13282 }
13283 } else if (!strcasecmp(v->name, "trunkmtu")) {
13284 mtuv = atoi(v->value);
13285 if (mtuv == 0 )
13286 global_max_trunk_mtu = 0;
13287 else if (mtuv >= 172 && mtuv < 4000)
13288 global_max_trunk_mtu = mtuv;
13289 else
13290 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13291 mtuv, v->lineno);
13292 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13293 trunkmaxsize = atoi(v->value);
13294 if (trunkmaxsize == 0)
13295 trunkmaxsize = MAX_TRUNKDATA;
13296 } else if (!strcasecmp(v->name, "autokill")) {
13297 if (sscanf(v->value, "%30d", &x) == 1) {
13298 if (x >= 0)
13299 autokill = x;
13300 else
13301 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13302 } else if (ast_true(v->value)) {
13303 autokill = DEFAULT_MAXMS;
13304 } else {
13305 autokill = 0;
13306 }
13307 } else if (!strcasecmp(v->name, "bandwidth")) {
13308 if (!strcasecmp(v->value, "low")) {
13309 capability = IAX_CAPABILITY_LOWBANDWIDTH;
13310 } else if (!strcasecmp(v->value, "medium")) {
13311 capability = IAX_CAPABILITY_MEDBANDWIDTH;
13312 } else if (!strcasecmp(v->value, "high")) {
13313 capability = IAX_CAPABILITY_FULLBANDWIDTH;
13314 } else
13315 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13316 } else if (!strcasecmp(v->name, "allow")) {
13317 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
13318 } else if (!strcasecmp(v->name, "disallow")) {
13319 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
13320 } else if (!strcasecmp(v->name, "register")) {
13321 iax2_register(v->value, v->lineno);
13322 } else if (!strcasecmp(v->name, "iaxcompat")) {
13323 iaxcompat = ast_true(v->value);
13324 } else if (!strcasecmp(v->name, "regcontext")) {
13325 ast_copy_string(regcontext, v->value, sizeof(regcontext));
13326
13327 ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13328 } else if (!strcasecmp(v->name, "tos")) {
13329 if (ast_str2tos(v->value, &qos.tos))
13330 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13331 } else if (!strcasecmp(v->name, "cos")) {
13332 if (ast_str2cos(v->value, &qos.cos))
13333 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13334 } else if (!strcasecmp(v->name, "parkinglot")) {
13335 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13336 } else if (!strcasecmp(v->name, "accountcode")) {
13337 ast_copy_string(accountcode, v->value, sizeof(accountcode));
13338 } else if (!strcasecmp(v->name, "mohinterpret")) {
13339 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13340 } else if (!strcasecmp(v->name, "mohsuggest")) {
13341 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13342 } else if (!strcasecmp(v->name, "amaflags")) {
13343 format = ast_cdr_amaflags2int(v->value);
13344 if (format < 0) {
13345 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13346 } else {
13347 amaflags = format;
13348 }
13349 } else if (!strcasecmp(v->name, "language")) {
13350 ast_copy_string(language, v->value, sizeof(language));
13351 } else if (!strcasecmp(v->name, "maxauthreq")) {
13352 maxauthreq = atoi(v->value);
13353 if (maxauthreq < 0)
13354 maxauthreq = 0;
13355 } else if (!strcasecmp(v->name, "adsi")) {
13356 adsi = ast_true(v->value);
13357 } else if (!strcasecmp(v->name, "srvlookup")) {
13358 srvlookup = ast_true(v->value);
13359 } else if (!strcasecmp(v->name, "connectedline")) {
13360 if (ast_true(v->value)) {
13361 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13362 } else if (!strcasecmp(v->value, "send")) {
13363 ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13364 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13365 } else if (!strcasecmp(v->value, "receive")) {
13366 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13367 ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13368 } else {
13369 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13370 }
13371 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13372 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13373 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
13374 }
13375 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13376 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13377 ast_log(LOG_WARNING, "maxcallnumbers_nonvalidated must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
13378 }
13379 } else if (!strcasecmp(v->name, "calltokenoptional")) {
13380 if (add_calltoken_ignore(v->value)) {
13381 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13382 }
13383 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13384 if (ast_true(v->value)) {
13385 subscribe_network_change = 1;
13386 } else if (ast_false(v->value)) {
13387 subscribe_network_change = 0;
13388 } else {
13389 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13390 }
13391 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13392 if (ast_true(v->value)) {
13393 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13394 } else if (ast_false(v->value)) {
13395 ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13396 } else {
13397 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13398 }
13399 }
13400
13401 v = v->next;
13402 }
13403
13404 if (subscribe_network_change) {
13405 network_change_event_subscribe();
13406 } else {
13407 network_change_event_unsubscribe();
13408 }
13409
13410 if (defaultsockfd < 0) {
13411 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13412 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13413 } else {
13414 ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13415 defaultsockfd = ast_netsock_sockfd(ns);
13416 ast_netsock_unref(ns);
13417 }
13418 }
13419 if (reload) {
13420 ast_netsock_release(outsock);
13421 outsock = ast_netsock_list_alloc();
13422 if (!outsock) {
13423 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13424 return -1;
13425 }
13426 ast_netsock_init(outsock);
13427 }
13428
13429 if (min_reg_expire > max_reg_expire) {
13430 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13431 min_reg_expire, max_reg_expire, max_reg_expire);
13432 min_reg_expire = max_reg_expire;
13433 }
13434 iax2_capability = capability;
13435
13436 if (ucfg) {
13437 struct ast_variable *gen;
13438 int genhasiax;
13439 int genregisteriax;
13440 const char *hasiax, *registeriax;
13441
13442 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13443 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13444 gen = ast_variable_browse(ucfg, "general");
13445 cat = ast_category_browse(ucfg, NULL);
13446 while (cat) {
13447 if (strcasecmp(cat, "general")) {
13448 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13449 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13450 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13451
13452 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13453 if (user) {
13454 ao2_link(users, user);
13455 user = user_unref(user);
13456 }
13457 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13458 if (peer) {
13459 if (ast_test_flag64(peer, IAX_DYNAMIC))
13460 reg_source_db(peer);
13461 ao2_link(peers, peer);
13462 peer = peer_unref(peer);
13463 }
13464 }
13465 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13466 char tmp[256];
13467 const char *host = ast_variable_retrieve(ucfg, cat, "host");
13468 const char *username = ast_variable_retrieve(ucfg, cat, "username");
13469 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13470 if (!host)
13471 host = ast_variable_retrieve(ucfg, "general", "host");
13472 if (!username)
13473 username = ast_variable_retrieve(ucfg, "general", "username");
13474 if (!secret)
13475 secret = ast_variable_retrieve(ucfg, "general", "secret");
13476 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13477 if (!ast_strlen_zero(secret))
13478 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13479 else
13480 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13481 iax2_register(tmp, 0);
13482 }
13483 }
13484 }
13485 cat = ast_category_browse(ucfg, cat);
13486 }
13487 ast_config_destroy(ucfg);
13488 }
13489
13490 cat = ast_category_browse(cfg, NULL);
13491 while(cat) {
13492 if (strcasecmp(cat, "general")) {
13493 utype = ast_variable_retrieve(cfg, cat, "type");
13494 if (!strcasecmp(cat, "callnumberlimits")) {
13495 build_callno_limits(ast_variable_browse(cfg, cat));
13496 } else if (utype) {
13497 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13498 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13499 if (user) {
13500 ao2_link(users, user);
13501 user = user_unref(user);
13502 }
13503 }
13504 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13505 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13506 if (peer) {
13507 if (ast_test_flag64(peer, IAX_DYNAMIC))
13508 reg_source_db(peer);
13509 ao2_link(peers, peer);
13510 peer = peer_unref(peer);
13511 }
13512 } else if (strcasecmp(utype, "user")) {
13513 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13514 }
13515 } else
13516 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13517 }
13518 cat = ast_category_browse(cfg, cat);
13519 }
13520 ast_config_destroy(cfg);
13521 return 1;
13522 }
13523
13524 static void poke_all_peers(void)
13525 {
13526 struct ao2_iterator i;
13527 struct iax2_peer *peer;
13528
13529 i = ao2_iterator_init(peers, 0);
13530 while ((peer = ao2_iterator_next(&i))) {
13531 iax2_poke_peer(peer, 0);
13532 peer_unref(peer);
13533 }
13534 ao2_iterator_destroy(&i);
13535 }
13536 static int reload_config(void)
13537 {
13538 static const char config[] = "iax.conf";
13539 struct iax2_registry *reg;
13540
13541 if (set_config(config, 1) > 0) {
13542 prune_peers();
13543 prune_users();
13544 ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13545 ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13546 ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13547 trunk_timed = trunk_untimed = 0;
13548 trunk_nmaxmtu = trunk_maxmtu = 0;
13549 memset(&debugaddr, '\0', sizeof(debugaddr));
13550
13551 AST_LIST_LOCK(®istrations);
13552 AST_LIST_TRAVERSE(®istrations, reg, entry)
13553 iax2_do_register(reg);
13554 AST_LIST_UNLOCK(®istrations);
13555
13556
13557 poke_all_peers();
13558 }
13559
13560 reload_firmware(0);
13561 iax_provision_reload(1);
13562 ast_unload_realtime("iaxpeers");
13563
13564 return 0;
13565 }
13566
13567 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13568 {
13569 switch (cmd) {
13570 case CLI_INIT:
13571 e->command = "iax2 reload";
13572 e->usage =
13573 "Usage: iax2 reload\n"
13574 " Reloads IAX configuration from iax.conf\n";
13575 return NULL;
13576 case CLI_GENERATE:
13577 return NULL;
13578 }
13579
13580 reload_config();
13581
13582 return CLI_SUCCESS;
13583 }
13584
13585 static int reload(void)
13586 {
13587 return reload_config();
13588 }
13589
13590 static int cache_get_callno_locked(const char *data)
13591 {
13592 struct sockaddr_in sin;
13593 int x;
13594 int callno;
13595 struct iax_ie_data ied;
13596 struct create_addr_info cai;
13597 struct parsed_dial_string pds;
13598 char *tmpstr;
13599
13600 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13601
13602
13603 if (!ast_mutex_trylock(&iaxsl[x])) {
13604 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13605 return x;
13606 ast_mutex_unlock(&iaxsl[x]);
13607 }
13608 }
13609
13610
13611
13612 memset(&cai, 0, sizeof(cai));
13613 memset(&ied, 0, sizeof(ied));
13614 memset(&pds, 0, sizeof(pds));
13615
13616 tmpstr = ast_strdupa(data);
13617 parse_dial_string(tmpstr, &pds);
13618
13619 if (ast_strlen_zero(pds.peer)) {
13620 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13621 return -1;
13622 }
13623
13624
13625 if (create_addr(pds.peer, NULL, &sin, &cai))
13626 return -1;
13627
13628 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13629 pds.peer, pds.username, pds.password, pds.context);
13630
13631 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13632 if (callno < 1) {
13633 ast_log(LOG_WARNING, "Unable to create call\n");
13634 return -1;
13635 }
13636
13637 ast_string_field_set(iaxs[callno], dproot, data);
13638 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13639
13640 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
13641 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
13642
13643
13644
13645 if (pds.exten)
13646 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
13647 if (pds.username)
13648 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
13649 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
13650 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
13651
13652 if (pds.password)
13653 ast_string_field_set(iaxs[callno], secret, pds.password);
13654 if (pds.key)
13655 ast_string_field_set(iaxs[callno], outkey, pds.key);
13656
13657 add_empty_calltoken_ie(iaxs[callno], &ied);
13658 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13659
13660 return callno;
13661 }
13662
13663 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13664 {
13665 struct iax2_dpcache *dp = NULL;
13666 struct timeval now = ast_tvnow();
13667 int x, com[2], timeout, old = 0, outfd, doabort, callno;
13668 struct ast_channel *c = NULL;
13669 struct ast_frame *f = NULL;
13670
13671 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13672 if (ast_tvcmp(now, dp->expiry) > 0) {
13673 AST_LIST_REMOVE_CURRENT(cache_list);
13674 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13675 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13676 else
13677 ast_free(dp);
13678 continue;
13679 }
13680 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13681 break;
13682 }
13683 AST_LIST_TRAVERSE_SAFE_END;
13684
13685 if (!dp) {
13686
13687
13688 if ((callno = cache_get_callno_locked(data)) < 0) {
13689 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13690 return NULL;
13691 }
13692 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13693 ast_mutex_unlock(&iaxsl[callno]);
13694 return NULL;
13695 }
13696 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13697 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13698 dp->expiry = ast_tvnow();
13699 dp->orig = dp->expiry;
13700
13701 dp->expiry.tv_sec += iaxdefaultdpcache;
13702 dp->flags = CACHE_FLAG_PENDING;
13703 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13704 dp->waiters[x] = -1;
13705
13706 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13707 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13708
13709 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13710 iax2_dprequest(dp, callno);
13711 ast_mutex_unlock(&iaxsl[callno]);
13712 }
13713
13714
13715 if (dp->flags & CACHE_FLAG_PENDING) {
13716
13717
13718 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13719
13720 if (dp->waiters[x] < 0)
13721 break;
13722 }
13723 if (x >= ARRAY_LEN(dp->waiters)) {
13724 ast_log(LOG_WARNING, "No more waiter positions available\n");
13725 return NULL;
13726 }
13727 if (pipe(com)) {
13728 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13729 return NULL;
13730 }
13731 dp->waiters[x] = com[1];
13732
13733 timeout = iaxdefaulttimeout * 1000;
13734
13735 AST_LIST_UNLOCK(&dpcache);
13736
13737 if (chan)
13738 old = ast_channel_defer_dtmf(chan);
13739 doabort = 0;
13740 while(timeout) {
13741 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
13742 if (outfd > -1)
13743 break;
13744 if (!c)
13745 continue;
13746 if (!(f = ast_read(c))) {
13747 doabort = 1;
13748 break;
13749 }
13750 ast_frfree(f);
13751 }
13752 if (!timeout) {
13753 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13754 }
13755 AST_LIST_LOCK(&dpcache);
13756 dp->waiters[x] = -1;
13757 close(com[1]);
13758 close(com[0]);
13759 if (doabort) {
13760
13761
13762 if (!old && chan)
13763 ast_channel_undefer_dtmf(chan);
13764 return NULL;
13765 }
13766 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13767
13768 if (dp->flags & CACHE_FLAG_PENDING) {
13769
13770
13771 dp->flags &= ~CACHE_FLAG_PENDING;
13772 dp->flags |= CACHE_FLAG_TIMEOUT;
13773
13774
13775 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
13776 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13777 if (dp->waiters[x] > -1) {
13778 if (write(dp->waiters[x], "asdf", 4) < 0) {
13779 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13780 }
13781 }
13782 }
13783 }
13784 }
13785
13786 if (!old && chan)
13787 ast_channel_undefer_dtmf(chan);
13788 }
13789 return dp;
13790 }
13791
13792
13793 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13794 {
13795 int res = 0;
13796 struct iax2_dpcache *dp = NULL;
13797 #if 0
13798 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13799 #endif
13800 if ((priority != 1) && (priority != 2))
13801 return 0;
13802
13803 AST_LIST_LOCK(&dpcache);
13804 if ((dp = find_cache(chan, data, context, exten, priority))) {
13805 if (dp->flags & CACHE_FLAG_EXISTS)
13806 res = 1;
13807 } else {
13808 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13809 }
13810 AST_LIST_UNLOCK(&dpcache);
13811
13812 return res;
13813 }
13814
13815
13816 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13817 {
13818 int res = 0;
13819 struct iax2_dpcache *dp = NULL;
13820 #if 0
13821 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13822 #endif
13823 if ((priority != 1) && (priority != 2))
13824 return 0;
13825
13826 AST_LIST_LOCK(&dpcache);
13827 if ((dp = find_cache(chan, data, context, exten, priority))) {
13828 if (dp->flags & CACHE_FLAG_CANEXIST)
13829 res = 1;
13830 } else {
13831 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13832 }
13833 AST_LIST_UNLOCK(&dpcache);
13834
13835 return res;
13836 }
13837
13838
13839 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13840 {
13841 int res = 0;
13842 struct iax2_dpcache *dp = NULL;
13843 #if 0
13844 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13845 #endif
13846 if ((priority != 1) && (priority != 2))
13847 return 0;
13848
13849 AST_LIST_LOCK(&dpcache);
13850 if ((dp = find_cache(chan, data, context, exten, priority))) {
13851 if (dp->flags & CACHE_FLAG_MATCHMORE)
13852 res = 1;
13853 } else {
13854 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13855 }
13856 AST_LIST_UNLOCK(&dpcache);
13857
13858 return res;
13859 }
13860
13861
13862 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13863 {
13864 char odata[256];
13865 char req[256];
13866 char *ncontext;
13867 struct iax2_dpcache *dp = NULL;
13868 struct ast_app *dial = NULL;
13869 #if 0
13870 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);
13871 #endif
13872 if (priority == 2) {
13873
13874 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
13875 if (dialstatus) {
13876 dial = pbx_findapp(dialstatus);
13877 if (dial)
13878 pbx_exec(chan, dial, "");
13879 }
13880 return -1;
13881 } else if (priority != 1)
13882 return -1;
13883
13884 AST_LIST_LOCK(&dpcache);
13885 if ((dp = find_cache(chan, data, context, exten, priority))) {
13886 if (dp->flags & CACHE_FLAG_EXISTS) {
13887 ast_copy_string(odata, data, sizeof(odata));
13888 ncontext = strchr(odata, '/');
13889 if (ncontext) {
13890 *ncontext = '\0';
13891 ncontext++;
13892 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
13893 } else {
13894 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
13895 }
13896 ast_verb(3, "Executing Dial('%s')\n", req);
13897 } else {
13898 AST_LIST_UNLOCK(&dpcache);
13899 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
13900 return -1;
13901 }
13902 }
13903 AST_LIST_UNLOCK(&dpcache);
13904
13905 if ((dial = pbx_findapp("Dial")))
13906 return pbx_exec(chan, dial, req);
13907 else
13908 ast_log(LOG_WARNING, "No dial application registered\n");
13909
13910 return -1;
13911 }
13912
13913 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
13914 {
13915 struct iax2_peer *peer;
13916 char *peername, *colname;
13917
13918 peername = ast_strdupa(data);
13919
13920
13921 if (!strcmp(peername,"CURRENTCHANNEL")) {
13922 unsigned short callno;
13923 if (chan->tech != &iax2_tech)
13924 return -1;
13925 callno = PTR_TO_CALLNO(chan->tech_pvt);
13926 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
13927 return 0;
13928 }
13929
13930 if ((colname = strchr(peername, ',')))
13931 *colname++ = '\0';
13932 else
13933 colname = "ip";
13934
13935 if (!(peer = find_peer(peername, 1)))
13936 return -1;
13937
13938 if (!strcasecmp(colname, "ip")) {
13939 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
13940 } else if (!strcasecmp(colname, "status")) {
13941 peer_status(peer, buf, len);
13942 } else if (!strcasecmp(colname, "mailbox")) {
13943 ast_copy_string(buf, peer->mailbox, len);
13944 } else if (!strcasecmp(colname, "context")) {
13945 ast_copy_string(buf, peer->context, len);
13946 } else if (!strcasecmp(colname, "expire")) {
13947 snprintf(buf, len, "%d", peer->expire);
13948 } else if (!strcasecmp(colname, "dynamic")) {
13949 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
13950 } else if (!strcasecmp(colname, "callerid_name")) {
13951 ast_copy_string(buf, peer->cid_name, len);
13952 } else if (!strcasecmp(colname, "callerid_num")) {
13953 ast_copy_string(buf, peer->cid_num, len);
13954 } else if (!strcasecmp(colname, "codecs")) {
13955 ast_getformatname_multiple(buf, len -1, peer->capability);
13956 } else if (!strncasecmp(colname, "codec[", 6)) {
13957 char *codecnum, *ptr;
13958 int codec = 0;
13959
13960
13961 codecnum = colname + 5;
13962 *codecnum = '\0';
13963 codecnum++;
13964 if ((ptr = strchr(codecnum, ']'))) {
13965 *ptr = '\0';
13966 }
13967 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
13968 ast_copy_string(buf, ast_getformatname(codec), len);
13969 } else {
13970 buf[0] = '\0';
13971 }
13972 } else {
13973 buf[0] = '\0';
13974 }
13975
13976 peer_unref(peer);
13977
13978 return 0;
13979 }
13980
13981 static struct ast_custom_function iaxpeer_function = {
13982 .name = "IAXPEER",
13983 .read = function_iaxpeer,
13984 };
13985
13986 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
13987 {
13988 struct chan_iax2_pvt *pvt;
13989 unsigned int callno;
13990 int res = 0;
13991
13992 if (!chan || chan->tech != &iax2_tech) {
13993 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
13994 return -1;
13995 }
13996
13997 callno = PTR_TO_CALLNO(chan->tech_pvt);
13998 ast_mutex_lock(&iaxsl[callno]);
13999 if (!(pvt = iaxs[callno])) {
14000 ast_mutex_unlock(&iaxsl[callno]);
14001 return -1;
14002 }
14003
14004 if (!strcasecmp(args, "osptoken")) {
14005 ast_copy_string(buf, pvt->osptoken, buflen);
14006 } else if (!strcasecmp(args, "peerip")) {
14007 ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
14008 } else if (!strcasecmp(args, "peername")) {
14009 ast_copy_string(buf, pvt->username, buflen);
14010 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14011 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14012 } else {
14013 res = -1;
14014 }
14015
14016 ast_mutex_unlock(&iaxsl[callno]);
14017
14018 return res;
14019 }
14020
14021
14022 static int iax2_devicestate(void *data)
14023 {
14024 struct parsed_dial_string pds;
14025 char *tmp = ast_strdupa(data);
14026 struct iax2_peer *p;
14027 int res = AST_DEVICE_INVALID;
14028
14029 memset(&pds, 0, sizeof(pds));
14030 parse_dial_string(tmp, &pds);
14031
14032 if (ast_strlen_zero(pds.peer)) {
14033 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
14034 return res;
14035 }
14036
14037 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14038
14039
14040 if (!(p = find_peer(pds.peer, 1)))
14041 return res;
14042
14043 res = AST_DEVICE_UNAVAILABLE;
14044 ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
14045 pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
14046
14047 if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
14048 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14049
14050
14051 if (p->historicms == 0 || p->historicms <= p->maxms)
14052
14053 res = AST_DEVICE_UNKNOWN;
14054 }
14055
14056 peer_unref(p);
14057
14058 return res;
14059 }
14060
14061 static struct ast_switch iax2_switch =
14062 {
14063 .name = "IAX2",
14064 .description = "IAX Remote Dialplan Switch",
14065 .exists = iax2_exists,
14066 .canmatch = iax2_canmatch,
14067 .exec = iax2_exec,
14068 .matchmore = iax2_matchmore,
14069 };
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175 static struct ast_cli_entry cli_iax2[] = {
14176 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14177 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14178 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14179 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14180 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14181 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14182 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14183 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14184 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14185 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14186 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14187 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14188 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14189 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14190 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14191 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14192 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14193 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14194 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14195 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14196 #ifdef IAXTESTS
14197 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14198 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14199 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14200 #endif
14201 };
14202
14203 #ifdef TEST_FRAMEWORK
14204 AST_TEST_DEFINE(test_iax2_peers_get)
14205 {
14206 struct ast_data_query query = {
14207 .path = "/asterisk/channel/iax2/peers",
14208 .search = "peers/peer/name=test_peer_data_provider"
14209 };
14210 struct ast_data *node;
14211 struct iax2_peer *peer;
14212
14213 switch (cmd) {
14214 case TEST_INIT:
14215 info->name = "iax2_peers_get_data_test";
14216 info->category = "/main/data/iax2/peers/";
14217 info->summary = "IAX2 peers data providers unit test";
14218 info->description =
14219 "Tests whether the IAX2 peers data provider implementation works as expected.";
14220 return AST_TEST_NOT_RUN;
14221 case TEST_EXECUTE:
14222 break;
14223 }
14224
14225
14226 peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14227 if (!peer) {
14228 return AST_TEST_FAIL;
14229 }
14230 peer->expiry= 1010;
14231 ao2_link(peers, peer);
14232
14233 node = ast_data_get(&query);
14234 if (!node) {
14235 ao2_unlink(peers, peer);
14236 peer_unref(peer);
14237 return AST_TEST_FAIL;
14238 }
14239
14240
14241 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14242 ao2_unlink(peers, peer);
14243 peer_unref(peer);
14244 ast_data_free(node);
14245 return AST_TEST_FAIL;
14246 }
14247
14248 if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14249 ao2_unlink(peers, peer);
14250 peer_unref(peer);
14251 ast_data_free(node);
14252 return AST_TEST_FAIL;
14253 }
14254
14255
14256 ast_data_free(node);
14257
14258 ao2_unlink(peers, peer);
14259 peer_unref(peer);
14260
14261 return AST_TEST_PASS;
14262 }
14263
14264 AST_TEST_DEFINE(test_iax2_users_get)
14265 {
14266 struct ast_data_query query = {
14267 .path = "/asterisk/channel/iax2/users",
14268 .search = "users/user/name=test_user_data_provider"
14269 };
14270 struct ast_data *node;
14271 struct iax2_user *user;
14272
14273 switch (cmd) {
14274 case TEST_INIT:
14275 info->name = "iax2_users_get_data_test";
14276 info->category = "/main/data/iax2/users/";
14277 info->summary = "IAX2 users data providers unit test";
14278 info->description =
14279 "Tests whether the IAX2 users data provider implementation works as expected.";
14280 return AST_TEST_NOT_RUN;
14281 case TEST_EXECUTE:
14282 break;
14283 }
14284
14285 user = build_user("test_user_data_provider", NULL, NULL, 0);
14286 if (!user) {
14287 ast_test_status_update(test, "Failed to build a test user\n");
14288 return AST_TEST_FAIL;
14289 }
14290 user->amaflags = 1010;
14291 ao2_link(users, user);
14292
14293 node = ast_data_get(&query);
14294 if (!node) {
14295 ast_test_status_update(test, "The data query to find our test user failed\n");
14296 ao2_unlink(users, user);
14297 user_unref(user);
14298 return AST_TEST_FAIL;
14299 }
14300
14301 if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14302 ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14303 ao2_unlink(users, user);
14304 user_unref(user);
14305 ast_data_free(node);
14306 return AST_TEST_FAIL;
14307 }
14308
14309 if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14310 ast_test_status_update(test, "The amaflags field in our test user was '%d' not the expected value '1010'\n", ast_data_retrieve_int(node, "user/amaflags/value"));
14311 ao2_unlink(users, user);
14312 user_unref(user);
14313 ast_data_free(node);
14314 return AST_TEST_FAIL;
14315 }
14316
14317 ast_data_free(node);
14318
14319 ao2_unlink(users, user);
14320 user_unref(user);
14321
14322 return AST_TEST_PASS;
14323 }
14324 #endif
14325
14326 static void cleanup_thread_list(void *head)
14327 {
14328 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14329 struct iax2_thread_list *list_head = head;
14330 struct iax2_thread *thread;
14331
14332 AST_LIST_LOCK(list_head);
14333 while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list))) {
14334 pthread_t thread_id = thread->threadid;
14335
14336 thread->stop = 1;
14337 signal_condition(&thread->lock, &thread->cond);
14338
14339 AST_LIST_UNLOCK(list_head);
14340 pthread_join(thread_id, NULL);
14341 AST_LIST_LOCK(list_head);
14342 }
14343 AST_LIST_UNLOCK(list_head);
14344 }
14345
14346 static int __unload_module(void)
14347 {
14348 struct ast_context *con;
14349 int x;
14350
14351 network_change_event_unsubscribe();
14352
14353 ast_manager_unregister("IAXpeers");
14354 ast_manager_unregister("IAXpeerlist");
14355 ast_manager_unregister("IAXnetstats");
14356 ast_manager_unregister("IAXregistry");
14357 ast_unregister_application(papp);
14358 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14359 ast_unregister_switch(&iax2_switch);
14360 ast_channel_unregister(&iax2_tech);
14361
14362 if (netthreadid != AST_PTHREADT_NULL) {
14363 pthread_cancel(netthreadid);
14364 pthread_kill(netthreadid, SIGURG);
14365 pthread_join(netthreadid, NULL);
14366 }
14367
14368 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14369 if (iaxs[x]) {
14370 iax2_destroy(x);
14371 }
14372 }
14373
14374
14375 cleanup_thread_list(&idle_list);
14376 cleanup_thread_list(&active_list);
14377 cleanup_thread_list(&dynamic_list);
14378
14379 ast_netsock_release(netsock);
14380 ast_netsock_release(outsock);
14381 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14382 if (iaxs[x]) {
14383 iax2_destroy(x);
14384 }
14385 }
14386 ast_manager_unregister( "IAXpeers" );
14387 ast_manager_unregister( "IAXpeerlist" );
14388 ast_manager_unregister( "IAXnetstats" );
14389 ast_manager_unregister( "IAXregistry" );
14390 ast_unregister_application(papp);
14391 #ifdef TEST_FRAMEWORK
14392 AST_TEST_UNREGISTER(test_iax2_peers_get);
14393 AST_TEST_UNREGISTER(test_iax2_users_get);
14394 #endif
14395 ast_data_unregister(NULL);
14396 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14397 ast_unregister_switch(&iax2_switch);
14398 ast_channel_unregister(&iax2_tech);
14399 delete_users();
14400 iax_provision_unload();
14401 reload_firmware(1);
14402
14403 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14404 ast_mutex_destroy(&iaxsl[x]);
14405 }
14406
14407 ao2_ref(peers, -1);
14408 ao2_ref(users, -1);
14409 ao2_ref(iax_peercallno_pvts, -1);
14410 ao2_ref(iax_transfercallno_pvts, -1);
14411 ao2_ref(peercnts, -1);
14412 ao2_ref(callno_limits, -1);
14413 ao2_ref(calltoken_ignores, -1);
14414 ao2_ref(callno_pool, -1);
14415 ao2_ref(callno_pool_trunk, -1);
14416 if (timer) {
14417 ast_timer_close(timer);
14418 }
14419 transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14420 sched = ast_sched_thread_destroy(sched);
14421
14422 con = ast_context_find(regcontext);
14423 if (con)
14424 ast_context_destroy(con, "IAX2");
14425 ast_unload_realtime("iaxpeers");
14426 return 0;
14427 }
14428
14429 static int unload_module(void)
14430 {
14431 ast_custom_function_unregister(&iaxpeer_function);
14432 ast_custom_function_unregister(&iaxvar_function);
14433 return __unload_module();
14434 }
14435
14436 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14437 {
14438 struct iax2_peer *peer = obj;
14439
14440 if (peer->sockfd < 0)
14441 peer->sockfd = defaultsockfd;
14442
14443 return 0;
14444 }
14445
14446 static int pvt_hash_cb(const void *obj, const int flags)
14447 {
14448 const struct chan_iax2_pvt *pvt = obj;
14449
14450 return pvt->peercallno;
14451 }
14452
14453 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14454 {
14455 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14456
14457
14458
14459
14460 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14461 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14462 }
14463
14464 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14465 {
14466 const struct chan_iax2_pvt *pvt = obj;
14467
14468 return pvt->transfercallno;
14469 }
14470
14471 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14472 {
14473 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14474
14475
14476
14477
14478 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14479 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14480 }
14481
14482 static int load_objects(void)
14483 {
14484 peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14485 peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14486
14487 if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
14488 goto container_fail;
14489 } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14490 goto container_fail;
14491 } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14492 goto container_fail;
14493 } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14494 goto container_fail;
14495 } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
14496 goto container_fail;
14497 } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14498 goto container_fail;
14499 } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14500 goto container_fail;
14501 } else if (create_callno_pools()) {
14502 goto container_fail;
14503 } else if (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14504 goto container_fail;
14505 }
14506
14507 return 0;
14508
14509 container_fail:
14510 if (peers) {
14511 ao2_ref(peers, -1);
14512 }
14513 if (users) {
14514 ao2_ref(users, -1);
14515 }
14516 if (iax_peercallno_pvts) {
14517 ao2_ref(iax_peercallno_pvts, -1);
14518 }
14519 if (iax_transfercallno_pvts) {
14520 ao2_ref(iax_transfercallno_pvts, -1);
14521 }
14522 if (peercnts) {
14523 ao2_ref(peercnts, -1);
14524 }
14525 if (callno_limits) {
14526 ao2_ref(callno_limits, -1);
14527 }
14528 if (calltoken_ignores) {
14529 ao2_ref(calltoken_ignores, -1);
14530 }
14531 if (callno_pool) {
14532 ao2_ref(callno_pool, -1);
14533 }
14534 if (callno_pool_trunk) {
14535 ao2_ref(callno_pool_trunk, -1);
14536 }
14537 return AST_MODULE_LOAD_FAILURE;
14538 }
14539
14540
14541 #define DATA_EXPORT_IAX2_PEER(MEMBER) \
14542 MEMBER(iax2_peer, name, AST_DATA_STRING) \
14543 MEMBER(iax2_peer, username, AST_DATA_STRING) \
14544 MEMBER(iax2_peer, secret, AST_DATA_PASSWORD) \
14545 MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD) \
14546 MEMBER(iax2_peer, outkey, AST_DATA_STRING) \
14547 MEMBER(iax2_peer, regexten, AST_DATA_STRING) \
14548 MEMBER(iax2_peer, context, AST_DATA_STRING) \
14549 MEMBER(iax2_peer, peercontext, AST_DATA_STRING) \
14550 MEMBER(iax2_peer, mailbox, AST_DATA_STRING) \
14551 MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING) \
14552 MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING) \
14553 MEMBER(iax2_peer, inkeys, AST_DATA_STRING) \
14554 MEMBER(iax2_peer, cid_num, AST_DATA_STRING) \
14555 MEMBER(iax2_peer, cid_name, AST_DATA_STRING) \
14556 MEMBER(iax2_peer, zonetag, AST_DATA_STRING) \
14557 MEMBER(iax2_peer, parkinglot, AST_DATA_STRING) \
14558 MEMBER(iax2_peer, expiry, AST_DATA_SECONDS) \
14559 MEMBER(iax2_peer, callno, AST_DATA_INTEGER) \
14560 MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS) \
14561 MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS) \
14562 MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS) \
14563 MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS) \
14564 MEMBER(iax2_peer, historicms, AST_DATA_INTEGER) \
14565 MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN) \
14566 MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14567
14568 AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
14569
14570 static int peers_data_provider_get(const struct ast_data_search *search,
14571 struct ast_data *data_root)
14572 {
14573 struct ast_data *data_peer;
14574 struct iax2_peer *peer;
14575 struct ao2_iterator i;
14576 char status[20];
14577 struct ast_str *encmethods = ast_str_alloca(256);
14578
14579 i = ao2_iterator_init(peers, 0);
14580 while ((peer = ao2_iterator_next(&i))) {
14581 data_peer = ast_data_add_node(data_root, "peer");
14582 if (!data_peer) {
14583 peer_unref(peer);
14584 continue;
14585 }
14586
14587 ast_data_add_structure(iax2_peer, data_peer, peer);
14588
14589 ast_data_add_codecs(data_peer, "codecs", peer->capability);
14590
14591 peer_status(peer, status, sizeof(status));
14592 ast_data_add_str(data_peer, "status", status);
14593
14594 ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
14595
14596 ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
14597
14598 ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
14599
14600 ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
14601
14602 ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
14603
14604 encmethods_to_str(peer->encmethods, encmethods);
14605 ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
14606
14607 peer_unref(peer);
14608
14609 if (!ast_data_search_match(search, data_peer)) {
14610 ast_data_remove_node(data_root, data_peer);
14611 }
14612 }
14613 ao2_iterator_destroy(&i);
14614
14615 return 0;
14616 }
14617
14618 #define DATA_EXPORT_IAX2_USER(MEMBER) \
14619 MEMBER(iax2_user, name, AST_DATA_STRING) \
14620 MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD) \
14621 MEMBER(iax2_user, accountcode, AST_DATA_STRING) \
14622 MEMBER(iax2_user, mohinterpret, AST_DATA_STRING) \
14623 MEMBER(iax2_user, mohsuggest, AST_DATA_STRING) \
14624 MEMBER(iax2_user, inkeys, AST_DATA_STRING) \
14625 MEMBER(iax2_user, language, AST_DATA_STRING) \
14626 MEMBER(iax2_user, cid_num, AST_DATA_STRING) \
14627 MEMBER(iax2_user, cid_name, AST_DATA_STRING) \
14628 MEMBER(iax2_user, parkinglot, AST_DATA_STRING) \
14629 MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER) \
14630 MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
14631
14632 AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
14633
14634 static int users_data_provider_get(const struct ast_data_search *search,
14635 struct ast_data *data_root)
14636 {
14637 struct ast_data *data_user, *data_authmethods, *data_enum_node;
14638 struct iax2_user *user;
14639 struct ao2_iterator i;
14640 char auth[90];
14641 char *pstr = "";
14642
14643 i = ao2_iterator_init(users, 0);
14644 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
14645 data_user = ast_data_add_node(data_root, "user");
14646 if (!data_user) {
14647 continue;
14648 }
14649
14650 ast_data_add_structure(iax2_user, data_user, user);
14651
14652 ast_data_add_codecs(data_user, "codecs", user->capability);
14653
14654 if (!ast_strlen_zero(user->secret)) {
14655 ast_copy_string(auth, user->secret, sizeof(auth));
14656 } else if (!ast_strlen_zero(user->inkeys)) {
14657 snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
14658 } else {
14659 ast_copy_string(auth, "no secret", sizeof(auth));
14660 }
14661 ast_data_add_password(data_user, "secret", auth);
14662
14663 ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
14664
14665
14666 data_authmethods = ast_data_add_node(data_user, "authmethods");
14667 if (!data_authmethods) {
14668 ast_data_remove_node(data_root, data_user);
14669 continue;
14670 }
14671 ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
14672 ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
14673 ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
14674
14675
14676 data_enum_node = ast_data_add_node(data_user, "amaflags");
14677 if (!data_enum_node) {
14678 ast_data_remove_node(data_root, data_user);
14679 continue;
14680 }
14681 ast_data_add_int(data_enum_node, "value", user->amaflags);
14682 ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
14683
14684 ast_data_add_bool(data_user, "access-control", user->ha ? 1 : 0);
14685
14686 if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
14687 pstr = "REQ only";
14688 } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
14689 pstr = "disabled";
14690 } else {
14691 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
14692 }
14693 ast_data_add_str(data_user, "codec-preferences", pstr);
14694
14695 if (!ast_data_search_match(search, data_user)) {
14696 ast_data_remove_node(data_root, data_user);
14697 }
14698 }
14699 ao2_iterator_destroy(&i);
14700
14701 return 0;
14702 }
14703
14704 static const struct ast_data_handler peers_data_provider = {
14705 .version = AST_DATA_HANDLER_VERSION,
14706 .get = peers_data_provider_get
14707 };
14708
14709 static const struct ast_data_handler users_data_provider = {
14710 .version = AST_DATA_HANDLER_VERSION,
14711 .get = users_data_provider_get
14712 };
14713
14714 static const struct ast_data_entry iax2_data_providers[] = {
14715 AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
14716 AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
14717 };
14718
14719
14720 static int load_module(void)
14721 {
14722 static const char config[] = "iax.conf";
14723 int x = 0;
14724 struct iax2_registry *reg = NULL;
14725
14726 if (load_objects()) {
14727 return AST_MODULE_LOAD_FAILURE;
14728 }
14729
14730 memset(iaxs, 0, sizeof(iaxs));
14731
14732 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14733 ast_mutex_init(&iaxsl[x]);
14734 }
14735
14736 if (!(sched = ast_sched_thread_create())) {
14737 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14738 return AST_MODULE_LOAD_FAILURE;
14739 }
14740
14741 if (!(io = io_context_create())) {
14742 ast_log(LOG_ERROR, "Failed to create I/O context\n");
14743 sched = ast_sched_thread_destroy(sched);
14744 return AST_MODULE_LOAD_FAILURE;
14745 }
14746
14747 if (!(netsock = ast_netsock_list_alloc())) {
14748 ast_log(LOG_ERROR, "Failed to create netsock list\n");
14749 io_context_destroy(io);
14750 sched = ast_sched_thread_destroy(sched);
14751 return AST_MODULE_LOAD_FAILURE;
14752 }
14753 ast_netsock_init(netsock);
14754
14755 outsock = ast_netsock_list_alloc();
14756 if (!outsock) {
14757 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14758 io_context_destroy(io);
14759 sched = ast_sched_thread_destroy(sched);
14760 return AST_MODULE_LOAD_FAILURE;
14761 }
14762 ast_netsock_init(outsock);
14763
14764 randomcalltokendata = ast_random();
14765
14766 iax_set_output(iax_debug_output);
14767 iax_set_error(iax_error_output);
14768 jb_setoutput(jb_error_output, jb_warning_output, NULL);
14769
14770 if ((timer = ast_timer_open())) {
14771 ast_timer_set_rate(timer, 1000 / trunkfreq);
14772 }
14773
14774 if (set_config(config, 0) == -1) {
14775 if (timer) {
14776 ast_timer_close(timer);
14777 }
14778 return AST_MODULE_LOAD_DECLINE;
14779 }
14780
14781 #ifdef TEST_FRAMEWORK
14782 AST_TEST_REGISTER(test_iax2_peers_get);
14783 AST_TEST_REGISTER(test_iax2_users_get);
14784 #endif
14785
14786
14787 ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
14788 ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14789
14790 ast_register_application_xml(papp, iax2_prov_app);
14791
14792 ast_custom_function_register(&iaxpeer_function);
14793 ast_custom_function_register(&iaxvar_function);
14794
14795 ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
14796 ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
14797 ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
14798 ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
14799
14800 if (ast_channel_register(&iax2_tech)) {
14801 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
14802 __unload_module();
14803 return AST_MODULE_LOAD_FAILURE;
14804 }
14805
14806 if (ast_register_switch(&iax2_switch)) {
14807 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
14808 }
14809
14810 if (start_network_thread()) {
14811 ast_log(LOG_ERROR, "Unable to start network thread\n");
14812 __unload_module();
14813 return AST_MODULE_LOAD_FAILURE;
14814 } else {
14815 ast_verb(2, "IAX Ready and Listening\n");
14816 }
14817
14818 AST_LIST_LOCK(®istrations);
14819 AST_LIST_TRAVERSE(®istrations, reg, entry)
14820 iax2_do_register(reg);
14821 AST_LIST_UNLOCK(®istrations);
14822
14823 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
14824 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
14825
14826
14827 reload_firmware(0);
14828 iax_provision_reload(0);
14829
14830 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
14831
14832 network_change_event_subscribe();
14833
14834 return AST_MODULE_LOAD_SUCCESS;
14835 }
14836
14837 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
14838 .load = load_module,
14839 .unload = unload_module,
14840 .reload = reload,
14841 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
14842 .nonoptreq = "res_crypto",
14843 );