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: 372804 $")
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 const 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 s2 = ast_alloca(strlen(s) + 100);
03038
03039 last = strrchr(s, '/');
03040 if (last)
03041 last++;
03042 else
03043 last = s;
03044
03045 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
03046
03047 if ((res = stat(s, &stbuf) < 0)) {
03048 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
03049 return -1;
03050 }
03051
03052
03053 if (S_ISDIR(stbuf.st_mode))
03054 return -1;
03055 ifd = open(s, O_RDONLY);
03056 if (ifd < 0) {
03057 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
03058 return -1;
03059 }
03060 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
03061 if (fd < 0) {
03062 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
03063 close(ifd);
03064 return -1;
03065 }
03066
03067 unlink(s2);
03068
03069
03070 len = stbuf.st_size;
03071 while(len) {
03072 chunk = len;
03073 if (chunk > sizeof(buf))
03074 chunk = sizeof(buf);
03075 res = read(ifd, buf, chunk);
03076 if (res != chunk) {
03077 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03078 close(ifd);
03079 close(fd);
03080 return -1;
03081 }
03082 res = write(fd, buf, chunk);
03083 if (res != chunk) {
03084 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
03085 close(ifd);
03086 close(fd);
03087 return -1;
03088 }
03089 len -= chunk;
03090 }
03091 close(ifd);
03092
03093 lseek(fd, 0, SEEK_SET);
03094 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
03095 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
03096 close(fd);
03097 return -1;
03098 }
03099 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
03100 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
03101 close(fd);
03102 return -1;
03103 }
03104 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
03105 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
03106 close(fd);
03107 return -1;
03108 }
03109 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
03110 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
03111 close(fd);
03112 return -1;
03113 }
03114 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
03115 if (fwh == MAP_FAILED) {
03116 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
03117 close(fd);
03118 return -1;
03119 }
03120 MD5Init(&md5);
03121 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
03122 MD5Final(sum, &md5);
03123 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
03124 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
03125 munmap((void*)fwh, stbuf.st_size);
03126 close(fd);
03127 return -1;
03128 }
03129
03130 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03131 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
03132
03133 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
03134
03135 break;
03136
03137
03138 munmap((void*)fwh, stbuf.st_size);
03139 close(fd);
03140 return 0;
03141 }
03142 }
03143
03144 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
03145 cur->fd = -1;
03146 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
03147 }
03148
03149 if (cur) {
03150 if (cur->fwh)
03151 munmap((void*)cur->fwh, cur->mmaplen);
03152 if (cur->fd > -1)
03153 close(cur->fd);
03154 cur->fwh = fwh;
03155 cur->fd = fd;
03156 cur->mmaplen = stbuf.st_size;
03157 cur->dead = 0;
03158 }
03159
03160 return 0;
03161 }
03162
03163 static int iax_check_version(char *dev)
03164 {
03165 int res = 0;
03166 struct iax_firmware *cur = NULL;
03167
03168 if (ast_strlen_zero(dev))
03169 return 0;
03170
03171 AST_LIST_LOCK(&firmwares);
03172 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03173 if (!strcmp(dev, (char *)cur->fwh->devname)) {
03174 res = ntohs(cur->fwh->version);
03175 break;
03176 }
03177 }
03178 AST_LIST_UNLOCK(&firmwares);
03179
03180 return res;
03181 }
03182
03183 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03184 {
03185 int res = -1;
03186 unsigned int bs = desc & 0xff;
03187 unsigned int start = (desc >> 8) & 0xffffff;
03188 unsigned int bytes;
03189 struct iax_firmware *cur;
03190
03191 if (ast_strlen_zero((char *)dev) || !bs)
03192 return -1;
03193
03194 start *= bs;
03195
03196 AST_LIST_LOCK(&firmwares);
03197 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03198 if (strcmp((char *)dev, (char *)cur->fwh->devname))
03199 continue;
03200 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03201 if (start < ntohl(cur->fwh->datalen)) {
03202 bytes = ntohl(cur->fwh->datalen) - start;
03203 if (bytes > bs)
03204 bytes = bs;
03205 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03206 } else {
03207 bytes = 0;
03208 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03209 }
03210 if (bytes == bs)
03211 res = 0;
03212 else
03213 res = 1;
03214 break;
03215 }
03216 AST_LIST_UNLOCK(&firmwares);
03217
03218 return res;
03219 }
03220
03221
03222 static void reload_firmware(int unload)
03223 {
03224 struct iax_firmware *cur = NULL;
03225 DIR *fwd;
03226 struct dirent *de;
03227 char dir[256], fn[256];
03228
03229 AST_LIST_LOCK(&firmwares);
03230
03231
03232 AST_LIST_TRAVERSE(&firmwares, cur, list)
03233 cur->dead = 1;
03234
03235
03236 if (!unload) {
03237 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03238 fwd = opendir(dir);
03239 if (fwd) {
03240 while((de = readdir(fwd))) {
03241 if (de->d_name[0] != '.') {
03242 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03243 if (!try_firmware(fn)) {
03244 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03245 }
03246 }
03247 }
03248 closedir(fwd);
03249 } else
03250 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03251 }
03252
03253
03254 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03255 if (!cur->dead)
03256 continue;
03257 AST_LIST_REMOVE_CURRENT(list);
03258 destroy_firmware(cur);
03259 }
03260 AST_LIST_TRAVERSE_SAFE_END;
03261
03262 AST_LIST_UNLOCK(&firmwares);
03263 }
03264
03265
03266
03267
03268
03269
03270
03271
03272
03273 static int __do_deliver(void *data)
03274 {
03275
03276
03277 struct iax_frame *fr = data;
03278 fr->retrans = -1;
03279 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03280 if (iaxs[fr->callno] && !ast_test_flag64(iaxs[fr->callno], IAX_ALREADYGONE))
03281 iax2_queue_frame(fr->callno, &fr->af);
03282
03283 iax2_frame_free(fr);
03284
03285 return 0;
03286 }
03287
03288 static int handle_error(void)
03289 {
03290
03291
03292
03293 #if 0
03294 struct sockaddr_in *sin;
03295 int res;
03296 struct msghdr m;
03297 struct sock_extended_err e;
03298 m.msg_name = NULL;
03299 m.msg_namelen = 0;
03300 m.msg_iov = NULL;
03301 m.msg_control = &e;
03302 m.msg_controllen = sizeof(e);
03303 m.msg_flags = 0;
03304 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03305 if (res < 0)
03306 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03307 else {
03308 if (m.msg_controllen) {
03309 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03310 if (sin)
03311 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03312 else
03313 ast_log(LOG_WARNING, "No address detected??\n");
03314 } else {
03315 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03316 }
03317 }
03318 #endif
03319 return 0;
03320 }
03321
03322 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03323 {
03324 int res;
03325 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03326 sizeof(*sin));
03327 if (res < 0) {
03328 ast_debug(1, "Received error: %s\n", strerror(errno));
03329 handle_error();
03330 } else
03331 res = 0;
03332 return res;
03333 }
03334
03335 static int send_packet(struct iax_frame *f)
03336 {
03337 int res;
03338 int callno = f->callno;
03339
03340
03341 if (!callno || !iaxs[callno] || iaxs[callno]->error)
03342 return -1;
03343
03344
03345 if (iaxdebug)
03346 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));
03347
03348 if (f->transfer) {
03349 iax_outputframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03350 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03351 } else {
03352 iax_outputframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03353 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03354 }
03355 if (res < 0) {
03356 if (iaxdebug)
03357 ast_debug(1, "Received error: %s\n", strerror(errno));
03358 handle_error();
03359 } else
03360 res = 0;
03361
03362 return res;
03363 }
03364
03365
03366
03367
03368
03369 static int iax2_predestroy(int callno)
03370 {
03371 struct ast_channel *c = NULL;
03372 struct chan_iax2_pvt *pvt = iaxs[callno];
03373
03374 if (!pvt)
03375 return -1;
03376
03377 if (!ast_test_flag64(pvt, IAX_ALREADYGONE)) {
03378 iax2_destroy_helper(pvt);
03379 ast_set_flag64(pvt, IAX_ALREADYGONE);
03380 }
03381
03382 if ((c = pvt->owner)) {
03383 c->tech_pvt = NULL;
03384 iax2_queue_hangup(callno);
03385 pvt->owner = NULL;
03386 ast_module_unref(ast_module_info->self);
03387 }
03388
03389 return 0;
03390 }
03391
03392 static void iax2_destroy(int callno)
03393 {
03394 struct chan_iax2_pvt *pvt = NULL;
03395 struct ast_channel *owner = NULL;
03396
03397 retry:
03398 if ((pvt = iaxs[callno])) {
03399 #if 0
03400
03401
03402
03403
03404
03405
03406
03407 iax2_destroy_helper(pvt);
03408 #endif
03409 }
03410
03411 owner = pvt ? pvt->owner : NULL;
03412
03413 if (owner) {
03414 if (ast_channel_trylock(owner)) {
03415 ast_debug(3, "Avoiding IAX destroy deadlock\n");
03416 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03417 goto retry;
03418 }
03419 }
03420
03421 if (!owner) {
03422 iaxs[callno] = NULL;
03423 }
03424
03425 if (pvt) {
03426 if (!owner) {
03427 pvt->owner = NULL;
03428 } else {
03429
03430
03431
03432 ast_queue_hangup(owner);
03433 }
03434
03435 if (pvt->peercallno) {
03436 remove_by_peercallno(pvt);
03437 }
03438
03439 if (pvt->transfercallno) {
03440 remove_by_transfercallno(pvt);
03441 }
03442
03443 if (!owner) {
03444 ao2_ref(pvt, -1);
03445 pvt = NULL;
03446 }
03447 }
03448
03449 if (owner) {
03450 ast_channel_unlock(owner);
03451 }
03452
03453 if (callno & TRUNK_CALL_START) {
03454 update_max_trunk();
03455 }
03456 }
03457
03458 static int update_packet(struct iax_frame *f)
03459 {
03460
03461 struct ast_iax2_full_hdr *fh = f->data;
03462 struct ast_frame af;
03463
03464
03465 if (f->encmethods) {
03466 decode_frame(&f->mydcx, fh, &af, &f->datalen);
03467 }
03468
03469 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03470
03471 f->iseqno = iaxs[f->callno]->iseqno;
03472 fh->iseqno = f->iseqno;
03473
03474
03475 if (f->encmethods) {
03476
03477
03478 build_rand_pad(f->semirand, sizeof(f->semirand));
03479 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03480 }
03481 return 0;
03482 }
03483
03484 static int attempt_transmit(const void *data);
03485 static void __attempt_transmit(const void *data)
03486 {
03487
03488
03489 struct iax_frame *f = (struct iax_frame *)data;
03490 int freeme = 0;
03491 int callno = f->callno;
03492
03493 if (callno)
03494 ast_mutex_lock(&iaxsl[callno]);
03495 if (callno && iaxs[callno]) {
03496 if ((f->retries < 0) ||
03497 (f->retries >= max_retries) ) {
03498
03499 if (f->retries >= max_retries) {
03500 if (f->transfer) {
03501
03502 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03503 } else if (f->final) {
03504 iax2_destroy(callno);
03505 } else {
03506 if (iaxs[callno]->owner)
03507 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);
03508 iaxs[callno]->error = ETIMEDOUT;
03509 if (iaxs[callno]->owner) {
03510 struct ast_frame fr = { AST_FRAME_CONTROL, { AST_CONTROL_HANGUP }, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03511
03512 iax2_queue_frame(callno, &fr);
03513
03514 if (iaxs[callno] && iaxs[callno]->owner)
03515 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03516 } else {
03517 if (iaxs[callno]->reg) {
03518 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03519 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03520 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03521 }
03522 iax2_destroy(callno);
03523 }
03524 }
03525
03526 }
03527 freeme = 1;
03528 } else {
03529
03530 update_packet(f);
03531
03532 send_packet(f);
03533 f->retries++;
03534
03535 f->retrytime *= 10;
03536 if (f->retrytime > MAX_RETRY_TIME)
03537 f->retrytime = MAX_RETRY_TIME;
03538
03539 if (f->transfer && (f->retrytime > 1000))
03540 f->retrytime = 1000;
03541 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03542 }
03543 } else {
03544
03545 f->retries = -1;
03546 freeme = 1;
03547 }
03548
03549 if (freeme) {
03550
03551 AST_LIST_REMOVE(&frame_queue[callno], f, list);
03552 ast_mutex_unlock(&iaxsl[callno]);
03553 f->retrans = -1;
03554
03555 iax2_frame_free(f);
03556 } else if (callno) {
03557 ast_mutex_unlock(&iaxsl[callno]);
03558 }
03559 }
03560
03561 static int attempt_transmit(const void *data)
03562 {
03563 #ifdef SCHED_MULTITHREADED
03564 if (schedule_action(__attempt_transmit, data))
03565 #endif
03566 __attempt_transmit(data);
03567 return 0;
03568 }
03569
03570 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03571 {
03572 struct iax2_peer *peer = NULL;
03573 struct iax2_user *user = NULL;
03574 static const char * const choices[] = { "all", NULL };
03575 char *cmplt;
03576
03577 switch (cmd) {
03578 case CLI_INIT:
03579 e->command = "iax2 prune realtime";
03580 e->usage =
03581 "Usage: iax2 prune realtime [<peername>|all]\n"
03582 " Prunes object(s) from the cache\n";
03583 return NULL;
03584 case CLI_GENERATE:
03585 if (a->pos == 3) {
03586 cmplt = ast_cli_complete(a->word, choices, a->n);
03587 if (!cmplt)
03588 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03589 return cmplt;
03590 }
03591 return NULL;
03592 }
03593 if (a->argc != 4)
03594 return CLI_SHOWUSAGE;
03595 if (!strcmp(a->argv[3], "all")) {
03596 prune_users();
03597 prune_peers();
03598 ast_cli(a->fd, "Cache flushed successfully.\n");
03599 return CLI_SUCCESS;
03600 }
03601 peer = find_peer(a->argv[3], 0);
03602 user = find_user(a->argv[3]);
03603 if (peer || user) {
03604 if (peer) {
03605 if (ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
03606 ast_set_flag64(peer, IAX_RTAUTOCLEAR);
03607 expire_registry(peer_ref(peer));
03608 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03609 } else {
03610 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03611 }
03612 peer_unref(peer);
03613 }
03614 if (user) {
03615 if (ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
03616 ast_set_flag64(user, IAX_RTAUTOCLEAR);
03617 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03618 } else {
03619 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03620 }
03621 ao2_unlink(users,user);
03622 user_unref(user);
03623 }
03624 } else {
03625 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03626 }
03627
03628 return CLI_SUCCESS;
03629 }
03630
03631 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03632 {
03633 switch (cmd) {
03634 case CLI_INIT:
03635 e->command = "iax2 test losspct";
03636 e->usage =
03637 "Usage: iax2 test losspct <percentage>\n"
03638 " For testing, throws away <percentage> percent of incoming packets\n";
03639 return NULL;
03640 case CLI_GENERATE:
03641 return NULL;
03642 }
03643 if (a->argc != 4)
03644 return CLI_SHOWUSAGE;
03645
03646 test_losspct = atoi(a->argv[3]);
03647
03648 return CLI_SUCCESS;
03649 }
03650
03651 #ifdef IAXTESTS
03652 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03653 {
03654 switch (cmd) {
03655 case CLI_INIT:
03656 e->command = "iax2 test late";
03657 e->usage =
03658 "Usage: iax2 test late <ms>\n"
03659 " For testing, count the next frame as <ms> ms late\n";
03660 return NULL;
03661 case CLI_GENERATE:
03662 return NULL;
03663 }
03664
03665 if (a->argc != 4)
03666 return CLI_SHOWUSAGE;
03667
03668 test_late = atoi(a->argv[3]);
03669
03670 return CLI_SUCCESS;
03671 }
03672
03673 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03674 {
03675 switch (cmd) {
03676 case CLI_INIT:
03677 e->command = "iax2 test resync";
03678 e->usage =
03679 "Usage: iax2 test resync <ms>\n"
03680 " For testing, adjust all future frames by <ms> ms\n";
03681 return NULL;
03682 case CLI_GENERATE:
03683 return NULL;
03684 }
03685
03686 if (a->argc != 4)
03687 return CLI_SHOWUSAGE;
03688
03689 test_resync = atoi(a->argv[3]);
03690
03691 return CLI_SUCCESS;
03692 }
03693
03694 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03695 {
03696 switch (cmd) {
03697 case CLI_INIT:
03698 e->command = "iax2 test jitter";
03699 e->usage =
03700 "Usage: iax2 test jitter <ms> <pct>\n"
03701 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03702 " percentage of packets. If <pct> is not specified, adds\n"
03703 " jitter to all packets.\n";
03704 return NULL;
03705 case CLI_GENERATE:
03706 return NULL;
03707 }
03708
03709 if (a->argc < 4 || a->argc > 5)
03710 return CLI_SHOWUSAGE;
03711
03712 test_jit = atoi(a->argv[3]);
03713 if (a->argc == 5)
03714 test_jitpct = atoi(a->argv[4]);
03715
03716 return CLI_SUCCESS;
03717 }
03718 #endif
03719
03720
03721
03722 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03723 {
03724 int res = 0;
03725 if (peer->maxms) {
03726 if (peer->lastms < 0) {
03727 ast_copy_string(status, "UNREACHABLE", statuslen);
03728 } else if (peer->lastms > peer->maxms) {
03729 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03730 res = 1;
03731 } else if (peer->lastms) {
03732 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03733 res = 1;
03734 } else {
03735 ast_copy_string(status, "UNKNOWN", statuslen);
03736 }
03737 } else {
03738 ast_copy_string(status, "Unmonitored", statuslen);
03739 res = -1;
03740 }
03741 return res;
03742 }
03743
03744
03745 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03746 {
03747 char status[30];
03748 char cbuf[256];
03749 struct iax2_peer *peer;
03750 char codec_buf[512];
03751 struct ast_str *encmethods = ast_str_alloca(256);
03752 int x = 0, codec = 0, load_realtime = 0;
03753
03754 switch (cmd) {
03755 case CLI_INIT:
03756 e->command = "iax2 show peer";
03757 e->usage =
03758 "Usage: iax2 show peer <name>\n"
03759 " Display details on specific IAX peer\n";
03760 return NULL;
03761 case CLI_GENERATE:
03762 if (a->pos == 3)
03763 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03764 return NULL;
03765 }
03766
03767 if (a->argc < 4)
03768 return CLI_SHOWUSAGE;
03769
03770 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03771
03772 peer = find_peer(a->argv[3], load_realtime);
03773 if (peer) {
03774 struct sockaddr_in peer_addr;
03775
03776 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
03777
03778 encmethods_to_str(peer->encmethods, encmethods);
03779 ast_cli(a->fd, "\n\n");
03780 ast_cli(a->fd, " * Name : %s\n", peer->name);
03781 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03782 ast_cli(a->fd, " Context : %s\n", peer->context);
03783 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
03784 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
03785 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
03786 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
03787 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03788 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
03789 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03790 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03791 ast_cli(a->fd, " Expire : %d\n", peer->expire);
03792 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
03793 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));
03794 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03795 ast_cli(a->fd, " Username : %s\n", peer->username);
03796 ast_cli(a->fd, " Codecs : ");
03797 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03798 ast_cli(a->fd, "%s\n", codec_buf);
03799
03800 ast_cli(a->fd, " Codec Order : (");
03801 for(x = 0; x < 32 ; x++) {
03802 codec = ast_codec_pref_index(&peer->prefs,x);
03803 if(!codec)
03804 break;
03805 ast_cli(a->fd, "%s", ast_getformatname(codec));
03806 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03807 ast_cli(a->fd, "|");
03808 }
03809
03810 if (!x)
03811 ast_cli(a->fd, "none");
03812 ast_cli(a->fd, ")\n");
03813
03814 ast_cli(a->fd, " Status : ");
03815 peer_status(peer, status, sizeof(status));
03816 ast_cli(a->fd, "%s\n",status);
03817 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");
03818 ast_cli(a->fd, "\n");
03819 peer_unref(peer);
03820 } else {
03821 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03822 ast_cli(a->fd, "\n");
03823 }
03824
03825 return CLI_SUCCESS;
03826 }
03827
03828 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, uint64_t flags)
03829 {
03830 int which = 0;
03831 struct iax2_peer *peer;
03832 char *res = NULL;
03833 int wordlen = strlen(word);
03834 struct ao2_iterator i;
03835
03836 i = ao2_iterator_init(peers, 0);
03837 while ((peer = ao2_iterator_next(&i))) {
03838 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03839 && (!flags || ast_test_flag64(peer, flags))) {
03840 res = ast_strdup(peer->name);
03841 peer_unref(peer);
03842 break;
03843 }
03844 peer_unref(peer);
03845 }
03846 ao2_iterator_destroy(&i);
03847
03848 return res;
03849 }
03850
03851 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03852 {
03853 struct iax_frame *cur;
03854 int cnt = 0, dead = 0, final = 0, i = 0;
03855
03856 switch (cmd) {
03857 case CLI_INIT:
03858 e->command = "iax2 show stats";
03859 e->usage =
03860 "Usage: iax2 show stats\n"
03861 " Display statistics on IAX channel driver.\n";
03862 return NULL;
03863 case CLI_GENERATE:
03864 return NULL;
03865 }
03866
03867 if (a->argc != 3)
03868 return CLI_SHOWUSAGE;
03869
03870 for (i = 0; i < ARRAY_LEN(frame_queue); i++) {
03871 ast_mutex_lock(&iaxsl[i]);
03872 AST_LIST_TRAVERSE(&frame_queue[i], cur, list) {
03873 if (cur->retries < 0)
03874 dead++;
03875 if (cur->final)
03876 final++;
03877 cnt++;
03878 }
03879 ast_mutex_unlock(&iaxsl[i]);
03880 }
03881
03882 ast_cli(a->fd, " IAX Statistics\n");
03883 ast_cli(a->fd, "---------------------\n");
03884 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03885 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03886 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03887 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03888
03889 trunk_timed = trunk_untimed = 0;
03890 if (trunk_maxmtu > trunk_nmaxmtu)
03891 trunk_nmaxmtu = trunk_maxmtu;
03892
03893 return CLI_SUCCESS;
03894 }
03895
03896
03897 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03898 {
03899 int mtuv;
03900
03901 switch (cmd) {
03902 case CLI_INIT:
03903 e->command = "iax2 set mtu";
03904 e->usage =
03905 "Usage: iax2 set mtu <value>\n"
03906 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
03907 " zero to disable. Disabling means that the operating system\n"
03908 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
03909 " packet exceeds the UDP payload size. This is substantially\n"
03910 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03911 " greater for G.711 samples.\n";
03912 return NULL;
03913 case CLI_GENERATE:
03914 return NULL;
03915 }
03916
03917 if (a->argc != 4)
03918 return CLI_SHOWUSAGE;
03919 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03920 mtuv = MAX_TRUNK_MTU;
03921 else
03922 mtuv = atoi(a->argv[3]);
03923
03924 if (mtuv == 0) {
03925 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
03926 global_max_trunk_mtu = 0;
03927 return CLI_SUCCESS;
03928 }
03929 if (mtuv < 172 || mtuv > 4000) {
03930 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
03931 return CLI_SHOWUSAGE;
03932 }
03933 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
03934 global_max_trunk_mtu = mtuv;
03935 return CLI_SUCCESS;
03936 }
03937
03938 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03939 {
03940 struct iax2_dpcache *dp = NULL;
03941 char tmp[1024], *pc = NULL;
03942 int s, x, y;
03943 struct timeval now = ast_tvnow();
03944
03945 switch (cmd) {
03946 case CLI_INIT:
03947 e->command = "iax2 show cache";
03948 e->usage =
03949 "Usage: iax2 show cache\n"
03950 " Display currently cached IAX Dialplan results.\n";
03951 return NULL;
03952 case CLI_GENERATE:
03953 return NULL;
03954 }
03955
03956 AST_LIST_LOCK(&dpcache);
03957
03958 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03959
03960 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03961 s = dp->expiry.tv_sec - now.tv_sec;
03962 tmp[0] = '\0';
03963 if (dp->flags & CACHE_FLAG_EXISTS)
03964 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03965 if (dp->flags & CACHE_FLAG_NONEXISTENT)
03966 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03967 if (dp->flags & CACHE_FLAG_CANEXIST)
03968 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03969 if (dp->flags & CACHE_FLAG_PENDING)
03970 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03971 if (dp->flags & CACHE_FLAG_TIMEOUT)
03972 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03973 if (dp->flags & CACHE_FLAG_TRANSMITTED)
03974 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03975 if (dp->flags & CACHE_FLAG_MATCHMORE)
03976 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03977 if (dp->flags & CACHE_FLAG_UNKNOWN)
03978 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03979
03980 if (!ast_strlen_zero(tmp)) {
03981 tmp[strlen(tmp) - 1] = '\0';
03982 } else {
03983 ast_copy_string(tmp, "(none)", sizeof(tmp));
03984 }
03985 y = 0;
03986 pc = strchr(dp->peercontext, '@');
03987 if (!pc) {
03988 pc = dp->peercontext;
03989 } else {
03990 pc++;
03991 }
03992 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03993 if (dp->waiters[x] > -1)
03994 y++;
03995 }
03996 if (s > 0) {
03997 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
03998 } else {
03999 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
04000 }
04001 }
04002
04003 AST_LIST_UNLOCK(&dpcache);
04004
04005 return CLI_SUCCESS;
04006 }
04007
04008 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
04009
04010 static void unwrap_timestamp(struct iax_frame *fr)
04011 {
04012
04013
04014 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
04015 const int lower_mask = (1 << ts_shift) - 1;
04016 const int upper_mask = ~lower_mask;
04017 const int last_upper = iaxs[fr->callno]->last & upper_mask;
04018
04019 if ( (fr->ts & upper_mask) == last_upper ) {
04020 const int x = fr->ts - iaxs[fr->callno]->last;
04021 const int threshold = (ts_shift == 15) ? 25000 : 50000;
04022
04023 if (x < -threshold) {
04024
04025
04026
04027
04028 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
04029 if (iaxdebug)
04030 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
04031 } else if (x > threshold) {
04032
04033
04034
04035
04036 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
04037 if (iaxdebug)
04038 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
04039 }
04040 }
04041 }
04042
04043 static int get_from_jb(const void *p);
04044
04045 static void update_jbsched(struct chan_iax2_pvt *pvt)
04046 {
04047 int when;
04048
04049 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
04050
04051 when = jb_next(pvt->jb) - when;
04052
04053 if (when <= 0) {
04054
04055 when = 1;
04056 }
04057
04058 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
04059 CALLNO_TO_PTR(pvt->callno));
04060 }
04061
04062 static void __get_from_jb(const void *p)
04063 {
04064 int callno = PTR_TO_CALLNO(p);
04065 struct chan_iax2_pvt *pvt = NULL;
04066 struct iax_frame *fr;
04067 jb_frame frame;
04068 int ret;
04069 long ms;
04070 long next;
04071 struct timeval now = ast_tvnow();
04072
04073
04074 ast_mutex_lock(&iaxsl[callno]);
04075 pvt = iaxs[callno];
04076 if (!pvt) {
04077
04078 ast_mutex_unlock(&iaxsl[callno]);
04079 return;
04080 }
04081
04082 pvt->jbid = -1;
04083
04084
04085
04086
04087 now.tv_usec += 1000;
04088
04089 ms = ast_tvdiff_ms(now, pvt->rxcore);
04090
04091 if(ms >= (next = jb_next(pvt->jb))) {
04092 ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
04093 switch(ret) {
04094 case JB_OK:
04095 fr = frame.data;
04096 __do_deliver(fr);
04097
04098 pvt = iaxs[callno];
04099 break;
04100 case JB_INTERP:
04101 {
04102 struct ast_frame af = { 0, };
04103
04104
04105 af.frametype = AST_FRAME_VOICE;
04106 af.subclass.codec = pvt->voiceformat;
04107 af.samples = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
04108 af.src = "IAX2 JB interpolation";
04109 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
04110 af.offset = AST_FRIENDLY_OFFSET;
04111
04112
04113
04114 if (!ast_test_flag64(iaxs[callno], IAX_ALREADYGONE)) {
04115 iax2_queue_frame(callno, &af);
04116
04117 pvt = iaxs[callno];
04118 }
04119 }
04120 break;
04121 case JB_DROP:
04122 iax2_frame_free(frame.data);
04123 break;
04124 case JB_NOFRAME:
04125 case JB_EMPTY:
04126
04127 break;
04128 default:
04129
04130 break;
04131 }
04132 }
04133 if (pvt)
04134 update_jbsched(pvt);
04135 ast_mutex_unlock(&iaxsl[callno]);
04136 }
04137
04138 static int get_from_jb(const void *data)
04139 {
04140 #ifdef SCHED_MULTITHREADED
04141 if (schedule_action(__get_from_jb, data))
04142 #endif
04143 __get_from_jb(data);
04144 return 0;
04145 }
04146
04147
04148
04149
04150
04151
04152
04153 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
04154 {
04155 int type, len;
04156 int ret;
04157 int needfree = 0;
04158 struct ast_channel *owner = NULL;
04159 struct ast_channel *bridge = NULL;
04160
04161
04162
04163
04164
04165
04166 if (!fr->af.datalen) {
04167 memset(&fr->af.data, 0, sizeof(fr->af.data));
04168 }
04169
04170
04171 unwrap_timestamp(fr);
04172
04173
04174 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04175 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04176 else {
04177 #if 0
04178 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04179 #endif
04180 fr->af.delivery = ast_tv(0,0);
04181 }
04182
04183 type = JB_TYPE_CONTROL;
04184 len = 0;
04185
04186 if(fr->af.frametype == AST_FRAME_VOICE) {
04187 type = JB_TYPE_VOICE;
04188 len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass.codec) / 1000);
04189 } else if(fr->af.frametype == AST_FRAME_CNG) {
04190 type = JB_TYPE_SILENCE;
04191 }
04192
04193 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04194 if (tsout)
04195 *tsout = fr->ts;
04196 __do_deliver(fr);
04197 return -1;
04198 }
04199
04200 iax2_lock_owner(fr->callno);
04201 if (!iaxs[fr->callno]) {
04202
04203 iax2_frame_free(fr);
04204 return -1;
04205 }
04206 if ((owner = iaxs[fr->callno]->owner))
04207 bridge = ast_bridged_channel(owner);
04208
04209
04210
04211 if ( (!ast_test_flag64(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04212 jb_frame frame;
04213
04214 ast_channel_unlock(owner);
04215
04216
04217 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04218 __do_deliver(frame.data);
04219
04220 if (!iaxs[fr->callno])
04221 return -1;
04222 }
04223
04224 jb_reset(iaxs[fr->callno]->jb);
04225
04226 ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04227
04228
04229 if (tsout)
04230 *tsout = fr->ts;
04231 __do_deliver(fr);
04232 return -1;
04233 }
04234 if (owner) {
04235 ast_channel_unlock(owner);
04236 }
04237
04238
04239
04240 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04241 calc_rxstamp(iaxs[fr->callno],fr->ts));
04242 if (ret == JB_DROP) {
04243 needfree++;
04244 } else if (ret == JB_SCHED) {
04245 update_jbsched(iaxs[fr->callno]);
04246 }
04247 if (tsout)
04248 *tsout = fr->ts;
04249 if (needfree) {
04250
04251 iax2_frame_free(fr);
04252 return -1;
04253 }
04254 return 0;
04255 }
04256
04257 static int transmit_frame(void *data)
04258 {
04259 struct iax_frame *fr = data;
04260
04261 ast_mutex_lock(&iaxsl[fr->callno]);
04262
04263 fr->sentyet = 1;
04264
04265 if (iaxs[fr->callno]) {
04266 send_packet(fr);
04267 }
04268
04269 if (fr->retries < 0) {
04270 ast_mutex_unlock(&iaxsl[fr->callno]);
04271
04272 iax_frame_free(fr);
04273 } else {
04274
04275 AST_LIST_INSERT_TAIL(&frame_queue[fr->callno], fr, list);
04276 fr->retries++;
04277 fr->retrans = iax2_sched_add(sched, fr->retrytime, attempt_transmit, fr);
04278 ast_mutex_unlock(&iaxsl[fr->callno]);
04279 }
04280
04281 return 0;
04282 }
04283
04284 static int iax2_transmit(struct iax_frame *fr)
04285 {
04286 fr->sentyet = 0;
04287
04288 return ast_taskprocessor_push(transmit_processor, transmit_frame, fr);
04289 }
04290
04291 static int iax2_digit_begin(struct ast_channel *c, char digit)
04292 {
04293 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04294 }
04295
04296 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04297 {
04298 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04299 }
04300
04301 static int iax2_sendtext(struct ast_channel *c, const char *text)
04302 {
04303
04304 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04305 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04306 }
04307
04308 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04309 {
04310 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass.integer, 0, img->data.ptr, img->datalen, -1);
04311 }
04312
04313 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04314 {
04315 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04316 }
04317
04318 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04319 {
04320 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04321 ast_mutex_lock(&iaxsl[callno]);
04322 if (iaxs[callno])
04323 iaxs[callno]->owner = newchan;
04324 else
04325 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04326 ast_mutex_unlock(&iaxsl[callno]);
04327 return 0;
04328 }
04329
04330
04331
04332
04333
04334 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04335 {
04336 struct ast_variable *var = NULL;
04337 struct ast_variable *tmp;
04338 struct iax2_peer *peer=NULL;
04339 time_t regseconds = 0, nowtime;
04340 int dynamic=0;
04341
04342 if (peername) {
04343 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04344 if (!var && sin)
04345 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04346 } else if (sin) {
04347 char porta[25];
04348 sprintf(porta, "%d", ntohs(sin->sin_port));
04349 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04350 if (var) {
04351
04352 for (tmp = var; tmp; tmp = tmp->next) {
04353 if (!strcasecmp(tmp->name, "name"))
04354 peername = tmp->value;
04355 }
04356 }
04357 }
04358 if (!var && peername) {
04359 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04360
04361
04362
04363
04364
04365
04366 if (var && sin) {
04367 for (tmp = var; tmp; tmp = tmp->next) {
04368 if (!strcasecmp(tmp->name, "host")) {
04369 struct ast_hostent ahp;
04370 struct hostent *hp;
04371 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04372
04373 ast_variables_destroy(var);
04374 var = NULL;
04375 }
04376 break;
04377 }
04378 }
04379 }
04380 }
04381 if (!var)
04382 return NULL;
04383
04384 peer = build_peer(peername, var, NULL, ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04385
04386 if (!peer) {
04387 ast_variables_destroy(var);
04388 return NULL;
04389 }
04390
04391 for (tmp = var; tmp; tmp = tmp->next) {
04392
04393 if (!strcasecmp(tmp->name, "type")) {
04394 if (strcasecmp(tmp->value, "friend") &&
04395 strcasecmp(tmp->value, "peer")) {
04396
04397 peer = peer_unref(peer);
04398 break;
04399 }
04400 } else if (!strcasecmp(tmp->name, "regseconds")) {
04401 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
04402 } else if (!strcasecmp(tmp->name, "ipaddr")) {
04403 if (!ast_sockaddr_parse(&peer->addr, tmp->value, PARSE_PORT_IGNORE)) {
04404 ast_log(LOG_WARNING, "Failed to parse sockaddr '%s' for ipaddr of realtime peer '%s'\n", tmp->value, tmp->name);
04405 }
04406 } else if (!strcasecmp(tmp->name, "port")) {
04407 ast_sockaddr_set_port(&peer->addr, atoi(tmp->value));
04408 } else if (!strcasecmp(tmp->name, "host")) {
04409 if (!strcasecmp(tmp->value, "dynamic"))
04410 dynamic = 1;
04411 }
04412 }
04413
04414 ast_variables_destroy(var);
04415
04416 if (!peer)
04417 return NULL;
04418
04419 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04420 ast_copy_flags64(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04421 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR)) {
04422 if (peer->expire > -1) {
04423 if (!ast_sched_thread_del(sched, peer->expire)) {
04424 peer->expire = -1;
04425 peer_unref(peer);
04426 }
04427 }
04428 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04429 if (peer->expire == -1)
04430 peer_unref(peer);
04431 }
04432 ao2_link(peers, peer);
04433 if (ast_test_flag64(peer, IAX_DYNAMIC))
04434 reg_source_db(peer);
04435 } else {
04436 ast_set_flag64(peer, IAX_TEMPONLY);
04437 }
04438
04439 if (!ast_test_flag64(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04440 time(&nowtime);
04441 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04442 memset(&peer->addr, 0, sizeof(peer->addr));
04443 realtime_update_peer(peer->name, &peer->addr, 0);
04444 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04445 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04446 }
04447 else {
04448 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04449 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04450 }
04451 }
04452
04453 return peer;
04454 }
04455
04456 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04457 {
04458 struct ast_variable *var;
04459 struct ast_variable *tmp;
04460 struct iax2_user *user=NULL;
04461
04462 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04463 if (!var)
04464 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04465 if (!var && sin) {
04466 char porta[6];
04467 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04468 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04469 if (!var)
04470 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04471 }
04472 if (!var) {
04473 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04474
04475
04476
04477
04478
04479
04480 if (var) {
04481 for (tmp = var; tmp; tmp = tmp->next) {
04482 if (!strcasecmp(tmp->name, "host")) {
04483 struct ast_hostent ahp;
04484 struct hostent *hp;
04485 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || memcmp(hp->h_addr, &sin->sin_addr, hp->h_length)) {
04486
04487 ast_variables_destroy(var);
04488 var = NULL;
04489 }
04490 break;
04491 }
04492 }
04493 }
04494 }
04495 if (!var)
04496 return NULL;
04497
04498 tmp = var;
04499 while(tmp) {
04500
04501 if (!strcasecmp(tmp->name, "type")) {
04502 if (strcasecmp(tmp->value, "friend") &&
04503 strcasecmp(tmp->value, "user")) {
04504 return NULL;
04505 }
04506 }
04507 tmp = tmp->next;
04508 }
04509
04510 user = build_user(username, var, NULL, !ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS));
04511
04512 ast_variables_destroy(var);
04513
04514 if (!user)
04515 return NULL;
04516
04517 if (ast_test_flag64((&globalflags), IAX_RTCACHEFRIENDS)) {
04518 ast_set_flag64(user, IAX_RTCACHEFRIENDS);
04519 ao2_link(users, user);
04520 } else {
04521 ast_set_flag64(user, IAX_TEMPONLY);
04522 }
04523
04524 return user;
04525 }
04526
04527 static void realtime_update_peer(const char *peername, struct ast_sockaddr *sockaddr, time_t regtime)
04528 {
04529 char port[10];
04530 char regseconds[20];
04531 const char *sysname = ast_config_AST_SYSTEM_NAME;
04532 char *syslabel = NULL;
04533
04534 if (ast_strlen_zero(sysname))
04535 sysname = NULL;
04536 else if (ast_test_flag64(&globalflags, IAX_RTSAVE_SYSNAME))
04537 syslabel = "regserver";
04538
04539 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04540 snprintf(port, sizeof(port), "%d", ast_sockaddr_port(sockaddr));
04541 ast_update_realtime("iaxpeers", "name", peername,
04542 "ipaddr", ast_sockaddr_stringify_addr(sockaddr), "port", port,
04543 "regseconds", regseconds, syslabel, sysname, SENTINEL);
04544 }
04545
04546 struct create_addr_info {
04547 format_t capability;
04548 uint64_t flags;
04549 int maxtime;
04550 int encmethods;
04551 int found;
04552 int sockfd;
04553 int adsi;
04554 char username[80];
04555 char secret[80];
04556 char outkey[80];
04557 char timezone[80];
04558 char prefs[32];
04559 char cid_num[80];
04560 char cid_name[80];
04561 char context[AST_MAX_CONTEXT];
04562 char peercontext[AST_MAX_CONTEXT];
04563 char mohinterpret[MAX_MUSICCLASS];
04564 char mohsuggest[MAX_MUSICCLASS];
04565 };
04566
04567 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04568 {
04569 struct iax2_peer *peer;
04570 int res = -1;
04571 struct ast_codec_pref ourprefs;
04572 struct sockaddr_in peer_addr;
04573
04574 ast_clear_flag64(cai, IAX_SENDANI | IAX_TRUNK);
04575 cai->sockfd = defaultsockfd;
04576 cai->maxtime = 0;
04577 sin->sin_family = AF_INET;
04578
04579 if (!(peer = find_peer(peername, 1))) {
04580 struct ast_sockaddr sin_tmp;
04581
04582 cai->found = 0;
04583 sin_tmp.ss.ss_family = AF_INET;
04584 if (ast_get_ip_or_srv(&sin_tmp, peername, srvlookup ? "_iax._udp" : NULL)) {
04585 ast_log(LOG_WARNING, "No such host: %s\n", peername);
04586 return -1;
04587 }
04588 ast_sockaddr_to_sin(&sin_tmp, sin);
04589 if (sin->sin_port == 0) {
04590 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04591 }
04592
04593
04594 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04595 if (c)
04596 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04597 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04598 return 0;
04599 }
04600
04601 cai->found = 1;
04602
04603 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
04604
04605
04606 if (!(peer_addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr)) {
04607 goto return_unref;
04608 }
04609
04610
04611 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04612 goto return_unref;
04613
04614 ast_copy_flags64(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
04615 cai->maxtime = peer->maxms;
04616 cai->capability = peer->capability;
04617 cai->encmethods = peer->encmethods;
04618 cai->sockfd = peer->sockfd;
04619 cai->adsi = peer->adsi;
04620 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04621
04622 if (c) {
04623 ast_debug(1, "prepending %llx to prefs\n", (unsigned long long) c->nativeformats);
04624 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04625 }
04626 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04627 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04628 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04629 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04630 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04631 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04632 ast_copy_string(cai->cid_num, peer->cid_num, sizeof(cai->cid_num));
04633 ast_copy_string(cai->cid_name, peer->cid_name, sizeof(cai->cid_name));
04634 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04635 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04636 if (ast_strlen_zero(peer->dbsecret)) {
04637 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04638 } else {
04639 char *family;
04640 char *key = NULL;
04641
04642 family = ast_strdupa(peer->dbsecret);
04643 key = strchr(family, '/');
04644 if (key)
04645 *key++ = '\0';
04646 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04647 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04648 goto return_unref;
04649 }
04650 }
04651
04652 if (peer_addr.sin_addr.s_addr) {
04653 sin->sin_addr = peer_addr.sin_addr;
04654 sin->sin_port = peer_addr.sin_port;
04655 } else {
04656 sin->sin_addr = peer->defaddr.sin_addr;
04657 sin->sin_port = peer->defaddr.sin_port;
04658 }
04659
04660 res = 0;
04661
04662 return_unref:
04663 peer_unref(peer);
04664
04665 return res;
04666 }
04667
04668 static void __auto_congest(const void *nothing)
04669 {
04670 int callno = PTR_TO_CALLNO(nothing);
04671 struct ast_frame f = { AST_FRAME_CONTROL, { AST_CONTROL_CONGESTION } };
04672 ast_mutex_lock(&iaxsl[callno]);
04673 if (iaxs[callno]) {
04674 iaxs[callno]->initid = -1;
04675 iax2_queue_frame(callno, &f);
04676 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04677 }
04678 ast_mutex_unlock(&iaxsl[callno]);
04679 }
04680
04681 static int auto_congest(const void *data)
04682 {
04683 #ifdef SCHED_MULTITHREADED
04684 if (schedule_action(__auto_congest, data))
04685 #endif
04686 __auto_congest(data);
04687 return 0;
04688 }
04689
04690 static unsigned int iax2_datetime(const char *tz)
04691 {
04692 struct timeval t = ast_tvnow();
04693 struct ast_tm tm;
04694 unsigned int tmp;
04695 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04696 tmp = (tm.tm_sec >> 1) & 0x1f;
04697 tmp |= (tm.tm_min & 0x3f) << 5;
04698 tmp |= (tm.tm_hour & 0x1f) << 11;
04699 tmp |= (tm.tm_mday & 0x1f) << 16;
04700 tmp |= ((tm.tm_mon + 1) & 0xf) << 21;
04701 tmp |= ((tm.tm_year - 100) & 0x7f) << 25;
04702 return tmp;
04703 }
04704
04705 struct parsed_dial_string {
04706 char *username;
04707 char *password;
04708 char *key;
04709 char *peer;
04710 char *port;
04711 char *exten;
04712 char *context;
04713 char *options;
04714 };
04715
04716 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04717 struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04718 int sockfd, struct iax_ie_data *ied)
04719 {
04720 struct {
04721 struct ast_iax2_full_hdr f;
04722 struct iax_ie_data ied;
04723 } data;
04724 size_t size = sizeof(struct ast_iax2_full_hdr);
04725
04726 if (ied) {
04727 size += ied->pos;
04728 memcpy(&data.ied, ied->buf, ied->pos);
04729 }
04730
04731 data.f.scallno = htons(0x8000 | callno);
04732 data.f.dcallno = htons(dcallno & ~IAX_FLAG_RETRANS);
04733 data.f.ts = htonl(ts);
04734 data.f.iseqno = seqno;
04735 data.f.oseqno = 0;
04736 data.f.type = AST_FRAME_IAX;
04737 data.f.csub = compress_subclass(command);
04738
04739 iax_outputframe(NULL, &data.f, 0, sin, size - sizeof(struct ast_iax2_full_hdr));
04740
04741 return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04742 }
04743
04744 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04745 {
04746
04747 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04748 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;
04749 ied->buf[ied->pos++] = 0;
04750 pvt->calltoken_ie_len = 2;
04751 }
04752 }
04753
04754 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04755 {
04756 struct chan_iax2_pvt *pvt = iaxs[callno];
04757 int frametype = f->af.frametype;
04758 int subclass = f->af.subclass.integer;
04759 struct {
04760 struct ast_iax2_full_hdr fh;
04761 struct iax_ie_data ied;
04762 } data = {
04763 .ied.buf = { 0 },
04764 .ied.pos = 0,
04765 };
04766
04767 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04768
04769 if (!pvt) {
04770 return;
04771 }
04772
04773
04774
04775
04776
04777
04778
04779
04780
04781
04782
04783
04784 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04785 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04786 (f->datalen > sizeof(data))) {
04787
04788 return;
04789 }
04790
04791
04792
04793
04794
04795
04796
04797
04798
04799
04800
04801
04802
04803
04804
04805 memcpy(&data, f->data, f->datalen);
04806 data.ied.pos = ie_data_pos;
04807
04808
04809
04810 data.ied.pos -= pvt->calltoken_ie_len;
04811 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04812
04813
04814 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos;
04815
04816
04817 AST_LIST_REMOVE(&frame_queue[callno], f, list);
04818
04819
04820 iax2_frame_free(f);
04821
04822
04823 pvt->oseqno = 0;
04824 pvt->rseqno = 0;
04825 pvt->iseqno = 0;
04826 pvt->aseqno = 0;
04827 if (pvt->peercallno) {
04828 remove_by_peercallno(pvt);
04829 pvt->peercallno = 0;
04830 }
04831
04832
04833 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04834 }
04835
04836 static void requirecalltoken_mark_auto(const char *name, int subclass)
04837 {
04838 struct iax2_user *user = NULL;
04839 struct iax2_peer *peer = NULL;
04840
04841 if (ast_strlen_zero(name)) {
04842 return;
04843 }
04844
04845 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04846 user->calltoken_required = CALLTOKEN_YES;
04847 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04848 peer->calltoken_required = CALLTOKEN_YES;
04849 }
04850
04851 if (peer) {
04852 peer_unref(peer);
04853 }
04854 if (user) {
04855 user_unref(user);
04856 }
04857 }
04858
04859
04860
04861
04862
04863
04864
04865
04866
04867
04868
04869
04870
04871
04872
04873
04874
04875
04876 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04877 struct sockaddr_in *sin, int fd)
04878 {
04879 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"
04880 #define CALLTOKEN_IE_FORMAT "%u?%s"
04881 struct ast_str *buf = ast_str_alloca(256);
04882 time_t t = time(NULL);
04883 char hash[41];
04884 int subclass = uncompress_subclass(fh->csub);
04885
04886
04887 if (ies->calltoken && !ies->calltokendata) {
04888 struct iax_ie_data ied = {
04889 .buf = { 0 },
04890 .pos = 0,
04891 };
04892
04893
04894 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04895 ast_sha1_hash(hash, ast_str_buffer(buf));
04896
04897 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04898 iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04899 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04900
04901 return 1;
04902
04903
04904 } else if (ies->calltoken && ies->calltokendata) {
04905 char *rec_hash = NULL;
04906 char *rec_ts = NULL;
04907 unsigned int rec_time;
04908
04909
04910 rec_hash = strchr((char *) ies->calltokendata, '?');
04911 if (rec_hash) {
04912 *rec_hash++ = '\0';
04913 rec_ts = (char *) ies->calltokendata;
04914 }
04915
04916
04917 if (!rec_hash || !rec_ts) {
04918 goto reject;
04919 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04920 goto reject;
04921 }
04922
04923
04924 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04925 ast_sha1_hash(hash, ast_str_buffer(buf));
04926
04927
04928 if (strcmp(hash, rec_hash)) {
04929 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04930 goto reject;
04931 } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04932 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04933 goto reject;
04934 }
04935
04936
04937
04938 requirecalltoken_mark_auto(ies->username, subclass);
04939 return 0;
04940
04941
04942 } else {
04943 if (calltoken_required(sin, ies->username, subclass)) {
04944 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"));
04945 goto reject;
04946 }
04947 return 0;
04948 }
04949
04950 reject:
04951
04952 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04953 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04954 } else {
04955 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04956 }
04957
04958 return 1;
04959 }
04960
04961
04962
04963
04964
04965
04966
04967
04968
04969
04970
04971
04972
04973
04974
04975
04976
04977
04978
04979 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04980 {
04981 if (ast_strlen_zero(data))
04982 return;
04983
04984 pds->peer = strsep(&data, "/");
04985 pds->exten = strsep(&data, "/");
04986 pds->options = data;
04987
04988 if (pds->exten) {
04989 data = pds->exten;
04990 pds->exten = strsep(&data, "@");
04991 pds->context = data;
04992 }
04993
04994 if (strchr(pds->peer, '@')) {
04995 data = pds->peer;
04996 pds->username = strsep(&data, "@");
04997 pds->peer = data;
04998 }
04999
05000 if (pds->username) {
05001 data = pds->username;
05002 pds->username = strsep(&data, ":");
05003 pds->password = data;
05004 }
05005
05006 data = pds->peer;
05007 pds->peer = strsep(&data, ":");
05008 pds->port = data;
05009
05010
05011
05012
05013 if (pds->password && (pds->password[0] == '[')) {
05014 pds->key = ast_strip_quoted(pds->password, "[", "]");
05015 pds->password = NULL;
05016 }
05017 }
05018
05019 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
05020 {
05021 struct sockaddr_in sin;
05022 char *l=NULL, *n=NULL, *tmpstr;
05023 struct iax_ie_data ied;
05024 char *defaultrdest = "s";
05025 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05026 struct parsed_dial_string pds;
05027 struct create_addr_info cai;
05028 struct ast_var_t *var;
05029 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
05030 const char* osp_token_ptr;
05031 unsigned int osp_token_length;
05032 unsigned char osp_block_index;
05033 unsigned int osp_block_length;
05034 unsigned char osp_buffer[256];
05035
05036 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
05037 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
05038 return -1;
05039 }
05040
05041 memset(&cai, 0, sizeof(cai));
05042 cai.encmethods = iax2_encryption;
05043
05044 memset(&pds, 0, sizeof(pds));
05045 tmpstr = ast_strdupa(dest);
05046 parse_dial_string(tmpstr, &pds);
05047
05048 if (ast_strlen_zero(pds.peer)) {
05049 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
05050 return -1;
05051 }
05052 if (!pds.exten) {
05053 pds.exten = defaultrdest;
05054 }
05055 if (create_addr(pds.peer, c, &sin, &cai)) {
05056 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
05057 return -1;
05058 }
05059 if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) && !cai.encmethods) {
05060 ast_log(LOG_WARNING, "Encryption forced for call, but not enabled\n");
05061 c->hangupcause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05062 return -1;
05063 }
05064 if (ast_strlen_zero(cai.secret) && ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
05065 ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
05066 return -1;
05067 }
05068 if (!pds.username && !ast_strlen_zero(cai.username))
05069 pds.username = cai.username;
05070 if (!pds.password && !ast_strlen_zero(cai.secret))
05071 pds.password = cai.secret;
05072 if (!pds.key && !ast_strlen_zero(cai.outkey))
05073 pds.key = cai.outkey;
05074 if (!pds.context && !ast_strlen_zero(cai.peercontext))
05075 pds.context = cai.peercontext;
05076
05077
05078 ast_copy_string(c->context, cai.context, sizeof(c->context));
05079
05080 if (pds.port)
05081 sin.sin_port = htons(atoi(pds.port));
05082
05083 l = c->connected.id.number.valid ? c->connected.id.number.str : NULL;
05084 n = c->connected.id.name.valid ? c->connected.id.name.str : NULL;
05085
05086
05087 memset(&ied, 0, sizeof(ied));
05088
05089
05090 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
05091 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
05092 if (pds.options && strchr(pds.options, 'a')) {
05093
05094 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
05095 }
05096
05097
05098 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
05099
05100 if (l) {
05101 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
05102 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05103 ast_party_id_presentation(&c->connected.id));
05104 } else if (n) {
05105 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES,
05106 ast_party_id_presentation(&c->connected.id));
05107 } else {
05108 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
05109 }
05110
05111 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->connected.id.number.plan);
05112 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->dialed.transit_network_select);
05113
05114 if (n)
05115 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
05116 if (ast_test_flag64(iaxs[callno], IAX_SENDANI)
05117 && c->connected.ani.number.valid
05118 && c->connected.ani.number.str) {
05119 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->connected.ani.number.str);
05120 }
05121
05122 if (!ast_strlen_zero(c->language))
05123 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
05124 if (!ast_strlen_zero(c->dialed.number.str)) {
05125 iax_ie_append_str(&ied, IAX_IE_DNID, c->dialed.number.str);
05126 }
05127 if (c->redirecting.from.number.valid
05128 && !ast_strlen_zero(c->redirecting.from.number.str)) {
05129 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->redirecting.from.number.str);
05130 }
05131
05132 if (pds.context)
05133 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
05134
05135 if (pds.username)
05136 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
05137
05138 if (cai.encmethods)
05139 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
05140
05141 ast_mutex_lock(&iaxsl[callno]);
05142
05143 if (!ast_strlen_zero(c->context))
05144 ast_string_field_set(iaxs[callno], context, c->context);
05145
05146 if (pds.username)
05147 ast_string_field_set(iaxs[callno], username, pds.username);
05148
05149 iaxs[callno]->encmethods = cai.encmethods;
05150
05151 iaxs[callno]->adsi = cai.adsi;
05152
05153 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
05154 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
05155
05156 if (pds.key)
05157 ast_string_field_set(iaxs[callno], outkey, pds.key);
05158 if (pds.password)
05159 ast_string_field_set(iaxs[callno], secret, pds.password);
05160
05161 iax_ie_append_int(&ied, IAX_IE_FORMAT, (int) c->nativeformats);
05162 iax_ie_append_versioned_uint64(&ied, IAX_IE_FORMAT2, 0, c->nativeformats);
05163 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, (int) iaxs[callno]->capability);
05164 iax_ie_append_versioned_uint64(&ied, IAX_IE_CAPABILITY2, 0, iaxs[callno]->capability);
05165 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
05166 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
05167
05168 if (iaxs[callno]->maxtime) {
05169
05170 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
05171 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
05172 } else if (autokill) {
05173 iaxs[callno]->pingtime = autokill / 2;
05174 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
05175 }
05176
05177
05178 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
05179 if (!ast_strlen_zero(osp_token_ptr)) {
05180 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
05181 osp_block_index = 0;
05182 while (osp_token_length > 0) {
05183 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
05184 osp_buffer[0] = osp_block_index;
05185 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
05186 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
05187 osp_block_index++;
05188 osp_token_ptr += osp_block_length;
05189 osp_token_length -= osp_block_length;
05190 }
05191 } else
05192 ast_log(LOG_WARNING, "OSP token is too long\n");
05193 } else if (iaxdebug)
05194 ast_debug(1, "OSP token is undefined\n");
05195
05196
05197 iaxs[callno]->sockfd = cai.sockfd;
05198
05199
05200 if (variablestore) {
05201 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
05202 ast_debug(1, "Found an IAX variable store on this channel\n");
05203 AST_LIST_LOCK(variablelist);
05204 AST_LIST_TRAVERSE(variablelist, var, entries) {
05205 char tmp[256];
05206 int i;
05207 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
05208
05209 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
05210 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
05211 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
05212 }
05213 }
05214 AST_LIST_UNLOCK(variablelist);
05215 }
05216
05217
05218 add_empty_calltoken_ie(iaxs[callno], &ied);
05219 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
05220
05221 ast_mutex_unlock(&iaxsl[callno]);
05222 ast_setstate(c, AST_STATE_RINGING);
05223
05224 return 0;
05225 }
05226
05227 static int iax2_hangup(struct ast_channel *c)
05228 {
05229 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05230 struct iax_ie_data ied;
05231 int alreadygone;
05232 memset(&ied, 0, sizeof(ied));
05233 ast_mutex_lock(&iaxsl[callno]);
05234 if (callno && iaxs[callno]) {
05235 ast_debug(1, "We're hanging up %s now...\n", c->name);
05236 alreadygone = ast_test_flag64(iaxs[callno], IAX_ALREADYGONE);
05237
05238 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05239 if (!iaxs[callno]->error && !alreadygone) {
05240 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05241 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05242 }
05243 if (!iaxs[callno]) {
05244 ast_mutex_unlock(&iaxsl[callno]);
05245 return 0;
05246 }
05247 }
05248
05249 iax2_predestroy(callno);
05250
05251 if (iaxs[callno] && alreadygone) {
05252 ast_debug(1, "Really destroying %s now...\n", c->name);
05253 iax2_destroy(callno);
05254 } else if (iaxs[callno]) {
05255 if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05256 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
05257 iax2_destroy(callno);
05258 }
05259 }
05260 } else if (c->tech_pvt) {
05261
05262
05263
05264
05265 c->tech_pvt = NULL;
05266 }
05267 ast_mutex_unlock(&iaxsl[callno]);
05268 ast_verb(3, "Hungup '%s'\n", c->name);
05269 return 0;
05270 }
05271
05272
05273
05274
05275 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05276 {
05277 unsigned short callno = pvt->callno;
05278
05279 if (!pvt->peercallno) {
05280
05281 int count = 10;
05282 while (count-- && pvt && !pvt->peercallno) {
05283 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05284 pvt = iaxs[callno];
05285 }
05286 if (!pvt || !pvt->peercallno) {
05287 return -1;
05288 }
05289 }
05290
05291 return 0;
05292 }
05293
05294 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05295 {
05296 struct ast_option_header *h;
05297 int res;
05298
05299 switch (option) {
05300 case AST_OPTION_TXGAIN:
05301 case AST_OPTION_RXGAIN:
05302
05303 errno = ENOSYS;
05304 return -1;
05305 case AST_OPTION_OPRMODE:
05306 errno = EINVAL;
05307 return -1;
05308 case AST_OPTION_SECURE_SIGNALING:
05309 case AST_OPTION_SECURE_MEDIA:
05310 {
05311 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05312 ast_mutex_lock(&iaxsl[callno]);
05313 if ((*(int *) data)) {
05314 ast_set_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05315 } else {
05316 ast_clear_flag64(iaxs[callno], IAX_FORCE_ENCRYPT);
05317 }
05318 ast_mutex_unlock(&iaxsl[callno]);
05319 return 0;
05320 }
05321
05322
05323
05324
05325 case AST_OPTION_TONE_VERIFY:
05326 case AST_OPTION_TDD:
05327 case AST_OPTION_RELAXDTMF:
05328 case AST_OPTION_AUDIO_MODE:
05329 case AST_OPTION_DIGIT_DETECT:
05330 case AST_OPTION_FAX_DETECT:
05331 {
05332 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05333 struct chan_iax2_pvt *pvt;
05334
05335 ast_mutex_lock(&iaxsl[callno]);
05336 pvt = iaxs[callno];
05337
05338 if (wait_for_peercallno(pvt)) {
05339 ast_mutex_unlock(&iaxsl[callno]);
05340 return -1;
05341 }
05342
05343 ast_mutex_unlock(&iaxsl[callno]);
05344
05345 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05346 return -1;
05347 }
05348
05349 h->flag = AST_OPTION_FLAG_REQUEST;
05350 h->option = htons(option);
05351 memcpy(h->data, data, datalen);
05352 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05353 AST_CONTROL_OPTION, 0, (unsigned char *) h,
05354 datalen + sizeof(*h), -1);
05355 ast_free(h);
05356 return res;
05357 }
05358 default:
05359 return -1;
05360 }
05361
05362
05363 return -1;
05364 }
05365
05366 static int iax2_queryoption(struct ast_channel *c, int option, void *data, int *datalen)
05367 {
05368 switch (option) {
05369 case AST_OPTION_SECURE_SIGNALING:
05370 case AST_OPTION_SECURE_MEDIA:
05371 {
05372 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05373 ast_mutex_lock(&iaxsl[callno]);
05374 *((int *) data) = ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT) ? 1 : 0;
05375 ast_mutex_unlock(&iaxsl[callno]);
05376 return 0;
05377 }
05378 default:
05379 return -1;
05380 }
05381 }
05382
05383 static struct ast_frame *iax2_read(struct ast_channel *c)
05384 {
05385 ast_debug(1, "I should never be called!\n");
05386 return &ast_null_frame;
05387 }
05388
05389 static int iax2_key_rotate(const void *vpvt)
05390 {
05391 int res = 0;
05392 struct chan_iax2_pvt *pvt = (void *) vpvt;
05393 struct MD5Context md5;
05394 char key[17] = "";
05395 struct iax_ie_data ied = {
05396 .pos = 0,
05397 };
05398
05399 ast_mutex_lock(&iaxsl[pvt->callno]);
05400 pvt->keyrotateid =
05401 ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05402
05403 snprintf(key, sizeof(key), "%lX", ast_random());
05404
05405 MD5Init(&md5);
05406 MD5Update(&md5, (unsigned char *) key, strlen(key));
05407 MD5Final((unsigned char *) key, &md5);
05408
05409 IAX_DEBUGDIGEST("Sending", key);
05410
05411 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05412
05413 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05414
05415 build_ecx_key((unsigned char *) key, pvt);
05416
05417 ast_mutex_unlock(&iaxsl[pvt->callno]);
05418
05419 return res;
05420 }
05421
05422 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05423 {
05424 int res;
05425 struct iax_ie_data ied0;
05426 struct iax_ie_data ied1;
05427 unsigned int transferid = (unsigned int)ast_random();
05428
05429 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05430 ast_debug(1, "transfers are not supported for encrypted calls at this time\n");
05431 ast_set_flag64(iaxs[callno0], IAX_NOTRANSFER);
05432 ast_set_flag64(iaxs[callno1], IAX_NOTRANSFER);
05433 return 0;
05434 }
05435
05436 memset(&ied0, 0, sizeof(ied0));
05437 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05438 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05439 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05440
05441 memset(&ied1, 0, sizeof(ied1));
05442 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05443 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05444 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05445
05446 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05447 if (res)
05448 return -1;
05449 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05450 if (res)
05451 return -1;
05452 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05453 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05454 return 0;
05455 }
05456
05457 static void lock_both(unsigned short callno0, unsigned short callno1)
05458 {
05459 ast_mutex_lock(&iaxsl[callno0]);
05460 while (ast_mutex_trylock(&iaxsl[callno1])) {
05461 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05462 }
05463 }
05464
05465 static void unlock_both(unsigned short callno0, unsigned short callno1)
05466 {
05467 ast_mutex_unlock(&iaxsl[callno1]);
05468 ast_mutex_unlock(&iaxsl[callno0]);
05469 }
05470
05471 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)
05472 {
05473 struct ast_channel *cs[3];
05474 struct ast_channel *who, *other;
05475 int to = -1;
05476 int res = -1;
05477 int transferstarted=0;
05478 struct ast_frame *f;
05479 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05480 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05481 struct timeval waittimer = {0, 0};
05482
05483
05484 if (timeoutms > 0) {
05485 return AST_BRIDGE_FAILED;
05486 }
05487
05488 timeoutms = -1;
05489
05490 lock_both(callno0, callno1);
05491 if (!iaxs[callno0] || !iaxs[callno1]) {
05492 unlock_both(callno0, callno1);
05493 return AST_BRIDGE_FAILED;
05494 }
05495
05496 if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05497 iaxs[callno0]->bridgecallno = callno1;
05498 iaxs[callno1]->bridgecallno = callno0;
05499 }
05500 unlock_both(callno0, callno1);
05501
05502
05503 cs[0] = c0;
05504 cs[1] = c1;
05505 for (;;) {
05506
05507 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05508 ast_verb(3, "Can't masquerade, we're different...\n");
05509
05510 if (c0->tech == &iax2_tech) {
05511 ast_mutex_lock(&iaxsl[callno0]);
05512 iaxs[callno0]->bridgecallno = 0;
05513 ast_mutex_unlock(&iaxsl[callno0]);
05514 }
05515 if (c1->tech == &iax2_tech) {
05516 ast_mutex_lock(&iaxsl[callno1]);
05517 iaxs[callno1]->bridgecallno = 0;
05518 ast_mutex_unlock(&iaxsl[callno1]);
05519 }
05520 return AST_BRIDGE_FAILED_NOWARN;
05521 }
05522 if (c0->nativeformats != c1->nativeformats) {
05523 char buf0[256];
05524 char buf1[256];
05525 ast_getformatname_multiple(buf0, sizeof(buf0), c0->nativeformats);
05526 ast_getformatname_multiple(buf1, sizeof(buf1), c1->nativeformats);
05527 ast_verb(3, "Operating with different codecs [%s] [%s] , can't native bridge...\n", buf0, buf1);
05528
05529 lock_both(callno0, callno1);
05530 if (iaxs[callno0])
05531 iaxs[callno0]->bridgecallno = 0;
05532 if (iaxs[callno1])
05533 iaxs[callno1]->bridgecallno = 0;
05534 unlock_both(callno0, callno1);
05535 return AST_BRIDGE_FAILED_NOWARN;
05536 }
05537
05538 if (!transferstarted && !ast_test_flag64(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag64(iaxs[callno1], IAX_NOTRANSFER)) {
05539
05540 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05541 ast_test_flag64(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag64(iaxs[callno1], IAX_TRANSFERMEDIA)))
05542 ast_log(LOG_WARNING, "Unable to start the transfer\n");
05543 transferstarted = 1;
05544 }
05545 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05546
05547 struct timeval now = ast_tvnow();
05548 if (ast_tvzero(waittimer)) {
05549 waittimer = now;
05550 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05551 c0->_softhangup |= AST_SOFTHANGUP_DEV;
05552 c1->_softhangup |= AST_SOFTHANGUP_DEV;
05553 *fo = NULL;
05554 *rc = c0;
05555 res = AST_BRIDGE_COMPLETE;
05556 break;
05557 }
05558 }
05559 to = 1000;
05560 who = ast_waitfor_n(cs, 2, &to);
05561 if (timeoutms > -1) {
05562 timeoutms -= (1000 - to);
05563 if (timeoutms < 0)
05564 timeoutms = 0;
05565 }
05566 if (!who) {
05567 if (!timeoutms) {
05568 res = AST_BRIDGE_RETRY;
05569 break;
05570 }
05571 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05572 res = AST_BRIDGE_FAILED;
05573 break;
05574 }
05575 continue;
05576 }
05577 f = ast_read(who);
05578 if (!f) {
05579 *fo = NULL;
05580 *rc = who;
05581 res = AST_BRIDGE_COMPLETE;
05582 break;
05583 }
05584 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass.integer != AST_CONTROL_SRCUPDATE)) {
05585 *fo = f;
05586 *rc = who;
05587 res = AST_BRIDGE_COMPLETE;
05588 break;
05589 }
05590 other = (who == c0) ? c1 : c0;
05591 if ((f->frametype == AST_FRAME_VOICE) ||
05592 (f->frametype == AST_FRAME_TEXT) ||
05593 (f->frametype == AST_FRAME_VIDEO) ||
05594 (f->frametype == AST_FRAME_IMAGE) ||
05595 (f->frametype == AST_FRAME_DTMF) ||
05596 (f->frametype == AST_FRAME_CONTROL)) {
05597
05598
05599
05600 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05601 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05602 *rc = who;
05603 *fo = f;
05604 res = AST_BRIDGE_COMPLETE;
05605
05606 break;
05607 }
05608
05609 ast_write(other, f);
05610 }
05611 ast_frfree(f);
05612
05613 cs[2] = cs[0];
05614 cs[0] = cs[1];
05615 cs[1] = cs[2];
05616 }
05617 lock_both(callno0, callno1);
05618 if(iaxs[callno0])
05619 iaxs[callno0]->bridgecallno = 0;
05620 if(iaxs[callno1])
05621 iaxs[callno1]->bridgecallno = 0;
05622 unlock_both(callno0, callno1);
05623 return res;
05624 }
05625
05626 static int iax2_answer(struct ast_channel *c)
05627 {
05628 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05629 ast_debug(1, "Answering IAX2 call\n");
05630 ast_mutex_lock(&iaxsl[callno]);
05631 if (iaxs[callno])
05632 iax2_ami_channelupdate(iaxs[callno]);
05633 ast_mutex_unlock(&iaxsl[callno]);
05634 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05635 }
05636
05637 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05638 {
05639 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05640 struct chan_iax2_pvt *pvt;
05641 int res = 0;
05642
05643 if (iaxdebug)
05644 ast_debug(1, "Indicating condition %d\n", condition);
05645
05646 ast_mutex_lock(&iaxsl[callno]);
05647 pvt = iaxs[callno];
05648
05649 if (wait_for_peercallno(pvt)) {
05650 res = -1;
05651 goto done;
05652 }
05653
05654 switch (condition) {
05655 case AST_CONTROL_HOLD:
05656 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05657 ast_moh_start(c, data, pvt->mohinterpret);
05658 goto done;
05659 }
05660 break;
05661 case AST_CONTROL_UNHOLD:
05662 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05663 ast_moh_stop(c);
05664 goto done;
05665 }
05666 break;
05667 case AST_CONTROL_CONNECTED_LINE:
05668 if (!ast_test_flag64(pvt, IAX_SENDCONNECTEDLINE))
05669 goto done;
05670 break;
05671 }
05672
05673 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05674
05675 done:
05676 ast_mutex_unlock(&iaxsl[callno]);
05677
05678 return res;
05679 }
05680
05681 static int iax2_transfer(struct ast_channel *c, const char *dest)
05682 {
05683 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05684 struct iax_ie_data ied = { "", };
05685 char tmp[256], *context;
05686 enum ast_control_transfer message = AST_TRANSFER_SUCCESS;
05687 ast_copy_string(tmp, dest, sizeof(tmp));
05688 context = strchr(tmp, '@');
05689 if (context) {
05690 *context = '\0';
05691 context++;
05692 }
05693 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05694 if (context)
05695 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05696 ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05697 ast_queue_control_data(c, AST_CONTROL_TRANSFER, &message, sizeof(message));
05698 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05699 }
05700
05701 static int iax2_getpeertrunk(struct sockaddr_in sin)
05702 {
05703 struct iax2_peer *peer;
05704 int res = 0;
05705 struct ao2_iterator i;
05706
05707 i = ao2_iterator_init(peers, 0);
05708 while ((peer = ao2_iterator_next(&i))) {
05709 struct sockaddr_in peer_addr;
05710
05711 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
05712
05713 if ((peer_addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05714 (peer_addr.sin_port == sin.sin_port)) {
05715 res = ast_test_flag64(peer, IAX_TRUNK);
05716 peer_unref(peer);
05717 break;
05718 }
05719 peer_unref(peer);
05720 }
05721 ao2_iterator_destroy(&i);
05722
05723 return res;
05724 }
05725
05726
05727 static struct ast_channel *ast_iax2_new(int callno, int state, format_t capability, const char *linkedid)
05728 {
05729 struct ast_channel *tmp;
05730 struct chan_iax2_pvt *i;
05731 struct ast_variable *v = NULL;
05732
05733 if (!(i = iaxs[callno])) {
05734 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05735 return NULL;
05736 }
05737
05738
05739 ast_mutex_unlock(&iaxsl[callno]);
05740 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);
05741 ast_mutex_lock(&iaxsl[callno]);
05742 if (i != iaxs[callno]) {
05743 if (tmp) {
05744
05745 ast_mutex_unlock(&iaxsl[callno]);
05746 tmp = ast_channel_release(tmp);
05747 ast_mutex_lock(&iaxsl[callno]);
05748 }
05749 return NULL;
05750 }
05751 iax2_ami_channelupdate(i);
05752 if (!tmp)
05753 return NULL;
05754 tmp->tech = &iax2_tech;
05755
05756 tmp->nativeformats = capability;
05757 tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05758 tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05759 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05760
05761 if (!ast_strlen_zero(i->parkinglot))
05762 ast_string_field_set(tmp, parkinglot, i->parkinglot);
05763
05764
05765 if (!ast_strlen_zero(i->ani)) {
05766 tmp->caller.ani.number.valid = 1;
05767 tmp->caller.ani.number.str = ast_strdup(i->ani);
05768 } else if (!ast_strlen_zero(i->cid_num)) {
05769 tmp->caller.ani.number.valid = 1;
05770 tmp->caller.ani.number.str = ast_strdup(i->cid_num);
05771 }
05772 tmp->dialed.number.str = ast_strdup(i->dnid);
05773 if (!ast_strlen_zero(i->rdnis)) {
05774 tmp->redirecting.from.number.valid = 1;
05775 tmp->redirecting.from.number.str = ast_strdup(i->rdnis);
05776 }
05777 tmp->caller.id.name.presentation = i->calling_pres;
05778 tmp->caller.id.number.presentation = i->calling_pres;
05779 tmp->caller.id.number.plan = i->calling_ton;
05780 tmp->dialed.transit_network_select = i->calling_tns;
05781 if (!ast_strlen_zero(i->language))
05782 ast_string_field_set(tmp, language, i->language);
05783 if (!ast_strlen_zero(i->accountcode))
05784 ast_string_field_set(tmp, accountcode, i->accountcode);
05785 if (i->amaflags)
05786 tmp->amaflags = i->amaflags;
05787 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05788 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05789 if (i->adsi)
05790 tmp->adsicpe = i->peeradsicpe;
05791 else
05792 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05793 i->owner = tmp;
05794 i->capability = capability;
05795
05796
05797 if (i->vars) {
05798 for (v = i->vars ; v ; v = v->next)
05799 pbx_builtin_setvar_helper(tmp, v->name, v->value);
05800 }
05801 if (i->iaxvars) {
05802 struct ast_datastore *variablestore;
05803 struct ast_variable *var, *prev = NULL;
05804 AST_LIST_HEAD(, ast_var_t) *varlist;
05805 ast_debug(1, "Loading up the channel with IAXVARs\n");
05806 varlist = ast_calloc(1, sizeof(*varlist));
05807 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05808 if (variablestore && varlist) {
05809 variablestore->data = varlist;
05810 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05811 AST_LIST_HEAD_INIT(varlist);
05812 for (var = i->iaxvars; var; var = var->next) {
05813 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05814 if (prev)
05815 ast_free(prev);
05816 prev = var;
05817 if (!newvar) {
05818
05819 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05820 } else {
05821 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05822 }
05823 }
05824 if (prev)
05825 ast_free(prev);
05826 i->iaxvars = NULL;
05827 ast_channel_datastore_add(i->owner, variablestore);
05828 } else {
05829 if (variablestore) {
05830 ast_datastore_free(variablestore);
05831 }
05832 if (varlist) {
05833 ast_free(varlist);
05834 }
05835 }
05836 }
05837
05838 if (state != AST_STATE_DOWN) {
05839 if (ast_pbx_start(tmp)) {
05840 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05841 ast_hangup(tmp);
05842 i->owner = NULL;
05843 return NULL;
05844 }
05845 }
05846
05847 ast_module_ref(ast_module_info->self);
05848 return tmp;
05849 }
05850
05851 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05852 {
05853 unsigned long int mssincetx;
05854 long int ms, pred;
05855
05856 tpeer->trunkact = *now;
05857 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05858 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05859
05860 tpeer->txtrunktime = *now;
05861 tpeer->lastsent = 999999;
05862 }
05863
05864 tpeer->lasttxtime = *now;
05865
05866
05867 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05868
05869 pred = tpeer->lastsent + sampms;
05870 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05871 ms = pred;
05872
05873
05874 if (ms == tpeer->lastsent)
05875 ms = tpeer->lastsent + 1;
05876 tpeer->lastsent = ms;
05877 return ms;
05878 }
05879
05880 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05881 {
05882 long ms;
05883 if (ast_tvzero(iaxs[callno]->rxcore)) {
05884
05885 iaxs[callno]->rxcore = ast_tvnow();
05886
05887 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05888 }
05889
05890 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05891
05892 return ms + ts;
05893 }
05894
05895 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05896 {
05897 int ms;
05898 int voice = 0;
05899 int genuine = 0;
05900 int adjust;
05901 int rate = ast_format_rate(f->subclass.codec) / 1000;
05902 struct timeval *delivery = NULL;
05903
05904
05905
05906
05907
05908
05909
05910
05911 if (f->frametype == AST_FRAME_VOICE) {
05912 voice = 1;
05913 delivery = &f->delivery;
05914 } else if (f->frametype == AST_FRAME_IAX) {
05915 genuine = 1;
05916 } else if (f->frametype == AST_FRAME_CNG) {
05917 p->notsilenttx = 0;
05918 }
05919
05920 if (ast_tvzero(p->offset)) {
05921 p->offset = ast_tvnow();
05922
05923 p->offset.tv_usec -= p->offset.tv_usec % 20000;
05924 }
05925
05926 if (ts)
05927 return ts;
05928
05929 if (delivery && !ast_tvzero(*delivery)) {
05930 ms = ast_tvdiff_ms(*delivery, p->offset);
05931 if (ms < 0) {
05932 ms = 0;
05933 }
05934 if (iaxdebug)
05935 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05936 } else {
05937 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05938 if (ms < 0)
05939 ms = 0;
05940 if (voice) {
05941
05942 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05943
05944
05945
05946
05947
05948
05949
05950
05951
05952
05953
05954
05955
05956
05957
05958
05959
05960
05961 adjust = (ms - p->nextpred);
05962 if (adjust < 0)
05963 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05964 else if (adjust > 0)
05965 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05966
05967 if (!p->nextpred) {
05968 p->nextpred = ms;
05969 if (p->nextpred <= p->lastsent)
05970 p->nextpred = p->lastsent + 3;
05971 }
05972 ms = p->nextpred;
05973 } else {
05974
05975
05976
05977
05978
05979
05980
05981
05982
05983 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05984 ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05985 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05986
05987 if (f->samples >= rate)
05988 {
05989 int diff = ms % (f->samples / rate);
05990 if (diff)
05991 ms += f->samples/rate - diff;
05992 }
05993
05994 p->nextpred = ms;
05995 p->notsilenttx = 1;
05996 }
05997 } else if ( f->frametype == AST_FRAME_VIDEO ) {
05998
05999
06000
06001
06002
06003
06004
06005
06006 if ( (unsigned int)ms < p->lastsent )
06007 ms = p->lastsent;
06008 } else {
06009
06010
06011 if (genuine) {
06012
06013 if (ms <= p->lastsent)
06014 ms = p->lastsent + 3;
06015 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
06016
06017 ms = p->lastsent + 3;
06018 }
06019 }
06020 }
06021 p->lastsent = ms;
06022 if (voice)
06023 p->nextpred = p->nextpred + f->samples / rate;
06024 return ms;
06025 }
06026
06027 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
06028 {
06029
06030
06031 int ms;
06032 #ifdef IAXTESTS
06033 int jit;
06034 #endif
06035
06036 if (ast_tvzero(p->rxcore)) {
06037 p->rxcore = ast_tvnow();
06038 if (iaxdebug)
06039 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
06040 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
06041 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
06042 #if 1
06043 if (iaxdebug)
06044 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
06045 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
06046 #endif
06047 }
06048
06049 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
06050 #ifdef IAXTESTS
06051 if (test_jit) {
06052 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
06053 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
06054 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
06055 jit = -jit;
06056 ms += jit;
06057 }
06058 }
06059 if (test_late) {
06060 ms += test_late;
06061 test_late = 0;
06062 }
06063 #endif
06064 return ms;
06065 }
06066
06067 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
06068 {
06069 struct iax2_trunk_peer *tpeer = NULL;
06070
06071
06072 AST_LIST_LOCK(&tpeers);
06073
06074 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
06075 if (!inaddrcmp(&tpeer->addr, sin)) {
06076 ast_mutex_lock(&tpeer->lock);
06077 break;
06078 }
06079 }
06080
06081 if (!tpeer) {
06082 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
06083 ast_mutex_init(&tpeer->lock);
06084 tpeer->lastsent = 9999;
06085 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
06086 tpeer->trunkact = ast_tvnow();
06087 ast_mutex_lock(&tpeer->lock);
06088 tpeer->sockfd = fd;
06089 #ifdef SO_NO_CHECK
06090 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
06091 #endif
06092 ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
06093 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
06094 }
06095 }
06096
06097 AST_LIST_UNLOCK(&tpeers);
06098
06099 return tpeer;
06100 }
06101
06102 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
06103 {
06104 struct ast_frame *f;
06105 struct iax2_trunk_peer *tpeer;
06106 void *tmp, *ptr;
06107 struct timeval now;
06108 struct ast_iax2_meta_trunk_entry *met;
06109 struct ast_iax2_meta_trunk_mini *mtm;
06110
06111 f = &fr->af;
06112 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
06113 if (tpeer) {
06114 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
06115
06116 if (tpeer->trunkdataalloc < trunkmaxsize) {
06117 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
06118 ast_mutex_unlock(&tpeer->lock);
06119 return -1;
06120 }
06121
06122 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
06123 tpeer->trunkdata = tmp;
06124 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);
06125 } else {
06126 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));
06127 ast_mutex_unlock(&tpeer->lock);
06128 return -1;
06129 }
06130 }
06131
06132
06133 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
06134 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS)) {
06135 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
06136 mtm->len = htons(f->datalen);
06137 mtm->mini.callno = htons(pvt->callno);
06138 mtm->mini.ts = htons(0xffff & fr->ts);
06139 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
06140 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
06141 } else {
06142 met = (struct ast_iax2_meta_trunk_entry *)ptr;
06143
06144 met->callno = htons(pvt->callno);
06145 met->len = htons(f->datalen);
06146
06147 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
06148 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
06149 }
06150
06151 memcpy(ptr, f->data.ptr, f->datalen);
06152 tpeer->trunkdatalen += f->datalen;
06153
06154 tpeer->calls++;
06155
06156
06157 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
06158 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
06159
06160
06161 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
06162 now = ast_tvnow();
06163 send_trunk(tpeer, &now);
06164 trunk_untimed ++;
06165 }
06166
06167 ast_mutex_unlock(&tpeer->lock);
06168 }
06169 return 0;
06170 }
06171
06172
06173
06174 static void build_rand_pad(unsigned char *buf, ssize_t len)
06175 {
06176 long tmp;
06177 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
06178 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
06179 buf += sizeof(tmp);
06180 len -= sizeof(tmp);
06181 }
06182 }
06183
06184 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06185 {
06186 build_ecx_key(digest, pvt);
06187 ast_aes_set_decrypt_key(digest, &pvt->dcx);
06188 }
06189
06190 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
06191 {
06192
06193
06194
06195 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
06196 ast_aes_set_encrypt_key(digest, &pvt->ecx);
06197 ast_aes_set_decrypt_key(digest, &pvt->mydcx);
06198 }
06199
06200 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
06201 {
06202 #if 0
06203
06204 int x;
06205 if (len % 16)
06206 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06207 for (x=0;x<len;x++)
06208 dst[x] = src[x] ^ 0xff;
06209 #else
06210 unsigned char lastblock[16] = { 0 };
06211 int x;
06212 while(len > 0) {
06213 ast_aes_decrypt(src, dst, dcx);
06214 for (x=0;x<16;x++)
06215 dst[x] ^= lastblock[x];
06216 memcpy(lastblock, src, sizeof(lastblock));
06217 dst += 16;
06218 src += 16;
06219 len -= 16;
06220 }
06221 #endif
06222 }
06223
06224 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
06225 {
06226 #if 0
06227
06228 int x;
06229 if (len % 16)
06230 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
06231 for (x=0;x<len;x++)
06232 dst[x] = src[x] ^ 0xff;
06233 #else
06234 unsigned char curblock[16] = { 0 };
06235 int x;
06236 while(len > 0) {
06237 for (x=0;x<16;x++)
06238 curblock[x] ^= src[x];
06239 ast_aes_encrypt(curblock, dst, ecx);
06240 memcpy(curblock, dst, sizeof(curblock));
06241 dst += 16;
06242 src += 16;
06243 len -= 16;
06244 }
06245 #endif
06246 }
06247
06248 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06249 {
06250 int padding;
06251 unsigned char *workspace;
06252
06253 workspace = ast_alloca(*datalen);
06254 memset(f, 0, sizeof(*f));
06255 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06256 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06257 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
06258 return -1;
06259
06260 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
06261
06262 padding = 16 + (workspace[15] & 0x0f);
06263 if (iaxdebug)
06264 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
06265 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
06266 return -1;
06267
06268 *datalen -= padding;
06269 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06270 f->frametype = fh->type;
06271 if (f->frametype == AST_FRAME_VIDEO) {
06272 f->subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
06273 } else if (f->frametype == AST_FRAME_VOICE) {
06274 f->subclass.codec = uncompress_subclass(fh->csub);
06275 } else {
06276 f->subclass.integer = uncompress_subclass(fh->csub);
06277 }
06278 } else {
06279 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06280 if (iaxdebug)
06281 ast_debug(1, "Decoding mini with length %d\n", *datalen);
06282 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
06283 return -1;
06284
06285 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
06286 padding = 16 + (workspace[15] & 0x0f);
06287 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
06288 return -1;
06289 *datalen -= padding;
06290 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06291 }
06292 return 0;
06293 }
06294
06295 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06296 {
06297 int padding;
06298 unsigned char *workspace;
06299 workspace = ast_alloca(*datalen + 32);
06300 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06301 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06302 if (iaxdebug)
06303 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06304 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06305 padding = 16 + (padding & 0xf);
06306 memcpy(workspace, poo, padding);
06307 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06308 workspace[15] &= 0xf0;
06309 workspace[15] |= (padding & 0xf);
06310 if (iaxdebug)
06311 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06312 *datalen += padding;
06313 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06314 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06315 memcpy(poo, workspace + *datalen - 32, 32);
06316 } else {
06317 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06318 if (iaxdebug)
06319 ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06320 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06321 padding = 16 + (padding & 0xf);
06322 memcpy(workspace, poo, padding);
06323 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06324 workspace[15] &= 0xf0;
06325 workspace[15] |= (padding & 0x0f);
06326 *datalen += padding;
06327 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06328 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06329 memcpy(poo, workspace + *datalen - 32, 32);
06330 }
06331 return 0;
06332 }
06333
06334 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06335 {
06336 int res=-1;
06337 if (!ast_test_flag64(iaxs[callno], IAX_KEYPOPULATED)) {
06338
06339 struct MD5Context md5;
06340 unsigned char digest[16];
06341 char *tmppw, *stringp;
06342
06343 tmppw = ast_strdupa(iaxs[callno]->secret);
06344 stringp = tmppw;
06345 while ((tmppw = strsep(&stringp, ";"))) {
06346 MD5Init(&md5);
06347 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06348 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06349 MD5Final(digest, &md5);
06350 build_encryption_keys(digest, iaxs[callno]);
06351 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06352 if (!res) {
06353 ast_set_flag64(iaxs[callno], IAX_KEYPOPULATED);
06354 break;
06355 }
06356 }
06357 } else
06358 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06359 return res;
06360 }
06361
06362 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06363 {
06364
06365
06366
06367 struct ast_iax2_full_hdr *fh;
06368 struct ast_iax2_mini_hdr *mh;
06369 struct ast_iax2_video_hdr *vh;
06370 struct {
06371 struct iax_frame fr2;
06372 unsigned char buffer[4096];
06373 } frb;
06374 struct iax_frame *fr;
06375 int res;
06376 int sendmini=0;
06377 unsigned int lastsent;
06378 unsigned int fts;
06379
06380 frb.fr2.afdatalen = sizeof(frb.buffer);
06381
06382 if (!pvt) {
06383 ast_log(LOG_WARNING, "No private structure for packet?\n");
06384 return -1;
06385 }
06386
06387 lastsent = pvt->lastsent;
06388
06389
06390 fts = calc_timestamp(pvt, ts, f);
06391
06392
06393
06394
06395 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06396 return 0;
06397 #if 0
06398 ast_log(LOG_NOTICE,
06399 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06400 *("=!" + (f->frametype == AST_FRAME_VOICE)),
06401 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06402 pvt->keyrotateid != -1 ? "" : "no "
06403 );
06404 #endif
06405 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06406 iax2_key_rotate(pvt);
06407 }
06408
06409 if ((ast_test_flag64(pvt, IAX_TRUNK) ||
06410 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06411 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06412 &&
06413 (f->frametype == AST_FRAME_VOICE)
06414 &&
06415 (f->subclass.codec == pvt->svoiceformat)
06416 ) {
06417
06418 now = 1;
06419
06420 sendmini = 1;
06421 }
06422 if ( f->frametype == AST_FRAME_VIDEO ) {
06423
06424
06425
06426
06427
06428 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06429 ((f->subclass.codec & ~0x1LL) == pvt->svideoformat)
06430 ) {
06431 now = 1;
06432 sendmini = 1;
06433 } else {
06434 now = 0;
06435 sendmini = 0;
06436 }
06437 pvt->lastvsent = fts;
06438 }
06439 if (f->frametype == AST_FRAME_IAX) {
06440
06441 pvt->last_iax_message = f->subclass.integer | MARK_IAX_SUBCLASS_TX;
06442 if (!pvt->first_iax_message) {
06443 pvt->first_iax_message = pvt->last_iax_message;
06444 }
06445 }
06446
06447 if (now) {
06448 fr = &frb.fr2;
06449 } else
06450 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));
06451 if (!fr) {
06452 ast_log(LOG_WARNING, "Out of memory\n");
06453 return -1;
06454 }
06455
06456 iax_frame_wrap(fr, f);
06457
06458 fr->ts = fts;
06459 fr->callno = pvt->callno;
06460 fr->transfer = transfer;
06461 fr->final = final;
06462 fr->encmethods = 0;
06463 if (!sendmini) {
06464
06465 if (seqno > -1)
06466 fr->oseqno = seqno;
06467 else
06468 fr->oseqno = pvt->oseqno++;
06469 fr->iseqno = pvt->iseqno;
06470 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06471 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06472 fh->ts = htonl(fr->ts);
06473 fh->oseqno = fr->oseqno;
06474 if (transfer) {
06475 fh->iseqno = 0;
06476 } else
06477 fh->iseqno = fr->iseqno;
06478
06479 if (!transfer)
06480 pvt->aseqno = fr->iseqno;
06481 fh->type = fr->af.frametype & 0xFF;
06482
06483 if (fr->af.frametype == AST_FRAME_VIDEO) {
06484 fh->csub = compress_subclass(fr->af.subclass.codec & ~0x1LL) | ((fr->af.subclass.codec & 0x1LL) << 6);
06485 } else if (fr->af.frametype == AST_FRAME_VOICE) {
06486 fh->csub = compress_subclass(fr->af.subclass.codec);
06487 } else {
06488 fh->csub = compress_subclass(fr->af.subclass.integer);
06489 }
06490
06491 if (transfer) {
06492 fr->dcallno = pvt->transfercallno;
06493 } else
06494 fr->dcallno = pvt->peercallno;
06495 fh->dcallno = htons(fr->dcallno);
06496 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06497 fr->data = fh;
06498 fr->retries = 0;
06499
06500 fr->retrytime = pvt->pingtime * 2;
06501 if (fr->retrytime < MIN_RETRY_TIME)
06502 fr->retrytime = MIN_RETRY_TIME;
06503 if (fr->retrytime > MAX_RETRY_TIME)
06504 fr->retrytime = MAX_RETRY_TIME;
06505
06506 if ((f->frametype == AST_FRAME_IAX) && (f->subclass.integer == IAX_COMMAND_ACK))
06507 fr->retries = -1;
06508 else if (f->frametype == AST_FRAME_VOICE)
06509 pvt->svoiceformat = f->subclass.codec;
06510 else if (f->frametype == AST_FRAME_VIDEO)
06511 pvt->svideoformat = f->subclass.codec & ~0x1LL;
06512 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06513 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06514 if (fr->transfer)
06515 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06516 else
06517 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06518 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06519 fr->encmethods = pvt->encmethods;
06520 fr->ecx = pvt->ecx;
06521 fr->mydcx = pvt->mydcx;
06522 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06523 } else
06524 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06525 }
06526
06527 if (now) {
06528 res = send_packet(fr);
06529 } else
06530 res = iax2_transmit(fr);
06531 } else {
06532 if (ast_test_flag64(pvt, IAX_TRUNK)) {
06533 iax2_trunk_queue(pvt, fr);
06534 res = 0;
06535 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06536
06537 fr->oseqno = -1;
06538 fr->iseqno = -1;
06539 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06540 vh->zeros = 0;
06541 vh->callno = htons(0x8000 | fr->callno);
06542 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass.codec & 0x1LL ? 0x8000 : 0));
06543 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06544 fr->data = vh;
06545 fr->retries = -1;
06546 res = send_packet(fr);
06547 } else {
06548
06549 fr->oseqno = -1;
06550 fr->iseqno = -1;
06551
06552 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06553 mh->callno = htons(fr->callno);
06554 mh->ts = htons(fr->ts & 0xFFFF);
06555 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06556 fr->data = mh;
06557 fr->retries = -1;
06558 if (pvt->transferring == TRANSFER_MEDIAPASS)
06559 fr->transfer = 1;
06560 if (ast_test_flag64(pvt, IAX_ENCRYPTED)) {
06561 if (ast_test_flag64(pvt, IAX_KEYPOPULATED)) {
06562 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06563 } else
06564 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06565 }
06566 res = send_packet(fr);
06567 }
06568 }
06569 return res;
06570 }
06571
06572 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06573 {
06574 regex_t regexbuf;
06575 int havepattern = 0;
06576
06577 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
06578 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
06579
06580 struct iax2_user *user = NULL;
06581 char auth[90];
06582 char *pstr = "";
06583 struct ao2_iterator i;
06584
06585 switch (cmd) {
06586 case CLI_INIT:
06587 e->command = "iax2 show users [like]";
06588 e->usage =
06589 "Usage: iax2 show users [like <pattern>]\n"
06590 " Lists all known IAX2 users.\n"
06591 " Optional regular expression pattern is used to filter the user list.\n";
06592 return NULL;
06593 case CLI_GENERATE:
06594 return NULL;
06595 }
06596
06597 switch (a->argc) {
06598 case 5:
06599 if (!strcasecmp(a->argv[3], "like")) {
06600 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06601 return CLI_SHOWUSAGE;
06602 havepattern = 1;
06603 } else
06604 return CLI_SHOWUSAGE;
06605 case 3:
06606 break;
06607 default:
06608 return CLI_SHOWUSAGE;
06609 }
06610
06611 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06612 i = ao2_iterator_init(users, 0);
06613 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
06614 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0))
06615 continue;
06616
06617 if (!ast_strlen_zero(user->secret)) {
06618 ast_copy_string(auth,user->secret, sizeof(auth));
06619 } else if (!ast_strlen_zero(user->inkeys)) {
06620 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06621 } else
06622 ast_copy_string(auth, "-no secret-", sizeof(auth));
06623
06624 if(ast_test_flag64(user, IAX_CODEC_NOCAP))
06625 pstr = "REQ Only";
06626 else if(ast_test_flag64(user, IAX_CODEC_NOPREFS))
06627 pstr = "Disabled";
06628 else
06629 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06630
06631 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
06632 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06633 user->ha ? "Yes" : "No", pstr);
06634 }
06635 ao2_iterator_destroy(&i);
06636
06637 if (havepattern)
06638 regfree(®exbuf);
06639
06640 return CLI_SUCCESS;
06641 #undef FORMAT
06642 #undef FORMAT2
06643 }
06644
06645 static int __iax2_show_peers(int fd, int *total, struct mansession *s, const int argc, const char * const argv[])
06646 {
06647 regex_t regexbuf;
06648 int havepattern = 0;
06649 int total_peers = 0;
06650 int online_peers = 0;
06651 int offline_peers = 0;
06652 int unmonitored_peers = 0;
06653 struct ao2_iterator i;
06654
06655 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s\n"
06656 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s\n"
06657
06658 struct iax2_peer *peer = NULL;
06659 char name[256];
06660 struct ast_str *encmethods = ast_str_alloca(256);
06661 int registeredonly=0;
06662 char idtext[256] = "";
06663 switch (argc) {
06664 case 6:
06665 if (!strcasecmp(argv[3], "registered"))
06666 registeredonly = 1;
06667 else
06668 return RESULT_SHOWUSAGE;
06669 if (!strcasecmp(argv[4], "like")) {
06670 if (regcomp(®exbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06671 return RESULT_SHOWUSAGE;
06672 havepattern = 1;
06673 } else
06674 return RESULT_SHOWUSAGE;
06675 break;
06676 case 5:
06677 if (!strcasecmp(argv[3], "like")) {
06678 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06679 return RESULT_SHOWUSAGE;
06680 havepattern = 1;
06681 } else
06682 return RESULT_SHOWUSAGE;
06683 break;
06684 case 4:
06685 if (!strcasecmp(argv[3], "registered"))
06686 registeredonly = 1;
06687 else
06688 return RESULT_SHOWUSAGE;
06689 break;
06690 case 3:
06691 break;
06692 default:
06693 return RESULT_SHOWUSAGE;
06694 }
06695
06696
06697 if (!s)
06698 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status");
06699
06700 i = ao2_iterator_init(peers, 0);
06701 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
06702 char nm[20];
06703 char status[20];
06704 int retstatus;
06705 struct sockaddr_in peer_addr;
06706
06707 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
06708
06709 if (registeredonly && !peer_addr.sin_addr.s_addr) {
06710 continue;
06711 }
06712 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0)) {
06713 continue;
06714 }
06715
06716 if (!ast_strlen_zero(peer->username))
06717 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06718 else
06719 ast_copy_string(name, peer->name, sizeof(name));
06720
06721 encmethods_to_str(peer->encmethods, encmethods);
06722 retstatus = peer_status(peer, status, sizeof(status));
06723 if (retstatus > 0)
06724 online_peers++;
06725 else if (!retstatus)
06726 offline_peers++;
06727 else
06728 unmonitored_peers++;
06729
06730 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06731
06732 if (s) {
06733 astman_append(s,
06734 "Event: PeerEntry\r\n%s"
06735 "Channeltype: IAX2\r\n"
06736 "ObjectName: %s\r\n"
06737 "ChanObjectType: peer\r\n"
06738 "IPaddress: %s\r\n"
06739 "IPport: %d\r\n"
06740 "Dynamic: %s\r\n"
06741 "Trunk: %s\r\n"
06742 "Encryption: %s\r\n"
06743 "Status: %s\r\n\r\n",
06744 idtext,
06745 name,
06746 ast_sockaddr_stringify_addr(&peer->addr),
06747 ast_sockaddr_port(&peer->addr),
06748 ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no",
06749 ast_test_flag64(peer, IAX_TRUNK) ? "yes" : "no",
06750 peer->encmethods ? ast_str_buffer(encmethods) : "no",
06751 status);
06752 } else {
06753 ast_cli(fd, FORMAT, name,
06754 ast_sockaddr_stringify_addr(&peer->addr),
06755 ast_test_flag64(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06756 nm,
06757 ast_sockaddr_port(&peer->addr),
06758 ast_test_flag64(peer, IAX_TRUNK) ? "(T)" : " ",
06759 peer->encmethods ? "(E)" : " ",
06760 status);
06761 }
06762 total_peers++;
06763 }
06764 ao2_iterator_destroy(&i);
06765
06766 if (!s)
06767 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]\n",
06768 total_peers, online_peers, offline_peers, unmonitored_peers);
06769
06770 if (havepattern)
06771 regfree(®exbuf);
06772
06773 if (total)
06774 *total = total_peers;
06775
06776 return RESULT_SUCCESS;
06777 #undef FORMAT
06778 #undef FORMAT2
06779 }
06780
06781 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06782 {
06783 struct iax2_thread *thread = NULL;
06784 time_t t;
06785 int threadcount = 0, dynamiccount = 0;
06786 char type;
06787
06788 switch (cmd) {
06789 case CLI_INIT:
06790 e->command = "iax2 show threads";
06791 e->usage =
06792 "Usage: iax2 show threads\n"
06793 " Lists status of IAX helper threads\n";
06794 return NULL;
06795 case CLI_GENERATE:
06796 return NULL;
06797 }
06798 if (a->argc != 3)
06799 return CLI_SHOWUSAGE;
06800
06801 ast_cli(a->fd, "IAX2 Thread Information\n");
06802 time(&t);
06803 ast_cli(a->fd, "Idle Threads:\n");
06804 AST_LIST_LOCK(&idle_list);
06805 AST_LIST_TRAVERSE(&idle_list, thread, list) {
06806 #ifdef DEBUG_SCHED_MULTITHREAD
06807 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06808 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06809 #else
06810 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06811 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06812 #endif
06813 threadcount++;
06814 }
06815 AST_LIST_UNLOCK(&idle_list);
06816 ast_cli(a->fd, "Active Threads:\n");
06817 AST_LIST_LOCK(&active_list);
06818 AST_LIST_TRAVERSE(&active_list, thread, list) {
06819 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06820 type = 'D';
06821 else
06822 type = 'P';
06823 #ifdef DEBUG_SCHED_MULTITHREAD
06824 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
06825 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06826 #else
06827 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
06828 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06829 #endif
06830 threadcount++;
06831 }
06832 AST_LIST_UNLOCK(&active_list);
06833 ast_cli(a->fd, "Dynamic Threads:\n");
06834 AST_LIST_LOCK(&dynamic_list);
06835 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06836 #ifdef DEBUG_SCHED_MULTITHREAD
06837 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06838 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06839 #else
06840 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06841 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06842 #endif
06843 dynamiccount++;
06844 }
06845 AST_LIST_UNLOCK(&dynamic_list);
06846 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06847 return CLI_SUCCESS;
06848 }
06849
06850 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06851 {
06852 struct iax2_peer *p;
06853
06854 switch (cmd) {
06855 case CLI_INIT:
06856 e->command = "iax2 unregister";
06857 e->usage =
06858 "Usage: iax2 unregister <peername>\n"
06859 " Unregister (force expiration) an IAX2 peer from the registry.\n";
06860 return NULL;
06861 case CLI_GENERATE:
06862 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06863 }
06864
06865 if (a->argc != 3)
06866 return CLI_SHOWUSAGE;
06867
06868 p = find_peer(a->argv[2], 1);
06869 if (p) {
06870 if (p->expire > 0) {
06871 struct iax2_peer tmp_peer = {
06872 .name = a->argv[2],
06873 };
06874 struct iax2_peer *peer;
06875
06876 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06877 if (peer) {
06878 expire_registry(peer_ref(peer));
06879 peer_unref(peer);
06880 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06881 } else {
06882 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06883 }
06884 } else {
06885 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06886 }
06887 peer_unref(p);
06888 } else {
06889 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06890 }
06891 return CLI_SUCCESS;
06892 }
06893
06894 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06895 {
06896 int which = 0;
06897 struct iax2_peer *p = NULL;
06898 char *res = NULL;
06899 int wordlen = strlen(word);
06900
06901
06902 if (pos == 2) {
06903 struct ao2_iterator i = ao2_iterator_init(peers, 0);
06904 while ((p = ao2_iterator_next(&i))) {
06905 if (!strncasecmp(p->name, word, wordlen) &&
06906 ++which > state && p->expire > 0) {
06907 res = ast_strdup(p->name);
06908 peer_unref(p);
06909 break;
06910 }
06911 peer_unref(p);
06912 }
06913 ao2_iterator_destroy(&i);
06914 }
06915
06916 return res;
06917 }
06918
06919 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06920 {
06921 switch (cmd) {
06922 case CLI_INIT:
06923 e->command = "iax2 show peers";
06924 e->usage =
06925 "Usage: iax2 show peers [registered] [like <pattern>]\n"
06926 " Lists all known IAX2 peers.\n"
06927 " Optional 'registered' argument lists only peers with known addresses.\n"
06928 " Optional regular expression pattern is used to filter the peer list.\n";
06929 return NULL;
06930 case CLI_GENERATE:
06931 return NULL;
06932 }
06933
06934 switch (__iax2_show_peers(a->fd, NULL, NULL, a->argc, a->argv)) {
06935 case RESULT_SHOWUSAGE:
06936 return CLI_SHOWUSAGE;
06937 case RESULT_FAILURE:
06938 return CLI_FAILURE;
06939 default:
06940 return CLI_SUCCESS;
06941 }
06942 }
06943
06944 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06945 {
06946 ast_cli_netstats(s, -1, 0);
06947 astman_append(s, "\r\n");
06948 return RESULT_SUCCESS;
06949 }
06950
06951 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06952 {
06953 struct iax_firmware *cur = NULL;
06954
06955 switch (cmd) {
06956 case CLI_INIT:
06957 e->command = "iax2 show firmware";
06958 e->usage =
06959 "Usage: iax2 show firmware\n"
06960 " Lists all known IAX firmware images.\n";
06961 return NULL;
06962 case CLI_GENERATE:
06963 return NULL;
06964 }
06965
06966 if (a->argc != 3 && a->argc != 4)
06967 return CLI_SHOWUSAGE;
06968
06969 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
06970 AST_LIST_LOCK(&firmwares);
06971 AST_LIST_TRAVERSE(&firmwares, cur, list) {
06972 if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
06973 ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
06974 ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06975 }
06976 }
06977 AST_LIST_UNLOCK(&firmwares);
06978
06979 return CLI_SUCCESS;
06980 }
06981
06982
06983 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06984 {
06985 static const char * const a[] = { "iax2", "show", "peers" };
06986 const char *id = astman_get_header(m,"ActionID");
06987 char idtext[256] = "";
06988 int total = 0;
06989
06990 if (!ast_strlen_zero(id))
06991 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06992
06993 astman_send_listack(s, m, "Peer status list will follow", "start");
06994
06995 __iax2_show_peers(-1, &total, s, 3, a);
06996
06997 astman_append(s,
06998 "Event: PeerlistComplete\r\n"
06999 "EventList: Complete\r\n"
07000 "ListItems: %d\r\n"
07001 "%s"
07002 "\r\n", total, idtext);
07003 return 0;
07004 }
07005
07006
07007 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
07008 {
07009 struct iax2_peer *peer = NULL;
07010 int peer_count = 0;
07011 char nm[20];
07012 char status[20];
07013 const char *id = astman_get_header(m,"ActionID");
07014 char idtext[256] = "";
07015 struct ast_str *encmethods = ast_str_alloca(256);
07016 struct ao2_iterator i;
07017
07018 if (!ast_strlen_zero(id))
07019 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07020
07021 astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
07022
07023
07024 i = ao2_iterator_init(peers, 0);
07025 for (; (peer = ao2_iterator_next(&i)); peer_unref(peer)) {
07026 encmethods_to_str(peer->encmethods, encmethods);
07027 astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
07028 if (!ast_strlen_zero(peer->username)) {
07029 astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
07030 } else {
07031 astman_append(s, "ObjectName: %s\r\n", peer->name);
07032 }
07033 astman_append(s, "ChanObjectType: peer\r\n");
07034 astman_append(s, "IPaddress: %s\r\n", ast_sockaddr_stringify_addr(&peer->addr));
07035 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
07036 astman_append(s, "Mask: %s\r\n", nm);
07037 astman_append(s, "Port: %d\r\n", ast_sockaddr_port(&peer->addr));
07038 astman_append(s, "Dynamic: %s\r\n", ast_test_flag64(peer, IAX_DYNAMIC) ? "Yes" : "No");
07039 astman_append(s, "Trunk: %s\r\n", ast_test_flag64(peer, IAX_TRUNK) ? "Yes" : "No");
07040 astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
07041 peer_status(peer, status, sizeof(status));
07042 astman_append(s, "Status: %s\r\n\r\n", status);
07043 peer_count++;
07044 }
07045 ao2_iterator_destroy(&i);
07046
07047 astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
07048 return RESULT_SUCCESS;
07049 }
07050
07051
07052 static char *regstate2str(int regstate)
07053 {
07054 switch(regstate) {
07055 case REG_STATE_UNREGISTERED:
07056 return "Unregistered";
07057 case REG_STATE_REGSENT:
07058 return "Request Sent";
07059 case REG_STATE_AUTHSENT:
07060 return "Auth. Sent";
07061 case REG_STATE_REGISTERED:
07062 return "Registered";
07063 case REG_STATE_REJECTED:
07064 return "Rejected";
07065 case REG_STATE_TIMEOUT:
07066 return "Timeout";
07067 case REG_STATE_NOAUTH:
07068 return "No Authentication";
07069 default:
07070 return "Unknown";
07071 }
07072 }
07073
07074 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07075 {
07076 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
07077 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
07078 struct iax2_registry *reg = NULL;
07079 char host[80];
07080 char perceived[80];
07081 int counter = 0;
07082
07083 switch (cmd) {
07084 case CLI_INIT:
07085 e->command = "iax2 show registry";
07086 e->usage =
07087 "Usage: iax2 show registry\n"
07088 " Lists all registration requests and status.\n";
07089 return NULL;
07090 case CLI_GENERATE:
07091 return NULL;
07092 }
07093 if (a->argc != 3)
07094 return CLI_SHOWUSAGE;
07095 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
07096 AST_LIST_LOCK(®istrations);
07097 AST_LIST_TRAVERSE(®istrations, reg, entry) {
07098 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(®->addr));
07099 if (reg->us.sin_addr.s_addr)
07100 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07101 else
07102 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07103 ast_cli(a->fd, FORMAT, host,
07104 (reg->dnsmgr) ? "Y" : "N",
07105 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
07106 counter++;
07107 }
07108 AST_LIST_UNLOCK(®istrations);
07109 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
07110 return CLI_SUCCESS;
07111 #undef FORMAT
07112 #undef FORMAT2
07113 }
07114
07115 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
07116 {
07117 const char *id = astman_get_header(m, "ActionID");
07118 struct iax2_registry *reg = NULL;
07119 char idtext[256] = "";
07120 char host[80] = "";
07121 char perceived[80] = "";
07122 int total = 0;
07123
07124 if (!ast_strlen_zero(id))
07125 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
07126
07127 astman_send_listack(s, m, "Registrations will follow", "start");
07128
07129 AST_LIST_LOCK(®istrations);
07130 AST_LIST_TRAVERSE(®istrations, reg, entry) {
07131 snprintf(host, sizeof(host), "%s", ast_sockaddr_stringify(®->addr));
07132
07133 if (reg->us.sin_addr.s_addr) {
07134 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
07135 } else {
07136 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
07137 }
07138
07139 astman_append(s,
07140 "Event: RegistryEntry\r\n"
07141 "%s"
07142 "Host: %s\r\n"
07143 "DNSmanager: %s\r\n"
07144 "Username: %s\r\n"
07145 "Perceived: %s\r\n"
07146 "Refresh: %d\r\n"
07147 "State: %s\r\n"
07148 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
07149 reg->refresh, regstate2str(reg->regstate));
07150
07151 total++;
07152 }
07153 AST_LIST_UNLOCK(®istrations);
07154
07155 astman_append(s,
07156 "Event: RegistrationsComplete\r\n"
07157 "EventList: Complete\r\n"
07158 "ListItems: %d\r\n"
07159 "%s"
07160 "\r\n", total, idtext);
07161
07162 return 0;
07163 }
07164
07165 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07166 {
07167 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
07168 #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"
07169 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
07170 int x;
07171 int numchans = 0;
07172 char first_message[10] = { 0, };
07173 char last_message[10] = { 0, };
07174
07175 switch (cmd) {
07176 case CLI_INIT:
07177 e->command = "iax2 show channels";
07178 e->usage =
07179 "Usage: iax2 show channels\n"
07180 " Lists all currently active IAX channels.\n";
07181 return NULL;
07182 case CLI_GENERATE:
07183 return NULL;
07184 }
07185
07186 if (a->argc != 3)
07187 return CLI_SHOWUSAGE;
07188 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
07189 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07190 ast_mutex_lock(&iaxsl[x]);
07191 if (iaxs[x]) {
07192 int lag, jitter, localdelay;
07193 jb_info jbinfo;
07194 if (ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07195 jb_getinfo(iaxs[x]->jb, &jbinfo);
07196 jitter = jbinfo.jitter;
07197 localdelay = jbinfo.current - jbinfo.min;
07198 } else {
07199 jitter = -1;
07200 localdelay = 0;
07201 }
07202
07203 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07204 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07205 lag = iaxs[x]->remote_rr.delay;
07206 ast_cli(a->fd, FORMAT,
07207 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07208 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
07209 S_OR(iaxs[x]->username, "(None)"),
07210 iaxs[x]->callno, iaxs[x]->peercallno,
07211 iaxs[x]->oseqno, iaxs[x]->iseqno,
07212 lag,
07213 jitter,
07214 localdelay,
07215 ast_getformatname(iaxs[x]->voiceformat),
07216 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07217 first_message,
07218 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07219 last_message);
07220 numchans++;
07221 }
07222 ast_mutex_unlock(&iaxsl[x]);
07223 }
07224 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07225 return CLI_SUCCESS;
07226 #undef FORMAT
07227 #undef FORMAT2
07228 #undef FORMATB
07229 }
07230
07231 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
07232 {
07233 int x;
07234 int numchans = 0;
07235 char first_message[10] = { 0, };
07236 char last_message[10] = { 0, };
07237 #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"
07238 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
07239 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
07240 ast_mutex_lock(&iaxsl[x]);
07241 if (iaxs[x]) {
07242 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
07243 jb_info jbinfo;
07244 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
07245 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
07246
07247 if(ast_test_flag64(iaxs[x], IAX_USEJITTERBUF)) {
07248 jb_getinfo(iaxs[x]->jb, &jbinfo);
07249 localjitter = jbinfo.jitter;
07250 localdelay = jbinfo.current - jbinfo.min;
07251 locallost = jbinfo.frames_lost;
07252 locallosspct = jbinfo.losspct/1000;
07253 localdropped = jbinfo.frames_dropped;
07254 localooo = jbinfo.frames_ooo;
07255 } else {
07256 localjitter = -1;
07257 localdelay = 0;
07258 locallost = -1;
07259 locallosspct = -1;
07260 localdropped = 0;
07261 localooo = -1;
07262 }
07263 if (s)
07264 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07265 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07266 iaxs[x]->pingtime,
07267 localjitter,
07268 localdelay,
07269 locallost,
07270 locallosspct,
07271 localdropped,
07272 localooo,
07273 iaxs[x]->frames_received/1000,
07274 iaxs[x]->remote_rr.jitter,
07275 iaxs[x]->remote_rr.delay,
07276 iaxs[x]->remote_rr.losscnt,
07277 iaxs[x]->remote_rr.losspct,
07278 iaxs[x]->remote_rr.dropped,
07279 iaxs[x]->remote_rr.ooo,
07280 iaxs[x]->remote_rr.packets/1000,
07281 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07282 first_message,
07283 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07284 last_message);
07285 else
07286 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
07287 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
07288 iaxs[x]->pingtime,
07289 localjitter,
07290 localdelay,
07291 locallost,
07292 locallosspct,
07293 localdropped,
07294 localooo,
07295 iaxs[x]->frames_received/1000,
07296 iaxs[x]->remote_rr.jitter,
07297 iaxs[x]->remote_rr.delay,
07298 iaxs[x]->remote_rr.losscnt,
07299 iaxs[x]->remote_rr.losspct,
07300 iaxs[x]->remote_rr.dropped,
07301 iaxs[x]->remote_rr.ooo,
07302 iaxs[x]->remote_rr.packets/1000,
07303 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07304 first_message,
07305 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
07306 last_message);
07307 numchans++;
07308 }
07309 ast_mutex_unlock(&iaxsl[x]);
07310 }
07311
07312 return numchans;
07313 }
07314
07315 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07316 {
07317 int numchans = 0;
07318
07319 switch (cmd) {
07320 case CLI_INIT:
07321 e->command = "iax2 show netstats";
07322 e->usage =
07323 "Usage: iax2 show netstats\n"
07324 " Lists network status for all currently active IAX channels.\n";
07325 return NULL;
07326 case CLI_GENERATE:
07327 return NULL;
07328 }
07329 if (a->argc != 3)
07330 return CLI_SHOWUSAGE;
07331 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
07332 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
07333 numchans = ast_cli_netstats(NULL, a->fd, 1);
07334 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07335 return CLI_SUCCESS;
07336 }
07337
07338 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07339 {
07340 switch (cmd) {
07341 case CLI_INIT:
07342 e->command = "iax2 set debug {on|off|peer}";
07343 e->usage =
07344 "Usage: iax2 set debug {on|off|peer peername}\n"
07345 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
07346 return NULL;
07347 case CLI_GENERATE:
07348 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07349 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07350 return NULL;
07351 }
07352
07353 if (a->argc < e->args || a->argc > e->args + 1)
07354 return CLI_SHOWUSAGE;
07355
07356 if (!strcasecmp(a->argv[3], "peer")) {
07357 struct iax2_peer *peer;
07358 struct sockaddr_in peer_addr;
07359
07360
07361 if (a->argc != e->args + 1)
07362 return CLI_SHOWUSAGE;
07363
07364 peer = find_peer(a->argv[4], 1);
07365
07366 if (!peer) {
07367 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07368 return CLI_FAILURE;
07369 }
07370
07371 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
07372
07373 debugaddr.sin_addr = peer_addr.sin_addr;
07374 debugaddr.sin_port = peer_addr.sin_port;
07375
07376 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07377 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07378
07379 ao2_ref(peer, -1);
07380 } else if (!strncasecmp(a->argv[3], "on", 2)) {
07381 iaxdebug = 1;
07382 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07383 } else {
07384 iaxdebug = 0;
07385 memset(&debugaddr, 0, sizeof(debugaddr));
07386 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07387 }
07388 return CLI_SUCCESS;
07389 }
07390
07391 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07392 {
07393 switch (cmd) {
07394 case CLI_INIT:
07395 e->command = "iax2 set debug trunk {on|off}";
07396 e->usage =
07397 "Usage: iax2 set debug trunk {on|off}\n"
07398 " Enables/Disables debugging of IAX trunking\n";
07399 return NULL;
07400 case CLI_GENERATE:
07401 return NULL;
07402 }
07403
07404 if (a->argc != e->args)
07405 return CLI_SHOWUSAGE;
07406
07407 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07408 iaxtrunkdebug = 1;
07409 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07410 } else {
07411 iaxtrunkdebug = 0;
07412 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07413 }
07414 return CLI_SUCCESS;
07415 }
07416
07417 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07418 {
07419 switch (cmd) {
07420 case CLI_INIT:
07421 e->command = "iax2 set debug jb {on|off}";
07422 e->usage =
07423 "Usage: iax2 set debug jb {on|off}\n"
07424 " Enables/Disables jitterbuffer debugging information\n";
07425 return NULL;
07426 case CLI_GENERATE:
07427 return NULL;
07428 }
07429
07430 if (a->argc != e->args)
07431 return CLI_SHOWUSAGE;
07432
07433 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07434 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07435 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07436 } else {
07437 jb_setoutput(jb_error_output, jb_warning_output, NULL);
07438 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07439 }
07440 return CLI_SUCCESS;
07441 }
07442
07443 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07444 {
07445 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
07446 int res = -1;
07447 ast_mutex_lock(&iaxsl[callno]);
07448 if (iaxs[callno]) {
07449
07450 if (!iaxs[callno]->error) {
07451 if (ast_test_flag64(iaxs[callno], IAX_ALREADYGONE))
07452 res = 0;
07453
07454 else if (f->frametype == AST_FRAME_NULL)
07455 res = 0;
07456 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag64(iaxs[callno], IAX_QUELCH))
07457 res = 0;
07458 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07459 res = 0;
07460 else
07461
07462 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07463 } else {
07464 ast_debug(1, "Write error: %s\n", strerror(errno));
07465 }
07466 }
07467
07468 ast_mutex_unlock(&iaxsl[callno]);
07469 return res;
07470 }
07471
07472 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
07473 int now, int transfer, int final)
07474 {
07475 struct ast_frame f = { 0, };
07476 int res = 0;
07477
07478 f.frametype = type;
07479 f.subclass.integer = command;
07480 f.datalen = datalen;
07481 f.src = __FUNCTION__;
07482 f.data.ptr = (void *) data;
07483
07484 if ((res = queue_signalling(i, &f)) <= 0) {
07485 return res;
07486 }
07487
07488 return iax2_send(i, &f, ts, seqno, now, transfer, final);
07489 }
07490
07491 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07492 {
07493 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07494 }
07495
07496 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07497 {
07498 int res;
07499 ast_mutex_lock(&iaxsl[callno]);
07500 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07501 ast_mutex_unlock(&iaxsl[callno]);
07502 return res;
07503 }
07504
07505
07506
07507
07508
07509
07510 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)
07511 {
07512 int call_num = i->callno;
07513
07514 iax2_predestroy(i->callno);
07515 if (!iaxs[call_num])
07516 return -1;
07517 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07518 }
07519
07520 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)
07521 {
07522 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07523 }
07524
07525 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07526 {
07527 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07528 }
07529
07530 static int apply_context(struct iax2_context *con, const char *context)
07531 {
07532 while(con) {
07533 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07534 return -1;
07535 con = con->next;
07536 }
07537 return 0;
07538 }
07539
07540
07541 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07542 {
07543
07544 int res = -1;
07545 int version = 2;
07546 struct iax2_user *user = NULL, *best = NULL;
07547 int bestscore = 0;
07548 int gotcapability = 0;
07549 struct ast_variable *v = NULL, *tmpvar = NULL;
07550 struct ao2_iterator i;
07551 struct ast_sockaddr addr;
07552
07553 if (!iaxs[callno])
07554 return res;
07555 if (ies->called_number)
07556 ast_string_field_set(iaxs[callno], exten, ies->called_number);
07557 if (ies->calling_number) {
07558 if (ast_test_flag64(&globalflags, IAX_SHRINKCALLERID)) {
07559 ast_shrink_phone_number(ies->calling_number);
07560 }
07561 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07562 }
07563 if (ies->calling_name)
07564 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07565 if (ies->calling_ani)
07566 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07567 if (ies->dnid)
07568 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07569 if (ies->rdnis)
07570 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07571 if (ies->called_context)
07572 ast_string_field_set(iaxs[callno], context, ies->called_context);
07573 if (ies->language)
07574 ast_string_field_set(iaxs[callno], language, ies->language);
07575 if (ies->username)
07576 ast_string_field_set(iaxs[callno], username, ies->username);
07577 if (ies->calling_ton > -1)
07578 iaxs[callno]->calling_ton = ies->calling_ton;
07579 if (ies->calling_tns > -1)
07580 iaxs[callno]->calling_tns = ies->calling_tns;
07581 if (ies->calling_pres > -1)
07582 iaxs[callno]->calling_pres = ies->calling_pres;
07583 if (ies->format)
07584 iaxs[callno]->peerformat = ies->format;
07585 if (ies->adsicpe)
07586 iaxs[callno]->peeradsicpe = ies->adsicpe;
07587 if (ies->capability) {
07588 gotcapability = 1;
07589 iaxs[callno]->peercapability = ies->capability;
07590 }
07591 if (ies->version)
07592 version = ies->version;
07593
07594
07595 if (ies->codec_prefs) {
07596 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07597 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07598 }
07599
07600 if (!gotcapability)
07601 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07602 if (version > IAX_PROTO_VERSION) {
07603 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
07604 ast_inet_ntoa(sin->sin_addr), version);
07605 return res;
07606 }
07607
07608 ast_sockaddr_from_sin(&addr, sin);
07609 i = ao2_iterator_init(users, 0);
07610 while ((user = ao2_iterator_next(&i))) {
07611 if ((ast_strlen_zero(iaxs[callno]->username) ||
07612 !strcmp(iaxs[callno]->username, user->name))
07613 && ast_apply_ha(user->ha, &addr) == AST_SENSE_ALLOW
07614 && (ast_strlen_zero(iaxs[callno]->context) ||
07615 apply_context(user->contexts, iaxs[callno]->context))) {
07616 if (!ast_strlen_zero(iaxs[callno]->username)) {
07617
07618 if (best)
07619 user_unref(best);
07620 best = user;
07621 break;
07622 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07623
07624 if (user->ha) {
07625
07626 if (bestscore < 4) {
07627 bestscore = 4;
07628 if (best)
07629 user_unref(best);
07630 best = user;
07631 continue;
07632 }
07633 } else {
07634
07635 if (bestscore < 3) {
07636 bestscore = 3;
07637 if (best)
07638 user_unref(best);
07639 best = user;
07640 continue;
07641 }
07642 }
07643 } else {
07644 if (user->ha) {
07645
07646 if (bestscore < 2) {
07647 bestscore = 2;
07648 if (best)
07649 user_unref(best);
07650 best = user;
07651 continue;
07652 }
07653 } else {
07654
07655 if (bestscore < 1) {
07656 bestscore = 1;
07657 if (best)
07658 user_unref(best);
07659 best = user;
07660 continue;
07661 }
07662 }
07663 }
07664 }
07665 user_unref(user);
07666 }
07667 ao2_iterator_destroy(&i);
07668 user = best;
07669 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07670 user = realtime_user(iaxs[callno]->username, sin);
07671 if (user && (ast_apply_ha(user->ha, &addr) == AST_SENSE_DENY
07672 || (!ast_strlen_zero(iaxs[callno]->context) &&
07673 !apply_context(user->contexts, iaxs[callno]->context)))) {
07674 user = user_unref(user);
07675 }
07676 }
07677 if (user) {
07678
07679
07680 for (v = user->vars ; v ; v = v->next) {
07681 if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07682 tmpvar->next = iaxs[callno]->vars;
07683 iaxs[callno]->vars = tmpvar;
07684 }
07685 }
07686
07687 if (user->maxauthreq > 0)
07688 ast_set_flag64(iaxs[callno], IAX_MAXAUTHREQ);
07689 iaxs[callno]->prefs = user->prefs;
07690 ast_copy_flags64(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07691 iaxs[callno]->encmethods = user->encmethods;
07692
07693 if (ast_strlen_zero(iaxs[callno]->username))
07694 ast_string_field_set(iaxs[callno], username, user->name);
07695
07696 ast_copy_flags64(iaxs[callno], user, IAX_TRUNK);
07697 iaxs[callno]->capability = user->capability;
07698
07699 if (ast_strlen_zero(iaxs[callno]->context)) {
07700 if (user->contexts)
07701 ast_string_field_set(iaxs[callno], context, user->contexts->context);
07702 else
07703 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07704 }
07705
07706 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07707
07708 iaxs[callno]->authmethods = user->authmethods;
07709 iaxs[callno]->adsi = user->adsi;
07710
07711 if (ast_test_flag64(user, IAX_HASCALLERID)) {
07712 iaxs[callno]->calling_tns = 0;
07713 iaxs[callno]->calling_ton = 0;
07714 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07715 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07716 ast_string_field_set(iaxs[callno], ani, user->cid_num);
07717 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07718 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07719 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07720 }
07721 if (!ast_strlen_zero(user->accountcode))
07722 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07723 if (!ast_strlen_zero(user->mohinterpret))
07724 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07725 if (!ast_strlen_zero(user->mohsuggest))
07726 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07727 if (!ast_strlen_zero(user->parkinglot))
07728 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07729 if (user->amaflags)
07730 iaxs[callno]->amaflags = user->amaflags;
07731 if (!ast_strlen_zero(user->language))
07732 ast_string_field_set(iaxs[callno], language, user->language);
07733 ast_copy_flags64(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
07734
07735 if (!ast_strlen_zero(user->dbsecret)) {
07736 char *family, *key=NULL;
07737 char buf[80];
07738 family = ast_strdupa(user->dbsecret);
07739 key = strchr(family, '/');
07740 if (key) {
07741 *key = '\0';
07742 key++;
07743 }
07744 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07745 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07746 else
07747 ast_string_field_set(iaxs[callno], secret, buf);
07748 } else
07749 ast_string_field_set(iaxs[callno], secret, user->secret);
07750 res = 0;
07751 user = user_unref(user);
07752 } else {
07753
07754
07755
07756
07757 iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07758 ast_string_field_set(iaxs[callno], secret, "badsecret");
07759 iaxs[callno]->authrej = 1;
07760 if (!ast_strlen_zero(iaxs[callno]->username)) {
07761
07762 res = 0;
07763 }
07764 }
07765 ast_set2_flag64(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07766 return res;
07767 }
07768
07769 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07770 {
07771 struct ast_iax2_full_hdr fh;
07772 fh.scallno = htons(src | IAX_FLAG_FULL);
07773 fh.dcallno = htons(dst);
07774 fh.ts = 0;
07775 fh.oseqno = 0;
07776 fh.iseqno = 0;
07777 fh.type = AST_FRAME_IAX;
07778 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07779 iax_outputframe(NULL, &fh, 0, sin, 0);
07780 #if 0
07781 if (option_debug)
07782 #endif
07783 ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07784 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07785 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07786 }
07787
07788 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07789 {
07790
07791 p->encmethods &= enc;
07792 if (p->encmethods) {
07793 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){
07794 p->keyrotateid = -2;
07795 }
07796 if (p->encmethods & IAX_ENCRYPT_AES128)
07797 p->encmethods = IAX_ENCRYPT_AES128;
07798 else
07799 p->encmethods = 0;
07800 }
07801 }
07802
07803
07804
07805
07806
07807
07808
07809 static int authenticate_request(int call_num)
07810 {
07811 struct iax_ie_data ied;
07812 int res = -1, authreq_restrict = 0;
07813 char challenge[10];
07814 struct chan_iax2_pvt *p = iaxs[call_num];
07815
07816 memset(&ied, 0, sizeof(ied));
07817
07818
07819 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07820 struct iax2_user *user, tmp_user = {
07821 .name = p->username,
07822 };
07823
07824 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07825 if (user) {
07826 if (user->curauthreq == user->maxauthreq)
07827 authreq_restrict = 1;
07828 else
07829 user->curauthreq++;
07830 user = user_unref(user);
07831 }
07832 }
07833
07834
07835 if (authreq_restrict) {
07836 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
07837 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
07838 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
07839 return 0;
07840 }
07841
07842 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
07843 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
07844 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
07845 ast_string_field_set(p, challenge, challenge);
07846
07847 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
07848 }
07849 if (p->encmethods)
07850 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
07851
07852 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
07853
07854 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
07855
07856 if (p->encmethods)
07857 ast_set_flag64(p, IAX_ENCRYPTED);
07858
07859 return res;
07860 }
07861
07862 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
07863 {
07864 char requeststr[256];
07865 char md5secret[256] = "";
07866 char secret[256] = "";
07867 char rsasecret[256] = "";
07868 int res = -1;
07869 int x;
07870 struct iax2_user *user, tmp_user = {
07871 .name = p->username,
07872 };
07873
07874 if (p->authrej) {
07875 return res;
07876 }
07877 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07878 if (user) {
07879 if (ast_test_flag64(p, IAX_MAXAUTHREQ)) {
07880 ast_atomic_fetchadd_int(&user->curauthreq, -1);
07881 ast_clear_flag64(p, IAX_MAXAUTHREQ);
07882 }
07883 ast_string_field_set(p, host, user->name);
07884 user = user_unref(user);
07885 }
07886 if (ast_test_flag64(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
07887 ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.\n");
07888 return res;
07889 }
07890 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
07891 return res;
07892 if (ies->password)
07893 ast_copy_string(secret, ies->password, sizeof(secret));
07894 if (ies->md5_result)
07895 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07896 if (ies->rsa_result)
07897 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07898 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
07899 struct ast_key *key;
07900 char *keyn;
07901 char tmpkey[256];
07902 char *stringp=NULL;
07903 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
07904 stringp=tmpkey;
07905 keyn = strsep(&stringp, ":");
07906 while(keyn) {
07907 key = ast_key_get(keyn, AST_KEY_PUBLIC);
07908 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
07909 res = 0;
07910 break;
07911 } else if (!key)
07912 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
07913 keyn = strsep(&stringp, ":");
07914 }
07915 } else if (p->authmethods & IAX_AUTH_MD5) {
07916 struct MD5Context md5;
07917 unsigned char digest[16];
07918 char *tmppw, *stringp;
07919
07920 tmppw = ast_strdupa(p->secret);
07921 stringp = tmppw;
07922 while((tmppw = strsep(&stringp, ";"))) {
07923 MD5Init(&md5);
07924 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
07925 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07926 MD5Final(digest, &md5);
07927
07928 for (x=0;x<16;x++)
07929 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
07930 if (!strcasecmp(requeststr, md5secret)) {
07931 res = 0;
07932 break;
07933 }
07934 }
07935 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
07936 if (!strcmp(secret, p->secret))
07937 res = 0;
07938 }
07939 return res;
07940 }
07941
07942
07943 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07944 {
07945 char requeststr[256] = "";
07946 char peer[256] = "";
07947 char md5secret[256] = "";
07948 char rsasecret[256] = "";
07949 char secret[256] = "";
07950 struct iax2_peer *p = NULL;
07951 struct ast_key *key;
07952 char *keyn;
07953 int x;
07954 int expire = 0;
07955 int res = -1;
07956 struct ast_sockaddr addr;
07957
07958 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07959
07960 if (ies->username)
07961 ast_copy_string(peer, ies->username, sizeof(peer));
07962 if (ies->password)
07963 ast_copy_string(secret, ies->password, sizeof(secret));
07964 if (ies->md5_result)
07965 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07966 if (ies->rsa_result)
07967 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07968 if (ies->refresh)
07969 expire = ies->refresh;
07970
07971 if (ast_strlen_zero(peer)) {
07972 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
07973 return -1;
07974 }
07975
07976
07977 ast_mutex_unlock(&iaxsl[callno]);
07978 p = find_peer(peer, 1);
07979 ast_mutex_lock(&iaxsl[callno]);
07980 if (!p || !iaxs[callno]) {
07981 if (iaxs[callno]) {
07982 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
07983
07984 ast_string_field_set(iaxs[callno], secret, "badsecret");
07985
07986
07987
07988
07989
07990
07991
07992
07993
07994 if (ast_strlen_zero(iaxs[callno]->challenge) &&
07995 !(!ast_strlen_zero(secret) && plaintext)) {
07996
07997 res = 0;
07998 }
07999 }
08000 if (authdebug && !p)
08001 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08002 goto return_unref;
08003 }
08004
08005 if (!ast_test_flag64(p, IAX_DYNAMIC)) {
08006 if (authdebug)
08007 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
08008 goto return_unref;
08009 }
08010
08011 ast_sockaddr_from_sin(&addr, sin);
08012 if (!ast_apply_ha(p->ha, &addr)) {
08013 if (authdebug)
08014 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08015 goto return_unref;
08016 }
08017 ast_string_field_set(iaxs[callno], secret, p->secret);
08018 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
08019
08020 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08021 if (!ast_strlen_zero(p->inkeys)) {
08022 char tmpkeys[256];
08023 char *stringp=NULL;
08024 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
08025 stringp=tmpkeys;
08026 keyn = strsep(&stringp, ":");
08027 while(keyn) {
08028 key = ast_key_get(keyn, AST_KEY_PUBLIC);
08029 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
08030 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08031 break;
08032 } else if (!key)
08033 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
08034 keyn = strsep(&stringp, ":");
08035 }
08036 if (!keyn) {
08037 if (authdebug)
08038 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
08039 goto return_unref;
08040 }
08041 } else {
08042 if (authdebug)
08043 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
08044 goto return_unref;
08045 }
08046 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
08047 struct MD5Context md5;
08048 unsigned char digest[16];
08049 char *tmppw, *stringp;
08050
08051 tmppw = ast_strdupa(p->secret);
08052 stringp = tmppw;
08053 while((tmppw = strsep(&stringp, ";"))) {
08054 MD5Init(&md5);
08055 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
08056 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
08057 MD5Final(digest, &md5);
08058 for (x=0;x<16;x++)
08059 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
08060 if (!strcasecmp(requeststr, md5secret))
08061 break;
08062 }
08063 if (tmppw) {
08064 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08065 } else {
08066 if (authdebug)
08067 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
08068 goto return_unref;
08069 }
08070 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
08071
08072 if (strcmp(secret, p->secret)) {
08073 if (authdebug)
08074 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
08075 goto return_unref;
08076 } else
08077 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
08078 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
08079
08080 goto return_unref;
08081 }
08082 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08083
08084
08085 res = 0;
08086
08087 return_unref:
08088 if (iaxs[callno]) {
08089 ast_string_field_set(iaxs[callno], peer, peer);
08090
08091
08092 if (expire && (expire < iaxs[callno]->expiry)) {
08093 iaxs[callno]->expiry = expire;
08094 }
08095 }
08096
08097 if (p) {
08098 peer_unref(p);
08099 }
08100 return res;
08101 }
08102
08103 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)
08104 {
08105 int res = -1;
08106 int x;
08107 if (!ast_strlen_zero(keyn)) {
08108 if (!(authmethods & IAX_AUTH_RSA)) {
08109 if (ast_strlen_zero(secret))
08110 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));
08111 } else if (ast_strlen_zero(challenge)) {
08112 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
08113 } else {
08114 char sig[256];
08115 struct ast_key *key;
08116 key = ast_key_get(keyn, AST_KEY_PRIVATE);
08117 if (!key) {
08118 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
08119 } else {
08120 if (ast_sign(key, (char*)challenge, sig)) {
08121 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
08122 res = -1;
08123 } else {
08124 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
08125 res = 0;
08126 }
08127 }
08128 }
08129 }
08130
08131 if (res && !ast_strlen_zero(secret)) {
08132 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
08133 struct MD5Context md5;
08134 unsigned char digest[16];
08135 char digres[128];
08136 MD5Init(&md5);
08137 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
08138 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
08139 MD5Final(digest, &md5);
08140
08141 for (x=0;x<16;x++)
08142 sprintf(digres + (x << 1), "%2.2x", digest[x]);
08143 if (pvt) {
08144 build_encryption_keys(digest, pvt);
08145 }
08146 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
08147 res = 0;
08148 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
08149 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
08150 res = 0;
08151 } else
08152 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
08153 }
08154 return res;
08155 }
08156
08157
08158
08159
08160
08161 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
08162 {
08163 struct iax2_peer *peer = NULL;
08164
08165 int res = -1;
08166 int authmethods = 0;
08167 struct iax_ie_data ied;
08168 uint16_t callno = p->callno;
08169
08170 memset(&ied, 0, sizeof(ied));
08171
08172 if (ies->username)
08173 ast_string_field_set(p, username, ies->username);
08174 if (ies->challenge)
08175 ast_string_field_set(p, challenge, ies->challenge);
08176 if (ies->authmethods)
08177 authmethods = ies->authmethods;
08178 if (authmethods & IAX_AUTH_MD5)
08179 merge_encryption(p, ies->encmethods);
08180 else
08181 p->encmethods = 0;
08182
08183
08184 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
08185
08186 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
08187 } else {
08188 struct ao2_iterator i = ao2_iterator_init(peers, 0);
08189 while ((peer = ao2_iterator_next(&i))) {
08190 struct sockaddr_in peer_addr;
08191
08192 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
08193
08194 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
08195
08196 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
08197
08198 && (!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)))
08199
08200 ) {
08201 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
08202 if (!res) {
08203 peer_unref(peer);
08204 break;
08205 }
08206 }
08207 peer_unref(peer);
08208 }
08209 ao2_iterator_destroy(&i);
08210 if (!peer) {
08211
08212
08213 const char *peer_name = ast_strdupa(p->peer);
08214 ast_mutex_unlock(&iaxsl[callno]);
08215 if ((peer = realtime_peer(peer_name, NULL))) {
08216 ast_mutex_lock(&iaxsl[callno]);
08217 if (!(p = iaxs[callno])) {
08218 peer_unref(peer);
08219 return -1;
08220 }
08221 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
08222 peer_unref(peer);
08223 }
08224 if (!peer) {
08225 ast_mutex_lock(&iaxsl[callno]);
08226 if (!(p = iaxs[callno]))
08227 return -1;
08228 }
08229 }
08230 }
08231
08232 if (ies->encmethods) {
08233 ast_set_flag64(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
08234 } else if (ast_test_flag64(iaxs[callno], IAX_FORCE_ENCRYPT)) {
08235 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set\n");
08236 return -1;
08237 }
08238 if (!res) {
08239 struct ast_datastore *variablestore;
08240 struct ast_variable *var, *prev = NULL;
08241 AST_LIST_HEAD(, ast_var_t) *varlist;
08242 varlist = ast_calloc(1, sizeof(*varlist));
08243 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
08244 if (variablestore && varlist && p->owner) {
08245 variablestore->data = varlist;
08246 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
08247 AST_LIST_HEAD_INIT(varlist);
08248 for (var = ies->vars; var; var = var->next) {
08249 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
08250 if (prev)
08251 ast_free(prev);
08252 prev = var;
08253 if (!newvar) {
08254
08255 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08256 } else {
08257 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
08258 }
08259 }
08260 if (prev)
08261 ast_free(prev);
08262 ies->vars = NULL;
08263 ast_channel_datastore_add(p->owner, variablestore);
08264 } else {
08265 if (p->owner)
08266 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
08267 if (variablestore)
08268 ast_datastore_free(variablestore);
08269 if (varlist)
08270 ast_free(varlist);
08271 }
08272 }
08273
08274 if (!res)
08275 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
08276 return res;
08277 }
08278
08279 static int iax2_do_register(struct iax2_registry *reg);
08280
08281 static void __iax2_do_register_s(const void *data)
08282 {
08283 struct iax2_registry *reg = (struct iax2_registry *)data;
08284 reg->expire = -1;
08285 iax2_do_register(reg);
08286 }
08287
08288 static int iax2_do_register_s(const void *data)
08289 {
08290 #ifdef SCHED_MULTITHREADED
08291 if (schedule_action(__iax2_do_register_s, data))
08292 #endif
08293 __iax2_do_register_s(data);
08294 return 0;
08295 }
08296
08297 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08298 {
08299 int newcall = 0;
08300 char newip[256];
08301 struct iax_ie_data ied;
08302 struct sockaddr_in new = { 0, };
08303
08304 memset(&ied, 0, sizeof(ied));
08305 if (ies->apparent_addr)
08306 memmove(&new, ies->apparent_addr, sizeof(new));
08307 if (ies->callno)
08308 newcall = ies->callno;
08309 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
08310 ast_log(LOG_WARNING, "Invalid transfer request\n");
08311 return -1;
08312 }
08313 pvt->transfercallno = newcall;
08314 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
08315 inet_aton(newip, &pvt->transfer.sin_addr);
08316 pvt->transfer.sin_family = AF_INET;
08317 pvt->transferid = ies->transferid;
08318
08319
08320 if (pvt->transferring == TRANSFER_NONE) {
08321 store_by_transfercallno(pvt);
08322 }
08323 pvt->transferring = TRANSFER_BEGIN;
08324
08325 if (ies->transferid)
08326 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08327 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08328 return 0;
08329 }
08330
08331 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08332 {
08333 char exten[256] = "";
08334 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08335 struct iax2_dpcache *dp = NULL;
08336
08337 if (ies->called_number)
08338 ast_copy_string(exten, ies->called_number, sizeof(exten));
08339
08340 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08341 status = CACHE_FLAG_EXISTS;
08342 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08343 status = CACHE_FLAG_CANEXIST;
08344 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08345 status = CACHE_FLAG_NONEXISTENT;
08346
08347 if (ies->refresh)
08348 expiry = ies->refresh;
08349 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08350 matchmore = CACHE_FLAG_MATCHMORE;
08351
08352 AST_LIST_LOCK(&dpcache);
08353 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08354 if (strcmp(dp->exten, exten))
08355 continue;
08356 AST_LIST_REMOVE_CURRENT(peer_list);
08357 dp->callno = 0;
08358 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08359 if (dp->flags & CACHE_FLAG_PENDING) {
08360 dp->flags &= ~CACHE_FLAG_PENDING;
08361 dp->flags |= status;
08362 dp->flags |= matchmore;
08363 }
08364
08365 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08366 if (dp->waiters[x] > -1) {
08367 if (write(dp->waiters[x], "asdf", 4) < 0) {
08368 }
08369 }
08370 }
08371 }
08372 AST_LIST_TRAVERSE_SAFE_END;
08373 AST_LIST_UNLOCK(&dpcache);
08374
08375 return 0;
08376 }
08377
08378 static int complete_transfer(int callno, struct iax_ies *ies)
08379 {
08380 int peercallno = 0;
08381 struct chan_iax2_pvt *pvt = iaxs[callno];
08382 struct iax_frame *cur;
08383 jb_frame frame;
08384
08385 if (ies->callno)
08386 peercallno = ies->callno;
08387
08388 if (peercallno < 1) {
08389 ast_log(LOG_WARNING, "Invalid transfer request\n");
08390 return -1;
08391 }
08392 remove_by_transfercallno(pvt);
08393
08394
08395
08396 peercnt_remove_by_addr(&pvt->addr);
08397 peercnt_add(&pvt->transfer);
08398
08399 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08400 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08401
08402 pvt->oseqno = 0;
08403 pvt->rseqno = 0;
08404 pvt->iseqno = 0;
08405 pvt->aseqno = 0;
08406
08407 if (pvt->peercallno) {
08408 remove_by_peercallno(pvt);
08409 }
08410 pvt->peercallno = peercallno;
08411
08412 store_by_peercallno(pvt);
08413 pvt->transferring = TRANSFER_NONE;
08414 pvt->svoiceformat = -1;
08415 pvt->voiceformat = 0;
08416 pvt->svideoformat = -1;
08417 pvt->videoformat = 0;
08418 pvt->transfercallno = 0;
08419 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08420 memset(&pvt->offset, 0, sizeof(pvt->offset));
08421
08422 while(jb_getall(pvt->jb,&frame) == JB_OK)
08423 iax2_frame_free(frame.data);
08424 jb_reset(pvt->jb);
08425 pvt->lag = 0;
08426 pvt->last = 0;
08427 pvt->lastsent = 0;
08428 pvt->nextpred = 0;
08429 pvt->pingtime = DEFAULT_RETRY_TIME;
08430 AST_LIST_TRAVERSE(&frame_queue[callno], cur, list) {
08431
08432
08433
08434 cur->retries = -1;
08435 }
08436 return 0;
08437 }
08438
08439
08440 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08441 {
08442 struct iax2_registry *reg;
08443
08444 char peer[256] = "";
08445 char msgstatus[60];
08446 int refresh = 60;
08447 char ourip[256] = "<Unspecified>";
08448 struct sockaddr_in oldus;
08449 struct sockaddr_in us;
08450 int oldmsgs;
08451 struct sockaddr_in reg_addr;
08452
08453 memset(&us, 0, sizeof(us));
08454 if (ies->apparent_addr) {
08455 memmove(&us, ies->apparent_addr, sizeof(us));
08456 }
08457 if (ies->username) {
08458 ast_copy_string(peer, ies->username, sizeof(peer));
08459 }
08460 if (ies->refresh) {
08461 refresh = ies->refresh;
08462 }
08463 if (ies->calling_number) {
08464
08465 }
08466 reg = iaxs[callno]->reg;
08467 if (!reg) {
08468 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08469 return -1;
08470 }
08471 memcpy(&oldus, ®->us, sizeof(oldus));
08472 oldmsgs = reg->messages;
08473 ast_sockaddr_to_sin(®->addr, ®_addr);
08474 if (inaddrcmp(®_addr, sin)) {
08475 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08476 return -1;
08477 }
08478 memcpy(®->us, &us, sizeof(reg->us));
08479 if (ies->msgcount >= 0) {
08480 reg->messages = ies->msgcount & 0xffff;
08481 }
08482
08483
08484
08485 reg->refresh = refresh;
08486 reg->expire = iax2_sched_replace(reg->expire, sched,
08487 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08488 if (inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) {
08489 if (reg->messages > 255) {
08490 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08491 } else if (reg->messages > 1) {
08492 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting", reg->messages);
08493 } else if (reg->messages > 0) {
08494 ast_copy_string(msgstatus, " with 1 new message waiting", sizeof(msgstatus));
08495 } else {
08496 ast_copy_string(msgstatus, " with no messages waiting", sizeof(msgstatus));
08497 }
08498 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08499 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08500 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08501 }
08502 reg->regstate = REG_STATE_REGISTERED;
08503 return 0;
08504 }
08505
08506 static int iax2_append_register(const char *hostname, const char *username,
08507 const char *secret, const char *porta)
08508 {
08509 struct iax2_registry *reg;
08510
08511 if (!(reg = ast_calloc(1, sizeof(*reg))))
08512 return -1;
08513
08514 reg->addr.ss.ss_family = AF_INET;
08515 if (ast_dnsmgr_lookup(hostname, ®->addr, ®->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08516 ast_free(reg);
08517 return -1;
08518 }
08519
08520 ast_copy_string(reg->username, username, sizeof(reg->username));
08521
08522 if (secret)
08523 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08524
08525 reg->expire = -1;
08526 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08527 ast_sockaddr_set_port(®->addr, porta ? atoi(porta) : IAX_DEFAULT_PORTNO);
08528
08529 AST_LIST_LOCK(®istrations);
08530 AST_LIST_INSERT_HEAD(®istrations, reg, entry);
08531 AST_LIST_UNLOCK(®istrations);
08532
08533 return 0;
08534 }
08535
08536 static int iax2_register(const char *value, int lineno)
08537 {
08538 char copy[256];
08539 char *username, *hostname, *secret;
08540 char *porta;
08541 char *stringp=NULL;
08542
08543 if (!value)
08544 return -1;
08545
08546 ast_copy_string(copy, value, sizeof(copy));
08547 stringp = copy;
08548 username = strsep(&stringp, "@");
08549 hostname = strsep(&stringp, "@");
08550
08551 if (!hostname) {
08552 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08553 return -1;
08554 }
08555
08556 stringp = username;
08557 username = strsep(&stringp, ":");
08558 secret = strsep(&stringp, ":");
08559 stringp = hostname;
08560 hostname = strsep(&stringp, ":");
08561 porta = strsep(&stringp, ":");
08562
08563 if (porta && !atoi(porta)) {
08564 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08565 return -1;
08566 }
08567
08568 return iax2_append_register(hostname, username, secret, porta);
08569 }
08570
08571
08572 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08573 {
08574 char multi[256];
08575 char *stringp, *ext;
08576 if (!ast_strlen_zero(regcontext)) {
08577 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08578 stringp = multi;
08579 while((ext = strsep(&stringp, "&"))) {
08580 if (onoff) {
08581 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08582 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08583 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08584 } else
08585 ast_context_remove_extension(regcontext, ext, 1, NULL);
08586 }
08587 }
08588 }
08589 static void prune_peers(void);
08590
08591 static void unlink_peer(struct iax2_peer *peer)
08592 {
08593 if (peer->expire > -1) {
08594 if (!ast_sched_thread_del(sched, peer->expire)) {
08595 peer->expire = -1;
08596 peer_unref(peer);
08597 }
08598 }
08599
08600 if (peer->pokeexpire > -1) {
08601 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
08602 peer->pokeexpire = -1;
08603 peer_unref(peer);
08604 }
08605 }
08606
08607 ao2_unlink(peers, peer);
08608 }
08609
08610 static void __expire_registry(const void *data)
08611 {
08612 struct iax2_peer *peer = (struct iax2_peer *) data;
08613
08614 if (!peer)
08615 return;
08616 if (peer->expire == -1) {
08617
08618 return;
08619 }
08620
08621 peer->expire = -1;
08622
08623 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08624 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08625 realtime_update_peer(peer->name, &peer->addr, 0);
08626 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08627
08628 peercnt_modify(0, 0, &peer->addr);
08629
08630 memset(&peer->addr, 0, sizeof(peer->addr));
08631
08632 peer->expiry = min_reg_expire;
08633 if (!ast_test_flag64(peer, IAX_TEMPONLY))
08634 ast_db_del("IAX/Registry", peer->name);
08635 register_peer_exten(peer, 0);
08636 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
08637 if (iax2_regfunk)
08638 iax2_regfunk(peer->name, 0);
08639
08640 if (ast_test_flag64(peer, IAX_RTAUTOCLEAR))
08641 unlink_peer(peer);
08642
08643 peer_unref(peer);
08644 }
08645
08646 static int expire_registry(const void *data)
08647 {
08648 #ifdef SCHED_MULTITHREADED
08649 if (schedule_action(__expire_registry, data))
08650 #endif
08651 __expire_registry(data);
08652 return 0;
08653 }
08654
08655 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
08656
08657 static void reg_source_db(struct iax2_peer *p)
08658 {
08659 char data[80];
08660 char *expiry;
08661
08662 if (ast_test_flag64(p, IAX_TEMPONLY) || ast_db_get("IAX/Registry", p->name, data, sizeof(data))) {
08663 return;
08664 }
08665
08666 expiry = strrchr(data, ':');
08667 if (!expiry) {
08668 ast_log(LOG_NOTICE, "IAX/Registry astdb entry missing expiry: '%s'\n", data);
08669 return;
08670 }
08671 *expiry++ = '\0';
08672
08673 if (!ast_sockaddr_parse(&p->addr, data, PARSE_PORT_REQUIRE)) {
08674 ast_log(LOG_NOTICE, "IAX/Registry astdb host:port invalid - '%s'\n", data);
08675 return;
08676 }
08677
08678 p->expiry = atoi(expiry);
08679
08680 ast_verb(3, "Seeding '%s' at %s for %d\n", p->name,
08681 ast_sockaddr_stringify(&p->addr), p->expiry);
08682
08683 iax2_poke_peer(p, 0);
08684 if (p->expire > -1) {
08685 if (!ast_sched_thread_del(sched, p->expire)) {
08686 p->expire = -1;
08687 peer_unref(p);
08688 }
08689 }
08690
08691 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08692
08693 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08694 if (p->expire == -1) {
08695 peer_unref(p);
08696 }
08697
08698 if (iax2_regfunk) {
08699 iax2_regfunk(p->name, 1);
08700 }
08701
08702 register_peer_exten(p, 1);
08703 }
08704
08705
08706
08707
08708
08709
08710
08711 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08712 {
08713
08714 struct iax_ie_data ied = {
08715 .pos = 0,
08716 };
08717 struct iax2_peer *p;
08718 int msgcount;
08719 char data[80];
08720 int version;
08721 const char *peer_name;
08722 int res = -1;
08723 struct ast_sockaddr sockaddr;
08724
08725 ast_sockaddr_from_sin(&sockaddr, sin);
08726
08727 peer_name = ast_strdupa(iaxs[callno]->peer);
08728
08729
08730 ast_mutex_unlock(&iaxsl[callno]);
08731 if (!(p = find_peer(peer_name, 1))) {
08732 ast_mutex_lock(&iaxsl[callno]);
08733 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08734 return -1;
08735 }
08736 ast_mutex_lock(&iaxsl[callno]);
08737 if (!iaxs[callno])
08738 goto return_unref;
08739
08740 if (ast_test_flag64((&globalflags), IAX_RTUPDATE) && (ast_test_flag64(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08741 if (sin->sin_addr.s_addr) {
08742 time_t nowtime;
08743 time(&nowtime);
08744 realtime_update_peer(peer_name, &sockaddr, nowtime);
08745 } else {
08746 realtime_update_peer(peer_name, &sockaddr, 0);
08747 }
08748 }
08749
08750 if (ast_sockaddr_cmp(&p->addr, &sockaddr)) {
08751 if (iax2_regfunk) {
08752 iax2_regfunk(p->name, 1);
08753 }
08754
08755
08756 peercnt_modify(0, 0, &p->addr);
08757
08758
08759 ast_sockaddr_from_sin(&p->addr, sin);
08760
08761 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08762 if (!ast_test_flag64(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08763 ast_db_put("IAX/Registry", p->name, data);
08764 ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08765 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08766 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
08767 register_peer_exten(p, 1);
08768 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08769 } else if (!ast_test_flag64(p, IAX_TEMPONLY)) {
08770 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08771 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08772 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08773 register_peer_exten(p, 0);
08774 ast_db_del("IAX/Registry", p->name);
08775 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name);
08776 }
08777
08778
08779 iax2_poke_peer(p, callno);
08780 }
08781
08782
08783 if (p->maxcallno) {
08784 peercnt_modify(1, p->maxcallno, &p->addr);
08785 }
08786
08787
08788 if (!iaxs[callno]) {
08789 res = -1;
08790 goto return_unref;
08791 }
08792
08793
08794 p->sockfd = fd;
08795
08796 if (p->expire > -1) {
08797 if (!ast_sched_thread_del(sched, p->expire)) {
08798 p->expire = -1;
08799 peer_unref(p);
08800 }
08801 }
08802
08803 if (!refresh)
08804 refresh = min_reg_expire;
08805 if (refresh > max_reg_expire) {
08806 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08807 p->name, max_reg_expire, refresh);
08808 p->expiry = max_reg_expire;
08809 } else if (refresh < min_reg_expire) {
08810 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08811 p->name, min_reg_expire, refresh);
08812 p->expiry = min_reg_expire;
08813 } else {
08814 p->expiry = refresh;
08815 }
08816 if (p->expiry && sin->sin_addr.s_addr) {
08817 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08818 if (p->expire == -1)
08819 peer_unref(p);
08820 }
08821 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
08822 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
08823 if (sin->sin_addr.s_addr) {
08824 struct sockaddr_in peer_addr;
08825
08826 ast_sockaddr_to_sin(&p->addr, &peer_addr);
08827
08828 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
08829 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &peer_addr);
08830 if (!ast_strlen_zero(p->mailbox)) {
08831 struct ast_event *event;
08832 int new, old;
08833 char *mailbox, *context;
08834
08835 context = mailbox = ast_strdupa(p->mailbox);
08836 strsep(&context, "@");
08837 if (ast_strlen_zero(context))
08838 context = "default";
08839
08840 event = ast_event_get_cached(AST_EVENT_MWI,
08841 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
08842 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
08843 AST_EVENT_IE_END);
08844 if (event) {
08845 new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
08846 old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
08847 ast_event_destroy(event);
08848 } else {
08849 ast_app_inboxcount(p->mailbox, &new, &old);
08850 }
08851
08852 if (new > 255) {
08853 new = 255;
08854 }
08855 if (old > 255) {
08856 old = 255;
08857 }
08858 msgcount = (old << 8) | new;
08859
08860 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
08861 }
08862 if (ast_test_flag64(p, IAX_HASCALLERID)) {
08863 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
08864 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
08865 }
08866 }
08867 version = iax_check_version(devtype);
08868 if (version)
08869 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
08870
08871 res = 0;
08872
08873 return_unref:
08874 peer_unref(p);
08875
08876 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
08877 }
08878
08879 static int registry_authrequest(int callno)
08880 {
08881 struct iax_ie_data ied;
08882 struct iax2_peer *p;
08883 char challenge[10];
08884 const char *peer_name;
08885 int sentauthmethod;
08886
08887 peer_name = ast_strdupa(iaxs[callno]->peer);
08888
08889
08890 ast_mutex_unlock(&iaxsl[callno]);
08891 if ((p = find_peer(peer_name, 1))) {
08892 last_authmethod = p->authmethods;
08893 }
08894
08895 ast_mutex_lock(&iaxsl[callno]);
08896 if (!iaxs[callno])
08897 goto return_unref;
08898
08899 memset(&ied, 0, sizeof(ied));
08900
08901
08902
08903
08904
08905
08906 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
08907 if (!p) {
08908 iaxs[callno]->authmethods = sentauthmethod;
08909 }
08910 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
08911 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
08912
08913 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08914 ast_string_field_set(iaxs[callno], challenge, challenge);
08915 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
08916 }
08917 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
08918
08919 return_unref:
08920 if (p) {
08921 peer_unref(p);
08922 }
08923
08924 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
08925 }
08926
08927 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
08928 {
08929 struct iax2_registry *reg;
08930
08931 struct iax_ie_data ied;
08932 char peer[256] = "";
08933 char challenge[256] = "";
08934 int res;
08935 int authmethods = 0;
08936 if (ies->authmethods)
08937 authmethods = ies->authmethods;
08938 if (ies->username)
08939 ast_copy_string(peer, ies->username, sizeof(peer));
08940 if (ies->challenge)
08941 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
08942 memset(&ied, 0, sizeof(ied));
08943 reg = iaxs[callno]->reg;
08944 if (reg) {
08945 struct sockaddr_in reg_addr;
08946
08947 ast_sockaddr_to_sin(®->addr, ®_addr);
08948
08949 if (inaddrcmp(®_addr, sin)) {
08950 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08951 return -1;
08952 }
08953 if (ast_strlen_zero(reg->secret)) {
08954 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
08955 reg->regstate = REG_STATE_NOAUTH;
08956 return -1;
08957 }
08958 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08959 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08960 if (reg->secret[0] == '[') {
08961 char tmpkey[256];
08962 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
08963 tmpkey[strlen(tmpkey) - 1] = '\0';
08964 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
08965 } else
08966 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
08967 if (!res) {
08968 reg->regstate = REG_STATE_AUTHSENT;
08969 add_empty_calltoken_ie(iaxs[callno], &ied);
08970 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08971 } else
08972 return -1;
08973 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
08974 } else
08975 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
08976 return -1;
08977 }
08978
08979 static void stop_stuff(int callno)
08980 {
08981 iax2_destroy_helper(iaxs[callno]);
08982 }
08983
08984 static void __auth_reject(const void *nothing)
08985 {
08986
08987 int callno = (int)(long)(nothing);
08988 struct iax_ie_data ied;
08989 ast_mutex_lock(&iaxsl[callno]);
08990 if (iaxs[callno]) {
08991 memset(&ied, 0, sizeof(ied));
08992 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
08993 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
08994 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
08995 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
08996 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
08997 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
08998 }
08999 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
09000 }
09001 ast_mutex_unlock(&iaxsl[callno]);
09002 }
09003
09004 static int auth_reject(const void *data)
09005 {
09006 int callno = (int)(long)(data);
09007 ast_mutex_lock(&iaxsl[callno]);
09008 if (iaxs[callno])
09009 iaxs[callno]->authid = -1;
09010 ast_mutex_unlock(&iaxsl[callno]);
09011 #ifdef SCHED_MULTITHREADED
09012 if (schedule_action(__auth_reject, data))
09013 #endif
09014 __auth_reject(data);
09015 return 0;
09016 }
09017
09018 static int auth_fail(int callno, int failcode)
09019 {
09020
09021
09022 if (iaxs[callno]) {
09023 iaxs[callno]->authfail = failcode;
09024 if (delayreject) {
09025 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
09026 sched, 1000, auth_reject, (void *)(long)callno);
09027 } else
09028 auth_reject((void *)(long)callno);
09029 }
09030 return 0;
09031 }
09032
09033 static void __auto_hangup(const void *nothing)
09034 {
09035
09036 int callno = (int)(long)(nothing);
09037 struct iax_ie_data ied;
09038 ast_mutex_lock(&iaxsl[callno]);
09039 if (iaxs[callno]) {
09040 memset(&ied, 0, sizeof(ied));
09041 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
09042 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
09043 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
09044 }
09045 ast_mutex_unlock(&iaxsl[callno]);
09046 }
09047
09048 static int auto_hangup(const void *data)
09049 {
09050 int callno = (int)(long)(data);
09051 ast_mutex_lock(&iaxsl[callno]);
09052 if (iaxs[callno]) {
09053 iaxs[callno]->autoid = -1;
09054 }
09055 ast_mutex_unlock(&iaxsl[callno]);
09056 #ifdef SCHED_MULTITHREADED
09057 if (schedule_action(__auto_hangup, data))
09058 #endif
09059 __auto_hangup(data);
09060 return 0;
09061 }
09062
09063 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
09064 {
09065 struct iax_ie_data ied;
09066
09067 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
09068 sched, 30000, auto_hangup, (void *)(long)callno);
09069 memset(&ied, 0, sizeof(ied));
09070 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
09071 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
09072 dp->flags |= CACHE_FLAG_TRANSMITTED;
09073 }
09074
09075 static int iax2_vnak(int callno)
09076 {
09077 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
09078 }
09079
09080 static void vnak_retransmit(int callno, int last)
09081 {
09082 struct iax_frame *f;
09083
09084 AST_LIST_TRAVERSE(&frame_queue[callno], f, list) {
09085
09086 if (((unsigned char) (f->oseqno - last) < 128) &&
09087 (f->retries >= 0)) {
09088 send_packet(f);
09089 }
09090 }
09091 }
09092
09093 static void __iax2_poke_peer_s(const void *data)
09094 {
09095 struct iax2_peer *peer = (struct iax2_peer *)data;
09096 iax2_poke_peer(peer, 0);
09097 peer_unref(peer);
09098 }
09099
09100 static int iax2_poke_peer_s(const void *data)
09101 {
09102 struct iax2_peer *peer = (struct iax2_peer *)data;
09103 peer->pokeexpire = -1;
09104 #ifdef SCHED_MULTITHREADED
09105 if (schedule_action(__iax2_poke_peer_s, data))
09106 #endif
09107 __iax2_poke_peer_s(data);
09108 return 0;
09109 }
09110
09111 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
09112 {
09113 int res = 0;
09114 struct iax_frame *fr;
09115 struct ast_iax2_meta_hdr *meta;
09116 struct ast_iax2_meta_trunk_hdr *mth;
09117 int calls = 0;
09118
09119
09120 fr = (struct iax_frame *)tpeer->trunkdata;
09121
09122 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
09123 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
09124 if (tpeer->trunkdatalen) {
09125
09126 meta->zeros = 0;
09127 meta->metacmd = IAX_META_TRUNK;
09128 if (ast_test_flag64(&globalflags, IAX_TRUNKTIMESTAMPS))
09129 meta->cmddata = IAX_META_TRUNK_MINI;
09130 else
09131 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
09132 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
09133
09134 fr->direction = DIRECTION_OUTGRESS;
09135 fr->retrans = -1;
09136 fr->transfer = 0;
09137
09138 fr->data = fr->afdata;
09139 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
09140 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
09141 calls = tpeer->calls;
09142 #if 0
09143 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));
09144 #endif
09145
09146 tpeer->trunkdatalen = 0;
09147 tpeer->calls = 0;
09148 }
09149 if (res < 0)
09150 return res;
09151 return calls;
09152 }
09153
09154 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
09155 {
09156
09157 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
09158 return 1;
09159 return 0;
09160 }
09161
09162 static int timing_read(int *id, int fd, short events, void *cbdata)
09163 {
09164 int res, processed = 0, totalcalls = 0;
09165 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
09166 struct timeval now = ast_tvnow();
09167
09168 if (iaxtrunkdebug)
09169 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
09170
09171 if (timer) {
09172 ast_timer_ack(timer, 1);
09173 }
09174
09175
09176 AST_LIST_LOCK(&tpeers);
09177 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
09178 processed++;
09179 res = 0;
09180 ast_mutex_lock(&tpeer->lock);
09181
09182
09183 if (!drop && iax2_trunk_expired(tpeer, &now)) {
09184
09185
09186 AST_LIST_REMOVE_CURRENT(list);
09187 drop = tpeer;
09188 } else {
09189 res = send_trunk(tpeer, &now);
09190 trunk_timed++;
09191 if (iaxtrunkdebug)
09192 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);
09193 }
09194 totalcalls += res;
09195 res = 0;
09196 ast_mutex_unlock(&tpeer->lock);
09197 }
09198 AST_LIST_TRAVERSE_SAFE_END;
09199 AST_LIST_UNLOCK(&tpeers);
09200
09201 if (drop) {
09202 ast_mutex_lock(&drop->lock);
09203
09204
09205 ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
09206 if (drop->trunkdata) {
09207 ast_free(drop->trunkdata);
09208 drop->trunkdata = NULL;
09209 }
09210 ast_mutex_unlock(&drop->lock);
09211 ast_mutex_destroy(&drop->lock);
09212 ast_free(drop);
09213
09214 }
09215
09216 if (iaxtrunkdebug)
09217 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
09218 iaxtrunkdebug = 0;
09219
09220 return 1;
09221 }
09222
09223 struct dpreq_data {
09224 int callno;
09225 char context[AST_MAX_EXTENSION];
09226 char callednum[AST_MAX_EXTENSION];
09227 char *callerid;
09228 };
09229
09230 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
09231 {
09232 unsigned short dpstatus = 0;
09233 struct iax_ie_data ied1;
09234 int mm;
09235
09236 memset(&ied1, 0, sizeof(ied1));
09237 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
09238
09239 if (ast_parking_ext_valid(callednum, NULL, context) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
09240 dpstatus = IAX_DPSTATUS_EXISTS;
09241 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
09242 dpstatus = IAX_DPSTATUS_CANEXIST;
09243 } else {
09244 dpstatus = IAX_DPSTATUS_NONEXISTENT;
09245 }
09246 if (ast_ignore_pattern(context, callednum))
09247 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
09248 if (mm)
09249 dpstatus |= IAX_DPSTATUS_MATCHMORE;
09250 if (!skiplock)
09251 ast_mutex_lock(&iaxsl[callno]);
09252 if (iaxs[callno]) {
09253 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
09254 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
09255 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
09256 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
09257 }
09258 if (!skiplock)
09259 ast_mutex_unlock(&iaxsl[callno]);
09260 }
09261
09262 static void *dp_lookup_thread(void *data)
09263 {
09264
09265 struct dpreq_data *dpr = data;
09266 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
09267 if (dpr->callerid)
09268 ast_free(dpr->callerid);
09269 ast_free(dpr);
09270 return NULL;
09271 }
09272
09273 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
09274 {
09275 pthread_t newthread;
09276 struct dpreq_data *dpr;
09277
09278 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
09279 return;
09280
09281 dpr->callno = callno;
09282 ast_copy_string(dpr->context, context, sizeof(dpr->context));
09283 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
09284 if (callerid)
09285 dpr->callerid = ast_strdup(callerid);
09286 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
09287 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
09288 }
09289 }
09290
09291 struct iax_dual {
09292 struct ast_channel *chan1;
09293 struct ast_channel *chan2;
09294 char *park_exten;
09295 char *park_context;
09296 };
09297
09298 static void *iax_park_thread(void *stuff)
09299 {
09300 struct iax_dual *d;
09301 int res;
09302 int ext = 0;
09303
09304 d = stuff;
09305
09306 ast_debug(4, "IAX Park: Transferer channel %s, Transferee %s\n",
09307 d->chan2->name, d->chan1->name);
09308
09309 res = ast_park_call_exten(d->chan1, d->chan2, d->park_exten, d->park_context, 0, &ext);
09310 if (res) {
09311
09312 ast_hangup(d->chan1);
09313 } else {
09314 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
09315 }
09316 ast_hangup(d->chan2);
09317
09318 ast_free(d->park_exten);
09319 ast_free(d->park_context);
09320 ast_free(d);
09321 return NULL;
09322 }
09323
09324
09325 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2, const char *park_exten, const char *park_context)
09326 {
09327 struct iax_dual *d;
09328 struct ast_channel *chan1m, *chan2m;
09329 pthread_t th;
09330
09331 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->linkedid, chan1->amaflags, "Parking/%s", chan1->name);
09332 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->linkedid, chan2->amaflags, "IAXPeer/%s", chan2->name);
09333 d = ast_calloc(1, sizeof(*d));
09334 if (!chan1m || !chan2m || !d) {
09335 if (chan1m) {
09336 ast_hangup(chan1m);
09337 }
09338 if (chan2m) {
09339 ast_hangup(chan2m);
09340 }
09341 ast_free(d);
09342 return -1;
09343 }
09344 d->park_exten = ast_strdup(park_exten);
09345 d->park_context = ast_strdup(park_context);
09346 if (!d->park_exten || !d->park_context) {
09347 ast_hangup(chan1m);
09348 ast_hangup(chan2m);
09349 ast_free(d->park_exten);
09350 ast_free(d->park_context);
09351 ast_free(d);
09352 return -1;
09353 }
09354
09355
09356 chan1m->readformat = chan1->readformat;
09357 chan1m->writeformat = chan1->writeformat;
09358
09359
09360 if (ast_channel_masquerade(chan1m, chan1)) {
09361 ast_hangup(chan1m);
09362 ast_hangup(chan2m);
09363 ast_free(d->park_exten);
09364 ast_free(d->park_context);
09365 ast_free(d);
09366 return -1;
09367 }
09368
09369
09370 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
09371 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
09372 chan1m->priority = chan1->priority;
09373
09374 ast_do_masquerade(chan1m);
09375
09376
09377
09378
09379
09380 chan2m->readformat = chan2->readformat;
09381 chan2m->writeformat = chan2->writeformat;
09382 ast_string_field_set(chan2m, parkinglot, chan2->parkinglot);
09383
09384
09385 if (ast_channel_masquerade(chan2m, chan2)) {
09386 ast_hangup(chan1m);
09387 ast_hangup(chan2m);
09388 ast_free(d->park_exten);
09389 ast_free(d->park_context);
09390 ast_free(d);
09391 return -1;
09392 }
09393
09394
09395 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
09396 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
09397 chan2m->priority = chan2->priority;
09398
09399 ast_do_masquerade(chan2m);
09400
09401 d->chan1 = chan1m;
09402 d->chan2 = chan2m;
09403 if (ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d) < 0) {
09404
09405 ast_hangup(chan1m);
09406 ast_hangup(chan2m);
09407 ast_free(d->park_exten);
09408 ast_free(d->park_context);
09409 ast_free(d);
09410 return -1;
09411 }
09412 return 0;
09413 }
09414
09415 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09416 {
09417 unsigned int ourver;
09418 char rsi[80];
09419 snprintf(rsi, sizeof(rsi), "si-%s", si);
09420 if (iax_provision_version(&ourver, rsi, 1))
09421 return 0;
09422 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09423 if (ourver != ver)
09424 iax2_provision(sin, sockfd, NULL, rsi, 1);
09425 return 0;
09426 }
09427
09428 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
09429 {
09430 jb_info stats;
09431 jb_getinfo(pvt->jb, &stats);
09432
09433 memset(iep, 0, sizeof(*iep));
09434
09435 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09436 if(stats.frames_in == 0) stats.frames_in = 1;
09437 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09438 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09439 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09440 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09441 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09442 }
09443
09444 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
09445 {
09446 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09447 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09448 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09449 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09450 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09451 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09452 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09453 }
09454
09455 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
09456 {
09457 int i;
09458 unsigned int length, offset = 0;
09459 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09460
09461 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09462 length = ies->ospblocklength[i];
09463 if (length != 0) {
09464 if (length > IAX_MAX_OSPBLOCK_SIZE) {
09465
09466 offset = 0;
09467 break;
09468 } else {
09469 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09470 offset += length;
09471 }
09472 } else {
09473 break;
09474 }
09475 }
09476 *(full_osptoken + offset) = '\0';
09477 if (strlen(full_osptoken) != offset) {
09478
09479 *full_osptoken = '\0';
09480 }
09481
09482 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09483 }
09484
09485 static void log_jitterstats(unsigned short callno)
09486 {
09487 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09488 jb_info jbinfo;
09489
09490 ast_mutex_lock(&iaxsl[callno]);
09491 if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
09492 if(ast_test_flag64(iaxs[callno], IAX_USEJITTERBUF)) {
09493 jb_getinfo(iaxs[callno]->jb, &jbinfo);
09494 localjitter = jbinfo.jitter;
09495 localdelay = jbinfo.current - jbinfo.min;
09496 locallost = jbinfo.frames_lost;
09497 locallosspct = jbinfo.losspct/1000;
09498 localdropped = jbinfo.frames_dropped;
09499 localooo = jbinfo.frames_ooo;
09500 localpackets = jbinfo.frames_in;
09501 }
09502 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",
09503 iaxs[callno]->owner->name,
09504 iaxs[callno]->pingtime,
09505 localjitter,
09506 localdelay,
09507 locallost,
09508 locallosspct,
09509 localdropped,
09510 localooo,
09511 localpackets,
09512 iaxs[callno]->remote_rr.jitter,
09513 iaxs[callno]->remote_rr.delay,
09514 iaxs[callno]->remote_rr.losscnt,
09515 iaxs[callno]->remote_rr.losspct/1000,
09516 iaxs[callno]->remote_rr.dropped,
09517 iaxs[callno]->remote_rr.ooo,
09518 iaxs[callno]->remote_rr.packets);
09519 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",
09520 iaxs[callno]->owner->name,
09521 iaxs[callno]->pingtime,
09522 localjitter,
09523 localdelay,
09524 locallost,
09525 locallosspct,
09526 localdropped,
09527 localooo,
09528 localpackets,
09529 iaxs[callno]->remote_rr.jitter,
09530 iaxs[callno]->remote_rr.delay,
09531 iaxs[callno]->remote_rr.losscnt,
09532 iaxs[callno]->remote_rr.losspct/1000,
09533 iaxs[callno]->remote_rr.dropped,
09534 iaxs[callno]->remote_rr.ooo,
09535 iaxs[callno]->remote_rr.packets);
09536 }
09537 ast_mutex_unlock(&iaxsl[callno]);
09538 }
09539
09540 static int socket_process(struct iax2_thread *thread);
09541
09542
09543
09544
09545 static void handle_deferred_full_frames(struct iax2_thread *thread)
09546 {
09547 struct iax2_pkt_buf *pkt_buf;
09548
09549 ast_mutex_lock(&thread->lock);
09550
09551 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09552 ast_mutex_unlock(&thread->lock);
09553
09554 thread->buf = pkt_buf->buf;
09555 thread->buf_len = pkt_buf->len;
09556 thread->buf_size = pkt_buf->len + 1;
09557
09558 socket_process(thread);
09559
09560 thread->buf = NULL;
09561 ast_free(pkt_buf);
09562
09563 ast_mutex_lock(&thread->lock);
09564 }
09565
09566 ast_mutex_unlock(&thread->lock);
09567 }
09568
09569
09570
09571
09572
09573
09574
09575 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09576 {
09577 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09578 struct ast_iax2_full_hdr *fh, *cur_fh;
09579
09580 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09581 return;
09582
09583 pkt_buf->len = from_here->buf_len;
09584 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09585
09586 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09587 ast_mutex_lock(&to_here->lock);
09588 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09589 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09590 if (fh->oseqno < cur_fh->oseqno) {
09591 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09592 break;
09593 }
09594 }
09595 AST_LIST_TRAVERSE_SAFE_END
09596
09597 if (!cur_pkt_buf)
09598 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09599
09600 ast_mutex_unlock(&to_here->lock);
09601 }
09602
09603 static int socket_read(int *id, int fd, short events, void *cbdata)
09604 {
09605 struct iax2_thread *thread;
09606 socklen_t len;
09607 time_t t;
09608 static time_t last_errtime = 0;
09609 struct ast_iax2_full_hdr *fh;
09610
09611 if (!(thread = find_idle_thread())) {
09612 time(&t);
09613 if (t != last_errtime)
09614 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09615 last_errtime = t;
09616 usleep(1);
09617 return 1;
09618 }
09619
09620 len = sizeof(thread->iosin);
09621 thread->iofd = fd;
09622 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09623 thread->buf_size = sizeof(thread->readbuf);
09624 thread->buf = thread->readbuf;
09625 if (thread->buf_len < 0) {
09626 if (errno != ECONNREFUSED && errno != EAGAIN)
09627 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09628 handle_error();
09629 thread->iostate = IAX_IOSTATE_IDLE;
09630 signal_condition(&thread->lock, &thread->cond);
09631 return 1;
09632 }
09633 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) {
09634 thread->iostate = IAX_IOSTATE_IDLE;
09635 signal_condition(&thread->lock, &thread->cond);
09636 return 1;
09637 }
09638
09639
09640
09641
09642 fh = (struct ast_iax2_full_hdr *) thread->buf;
09643 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09644 struct iax2_thread *cur = NULL;
09645 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09646
09647 AST_LIST_LOCK(&active_list);
09648 AST_LIST_TRAVERSE(&active_list, cur, list) {
09649 if ((cur->ffinfo.callno == callno) &&
09650 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09651 break;
09652 }
09653 if (cur) {
09654
09655
09656 defer_full_frame(thread, cur);
09657 AST_LIST_UNLOCK(&active_list);
09658 thread->iostate = IAX_IOSTATE_IDLE;
09659 signal_condition(&thread->lock, &thread->cond);
09660 return 1;
09661 } else {
09662
09663 thread->ffinfo.callno = callno;
09664 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09665 thread->ffinfo.type = fh->type;
09666 thread->ffinfo.csub = fh->csub;
09667 AST_LIST_INSERT_HEAD(&active_list, thread, list);
09668 }
09669 AST_LIST_UNLOCK(&active_list);
09670 }
09671
09672
09673 thread->iostate = IAX_IOSTATE_READY;
09674 #ifdef DEBUG_SCHED_MULTITHREAD
09675 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09676 #endif
09677 signal_condition(&thread->lock, &thread->cond);
09678
09679 return 1;
09680 }
09681
09682 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09683 struct iax_frame *fr)
09684 {
09685 unsigned char metatype;
09686 struct ast_iax2_meta_trunk_mini *mtm;
09687 struct ast_iax2_meta_trunk_hdr *mth;
09688 struct ast_iax2_meta_trunk_entry *mte;
09689 struct iax2_trunk_peer *tpeer;
09690 unsigned int ts;
09691 void *ptr;
09692 struct timeval rxtrunktime;
09693 struct ast_frame f = { 0, };
09694
09695 if (packet_len < sizeof(*meta)) {
09696 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
09697 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09698 return 1;
09699 }
09700
09701 if (meta->metacmd != IAX_META_TRUNK)
09702 return 1;
09703
09704 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09705 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09706 (int) (sizeof(*meta) + sizeof(*mth)));
09707 return 1;
09708 }
09709 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09710 ts = ntohl(mth->ts);
09711 metatype = meta->cmddata;
09712 packet_len -= (sizeof(*meta) + sizeof(*mth));
09713 ptr = mth->data;
09714 tpeer = find_tpeer(sin, sockfd);
09715 if (!tpeer) {
09716 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
09717 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09718 return 1;
09719 }
09720 tpeer->trunkact = ast_tvnow();
09721 if (!ts || ast_tvzero(tpeer->rxtrunktime))
09722 tpeer->rxtrunktime = tpeer->trunkact;
09723 rxtrunktime = tpeer->rxtrunktime;
09724 ast_mutex_unlock(&tpeer->lock);
09725 while (packet_len >= sizeof(*mte)) {
09726
09727 unsigned short callno, trunked_ts, len;
09728
09729 if (metatype == IAX_META_TRUNK_MINI) {
09730 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09731 ptr += sizeof(*mtm);
09732 packet_len -= sizeof(*mtm);
09733 len = ntohs(mtm->len);
09734 callno = ntohs(mtm->mini.callno);
09735 trunked_ts = ntohs(mtm->mini.ts);
09736 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09737 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09738 ptr += sizeof(*mte);
09739 packet_len -= sizeof(*mte);
09740 len = ntohs(mte->len);
09741 callno = ntohs(mte->callno);
09742 trunked_ts = 0;
09743 } else {
09744 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09745 break;
09746 }
09747
09748 if (len > packet_len)
09749 break;
09750 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09751 if (!fr->callno)
09752 continue;
09753
09754
09755
09756
09757 memset(&f, 0, sizeof(f));
09758 f.frametype = AST_FRAME_VOICE;
09759 if (!iaxs[fr->callno]) {
09760
09761 } else if (iaxs[fr->callno]->voiceformat == 0) {
09762 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09763 iax2_vnak(fr->callno);
09764 } else {
09765 f.subclass.codec = iaxs[fr->callno]->voiceformat;
09766 f.datalen = len;
09767 if (f.datalen >= 0) {
09768 if (f.datalen)
09769 f.data.ptr = ptr;
09770 else
09771 f.data.ptr = NULL;
09772 if (trunked_ts)
09773 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09774 else
09775 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09776
09777 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09778 struct iax_frame *duped_fr;
09779
09780
09781 f.src = "IAX2";
09782 f.mallocd = 0;
09783 f.offset = 0;
09784 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
09785 f.samples = ast_codec_get_samples(&f);
09786 else
09787 f.samples = 0;
09788 fr->outoforder = 0;
09789 iax_frame_wrap(fr, &f);
09790 duped_fr = iaxfrdup2(fr);
09791 if (duped_fr)
09792 schedule_delivery(duped_fr, 1, 1, &fr->ts);
09793 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
09794 iaxs[fr->callno]->last = fr->ts;
09795 }
09796 } else {
09797 ast_log(LOG_WARNING, "Datalen < 0?\n");
09798 }
09799 }
09800 ast_mutex_unlock(&iaxsl[fr->callno]);
09801 ptr += len;
09802 packet_len -= len;
09803 }
09804
09805 return 1;
09806 }
09807
09808 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
09809 {
09810 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09811 AST_LIST_HEAD(, ast_var_t) *varlist;
09812 struct ast_var_t *var;
09813
09814 if (!variablestore) {
09815 *buf = '\0';
09816 return 0;
09817 }
09818 varlist = variablestore->data;
09819
09820 AST_LIST_LOCK(varlist);
09821 AST_LIST_TRAVERSE(varlist, var, entries) {
09822 if (strcmp(var->name, data) == 0) {
09823 ast_copy_string(buf, var->value, len);
09824 break;
09825 }
09826 }
09827 AST_LIST_UNLOCK(varlist);
09828 return 0;
09829 }
09830
09831 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
09832 {
09833 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09834 AST_LIST_HEAD(, ast_var_t) *varlist;
09835 struct ast_var_t *var;
09836
09837 if (!variablestore) {
09838 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09839 if (!variablestore) {
09840 ast_log(LOG_ERROR, "Memory allocation error\n");
09841 return -1;
09842 }
09843 varlist = ast_calloc(1, sizeof(*varlist));
09844 if (!varlist) {
09845 ast_datastore_free(variablestore);
09846 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09847 return -1;
09848 }
09849
09850 AST_LIST_HEAD_INIT(varlist);
09851 variablestore->data = varlist;
09852 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09853 ast_channel_datastore_add(chan, variablestore);
09854 } else
09855 varlist = variablestore->data;
09856
09857 AST_LIST_LOCK(varlist);
09858 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
09859 if (strcmp(var->name, data) == 0) {
09860 AST_LIST_REMOVE_CURRENT(entries);
09861 ast_var_delete(var);
09862 break;
09863 }
09864 }
09865 AST_LIST_TRAVERSE_SAFE_END;
09866 var = ast_var_assign(data, value);
09867 if (var)
09868 AST_LIST_INSERT_TAIL(varlist, var, entries);
09869 else
09870 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09871 AST_LIST_UNLOCK(varlist);
09872 return 0;
09873 }
09874
09875 static struct ast_custom_function iaxvar_function = {
09876 .name = "IAXVAR",
09877 .read = acf_iaxvar_read,
09878 .write = acf_iaxvar_write,
09879 };
09880
09881 static void set_hangup_source_and_cause(int callno, unsigned char causecode)
09882 {
09883 iax2_lock_owner(callno);
09884 if (iaxs[callno] && iaxs[callno]->owner) {
09885 struct ast_channel *owner;
09886 const char *name;
09887
09888 owner = iaxs[callno]->owner;
09889 if (causecode) {
09890 owner->hangupcause = causecode;
09891 }
09892 name = ast_strdupa(owner->name);
09893 ast_channel_ref(owner);
09894 ast_channel_unlock(owner);
09895 ast_mutex_unlock(&iaxsl[callno]);
09896 ast_set_hangupsource(owner, name, 0);
09897 ast_channel_unref(owner);
09898 ast_mutex_lock(&iaxsl[callno]);
09899 }
09900 }
09901
09902 static int socket_process(struct iax2_thread *thread)
09903 {
09904 struct sockaddr_in sin;
09905 int res;
09906 int updatehistory=1;
09907 int new = NEW_PREVENT;
09908 int dcallno = 0;
09909 char decrypted = 0;
09910 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
09911 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
09912 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
09913 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
09914 struct iax_frame *fr;
09915 struct iax_frame *cur;
09916 struct ast_frame f = { 0, };
09917 struct ast_channel *c = NULL;
09918 struct iax2_dpcache *dp;
09919 struct iax2_peer *peer;
09920 struct iax_ies ies;
09921 struct iax_ie_data ied0, ied1;
09922 format_t format;
09923 int fd;
09924 int exists;
09925 int minivid = 0;
09926 char empty[32]="";
09927 struct iax_frame *duped_fr;
09928 char host_pref_buf[128];
09929 char caller_pref_buf[128];
09930 struct ast_codec_pref pref;
09931 char *using_prefs = "mine";
09932
09933
09934 fr = ast_alloca(sizeof(*fr) + 4096);
09935 memset(fr, 0, sizeof(*fr));
09936 fr->afdatalen = 4096;
09937
09938
09939 res = thread->buf_len;
09940 fd = thread->iofd;
09941 memcpy(&sin, &thread->iosin, sizeof(sin));
09942
09943 if (res < sizeof(*mh)) {
09944 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
09945 return 1;
09946 }
09947 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
09948 if (res < sizeof(*vh)) {
09949 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));
09950 return 1;
09951 }
09952
09953
09954 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
09955 minivid = 1;
09956 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
09957 return socket_process_meta(res, meta, &sin, fd, fr);
09958
09959 #ifdef DEBUG_SUPPORT
09960 if (res >= sizeof(*fh))
09961 iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
09962 #endif
09963 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09964 if (res < sizeof(*fh)) {
09965 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));
09966 return 1;
09967 }
09968
09969
09970 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
09971
09972
09973
09974
09975
09976
09977 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
09978 ast_mutex_lock(&iaxsl[fr->callno]);
09979 if (iaxs[fr->callno] && ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED)) {
09980 if (decrypt_frame(fr->callno, fh, &f, &res)) {
09981 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09982 ast_mutex_unlock(&iaxsl[fr->callno]);
09983 return 1;
09984 }
09985 decrypted = 1;
09986 }
09987 ast_mutex_unlock(&iaxsl[fr->callno]);
09988 }
09989
09990
09991 f.frametype = fh->type;
09992 if (f.frametype == AST_FRAME_VIDEO) {
09993 f.subclass.codec = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
09994 } else if (f.frametype == AST_FRAME_VOICE) {
09995 f.subclass.codec = uncompress_subclass(fh->csub);
09996 } else {
09997 f.subclass.integer = uncompress_subclass(fh->csub);
09998 }
09999
10000
10001 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_POKE) {
10002
10003 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10004 return 1;
10005 } else if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_ACK && dcallno == 1) {
10006
10007 return 1;
10008 }
10009
10010 f.datalen = res - sizeof(*fh);
10011 if (f.datalen) {
10012 if (f.frametype == AST_FRAME_IAX) {
10013 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
10014 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
10015 ast_variables_destroy(ies.vars);
10016 return 1;
10017 }
10018 f.data.ptr = NULL;
10019 f.datalen = 0;
10020 } else {
10021 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
10022 memset(&ies, 0, sizeof(ies));
10023 }
10024 } else {
10025 if (f.frametype == AST_FRAME_IAX)
10026 f.data.ptr = NULL;
10027 else
10028 f.data.ptr = empty;
10029 memset(&ies, 0, sizeof(ies));
10030 }
10031
10032 if (!dcallno && iax2_allow_new(f.frametype, f.subclass.integer, 1)) {
10033
10034 if (handle_call_token(fh, &ies, &sin, fd)) {
10035 ast_variables_destroy(ies.vars);
10036 return 1;
10037 }
10038
10039 if (ies.calltoken && ies.calltokendata) {
10040
10041
10042
10043
10044 new = NEW_ALLOW_CALLTOKEN_VALIDATED;
10045 } else {
10046 new = NEW_ALLOW;
10047 }
10048 }
10049 } else {
10050
10051 f.frametype = AST_FRAME_NULL;
10052 f.subclass.integer = 0;
10053 memset(&ies, 0, sizeof(ies));
10054 }
10055
10056 if (!fr->callno) {
10057 int check_dcallno = 0;
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer == IAX_COMMAND_ACK))) {
10068 check_dcallno = 1;
10069 }
10070
10071 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
10072 if (f.frametype == AST_FRAME_IAX && f.subclass.integer == IAX_COMMAND_NEW) {
10073 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10074 } else if (f.frametype == AST_FRAME_IAX && (f.subclass.integer == IAX_COMMAND_REGREQ || f.subclass.integer == IAX_COMMAND_REGREL)) {
10075 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
10076 }
10077 ast_variables_destroy(ies.vars);
10078 return 1;
10079 }
10080 }
10081
10082 if (fr->callno > 0)
10083 ast_mutex_lock(&iaxsl[fr->callno]);
10084
10085 if (!fr->callno || !iaxs[fr->callno]) {
10086
10087
10088 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10089
10090 if (((f.subclass.integer != IAX_COMMAND_INVAL) &&
10091 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10092 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10093 (f.subclass.integer != IAX_COMMAND_FWDOWNL))||
10094 (f.frametype != AST_FRAME_IAX))
10095 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
10096 fd);
10097 }
10098 if (fr->callno > 0)
10099 ast_mutex_unlock(&iaxsl[fr->callno]);
10100 ast_variables_destroy(ies.vars);
10101 return 1;
10102 }
10103 if (ast_test_flag64(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
10104 if (decrypt_frame(fr->callno, fh, &f, &res)) {
10105 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
10106 ast_variables_destroy(ies.vars);
10107 ast_mutex_unlock(&iaxsl[fr->callno]);
10108 return 1;
10109 }
10110 decrypted = 1;
10111 }
10112
10113 #ifdef DEBUG_SUPPORT
10114 if (decrypted) {
10115 iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
10116 }
10117 #endif
10118
10119
10120
10121 iaxs[fr->callno]->frames_received++;
10122
10123 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
10124 f.subclass.integer != IAX_COMMAND_TXCNT &&
10125 f.subclass.integer != IAX_COMMAND_TXACC) {
10126 unsigned short new_peercallno;
10127
10128 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
10129 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
10130 if (iaxs[fr->callno]->peercallno) {
10131 remove_by_peercallno(iaxs[fr->callno]);
10132 }
10133 iaxs[fr->callno]->peercallno = new_peercallno;
10134 store_by_peercallno(iaxs[fr->callno]);
10135 }
10136 }
10137 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
10138 if (iaxdebug)
10139 ast_debug(1, "Received packet %d, (%d, %u)\n", fh->oseqno, f.frametype, f.subclass.integer);
10140
10141 fr->oseqno = fh->oseqno;
10142 fr->iseqno = fh->iseqno;
10143 fr->ts = ntohl(fh->ts);
10144 #ifdef IAXTESTS
10145 if (test_resync) {
10146 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
10147 fr->ts += test_resync;
10148 }
10149 #endif
10150 #if 0
10151 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
10152 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
10153 (f.subclass == IAX_COMMAND_NEW ||
10154 f.subclass == IAX_COMMAND_AUTHREQ ||
10155 f.subclass == IAX_COMMAND_ACCEPT ||
10156 f.subclass == IAX_COMMAND_REJECT)) ) )
10157 #endif
10158 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
10159 updatehistory = 0;
10160 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
10161 (iaxs[fr->callno]->iseqno ||
10162 ((f.subclass.integer != IAX_COMMAND_TXCNT) &&
10163 (f.subclass.integer != IAX_COMMAND_TXREADY) &&
10164 (f.subclass.integer != IAX_COMMAND_TXREL) &&
10165 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&
10166 (f.subclass.integer != IAX_COMMAND_TXACC)) ||
10167 (f.frametype != AST_FRAME_IAX))) {
10168 if (
10169 ((f.subclass.integer != IAX_COMMAND_ACK) &&
10170 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10171 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10172 (f.subclass.integer != IAX_COMMAND_TXREADY) &&
10173 (f.subclass.integer != IAX_COMMAND_TXREL) &&
10174 (f.subclass.integer != IAX_COMMAND_UNQUELCH ) &&
10175 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10176 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10177 (f.frametype != AST_FRAME_IAX)) {
10178
10179 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
10180 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass.integer);
10181
10182
10183 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
10184
10185 if ((f.frametype != AST_FRAME_IAX) ||
10186 ((f.subclass.integer != IAX_COMMAND_ACK) && (f.subclass.integer != IAX_COMMAND_INVAL))) {
10187 ast_debug(1, "Acking anyway\n");
10188
10189
10190 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10191 }
10192 } else {
10193
10194 iax2_vnak(fr->callno);
10195 }
10196 ast_variables_destroy(ies.vars);
10197 ast_mutex_unlock(&iaxsl[fr->callno]);
10198 return 1;
10199 }
10200 } else {
10201
10202 if (((f.subclass.integer != IAX_COMMAND_ACK) &&
10203 (f.subclass.integer != IAX_COMMAND_INVAL) &&
10204 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
10205 (f.subclass.integer != IAX_COMMAND_TXACC) &&
10206 (f.subclass.integer != IAX_COMMAND_VNAK)) ||
10207 (f.frametype != AST_FRAME_IAX))
10208 iaxs[fr->callno]->iseqno++;
10209 }
10210
10211 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
10212 if (res < thread->buf_size)
10213 thread->buf[res++] = '\0';
10214 else
10215 thread->buf[res - 1] = '\0';
10216 }
10217
10218
10219
10220 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10221 ((f.subclass.integer != IAX_COMMAND_INVAL) ||
10222 (f.frametype != AST_FRAME_IAX))) {
10223 unsigned char x;
10224 int call_to_destroy;
10225
10226 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
10227 x = fr->iseqno;
10228 else
10229 x = iaxs[fr->callno]->oseqno;
10230 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
10231
10232
10233 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
10234
10235 if (iaxdebug)
10236 ast_debug(1, "Cancelling transmission of packet %d\n", x);
10237 call_to_destroy = 0;
10238 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10239
10240 if (x == cur->oseqno) {
10241 cur->retries = -1;
10242
10243 if (cur->final)
10244 call_to_destroy = fr->callno;
10245 }
10246 }
10247 if (call_to_destroy) {
10248 if (iaxdebug)
10249 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
10250 ast_mutex_lock(&iaxsl[call_to_destroy]);
10251 iax2_destroy(call_to_destroy);
10252 ast_mutex_unlock(&iaxsl[call_to_destroy]);
10253 }
10254 }
10255
10256 if (iaxs[fr->callno])
10257 iaxs[fr->callno]->rseqno = fr->iseqno;
10258 else {
10259
10260 ast_variables_destroy(ies.vars);
10261 ast_mutex_unlock(&iaxsl[fr->callno]);
10262 return 1;
10263 }
10264 } else {
10265 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
10266 }
10267 }
10268 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
10269 ((f.frametype != AST_FRAME_IAX) ||
10270 ((f.subclass.integer != IAX_COMMAND_TXACC) &&
10271 (f.subclass.integer != IAX_COMMAND_TXCNT)))) {
10272
10273 ast_variables_destroy(ies.vars);
10274 ast_mutex_unlock(&iaxsl[fr->callno]);
10275 return 1;
10276 }
10277
10278
10279
10280
10281 if ((f.frametype == AST_FRAME_VOICE) ||
10282 (f.frametype == AST_FRAME_VIDEO) ||
10283 (f.frametype == AST_FRAME_IAX)) {
10284 if (ast_test_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
10285 ast_clear_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10286 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat, NULL)) {
10287 ast_variables_destroy(ies.vars);
10288 ast_mutex_unlock(&iaxsl[fr->callno]);
10289 return 1;
10290 }
10291 }
10292
10293 if (ies.vars) {
10294 struct ast_datastore *variablestore = NULL;
10295 struct ast_variable *var, *prev = NULL;
10296 AST_LIST_HEAD(, ast_var_t) *varlist;
10297
10298 iax2_lock_owner(fr->callno);
10299 if (!iaxs[fr->callno]) {
10300 ast_variables_destroy(ies.vars);
10301 ast_mutex_unlock(&iaxsl[fr->callno]);
10302 return 1;
10303 }
10304 if ((c = iaxs[fr->callno]->owner)) {
10305 varlist = ast_calloc(1, sizeof(*varlist));
10306 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10307
10308 if (variablestore && varlist) {
10309 variablestore->data = varlist;
10310 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10311 AST_LIST_HEAD_INIT(varlist);
10312 ast_debug(1, "I can haz IAX vars?\n");
10313 for (var = ies.vars; var; var = var->next) {
10314 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10315 if (prev) {
10316 ast_free(prev);
10317 }
10318 prev = var;
10319 if (!newvar) {
10320
10321 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10322 } else {
10323 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10324 }
10325 }
10326 if (prev) {
10327 ast_free(prev);
10328 }
10329 ies.vars = NULL;
10330 ast_channel_datastore_add(c, variablestore);
10331 } else {
10332 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10333 if (variablestore) {
10334 ast_datastore_free(variablestore);
10335 }
10336 if (varlist) {
10337 ast_free(varlist);
10338 }
10339 }
10340 ast_channel_unlock(c);
10341 } else {
10342
10343
10344 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
10345 for (var = ies.vars; var && var->next; var = var->next);
10346 if (var) {
10347 var->next = iaxs[fr->callno]->iaxvars;
10348 iaxs[fr->callno]->iaxvars = ies.vars;
10349 ies.vars = NULL;
10350 }
10351 }
10352 }
10353
10354 if (ies.vars) {
10355 ast_debug(1, "I have IAX variables, but they were not processed\n");
10356 }
10357 }
10358
10359
10360
10361 if ((f.frametype == AST_FRAME_IAX) && (f.subclass.integer != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
10362 send_signaling(iaxs[fr->callno]);
10363 }
10364
10365 if (f.frametype == AST_FRAME_VOICE) {
10366 if (f.subclass.codec != iaxs[fr->callno]->voiceformat) {
10367 iaxs[fr->callno]->voiceformat = f.subclass.codec;
10368 ast_debug(1, "Ooh, voice format changed to '%s'\n", ast_getformatname(f.subclass.codec));
10369 if (iaxs[fr->callno]->owner) {
10370 iax2_lock_owner(fr->callno);
10371 if (iaxs[fr->callno]) {
10372 if (iaxs[fr->callno]->owner) {
10373 format_t orignative;
10374
10375 orignative = iaxs[fr->callno]->owner->nativeformats;
10376 iaxs[fr->callno]->owner->nativeformats = f.subclass.codec;
10377 if (iaxs[fr->callno]->owner->readformat)
10378 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10379 iaxs[fr->callno]->owner->nativeformats = orignative;
10380 ast_channel_unlock(iaxs[fr->callno]->owner);
10381 }
10382 } else {
10383 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
10384
10385 if (ies.vars) {
10386 ast_variables_destroy(ies.vars);
10387 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
10388 ies.vars = NULL;
10389 }
10390 ast_mutex_unlock(&iaxsl[fr->callno]);
10391 return 1;
10392 }
10393 }
10394 }
10395 }
10396 if (f.frametype == AST_FRAME_VIDEO) {
10397 if (f.subclass.codec != iaxs[fr->callno]->videoformat) {
10398 ast_debug(1, "Ooh, video format changed to %s\n", ast_getformatname(f.subclass.codec & ~0x1LL));
10399 iaxs[fr->callno]->videoformat = f.subclass.codec & ~0x1LL;
10400 }
10401 }
10402 if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
10403 if (f.subclass.integer == AST_CONTROL_BUSY) {
10404 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
10405 } else if (f.subclass.integer == AST_CONTROL_CONGESTION) {
10406 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
10407 }
10408 }
10409 if (f.frametype == AST_FRAME_IAX) {
10410 ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
10411
10412 if (iaxdebug)
10413 ast_debug(1, "IAX subclass %d received\n", f.subclass.integer);
10414
10415
10416 if (iaxs[fr->callno]->last < fr->ts &&
10417 f.subclass.integer != IAX_COMMAND_ACK &&
10418 f.subclass.integer != IAX_COMMAND_PONG &&
10419 f.subclass.integer != IAX_COMMAND_LAGRP) {
10420 iaxs[fr->callno]->last = fr->ts;
10421 if (iaxdebug)
10422 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10423 }
10424 iaxs[fr->callno]->last_iax_message = f.subclass.integer;
10425 if (!iaxs[fr->callno]->first_iax_message) {
10426 iaxs[fr->callno]->first_iax_message = f.subclass.integer;
10427 }
10428 switch(f.subclass.integer) {
10429 case IAX_COMMAND_ACK:
10430
10431 break;
10432 case IAX_COMMAND_QUELCH:
10433 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10434
10435 if (iaxs[fr->callno]->owner) {
10436 ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10437 "Status: On\r\n"
10438 "Channel: %s\r\n"
10439 "Uniqueid: %s\r\n",
10440 iaxs[fr->callno]->owner->name,
10441 iaxs[fr->callno]->owner->uniqueid);
10442 }
10443
10444 ast_set_flag64(iaxs[fr->callno], IAX_QUELCH);
10445 if (ies.musiconhold) {
10446 iax2_lock_owner(fr->callno);
10447 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10448 break;
10449 }
10450 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10451 const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10452
10453
10454
10455
10456
10457 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
10458 S_OR(moh_suggest, NULL),
10459 !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10460 }
10461 ast_channel_unlock(iaxs[fr->callno]->owner);
10462 }
10463 }
10464 break;
10465 case IAX_COMMAND_UNQUELCH:
10466 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10467 iax2_lock_owner(fr->callno);
10468 if (!iaxs[fr->callno]) {
10469 break;
10470 }
10471
10472 if (iaxs[fr->callno]->owner && ast_test_flag64(iaxs[fr->callno], IAX_QUELCH)) {
10473 ast_manager_event(iaxs[fr->callno]->owner, EVENT_FLAG_CALL, "Hold",
10474 "Status: Off\r\n"
10475 "Channel: %s\r\n"
10476 "Uniqueid: %s\r\n",
10477 iaxs[fr->callno]->owner->name,
10478 iaxs[fr->callno]->owner->uniqueid);
10479 }
10480
10481 ast_clear_flag64(iaxs[fr->callno], IAX_QUELCH);
10482 if (!iaxs[fr->callno]->owner) {
10483 break;
10484 }
10485 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10486
10487
10488
10489
10490 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10491 }
10492 ast_channel_unlock(iaxs[fr->callno]->owner);
10493 }
10494 break;
10495 case IAX_COMMAND_TXACC:
10496 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10497
10498 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
10499
10500 if (cur->transfer) {
10501 cur->retries = -1;
10502 }
10503 }
10504 memset(&ied1, 0, sizeof(ied1));
10505 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10506 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10507 iaxs[fr->callno]->transferring = TRANSFER_READY;
10508 }
10509 break;
10510 case IAX_COMMAND_NEW:
10511
10512 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10513 break;
10514 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10515 ast_mutex_unlock(&iaxsl[fr->callno]);
10516 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10517 ast_mutex_lock(&iaxsl[fr->callno]);
10518 if (!iaxs[fr->callno]) {
10519 break;
10520 }
10521 }
10522
10523 if (ast_test_flag64(iaxs[fr->callno], IAX_TRUNK)) {
10524 int new_callno;
10525 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10526 fr->callno = new_callno;
10527 }
10528
10529 if (delayreject)
10530 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10531 if (check_access(fr->callno, &sin, &ies)) {
10532
10533 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10534 if (authdebug)
10535 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);
10536 break;
10537 }
10538 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag64(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10539 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10540 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10541 break;
10542 }
10543 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10544 const char *context, *exten, *cid_num;
10545
10546 context = ast_strdupa(iaxs[fr->callno]->context);
10547 exten = ast_strdupa(iaxs[fr->callno]->exten);
10548 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10549
10550
10551 ast_mutex_unlock(&iaxsl[fr->callno]);
10552 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10553 ast_mutex_lock(&iaxsl[fr->callno]);
10554
10555 if (!iaxs[fr->callno]) {
10556 break;
10557 }
10558 } else
10559 exists = 0;
10560
10561 save_osptoken(fr, &ies);
10562 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10563 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10564 memset(&ied0, 0, sizeof(ied0));
10565 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10566 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10567 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10568 if (!iaxs[fr->callno]) {
10569 break;
10570 }
10571 if (authdebug)
10572 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);
10573 } else {
10574
10575
10576 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10577 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10578 using_prefs = "reqonly";
10579 } else {
10580 using_prefs = "disabled";
10581 }
10582 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10583 memset(&pref, 0, sizeof(pref));
10584 strcpy(caller_pref_buf, "disabled");
10585 strcpy(host_pref_buf, "disabled");
10586 } else {
10587 using_prefs = "mine";
10588
10589 if (ies.codec_prefs)
10590 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10591 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10592
10593 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10594 pref = iaxs[fr->callno]->rprefs;
10595 using_prefs = "caller";
10596 } else {
10597 pref = iaxs[fr->callno]->prefs;
10598 }
10599 } else
10600 pref = iaxs[fr->callno]->prefs;
10601
10602 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10603 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10604 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10605 }
10606 if (!format) {
10607 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP))
10608 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10609 if (!format) {
10610 memset(&ied0, 0, sizeof(ied0));
10611 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10612 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10613 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10614 if (!iaxs[fr->callno]) {
10615 break;
10616 }
10617 if (authdebug) {
10618 char tmp[256], tmp2[256], tmp3[256];
10619 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10620 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
10621 ast_inet_ntoa(sin.sin_addr),
10622 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10623 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10624 } else {
10625 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10626 ast_inet_ntoa(sin.sin_addr),
10627 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10628 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10629 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10630 }
10631 }
10632 } else {
10633
10634 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10635 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10636 format = 0;
10637 } else {
10638 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10639 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10640 memset(&pref, 0, sizeof(pref));
10641 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10642 strcpy(caller_pref_buf,"disabled");
10643 strcpy(host_pref_buf,"disabled");
10644 } else {
10645 using_prefs = "mine";
10646 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10647
10648 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10649 pref = iaxs[fr->callno]->prefs;
10650 } else {
10651 pref = iaxs[fr->callno]->rprefs;
10652 using_prefs = "caller";
10653 }
10654 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10655 } else
10656 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10657 }
10658 }
10659
10660 if (!format) {
10661 char tmp[256], tmp2[256], tmp3[256];
10662 memset(&ied0, 0, sizeof(ied0));
10663 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10664 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10665 ast_log(LOG_ERROR, "No best format in '%s'???\n", ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
10666 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10667 if (!iaxs[fr->callno]) {
10668 break;
10669 }
10670 if (authdebug) {
10671 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
10672 ast_inet_ntoa(sin.sin_addr),
10673 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat),
10674 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
10675 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
10676 }
10677 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10678 break;
10679 }
10680 }
10681 }
10682 if (format) {
10683
10684 memset(&ied1, 0, sizeof(ied1));
10685 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10686 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
10687 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10688 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10689 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10690 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10691 "%srequested format = %s,\n"
10692 "%srequested prefs = %s,\n"
10693 "%sactual format = %s,\n"
10694 "%shost prefs = %s,\n"
10695 "%spriority = %s\n",
10696 ast_inet_ntoa(sin.sin_addr),
10697 VERBOSE_PREFIX_4,
10698 ast_getformatname(iaxs[fr->callno]->peerformat),
10699 VERBOSE_PREFIX_4,
10700 caller_pref_buf,
10701 VERBOSE_PREFIX_4,
10702 ast_getformatname(format),
10703 VERBOSE_PREFIX_4,
10704 host_pref_buf,
10705 VERBOSE_PREFIX_4,
10706 using_prefs);
10707
10708 iaxs[fr->callno]->chosenformat = format;
10709 ast_set_flag64(iaxs[fr->callno], IAX_DELAYPBXSTART);
10710 } else {
10711 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10712
10713 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10714 }
10715 }
10716 }
10717 break;
10718 }
10719 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10720 merge_encryption(iaxs[fr->callno],ies.encmethods);
10721 else
10722 iaxs[fr->callno]->encmethods = 0;
10723 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10724 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10725 break;
10726 case IAX_COMMAND_DPREQ:
10727
10728 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10729 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10730 if (iaxcompat) {
10731
10732 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10733 } else {
10734
10735 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10736 }
10737 }
10738 break;
10739 case IAX_COMMAND_HANGUP:
10740 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
10741 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10742
10743 if (iaxs[fr->callno]->owner) {
10744 set_hangup_source_and_cause(fr->callno, ies.causecode);
10745 if (!iaxs[fr->callno]) {
10746 break;
10747 }
10748 }
10749
10750
10751 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10752 iax2_destroy(fr->callno);
10753 break;
10754 case IAX_COMMAND_REJECT:
10755
10756 if (iaxs[fr->callno]->owner) {
10757 set_hangup_source_and_cause(fr->callno, ies.causecode);
10758 if (!iaxs[fr->callno]) {
10759 break;
10760 }
10761 }
10762
10763 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10764 if (iaxs[fr->callno]->owner && authdebug)
10765 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10766 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10767 ies.cause ? ies.cause : "<Unknown>");
10768 ast_debug(1, "Immediately destroying %d, having received reject\n",
10769 fr->callno);
10770 }
10771
10772 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
10773 fr->ts, NULL, 0, fr->iseqno);
10774 if (!ast_test_flag64(iaxs[fr->callno], IAX_PROVISION))
10775 iaxs[fr->callno]->error = EPERM;
10776 iax2_destroy(fr->callno);
10777 break;
10778 case IAX_COMMAND_TRANSFER:
10779 {
10780 struct ast_channel *bridged_chan;
10781 struct ast_channel *owner;
10782
10783 iax2_lock_owner(fr->callno);
10784 if (!iaxs[fr->callno]) {
10785
10786 break;
10787 }
10788 owner = iaxs[fr->callno]->owner;
10789 bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10790 if (bridged_chan && ies.called_number) {
10791 const char *context;
10792
10793 context = ast_strdupa(iaxs[fr->callno]->context);
10794
10795 ast_channel_ref(owner);
10796 ast_channel_ref(bridged_chan);
10797 ast_channel_unlock(owner);
10798 ast_mutex_unlock(&iaxsl[fr->callno]);
10799
10800
10801 pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10802 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10803
10804
10805 if (ast_parking_ext_valid(ies.called_number, owner, context)) {
10806 ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10807 if (iax_park(bridged_chan, owner, ies.called_number, context)) {
10808 ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10809 bridged_chan->name);
10810 }
10811 } else {
10812 if (ast_async_goto(bridged_chan, context, ies.called_number, 1)) {
10813 ast_log(LOG_WARNING,
10814 "Async goto of '%s' to '%s@%s' failed\n",
10815 bridged_chan->name, ies.called_number, context);
10816 } else {
10817 ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10818 bridged_chan->name, ies.called_number, context);
10819 }
10820 }
10821 ast_channel_unref(owner);
10822 ast_channel_unref(bridged_chan);
10823
10824 ast_mutex_lock(&iaxsl[fr->callno]);
10825 } else {
10826 ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10827 if (owner) {
10828 ast_channel_unlock(owner);
10829 }
10830 }
10831
10832 break;
10833 }
10834 case IAX_COMMAND_ACCEPT:
10835
10836 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
10837 break;
10838 if (ast_test_flag64(iaxs[fr->callno], IAX_PROVISION)) {
10839
10840 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10841 iax2_destroy(fr->callno);
10842 break;
10843 }
10844 if (ies.format) {
10845 iaxs[fr->callno]->peerformat = ies.format;
10846 } else {
10847 if (iaxs[fr->callno]->owner)
10848 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10849 else
10850 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10851 }
10852 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));
10853 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10854 memset(&ied0, 0, sizeof(ied0));
10855 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10856 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10857 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10858 if (!iaxs[fr->callno]) {
10859 break;
10860 }
10861 if (authdebug) {
10862 char tmp1[256], tmp2[256];
10863 ast_log(LOG_NOTICE, "Rejected call to %s, format %s incompatible with our capability %s.\n",
10864 ast_inet_ntoa(sin.sin_addr),
10865 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
10866 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
10867 }
10868 } else {
10869 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10870 iax2_lock_owner(fr->callno);
10871 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10872
10873 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
10874 ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
10875
10876
10877 if (iaxs[fr->callno]->owner->writeformat)
10878 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
10879 if (iaxs[fr->callno]->owner->readformat)
10880 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10881 ast_channel_unlock(iaxs[fr->callno]->owner);
10882 }
10883 }
10884 if (iaxs[fr->callno]) {
10885 AST_LIST_LOCK(&dpcache);
10886 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
10887 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
10888 iax2_dprequest(dp, fr->callno);
10889 AST_LIST_UNLOCK(&dpcache);
10890 }
10891 break;
10892 case IAX_COMMAND_POKE:
10893
10894 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
10895 break;
10896 case IAX_COMMAND_PING:
10897 {
10898 struct iax_ie_data pingied;
10899 construct_rr(iaxs[fr->callno], &pingied);
10900
10901 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
10902 }
10903 break;
10904 case IAX_COMMAND_PONG:
10905
10906 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
10907
10908 save_rr(fr, &ies);
10909
10910
10911 log_jitterstats(fr->callno);
10912
10913 if (iaxs[fr->callno]->peerpoke) {
10914 peer = iaxs[fr->callno]->peerpoke;
10915 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
10916 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
10917 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
10918 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);
10919 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name);
10920 }
10921 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
10922 if (iaxs[fr->callno]->pingtime > peer->maxms) {
10923 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
10924 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);
10925 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
10926 }
10927 }
10928 peer->lastms = iaxs[fr->callno]->pingtime;
10929 if (peer->smoothing && (peer->lastms > -1))
10930 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
10931 else if (peer->smoothing && peer->lastms < 0)
10932 peer->historicms = (0 + peer->historicms) / 2;
10933 else
10934 peer->historicms = iaxs[fr->callno]->pingtime;
10935
10936
10937 if (peer->pokeexpire > -1) {
10938 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
10939 peer_unref(peer);
10940 peer->pokeexpire = -1;
10941 }
10942 }
10943
10944 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
10945 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
10946 else
10947 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
10948 if (peer->pokeexpire == -1)
10949 peer_unref(peer);
10950
10951 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10952
10953 iax2_destroy(fr->callno);
10954 peer->callno = 0;
10955 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
10956 }
10957 break;
10958 case IAX_COMMAND_LAGRQ:
10959 case IAX_COMMAND_LAGRP:
10960 f.src = "LAGRQ";
10961 f.mallocd = 0;
10962 f.offset = 0;
10963 f.samples = 0;
10964 iax_frame_wrap(fr, &f);
10965 if (f.subclass.integer == IAX_COMMAND_LAGRQ) {
10966
10967 fr->af.subclass.integer = IAX_COMMAND_LAGRP;
10968 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
10969 } else {
10970
10971 unsigned int ts;
10972
10973 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
10974 iaxs[fr->callno]->lag = ts - fr->ts;
10975 if (iaxdebug)
10976 ast_debug(1, "Peer %s lag measured as %dms\n",
10977 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
10978 }
10979 break;
10980 case IAX_COMMAND_AUTHREQ:
10981 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10982 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>");
10983 break;
10984 }
10985 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
10986 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
10987 .subclass.integer = AST_CONTROL_HANGUP,
10988 };
10989 ast_log(LOG_WARNING,
10990 "I don't know how to authenticate %s to %s\n",
10991 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
10992 iax2_queue_frame(fr->callno, &hangup_fr);
10993 }
10994 break;
10995 case IAX_COMMAND_AUTHREP:
10996
10997 if (delayreject)
10998 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10999
11000 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
11001 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>");
11002 break;
11003 }
11004 if (authenticate_verify(iaxs[fr->callno], &ies)) {
11005 if (authdebug)
11006 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);
11007 memset(&ied0, 0, sizeof(ied0));
11008 auth_fail(fr->callno, IAX_COMMAND_REJECT);
11009 break;
11010 }
11011 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
11012
11013 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
11014 } else
11015 exists = 0;
11016 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
11017 if (authdebug)
11018 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);
11019 memset(&ied0, 0, sizeof(ied0));
11020 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11021 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11022 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11023 if (!iaxs[fr->callno]) {
11024 break;
11025 }
11026 } else {
11027
11028 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11029 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11030 using_prefs = "reqonly";
11031 } else {
11032 using_prefs = "disabled";
11033 }
11034 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
11035 memset(&pref, 0, sizeof(pref));
11036 strcpy(caller_pref_buf, "disabled");
11037 strcpy(host_pref_buf, "disabled");
11038 } else {
11039 using_prefs = "mine";
11040 if (ies.codec_prefs)
11041 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
11042 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11043 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11044 pref = iaxs[fr->callno]->rprefs;
11045 using_prefs = "caller";
11046 } else {
11047 pref = iaxs[fr->callno]->prefs;
11048 }
11049 } else
11050 pref = iaxs[fr->callno]->prefs;
11051 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
11052 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
11053 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
11054 }
11055 if (!format) {
11056 char tmp1[256], tmp2[256], tmp3[256];
11057 if(!ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11058 ast_debug(1, "We don't do requested format %s, falling back to peer capability '%s'\n",
11059 ast_getformatname(iaxs[fr->callno]->peerformat),
11060 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability));
11061 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
11062 }
11063 if (!format) {
11064 if (authdebug) {
11065 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11066 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n", ast_inet_ntoa(sin.sin_addr),
11067 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11068 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11069 } else {
11070 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11071 ast_inet_ntoa(sin.sin_addr),
11072 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11073 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11074 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11075 }
11076 }
11077 memset(&ied0, 0, sizeof(ied0));
11078 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11079 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11080 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11081 if (!iaxs[fr->callno]) {
11082 break;
11083 }
11084 } else {
11085
11086 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11087 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
11088 format = 0;
11089 } else {
11090 if(ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
11091 using_prefs = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
11092 memset(&pref, 0, sizeof(pref));
11093 format = ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
11094 iaxs[fr->callno]->peerformat : ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11095 strcpy(caller_pref_buf,"disabled");
11096 strcpy(host_pref_buf,"disabled");
11097 } else {
11098 using_prefs = "mine";
11099 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
11100
11101 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
11102 pref = iaxs[fr->callno]->prefs;
11103 } else {
11104 pref = iaxs[fr->callno]->rprefs;
11105 using_prefs = "caller";
11106 }
11107 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
11108 } else
11109 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
11110 }
11111 }
11112 if (!format) {
11113 char tmp1[256], tmp2[256], tmp3[256];
11114 ast_log(LOG_ERROR, "No best format in %s???\n",
11115 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability));
11116 if (authdebug) {
11117 if (ast_test_flag64(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
11118 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested '%s' incompatible with our capability '%s'.\n",
11119 ast_inet_ntoa(sin.sin_addr),
11120 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11121 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->capability));
11122 } else {
11123 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability '%s'/'%s' incompatible with our capability '%s'.\n",
11124 ast_inet_ntoa(sin.sin_addr),
11125 ast_getformatname_multiple(tmp1, sizeof(tmp1), iaxs[fr->callno]->peerformat),
11126 ast_getformatname_multiple(tmp2, sizeof(tmp2), iaxs[fr->callno]->peercapability),
11127 ast_getformatname_multiple(tmp3, sizeof(tmp3), iaxs[fr->callno]->capability));
11128 }
11129 }
11130 memset(&ied0, 0, sizeof(ied0));
11131 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
11132 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
11133 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11134 if (!iaxs[fr->callno]) {
11135 break;
11136 }
11137 }
11138 }
11139 }
11140 if (format) {
11141
11142 memset(&ied1, 0, sizeof(ied1));
11143 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
11144 iax_ie_append_versioned_uint64(&ied1, IAX_IE_FORMAT2, 0, format);
11145 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
11146 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
11147 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11148 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
11149 "%srequested format = %s,\n"
11150 "%srequested prefs = %s,\n"
11151 "%sactual format = %s,\n"
11152 "%shost prefs = %s,\n"
11153 "%spriority = %s\n",
11154 ast_inet_ntoa(sin.sin_addr),
11155 VERBOSE_PREFIX_4,
11156 ast_getformatname(iaxs[fr->callno]->peerformat),
11157 VERBOSE_PREFIX_4,
11158 caller_pref_buf,
11159 VERBOSE_PREFIX_4,
11160 ast_getformatname(format),
11161 VERBOSE_PREFIX_4,
11162 host_pref_buf,
11163 VERBOSE_PREFIX_4,
11164 using_prefs);
11165
11166 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11167 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format, NULL)))
11168 iax2_destroy(fr->callno);
11169 else if (ies.vars) {
11170 struct ast_datastore *variablestore;
11171 struct ast_variable *var, *prev = NULL;
11172 AST_LIST_HEAD(, ast_var_t) *varlist;
11173 varlist = ast_calloc(1, sizeof(*varlist));
11174 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11175 if (variablestore && varlist) {
11176 variablestore->data = varlist;
11177 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11178 AST_LIST_HEAD_INIT(varlist);
11179 ast_debug(1, "I can haz IAX vars? w00t\n");
11180 for (var = ies.vars; var; var = var->next) {
11181 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11182 if (prev)
11183 ast_free(prev);
11184 prev = var;
11185 if (!newvar) {
11186
11187 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11188 } else {
11189 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11190 }
11191 }
11192 if (prev)
11193 ast_free(prev);
11194 ies.vars = NULL;
11195 ast_channel_datastore_add(c, variablestore);
11196 } else {
11197 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11198 if (variablestore)
11199 ast_datastore_free(variablestore);
11200 if (varlist)
11201 ast_free(varlist);
11202 }
11203 }
11204 } else {
11205 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11206
11207 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
11208 if (ast_test_flag64(iaxs[fr->callno], IAX_IMMEDIATE)) {
11209 goto immediatedial;
11210 }
11211 }
11212 }
11213 }
11214 break;
11215 case IAX_COMMAND_DIAL:
11216 immediatedial:
11217 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
11218 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
11219 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
11220 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
11221 if (authdebug)
11222 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);
11223 memset(&ied0, 0, sizeof(ied0));
11224 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
11225 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
11226 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11227 if (!iaxs[fr->callno]) {
11228 break;
11229 }
11230 } else {
11231 char tmp[256];
11232 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11233 ast_verb(3, "Accepting DIAL from %s, formats = %s\n",
11234 ast_inet_ntoa(sin.sin_addr),
11235 ast_getformatname_multiple(tmp, sizeof(tmp), iaxs[fr->callno]->peerformat));
11236 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
11237 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
11238 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat, NULL)))
11239 iax2_destroy(fr->callno);
11240 else if (ies.vars) {
11241 struct ast_datastore *variablestore;
11242 struct ast_variable *var, *prev = NULL;
11243 AST_LIST_HEAD(, ast_var_t) *varlist;
11244 varlist = ast_calloc(1, sizeof(*varlist));
11245 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
11246 ast_debug(1, "I can haz IAX vars? w00t\n");
11247 if (variablestore && varlist) {
11248 variablestore->data = varlist;
11249 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
11250 AST_LIST_HEAD_INIT(varlist);
11251 for (var = ies.vars; var; var = var->next) {
11252 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
11253 if (prev)
11254 ast_free(prev);
11255 prev = var;
11256 if (!newvar) {
11257
11258 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11259 } else {
11260 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
11261 }
11262 }
11263 if (prev)
11264 ast_free(prev);
11265 ies.vars = NULL;
11266 ast_channel_datastore_add(c, variablestore);
11267 } else {
11268 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
11269 if (variablestore)
11270 ast_datastore_free(variablestore);
11271 if (varlist)
11272 ast_free(varlist);
11273 }
11274 }
11275 }
11276 }
11277 break;
11278 case IAX_COMMAND_INVAL:
11279 iaxs[fr->callno]->error = ENOTCONN;
11280 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
11281 iax2_destroy(fr->callno);
11282 ast_debug(1, "Destroying call %d\n", fr->callno);
11283 break;
11284 case IAX_COMMAND_VNAK:
11285 ast_debug(1, "Received VNAK: resending outstanding frames\n");
11286
11287 vnak_retransmit(fr->callno, fr->iseqno);
11288 break;
11289 case IAX_COMMAND_REGREQ:
11290 case IAX_COMMAND_REGREL:
11291
11292 if (delayreject)
11293 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11294 if (register_verify(fr->callno, &sin, &ies)) {
11295 if (!iaxs[fr->callno]) {
11296 break;
11297 }
11298
11299 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
11300 break;
11301 }
11302 if (!iaxs[fr->callno]) {
11303 break;
11304 }
11305 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
11306 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
11307
11308 if (f.subclass.integer == IAX_COMMAND_REGREL) {
11309 memset(&sin, 0, sizeof(sin));
11310 sin.sin_family = AF_INET;
11311 }
11312 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh)) {
11313 ast_log(LOG_WARNING, "Registry error\n");
11314 }
11315 if (!iaxs[fr->callno]) {
11316 break;
11317 }
11318 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
11319 ast_mutex_unlock(&iaxsl[fr->callno]);
11320 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
11321 ast_mutex_lock(&iaxsl[fr->callno]);
11322 }
11323 break;
11324 }
11325 registry_authrequest(fr->callno);
11326 break;
11327 case IAX_COMMAND_REGACK:
11328 if (iax2_ack_registry(&ies, &sin, fr->callno))
11329 ast_log(LOG_WARNING, "Registration failure\n");
11330
11331 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11332 iax2_destroy(fr->callno);
11333 break;
11334 case IAX_COMMAND_REGREJ:
11335 if (iaxs[fr->callno]->reg) {
11336 if (authdebug) {
11337 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));
11338 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>");
11339 }
11340 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
11341 }
11342
11343 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11344 iax2_destroy(fr->callno);
11345 break;
11346 case IAX_COMMAND_REGAUTH:
11347
11348 if (registry_rerequest(&ies, fr->callno, &sin)) {
11349 memset(&ied0, 0, sizeof(ied0));
11350 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
11351 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
11352 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11353 }
11354 break;
11355 case IAX_COMMAND_TXREJ:
11356 iaxs[fr->callno]->transferring = 0;
11357 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11358 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
11359 if (iaxs[fr->callno]->bridgecallno) {
11360 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
11361 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
11362 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
11363 }
11364 }
11365 break;
11366 case IAX_COMMAND_TXREADY:
11367 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
11368 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
11369 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
11370 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
11371 else
11372 iaxs[fr->callno]->transferring = TRANSFER_READY;
11373 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
11374 if (iaxs[fr->callno]->bridgecallno) {
11375 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
11376 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
11377
11378 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
11379 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11380 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11381
11382 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
11383 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
11384
11385 memset(&ied0, 0, sizeof(ied0));
11386 memset(&ied1, 0, sizeof(ied1));
11387 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11388 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11389 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
11390 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
11391 } else {
11392 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
11393 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
11394
11395 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
11396 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
11397 ast_set_flag64(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
11398 ast_set_flag64(iaxs[fr->callno], IAX_ALREADYGONE);
11399
11400
11401 stop_stuff(fr->callno);
11402 stop_stuff(iaxs[fr->callno]->bridgecallno);
11403
11404 memset(&ied0, 0, sizeof(ied0));
11405 memset(&ied1, 0, sizeof(ied1));
11406 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
11407 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
11408 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
11409 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
11410 }
11411
11412 }
11413 }
11414 }
11415 break;
11416 case IAX_COMMAND_TXREQ:
11417 try_transfer(iaxs[fr->callno], &ies);
11418 break;
11419 case IAX_COMMAND_TXCNT:
11420 if (iaxs[fr->callno]->transferring)
11421 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
11422 break;
11423 case IAX_COMMAND_TXREL:
11424
11425 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11426 complete_transfer(fr->callno, &ies);
11427 stop_stuff(fr->callno);
11428 break;
11429 case IAX_COMMAND_TXMEDIA:
11430 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
11431 AST_LIST_TRAVERSE(&frame_queue[fr->callno], cur, list) {
11432
11433 if (cur->transfer) {
11434 cur->retries = -1;
11435 }
11436 }
11437
11438 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
11439 }
11440 break;
11441 case IAX_COMMAND_RTKEY:
11442 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
11443 ast_log(LOG_WARNING,
11444 "we've been told to rotate our encryption key, "
11445 "but this isn't an encrypted call. bad things will happen.\n"
11446 );
11447 break;
11448 }
11449
11450 IAX_DEBUGDIGEST("Receiving", ies.challenge);
11451
11452 ast_aes_set_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
11453 break;
11454 case IAX_COMMAND_DPREP:
11455 complete_dpreply(iaxs[fr->callno], &ies);
11456 break;
11457 case IAX_COMMAND_UNSUPPORT:
11458 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
11459 break;
11460 case IAX_COMMAND_FWDOWNL:
11461
11462 if (!ast_test_flag64(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
11463 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
11464 break;
11465 }
11466 memset(&ied0, 0, sizeof(ied0));
11467 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
11468 if (res < 0)
11469 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11470 else if (res > 0)
11471 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11472 else
11473 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11474 break;
11475 case IAX_COMMAND_CALLTOKEN:
11476 {
11477 struct iax_frame *cur;
11478
11479 if ((cur = AST_LIST_LAST(&frame_queue[fr->callno])) && ies.calltoken && ies.calltokendata) {
11480 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11481 }
11482 break;
11483 }
11484 default:
11485 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass.integer, fr->callno, iaxs[fr->callno]->peercallno);
11486 memset(&ied0, 0, sizeof(ied0));
11487 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass.integer);
11488 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11489 }
11490
11491 if (ies.vars) {
11492 ast_variables_destroy(ies.vars);
11493 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11494 ies.vars = NULL;
11495 }
11496
11497
11498 if ((f.subclass.integer != IAX_COMMAND_ACK) &&
11499 (f.subclass.integer != IAX_COMMAND_TXCNT) &&
11500 (f.subclass.integer != IAX_COMMAND_TXACC) &&
11501 (f.subclass.integer != IAX_COMMAND_INVAL) &&
11502 (f.subclass.integer != IAX_COMMAND_VNAK)) {
11503 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11504 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11505 }
11506 ast_mutex_unlock(&iaxsl[fr->callno]);
11507 return 1;
11508 }
11509
11510 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11511 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11512 } else if (minivid) {
11513 f.frametype = AST_FRAME_VIDEO;
11514 if (iaxs[fr->callno]->videoformat > 0)
11515 f.subclass.codec = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000LL ? 1 : 0);
11516 else {
11517 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11518 iax2_vnak(fr->callno);
11519 ast_variables_destroy(ies.vars);
11520 ast_mutex_unlock(&iaxsl[fr->callno]);
11521 return 1;
11522 }
11523 f.datalen = res - sizeof(*vh);
11524 if (f.datalen)
11525 f.data.ptr = thread->buf + sizeof(*vh);
11526 else
11527 f.data.ptr = NULL;
11528 #ifdef IAXTESTS
11529 if (test_resync) {
11530 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11531 } else
11532 #endif
11533 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11534 } else {
11535
11536 f.frametype = AST_FRAME_VOICE;
11537 if (iaxs[fr->callno]->voiceformat > 0)
11538 f.subclass.codec = iaxs[fr->callno]->voiceformat;
11539 else {
11540 ast_debug(1, "Received mini frame before first full voice frame\n");
11541 iax2_vnak(fr->callno);
11542 ast_variables_destroy(ies.vars);
11543 ast_mutex_unlock(&iaxsl[fr->callno]);
11544 return 1;
11545 }
11546 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11547 if (f.datalen < 0) {
11548 ast_log(LOG_WARNING, "Datalen < 0?\n");
11549 ast_variables_destroy(ies.vars);
11550 ast_mutex_unlock(&iaxsl[fr->callno]);
11551 return 1;
11552 }
11553 if (f.datalen)
11554 f.data.ptr = thread->buf + sizeof(*mh);
11555 else
11556 f.data.ptr = NULL;
11557 #ifdef IAXTESTS
11558 if (test_resync) {
11559 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11560 } else
11561 #endif
11562 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11563
11564 }
11565
11566 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11567 ast_variables_destroy(ies.vars);
11568 ast_mutex_unlock(&iaxsl[fr->callno]);
11569 return 1;
11570 }
11571
11572 if (f.frametype == AST_FRAME_CONTROL && f.subclass.integer == AST_CONTROL_CONNECTED_LINE) {
11573 struct ast_party_connected_line connected;
11574
11575 if (!ast_test_flag64(iaxs[fr->callno], IAX_RECVCONNECTEDLINE)) {
11576 ast_variables_destroy(ies.vars);
11577 ast_mutex_unlock(&iaxsl[fr->callno]);
11578 return 1;
11579 }
11580
11581
11582 ast_party_connected_line_init(&connected);
11583 connected.id.number.presentation = iaxs[fr->callno]->calling_pres;
11584 connected.id.name.presentation = iaxs[fr->callno]->calling_pres;
11585
11586 if (!ast_connected_line_parse_data(f.data.ptr, f.datalen, &connected)) {
11587 ast_string_field_set(iaxs[fr->callno], cid_num, connected.id.number.str);
11588 ast_string_field_set(iaxs[fr->callno], cid_name, connected.id.name.str);
11589 iaxs[fr->callno]->calling_pres = ast_party_id_presentation(&connected.id);
11590
11591 if (iaxs[fr->callno]->owner) {
11592 ast_set_callerid(iaxs[fr->callno]->owner,
11593 S_COR(connected.id.number.valid, connected.id.number.str, ""),
11594 S_COR(connected.id.name.valid, connected.id.name.str, ""),
11595 NULL);
11596 iaxs[fr->callno]->owner->caller.id.number.presentation = connected.id.number.presentation;
11597 iaxs[fr->callno]->owner->caller.id.name.presentation = connected.id.name.presentation;
11598 }
11599 }
11600 ast_party_connected_line_free(&connected);
11601 }
11602
11603 f.src = "IAX2";
11604 f.mallocd = 0;
11605 f.offset = 0;
11606 f.len = 0;
11607 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11608 f.samples = ast_codec_get_samples(&f);
11609
11610 if (f.subclass.codec == AST_FORMAT_SLINEAR)
11611 ast_frame_byteswap_be(&f);
11612 } else
11613 f.samples = 0;
11614 iax_frame_wrap(fr, &f);
11615
11616
11617 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11618
11619 fr->outoforder = 0;
11620 } else {
11621 if (iaxdebug && iaxs[fr->callno])
11622 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);
11623 fr->outoforder = -1;
11624 }
11625 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11626 duped_fr = iaxfrdup2(fr);
11627 if (duped_fr) {
11628 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11629 }
11630 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11631 iaxs[fr->callno]->last = fr->ts;
11632 #if 1
11633 if (iaxdebug)
11634 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11635 #endif
11636 }
11637
11638
11639 ast_variables_destroy(ies.vars);
11640 ast_mutex_unlock(&iaxsl[fr->callno]);
11641 return 1;
11642 }
11643
11644
11645 static void iax2_process_thread_cleanup(void *data)
11646 {
11647 struct iax2_thread *thread = data;
11648 ast_mutex_destroy(&thread->lock);
11649 ast_cond_destroy(&thread->cond);
11650 ast_mutex_destroy(&thread->init_lock);
11651 ast_cond_destroy(&thread->init_cond);
11652 ast_free(thread);
11653
11654 ast_atomic_dec_and_test(&iaxactivethreadcount);
11655 }
11656
11657 static void *iax2_process_thread(void *data)
11658 {
11659 struct iax2_thread *thread = data;
11660 struct timeval wait;
11661 struct timespec ts;
11662 int put_into_idle = 0;
11663 int first_time = 1;
11664 int old_state;
11665
11666 ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
11667
11668 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11669 pthread_cleanup_push(iax2_process_thread_cleanup, data);
11670
11671 for (;;) {
11672
11673 ast_mutex_lock(&thread->lock);
11674
11675 if (thread->stop) {
11676 ast_mutex_unlock(&thread->lock);
11677 break;
11678 }
11679
11680
11681 if (first_time) {
11682 signal_condition(&thread->init_lock, &thread->init_cond);
11683 first_time = 0;
11684 }
11685
11686
11687 if (put_into_idle) {
11688 insert_idle_thread(thread);
11689 }
11690
11691 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11692 struct iax2_thread *t = NULL;
11693
11694 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11695 ts.tv_sec = wait.tv_sec;
11696 ts.tv_nsec = wait.tv_usec * 1000;
11697 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11698
11699
11700 if (!put_into_idle || thread->stop) {
11701 ast_mutex_unlock(&thread->lock);
11702 break;
11703 }
11704 AST_LIST_LOCK(&dynamic_list);
11705
11706 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11707 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
11708 AST_LIST_UNLOCK(&dynamic_list);
11709 if (t) {
11710
11711
11712
11713 ast_mutex_unlock(&thread->lock);
11714 break;
11715 }
11716
11717
11718
11719 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11720 ts.tv_sec = wait.tv_sec;
11721 ts.tv_nsec = wait.tv_usec * 1000;
11722 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11723 ast_mutex_unlock(&thread->lock);
11724 break;
11725 }
11726 }
11727 } else {
11728 ast_cond_wait(&thread->cond, &thread->lock);
11729 }
11730
11731
11732 put_into_idle = 1;
11733
11734 ast_mutex_unlock(&thread->lock);
11735
11736 if (thread->stop) {
11737 break;
11738 }
11739
11740 if (thread->iostate == IAX_IOSTATE_IDLE)
11741 continue;
11742
11743
11744 switch (thread->iostate) {
11745 case IAX_IOSTATE_READY:
11746 thread->actions++;
11747 thread->iostate = IAX_IOSTATE_PROCESSING;
11748 socket_process(thread);
11749 handle_deferred_full_frames(thread);
11750 break;
11751 case IAX_IOSTATE_SCHEDREADY:
11752 thread->actions++;
11753 thread->iostate = IAX_IOSTATE_PROCESSING;
11754 #ifdef SCHED_MULTITHREADED
11755 thread->schedfunc(thread->scheddata);
11756 #endif
11757 default:
11758 break;
11759 }
11760 time(&thread->checktime);
11761 thread->iostate = IAX_IOSTATE_IDLE;
11762 #ifdef DEBUG_SCHED_MULTITHREAD
11763 thread->curfunc[0]='\0';
11764 #endif
11765
11766
11767
11768
11769 AST_LIST_LOCK(&active_list);
11770 AST_LIST_REMOVE(&active_list, thread, list);
11771 AST_LIST_UNLOCK(&active_list);
11772
11773
11774 handle_deferred_full_frames(thread);
11775 }
11776
11777
11778
11779
11780
11781
11782 AST_LIST_LOCK(&idle_list);
11783 AST_LIST_REMOVE(&idle_list, thread, list);
11784 AST_LIST_UNLOCK(&idle_list);
11785
11786 AST_LIST_LOCK(&dynamic_list);
11787 AST_LIST_REMOVE(&dynamic_list, thread, list);
11788 AST_LIST_UNLOCK(&dynamic_list);
11789
11790 if (!thread->stop) {
11791
11792 pthread_detach(pthread_self());
11793 }
11794
11795
11796
11797
11798 pthread_cleanup_pop(1);
11799 return NULL;
11800 }
11801
11802 static int iax2_do_register(struct iax2_registry *reg)
11803 {
11804 struct iax_ie_data ied;
11805 if (iaxdebug)
11806 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
11807
11808 if (reg->dnsmgr &&
11809 ((reg->regstate == REG_STATE_TIMEOUT) || !ast_sockaddr_ipv4(®->addr))) {
11810
11811 ast_dnsmgr_refresh(reg->dnsmgr);
11812 }
11813
11814
11815
11816
11817
11818 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
11819 int callno = reg->callno;
11820 ast_mutex_lock(&iaxsl[callno]);
11821 iax2_destroy(callno);
11822 ast_mutex_unlock(&iaxsl[callno]);
11823 reg->callno = 0;
11824 }
11825 if (!ast_sockaddr_ipv4(®->addr)) {
11826 if (iaxdebug)
11827 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
11828
11829 reg->expire = iax2_sched_replace(reg->expire, sched,
11830 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11831 return -1;
11832 }
11833
11834 if (!reg->callno) {
11835 struct sockaddr_in reg_addr;
11836
11837 ast_debug(3, "Allocate call number\n");
11838
11839 ast_sockaddr_to_sin(®->addr, ®_addr);
11840
11841 reg->callno = find_callno_locked(0, 0, ®_addr, NEW_FORCE, defaultsockfd, 0);
11842 if (reg->callno < 1) {
11843 ast_log(LOG_WARNING, "Unable to create call for registration\n");
11844 return -1;
11845 } else
11846 ast_debug(3, "Registration created on call %d\n", reg->callno);
11847 iaxs[reg->callno]->reg = reg;
11848 ast_mutex_unlock(&iaxsl[reg->callno]);
11849 }
11850
11851 reg->expire = iax2_sched_replace(reg->expire, sched,
11852 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11853
11854 memset(&ied, 0, sizeof(ied));
11855 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
11856 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
11857 add_empty_calltoken_ie(iaxs[reg->callno], &ied);
11858 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
11859 reg->regstate = REG_STATE_REGSENT;
11860 return 0;
11861 }
11862
11863 static int iax2_provision(struct sockaddr_in *end, int sockfd, const char *dest, const char *template, int force)
11864 {
11865
11866
11867 struct iax_ie_data provdata;
11868 struct iax_ie_data ied;
11869 unsigned int sig;
11870 struct sockaddr_in sin;
11871 int callno;
11872 struct create_addr_info cai;
11873
11874 memset(&cai, 0, sizeof(cai));
11875
11876 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
11877
11878 if (iax_provision_build(&provdata, &sig, template, force)) {
11879 ast_debug(1, "No provisioning found for template '%s'\n", template);
11880 return 0;
11881 }
11882
11883 if (end) {
11884 memcpy(&sin, end, sizeof(sin));
11885 cai.sockfd = sockfd;
11886 } else if (create_addr(dest, NULL, &sin, &cai))
11887 return -1;
11888
11889
11890 memset(&ied, 0, sizeof(ied));
11891 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
11892
11893 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11894 if (!callno)
11895 return -1;
11896
11897 if (iaxs[callno]) {
11898
11899 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
11900 sched, 15000, auto_hangup, (void *)(long)callno);
11901 ast_set_flag64(iaxs[callno], IAX_PROVISION);
11902
11903 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
11904 }
11905 ast_mutex_unlock(&iaxsl[callno]);
11906
11907 return 1;
11908 }
11909
11910 static char *papp = "IAX2Provision";
11911
11912
11913
11914
11915 static int iax2_prov_app(struct ast_channel *chan, const char *data)
11916 {
11917 int res;
11918 char *sdata;
11919 char *opts;
11920 int force =0;
11921 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
11922 if (ast_strlen_zero(data))
11923 data = "default";
11924 sdata = ast_strdupa(data);
11925 opts = strchr(sdata, '|');
11926 if (opts)
11927 *opts='\0';
11928
11929 if (chan->tech != &iax2_tech) {
11930 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
11931 return -1;
11932 }
11933 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
11934 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
11935 return -1;
11936 }
11937 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
11938 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
11939 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
11940 sdata, res);
11941 return res;
11942 }
11943
11944 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11945 {
11946 int force = 0;
11947 int res;
11948
11949 switch (cmd) {
11950 case CLI_INIT:
11951 e->command = "iax2 provision";
11952 e->usage =
11953 "Usage: iax2 provision <host> <template> [forced]\n"
11954 " Provisions the given peer or IP address using a template\n"
11955 " matching either 'template' or '*' if the template is not\n"
11956 " found. If 'forced' is specified, even empty provisioning\n"
11957 " fields will be provisioned as empty fields.\n";
11958 return NULL;
11959 case CLI_GENERATE:
11960 if (a->pos == 3)
11961 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
11962 return NULL;
11963 }
11964
11965 if (a->argc < 4)
11966 return CLI_SHOWUSAGE;
11967 if (a->argc > 4) {
11968 if (!strcasecmp(a->argv[4], "forced"))
11969 force = 1;
11970 else
11971 return CLI_SHOWUSAGE;
11972 }
11973 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
11974 if (res < 0)
11975 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
11976 else if (res < 1)
11977 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
11978 else
11979 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
11980 return CLI_SUCCESS;
11981 }
11982
11983 static void __iax2_poke_noanswer(const void *data)
11984 {
11985 struct iax2_peer *peer = (struct iax2_peer *)data;
11986 int callno;
11987
11988 if (peer->lastms > -1) {
11989 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
11990 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
11991 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
11992 }
11993 if ((callno = peer->callno) > 0) {
11994 ast_mutex_lock(&iaxsl[callno]);
11995 iax2_destroy(callno);
11996 ast_mutex_unlock(&iaxsl[callno]);
11997 }
11998 peer->callno = 0;
11999 peer->lastms = -1;
12000
12001 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
12002 if (peer->pokeexpire == -1)
12003 peer_unref(peer);
12004 }
12005
12006 static int iax2_poke_noanswer(const void *data)
12007 {
12008 struct iax2_peer *peer = (struct iax2_peer *)data;
12009 peer->pokeexpire = -1;
12010 #ifdef SCHED_MULTITHREADED
12011 if (schedule_action(__iax2_poke_noanswer, data))
12012 #endif
12013 __iax2_poke_noanswer(data);
12014 peer_unref(peer);
12015 return 0;
12016 }
12017
12018 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
12019 {
12020 struct iax2_peer *peer = obj;
12021
12022 iax2_poke_peer(peer, 0);
12023
12024 return 0;
12025 }
12026
12027 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
12028 {
12029 int callno;
12030 struct sockaddr_in peer_addr;
12031
12032 if (!peer->maxms || (!ast_sockaddr_ipv4(&peer->addr) && !peer->dnsmgr)) {
12033
12034
12035 peer->lastms = 0;
12036 peer->historicms = 0;
12037 peer->pokeexpire = -1;
12038 peer->callno = 0;
12039 return 0;
12040 }
12041
12042 ast_sockaddr_to_sin(&peer->addr, &peer_addr);
12043
12044
12045 if ((callno = peer->callno) > 0) {
12046 ast_log(LOG_NOTICE, "Still have a callno...\n");
12047 ast_mutex_lock(&iaxsl[callno]);
12048 iax2_destroy(callno);
12049 ast_mutex_unlock(&iaxsl[callno]);
12050 }
12051 if (heldcall)
12052 ast_mutex_unlock(&iaxsl[heldcall]);
12053 callno = peer->callno = find_callno(0, 0, &peer_addr, NEW_FORCE, peer->sockfd, 0);
12054 if (heldcall)
12055 ast_mutex_lock(&iaxsl[heldcall]);
12056 if (peer->callno < 1) {
12057 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
12058 return -1;
12059 }
12060
12061
12062 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
12063 iaxs[peer->callno]->peerpoke = peer;
12064
12065 if (peer->pokeexpire > -1) {
12066 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
12067 peer->pokeexpire = -1;
12068 peer_unref(peer);
12069 }
12070 }
12071
12072
12073
12074 if (peer->lastms < 0)
12075 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
12076 else
12077 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
12078
12079 if (peer->pokeexpire == -1)
12080 peer_unref(peer);
12081
12082
12083 ast_mutex_lock(&iaxsl[callno]);
12084 if (iaxs[callno]) {
12085 struct iax_ie_data ied = {
12086 .buf = { 0 },
12087 .pos = 0,
12088 };
12089 add_empty_calltoken_ie(iaxs[callno], &ied);
12090 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
12091 }
12092 ast_mutex_unlock(&iaxsl[callno]);
12093
12094 return 0;
12095 }
12096
12097 static void free_context(struct iax2_context *con)
12098 {
12099 struct iax2_context *conl;
12100 while(con) {
12101 conl = con;
12102 con = con->next;
12103 ast_free(conl);
12104 }
12105 }
12106
12107 static struct ast_channel *iax2_request(const char *type, format_t format, const struct ast_channel *requestor, void *data, int *cause)
12108 {
12109 int callno;
12110 int res;
12111 format_t fmt, native;
12112 struct sockaddr_in sin;
12113 struct ast_channel *c;
12114 struct parsed_dial_string pds;
12115 struct create_addr_info cai;
12116 char *tmpstr;
12117
12118 memset(&pds, 0, sizeof(pds));
12119 tmpstr = ast_strdupa(data);
12120 parse_dial_string(tmpstr, &pds);
12121
12122 if (ast_strlen_zero(pds.peer)) {
12123 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
12124 return NULL;
12125 }
12126
12127 memset(&cai, 0, sizeof(cai));
12128 cai.capability = iax2_capability;
12129
12130 ast_copy_flags64(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12131
12132
12133 if (create_addr(pds.peer, NULL, &sin, &cai)) {
12134 *cause = AST_CAUSE_UNREGISTERED;
12135 return NULL;
12136 }
12137
12138 if (pds.port)
12139 sin.sin_port = htons(atoi(pds.port));
12140
12141 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
12142 if (callno < 1) {
12143 ast_log(LOG_WARNING, "Unable to create call\n");
12144 *cause = AST_CAUSE_CONGESTION;
12145 return NULL;
12146 }
12147
12148
12149 ast_copy_flags64(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12150 if (ast_test_flag64(&cai, IAX_TRUNK)) {
12151 int new_callno;
12152 if ((new_callno = make_trunk(callno, 1)) != -1)
12153 callno = new_callno;
12154 }
12155 iaxs[callno]->maxtime = cai.maxtime;
12156 if (cai.found)
12157 ast_string_field_set(iaxs[callno], host, pds.peer);
12158
12159 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability, requestor ? requestor->linkedid : NULL);
12160
12161 ast_mutex_unlock(&iaxsl[callno]);
12162
12163 if (c) {
12164
12165 if (c->nativeformats & format)
12166 c->nativeformats &= format;
12167 else {
12168 native = c->nativeformats;
12169 fmt = format;
12170 res = ast_translator_best_choice(&fmt, &native);
12171 if (res < 0) {
12172 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
12173 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
12174 ast_hangup(c);
12175 return NULL;
12176 }
12177 c->nativeformats = native;
12178 }
12179 c->readformat = ast_best_codec(c->nativeformats);
12180 c->writeformat = c->readformat;
12181 }
12182
12183 return c;
12184 }
12185
12186 static void *network_thread(void *ignore)
12187 {
12188 if (timer) {
12189 ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
12190 }
12191
12192 for (;;) {
12193 pthread_testcancel();
12194
12195
12196
12197 ast_io_wait(io, 1000);
12198 }
12199
12200 return NULL;
12201 }
12202
12203 static int start_network_thread(void)
12204 {
12205 struct iax2_thread *thread;
12206 int threadcount = 0;
12207 int x;
12208 for (x = 0; x < iaxthreadcount; x++) {
12209 thread = ast_calloc(1, sizeof(*thread));
12210 if (thread) {
12211 thread->type = IAX_THREAD_TYPE_POOL;
12212 thread->threadnum = ++threadcount;
12213 ast_mutex_init(&thread->lock);
12214 ast_cond_init(&thread->cond, NULL);
12215 ast_mutex_init(&thread->init_lock);
12216 ast_cond_init(&thread->init_cond, NULL);
12217 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
12218 ast_log(LOG_WARNING, "Failed to create new thread!\n");
12219 ast_mutex_destroy(&thread->lock);
12220 ast_cond_destroy(&thread->cond);
12221 ast_mutex_destroy(&thread->init_lock);
12222 ast_cond_destroy(&thread->init_cond);
12223 ast_free(thread);
12224 thread = NULL;
12225 continue;
12226 }
12227 AST_LIST_LOCK(&idle_list);
12228 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
12229 AST_LIST_UNLOCK(&idle_list);
12230 }
12231 }
12232 if (ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL)) {
12233 ast_log(LOG_ERROR, "Failed to create new thread!\n");
12234 return -1;
12235 }
12236 ast_verb(2, "%d helper threads started\n", threadcount);
12237 return 0;
12238 }
12239
12240 static struct iax2_context *build_context(const char *context)
12241 {
12242 struct iax2_context *con;
12243
12244 if ((con = ast_calloc(1, sizeof(*con))))
12245 ast_copy_string(con->context, context, sizeof(con->context));
12246
12247 return con;
12248 }
12249
12250 static int get_auth_methods(const char *value)
12251 {
12252 int methods = 0;
12253 if (strstr(value, "rsa"))
12254 methods |= IAX_AUTH_RSA;
12255 if (strstr(value, "md5"))
12256 methods |= IAX_AUTH_MD5;
12257 if (strstr(value, "plaintext"))
12258 methods |= IAX_AUTH_PLAINTEXT;
12259 return methods;
12260 }
12261
12262
12263
12264
12265
12266 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
12267 {
12268 int sd;
12269 int res;
12270
12271 sd = socket(AF_INET, SOCK_DGRAM, 0);
12272 if (sd < 0) {
12273 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
12274 return -1;
12275 }
12276
12277 res = bind(sd, sa, salen);
12278 if (res < 0) {
12279 ast_debug(1, "Can't bind: %s\n", strerror(errno));
12280 close(sd);
12281 return 1;
12282 }
12283
12284 close(sd);
12285 return 0;
12286 }
12287
12288
12289
12290
12291 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
12292 {
12293 struct sockaddr_in sin;
12294 struct ast_sockaddr sin_tmp;
12295 int nonlocal = 1;
12296 int port = IAX_DEFAULT_PORTNO;
12297 int sockfd = defaultsockfd;
12298 char *tmp;
12299 char *addr;
12300 char *portstr;
12301
12302 tmp = ast_strdupa(srcaddr);
12303 addr = strsep(&tmp, ":");
12304 portstr = tmp;
12305
12306 if (portstr) {
12307 port = atoi(portstr);
12308 if (port < 1)
12309 port = IAX_DEFAULT_PORTNO;
12310 }
12311
12312 sin_tmp.ss.ss_family = AF_INET;
12313 if (!ast_get_ip(&sin_tmp, addr)) {
12314 struct ast_netsock *sock;
12315 int res;
12316
12317 ast_sockaddr_to_sin(&sin_tmp, &sin);
12318 sin.sin_port = 0;
12319 sin.sin_family = AF_INET;
12320 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
12321 if (res == 0) {
12322
12323 sin.sin_port = htons(port);
12324 if (!(sock = ast_netsock_find(netsock, &sin)))
12325 sock = ast_netsock_find(outsock, &sin);
12326 if (sock) {
12327 sockfd = ast_netsock_sockfd(sock);
12328 nonlocal = 0;
12329 } else {
12330 unsigned int orig_saddr = sin.sin_addr.s_addr;
12331
12332 sin.sin_addr.s_addr = INADDR_ANY;
12333 if (ast_netsock_find(netsock, &sin)) {
12334 sin.sin_addr.s_addr = orig_saddr;
12335 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
12336 if (sock) {
12337 sockfd = ast_netsock_sockfd(sock);
12338 ast_netsock_unref(sock);
12339 nonlocal = 0;
12340 } else {
12341 nonlocal = 2;
12342 }
12343 }
12344 }
12345 }
12346 }
12347
12348 peer->sockfd = sockfd;
12349
12350 if (nonlocal == 1) {
12351 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
12352 srcaddr, peer->name);
12353 return -1;
12354 } else if (nonlocal == 2) {
12355 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
12356 srcaddr, peer->name);
12357 return -1;
12358 } else {
12359 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
12360 return 0;
12361 }
12362 }
12363
12364 static void peer_destructor(void *obj)
12365 {
12366 struct iax2_peer *peer = obj;
12367 int callno = peer->callno;
12368
12369 ast_free_ha(peer->ha);
12370
12371 if (callno > 0) {
12372 ast_mutex_lock(&iaxsl[callno]);
12373 iax2_destroy(callno);
12374 ast_mutex_unlock(&iaxsl[callno]);
12375 }
12376
12377 register_peer_exten(peer, 0);
12378
12379 if (peer->dnsmgr)
12380 ast_dnsmgr_release(peer->dnsmgr);
12381
12382 if (peer->mwi_event_sub)
12383 ast_event_unsubscribe(peer->mwi_event_sub);
12384
12385 ast_string_field_free_memory(peer);
12386 }
12387
12388
12389 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12390 {
12391 struct iax2_peer *peer = NULL;
12392 struct ast_ha *oldha = NULL;
12393 int maskfound = 0;
12394 int found = 0;
12395 int firstpass = 1;
12396 struct iax2_peer tmp_peer = {
12397 .name = name,
12398 };
12399
12400 if (!temponly) {
12401 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
12402 if (peer && !ast_test_flag64(peer, IAX_DELME))
12403 firstpass = 0;
12404 }
12405
12406 if (peer) {
12407 found++;
12408 if (firstpass) {
12409 oldha = peer->ha;
12410 peer->ha = NULL;
12411 }
12412 unlink_peer(peer);
12413 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
12414 peer->expire = -1;
12415 peer->pokeexpire = -1;
12416 peer->sockfd = defaultsockfd;
12417 peer->addr.ss.ss_family = AF_INET;
12418 peer->addr.len = sizeof(struct sockaddr_in);
12419 if (ast_string_field_init(peer, 32))
12420 peer = peer_unref(peer);
12421 }
12422
12423 if (peer) {
12424 if (firstpass) {
12425 ast_copy_flags64(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE | IAX_FORCE_ENCRYPT);
12426 peer->encmethods = iax2_encryption;
12427 peer->adsi = adsi;
12428 ast_string_field_set(peer,secret,"");
12429 if (!found) {
12430 ast_string_field_set(peer, name, name);
12431 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12432 peer->expiry = min_reg_expire;
12433 }
12434 peer->prefs = prefs;
12435 peer->capability = iax2_capability;
12436 peer->smoothing = 0;
12437 peer->pokefreqok = DEFAULT_FREQ_OK;
12438 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
12439 peer->maxcallno = 0;
12440 peercnt_modify(0, 0, &peer->addr);
12441 peer->calltoken_required = CALLTOKEN_DEFAULT;
12442 ast_string_field_set(peer,context,"");
12443 ast_string_field_set(peer,peercontext,"");
12444 ast_clear_flag64(peer, IAX_HASCALLERID);
12445 ast_string_field_set(peer, cid_name, "");
12446 ast_string_field_set(peer, cid_num, "");
12447 ast_string_field_set(peer, mohinterpret, mohinterpret);
12448 ast_string_field_set(peer, mohsuggest, mohsuggest);
12449 }
12450
12451 if (!v) {
12452 v = alt;
12453 alt = NULL;
12454 }
12455 while(v) {
12456 if (!strcasecmp(v->name, "secret")) {
12457 ast_string_field_set(peer, secret, v->value);
12458 } else if (!strcasecmp(v->name, "mailbox")) {
12459 ast_string_field_set(peer, mailbox, v->value);
12460 } else if (!strcasecmp(v->name, "hasvoicemail")) {
12461 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
12462 ast_string_field_set(peer, mailbox, name);
12463 }
12464 } else if (!strcasecmp(v->name, "mohinterpret")) {
12465 ast_string_field_set(peer, mohinterpret, v->value);
12466 } else if (!strcasecmp(v->name, "mohsuggest")) {
12467 ast_string_field_set(peer, mohsuggest, v->value);
12468 } else if (!strcasecmp(v->name, "dbsecret")) {
12469 ast_string_field_set(peer, dbsecret, v->value);
12470 } else if (!strcasecmp(v->name, "trunk")) {
12471 ast_set2_flag64(peer, ast_true(v->value), IAX_TRUNK);
12472 if (ast_test_flag64(peer, IAX_TRUNK) && !timer) {
12473 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12474 ast_clear_flag64(peer, IAX_TRUNK);
12475 }
12476 } else if (!strcasecmp(v->name, "auth")) {
12477 peer->authmethods = get_auth_methods(v->value);
12478 } else if (!strcasecmp(v->name, "encryption")) {
12479 peer->encmethods |= get_encrypt_methods(v->value);
12480 if (!peer->encmethods) {
12481 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12482 }
12483 } else if (!strcasecmp(v->name, "forceencryption")) {
12484 if (ast_false(v->value)) {
12485 ast_clear_flag64(peer, IAX_FORCE_ENCRYPT);
12486 } else {
12487 peer->encmethods |= get_encrypt_methods(v->value);
12488 if (peer->encmethods) {
12489 ast_set_flag64(peer, IAX_FORCE_ENCRYPT);
12490 }
12491 }
12492 } else if (!strcasecmp(v->name, "transfer")) {
12493 if (!strcasecmp(v->value, "mediaonly")) {
12494 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12495 } else if (ast_true(v->value)) {
12496 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12497 } else
12498 ast_set_flags_to64(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12499 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12500 ast_set2_flag64(peer, ast_true(v->value), IAX_USEJITTERBUF);
12501 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12502 ast_set2_flag64(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12503 } else if (!strcasecmp(v->name, "host")) {
12504 if (!strcasecmp(v->value, "dynamic")) {
12505
12506 ast_set_flag64(peer, IAX_DYNAMIC);
12507 if (!found) {
12508
12509
12510 if (ast_sockaddr_port(&peer->addr)) {
12511 peer->defaddr.sin_port = htons(ast_sockaddr_port(&peer->addr));
12512 }
12513 ast_sockaddr_setnull(&peer->addr);
12514 }
12515 } else {
12516
12517 ast_sched_thread_del(sched, peer->expire);
12518 ast_clear_flag64(peer, IAX_DYNAMIC);
12519 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12520 return peer_unref(peer);
12521 if (!ast_sockaddr_port(&peer->addr)) {
12522 ast_sockaddr_set_port(&peer->addr, IAX_DEFAULT_PORTNO);
12523 }
12524 }
12525 if (!maskfound)
12526 inet_aton("255.255.255.255", &peer->mask);
12527 } else if (!strcasecmp(v->name, "defaultip")) {
12528 struct ast_sockaddr peer_defaddr_tmp;
12529
12530 peer_defaddr_tmp.ss.ss_family = AF_INET;
12531 if (ast_get_ip(&peer_defaddr_tmp, v->value)) {
12532 return peer_unref(peer);
12533 }
12534 ast_sockaddr_to_sin(&peer_defaddr_tmp,
12535 &peer->defaddr);
12536 } else if (!strcasecmp(v->name, "sourceaddress")) {
12537 peer_set_srcaddr(peer, v->value);
12538 } else if (!strcasecmp(v->name, "permit") ||
12539 !strcasecmp(v->name, "deny")) {
12540 peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12541 } else if (!strcasecmp(v->name, "mask")) {
12542 maskfound++;
12543 inet_aton(v->value, &peer->mask);
12544 } else if (!strcasecmp(v->name, "context")) {
12545 ast_string_field_set(peer, context, v->value);
12546 } else if (!strcasecmp(v->name, "regexten")) {
12547 ast_string_field_set(peer, regexten, v->value);
12548 } else if (!strcasecmp(v->name, "peercontext")) {
12549 ast_string_field_set(peer, peercontext, v->value);
12550 } else if (!strcasecmp(v->name, "port")) {
12551 if (ast_test_flag64(peer, IAX_DYNAMIC)) {
12552 peer->defaddr.sin_port = htons(atoi(v->value));
12553 } else {
12554 ast_sockaddr_set_port(&peer->addr, atoi(v->value));
12555 }
12556 } else if (!strcasecmp(v->name, "username")) {
12557 ast_string_field_set(peer, username, v->value);
12558 } else if (!strcasecmp(v->name, "allow")) {
12559 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12560 } else if (!strcasecmp(v->name, "disallow")) {
12561 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12562 } else if (!strcasecmp(v->name, "callerid")) {
12563 if (!ast_strlen_zero(v->value)) {
12564 char name2[80];
12565 char num2[80];
12566 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12567 ast_string_field_set(peer, cid_name, name2);
12568 ast_string_field_set(peer, cid_num, num2);
12569 } else {
12570 ast_string_field_set(peer, cid_name, "");
12571 ast_string_field_set(peer, cid_num, "");
12572 }
12573 ast_set_flag64(peer, IAX_HASCALLERID);
12574 } else if (!strcasecmp(v->name, "fullname")) {
12575 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12576 ast_set_flag64(peer, IAX_HASCALLERID);
12577 } else if (!strcasecmp(v->name, "cid_number")) {
12578 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12579 ast_set_flag64(peer, IAX_HASCALLERID);
12580 } else if (!strcasecmp(v->name, "sendani")) {
12581 ast_set2_flag64(peer, ast_true(v->value), IAX_SENDANI);
12582 } else if (!strcasecmp(v->name, "inkeys")) {
12583 ast_string_field_set(peer, inkeys, v->value);
12584 } else if (!strcasecmp(v->name, "outkey")) {
12585 ast_string_field_set(peer, outkey, v->value);
12586 } else if (!strcasecmp(v->name, "qualify")) {
12587 if (!strcasecmp(v->value, "no")) {
12588 peer->maxms = 0;
12589 } else if (!strcasecmp(v->value, "yes")) {
12590 peer->maxms = DEFAULT_MAXMS;
12591 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12592 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);
12593 peer->maxms = 0;
12594 }
12595 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12596 peer->smoothing = ast_true(v->value);
12597 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12598 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12599 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);
12600 }
12601 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12602 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12603 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);
12604 }
12605 } else if (!strcasecmp(v->name, "timezone")) {
12606 ast_string_field_set(peer, zonetag, v->value);
12607 } else if (!strcasecmp(v->name, "adsi")) {
12608 peer->adsi = ast_true(v->value);
12609 } else if (!strcasecmp(v->name, "connectedline")) {
12610 if (ast_true(v->value)) {
12611 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12612 } else if (!strcasecmp(v->value, "send")) {
12613 ast_clear_flag64(peer, IAX_RECVCONNECTEDLINE);
12614 ast_set_flag64(peer, IAX_SENDCONNECTEDLINE);
12615 } else if (!strcasecmp(v->value, "receive")) {
12616 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE);
12617 ast_set_flag64(peer, IAX_RECVCONNECTEDLINE);
12618 } else {
12619 ast_clear_flag64(peer, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12620 }
12621 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12622 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12623 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12624 } else {
12625 peercnt_modify(1, peer->maxcallno, &peer->addr);
12626 }
12627 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12628
12629 if (ast_false(v->value)) {
12630 peer->calltoken_required = CALLTOKEN_NO;
12631 } else if (!strcasecmp(v->value, "auto")) {
12632 peer->calltoken_required = CALLTOKEN_AUTO;
12633 } else if (ast_true(v->value)) {
12634 peer->calltoken_required = CALLTOKEN_YES;
12635 } else {
12636 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12637 }
12638 }
12639
12640 v = v->next;
12641 if (!v) {
12642 v = alt;
12643 alt = NULL;
12644 }
12645 }
12646 if (!peer->authmethods)
12647 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12648 ast_clear_flag64(peer, IAX_DELME);
12649 }
12650
12651 if (oldha)
12652 ast_free_ha(oldha);
12653
12654 if (!ast_strlen_zero(peer->mailbox)) {
12655 char *mailbox, *context;
12656 context = mailbox = ast_strdupa(peer->mailbox);
12657 strsep(&context, "@");
12658 if (ast_strlen_zero(context))
12659 context = "default";
12660 peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, "IAX MWI subscription", NULL,
12661 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12662 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12663 AST_EVENT_IE_END);
12664 }
12665
12666 return peer;
12667 }
12668
12669 static void user_destructor(void *obj)
12670 {
12671 struct iax2_user *user = obj;
12672
12673 ast_free_ha(user->ha);
12674 free_context(user->contexts);
12675 if(user->vars) {
12676 ast_variables_destroy(user->vars);
12677 user->vars = NULL;
12678 }
12679 ast_string_field_free_memory(user);
12680 }
12681
12682
12683 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12684 {
12685 struct iax2_user *user = NULL;
12686 struct iax2_context *con, *conl = NULL;
12687 struct ast_ha *oldha = NULL;
12688 struct iax2_context *oldcon = NULL;
12689 int format;
12690 int firstpass=1;
12691 int oldcurauthreq = 0;
12692 char *varname = NULL, *varval = NULL;
12693 struct ast_variable *tmpvar = NULL;
12694 struct iax2_user tmp_user = {
12695 .name = name,
12696 };
12697
12698 if (!temponly) {
12699 user = ao2_find(users, &tmp_user, OBJ_POINTER);
12700 if (user && !ast_test_flag64(user, IAX_DELME))
12701 firstpass = 0;
12702 }
12703
12704 if (user) {
12705 if (firstpass) {
12706 oldcurauthreq = user->curauthreq;
12707 oldha = user->ha;
12708 oldcon = user->contexts;
12709 user->ha = NULL;
12710 user->contexts = NULL;
12711 }
12712
12713 ao2_unlink(users, user);
12714 } else {
12715 user = ao2_alloc(sizeof(*user), user_destructor);
12716 }
12717
12718 if (user) {
12719 if (firstpass) {
12720 ast_string_field_free_memory(user);
12721 memset(user, 0, sizeof(struct iax2_user));
12722 if (ast_string_field_init(user, 32)) {
12723 user = user_unref(user);
12724 goto cleanup;
12725 }
12726 user->maxauthreq = maxauthreq;
12727 user->curauthreq = oldcurauthreq;
12728 user->prefs = prefs;
12729 user->capability = iax2_capability;
12730 user->encmethods = iax2_encryption;
12731 user->adsi = adsi;
12732 user->calltoken_required = CALLTOKEN_DEFAULT;
12733 ast_string_field_set(user, name, name);
12734 ast_string_field_set(user, language, language);
12735 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);
12736 ast_clear_flag64(user, IAX_HASCALLERID);
12737 ast_string_field_set(user, cid_name, "");
12738 ast_string_field_set(user, cid_num, "");
12739 ast_string_field_set(user, accountcode, accountcode);
12740 ast_string_field_set(user, mohinterpret, mohinterpret);
12741 ast_string_field_set(user, mohsuggest, mohsuggest);
12742 }
12743 if (!v) {
12744 v = alt;
12745 alt = NULL;
12746 }
12747 while(v) {
12748 if (!strcasecmp(v->name, "context")) {
12749 con = build_context(v->value);
12750 if (con) {
12751 if (conl)
12752 conl->next = con;
12753 else
12754 user->contexts = con;
12755 conl = con;
12756 }
12757 } else if (!strcasecmp(v->name, "permit") ||
12758 !strcasecmp(v->name, "deny")) {
12759 user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12760 } else if (!strcasecmp(v->name, "setvar")) {
12761 varname = ast_strdupa(v->value);
12762 if ((varval = strchr(varname, '='))) {
12763 *varval = '\0';
12764 varval++;
12765 if((tmpvar = ast_variable_new(varname, varval, ""))) {
12766 tmpvar->next = user->vars;
12767 user->vars = tmpvar;
12768 }
12769 }
12770 } else if (!strcasecmp(v->name, "allow")) {
12771 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
12772 } else if (!strcasecmp(v->name, "disallow")) {
12773 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
12774 } else if (!strcasecmp(v->name, "trunk")) {
12775 ast_set2_flag64(user, ast_true(v->value), IAX_TRUNK);
12776 if (ast_test_flag64(user, IAX_TRUNK) && !timer) {
12777 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
12778 ast_clear_flag64(user, IAX_TRUNK);
12779 }
12780 } else if (!strcasecmp(v->name, "auth")) {
12781 user->authmethods = get_auth_methods(v->value);
12782 } else if (!strcasecmp(v->name, "encryption")) {
12783 user->encmethods |= get_encrypt_methods(v->value);
12784 if (!user->encmethods) {
12785 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12786 }
12787 } else if (!strcasecmp(v->name, "forceencryption")) {
12788 if (ast_false(v->value)) {
12789 ast_clear_flag64(user, IAX_FORCE_ENCRYPT);
12790 } else {
12791 user->encmethods |= get_encrypt_methods(v->value);
12792 if (user->encmethods) {
12793 ast_set_flag64(user, IAX_FORCE_ENCRYPT);
12794 }
12795 }
12796 } else if (!strcasecmp(v->name, "transfer")) {
12797 if (!strcasecmp(v->value, "mediaonly")) {
12798 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12799 } else if (ast_true(v->value)) {
12800 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12801 } else
12802 ast_set_flags_to64(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12803 } else if (!strcasecmp(v->name, "codecpriority")) {
12804 if(!strcasecmp(v->value, "caller"))
12805 ast_set_flag64(user, IAX_CODEC_USER_FIRST);
12806 else if(!strcasecmp(v->value, "disabled"))
12807 ast_set_flag64(user, IAX_CODEC_NOPREFS);
12808 else if(!strcasecmp(v->value, "reqonly")) {
12809 ast_set_flag64(user, IAX_CODEC_NOCAP);
12810 ast_set_flag64(user, IAX_CODEC_NOPREFS);
12811 }
12812 } else if (!strcasecmp(v->name, "immediate")) {
12813 ast_set2_flag64(user, ast_true(v->value), IAX_IMMEDIATE);
12814 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12815 ast_set2_flag64(user, ast_true(v->value), IAX_USEJITTERBUF);
12816 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12817 ast_set2_flag64(user, ast_true(v->value), IAX_FORCEJITTERBUF);
12818 } else if (!strcasecmp(v->name, "dbsecret")) {
12819 ast_string_field_set(user, dbsecret, v->value);
12820 } else if (!strcasecmp(v->name, "secret")) {
12821 if (!ast_strlen_zero(user->secret)) {
12822 char *old = ast_strdupa(user->secret);
12823
12824 ast_string_field_build(user, secret, "%s;%s", old, v->value);
12825 } else
12826 ast_string_field_set(user, secret, v->value);
12827 } else if (!strcasecmp(v->name, "callerid")) {
12828 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
12829 char name2[80];
12830 char num2[80];
12831 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12832 ast_string_field_set(user, cid_name, name2);
12833 ast_string_field_set(user, cid_num, num2);
12834 ast_set_flag64(user, IAX_HASCALLERID);
12835 } else {
12836 ast_clear_flag64(user, IAX_HASCALLERID);
12837 ast_string_field_set(user, cid_name, "");
12838 ast_string_field_set(user, cid_num, "");
12839 }
12840 } else if (!strcasecmp(v->name, "fullname")) {
12841 if (!ast_strlen_zero(v->value)) {
12842 ast_string_field_set(user, cid_name, v->value);
12843 ast_set_flag64(user, IAX_HASCALLERID);
12844 } else {
12845 ast_string_field_set(user, cid_name, "");
12846 if (ast_strlen_zero(user->cid_num))
12847 ast_clear_flag64(user, IAX_HASCALLERID);
12848 }
12849 } else if (!strcasecmp(v->name, "cid_number")) {
12850 if (!ast_strlen_zero(v->value)) {
12851 ast_string_field_set(user, cid_num, v->value);
12852 ast_set_flag64(user, IAX_HASCALLERID);
12853 } else {
12854 ast_string_field_set(user, cid_num, "");
12855 if (ast_strlen_zero(user->cid_name))
12856 ast_clear_flag64(user, IAX_HASCALLERID);
12857 }
12858 } else if (!strcasecmp(v->name, "accountcode")) {
12859 ast_string_field_set(user, accountcode, v->value);
12860 } else if (!strcasecmp(v->name, "mohinterpret")) {
12861 ast_string_field_set(user, mohinterpret, v->value);
12862 } else if (!strcasecmp(v->name, "mohsuggest")) {
12863 ast_string_field_set(user, mohsuggest, v->value);
12864 } else if (!strcasecmp(v->name, "parkinglot")) {
12865 ast_string_field_set(user, parkinglot, v->value);
12866 } else if (!strcasecmp(v->name, "language")) {
12867 ast_string_field_set(user, language, v->value);
12868 } else if (!strcasecmp(v->name, "amaflags")) {
12869 format = ast_cdr_amaflags2int(v->value);
12870 if (format < 0) {
12871 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12872 } else {
12873 user->amaflags = format;
12874 }
12875 } else if (!strcasecmp(v->name, "inkeys")) {
12876 ast_string_field_set(user, inkeys, v->value);
12877 } else if (!strcasecmp(v->name, "maxauthreq")) {
12878 user->maxauthreq = atoi(v->value);
12879 if (user->maxauthreq < 0)
12880 user->maxauthreq = 0;
12881 } else if (!strcasecmp(v->name, "adsi")) {
12882 user->adsi = ast_true(v->value);
12883 } else if (!strcasecmp(v->name, "connectedline")) {
12884 if (ast_true(v->value)) {
12885 ast_set_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12886 } else if (!strcasecmp(v->value, "send")) {
12887 ast_clear_flag64(user, IAX_RECVCONNECTEDLINE);
12888 ast_set_flag64(user, IAX_SENDCONNECTEDLINE);
12889 } else if (!strcasecmp(v->value, "receive")) {
12890 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE);
12891 ast_set_flag64(user, IAX_RECVCONNECTEDLINE);
12892 } else {
12893 ast_clear_flag64(user, IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
12894 }
12895 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12896
12897 if (ast_false(v->value)) {
12898 user->calltoken_required = CALLTOKEN_NO;
12899 } else if (!strcasecmp(v->value, "auto")) {
12900 user->calltoken_required = CALLTOKEN_AUTO;
12901 } else if (ast_true(v->value)) {
12902 user->calltoken_required = CALLTOKEN_YES;
12903 } else {
12904 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12905 }
12906 }
12907
12908 v = v->next;
12909 if (!v) {
12910 v = alt;
12911 alt = NULL;
12912 }
12913 }
12914 if (!user->authmethods) {
12915 if (!ast_strlen_zero(user->secret)) {
12916 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12917 if (!ast_strlen_zero(user->inkeys))
12918 user->authmethods |= IAX_AUTH_RSA;
12919 } else if (!ast_strlen_zero(user->inkeys)) {
12920 user->authmethods = IAX_AUTH_RSA;
12921 } else {
12922 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12923 }
12924 }
12925 ast_clear_flag64(user, IAX_DELME);
12926 }
12927 cleanup:
12928 if (oldha)
12929 ast_free_ha(oldha);
12930 if (oldcon)
12931 free_context(oldcon);
12932 return user;
12933 }
12934
12935 static int peer_delme_cb(void *obj, void *arg, int flags)
12936 {
12937 struct iax2_peer *peer = obj;
12938
12939 ast_set_flag64(peer, IAX_DELME);
12940
12941 return 0;
12942 }
12943
12944 static int user_delme_cb(void *obj, void *arg, int flags)
12945 {
12946 struct iax2_user *user = obj;
12947
12948 ast_set_flag64(user, IAX_DELME);
12949
12950 return 0;
12951 }
12952
12953 static void delete_users(void)
12954 {
12955 struct iax2_registry *reg;
12956
12957 ao2_callback(users, 0, user_delme_cb, NULL);
12958
12959 AST_LIST_LOCK(®istrations);
12960 while ((reg = AST_LIST_REMOVE_HEAD(®istrations, entry))) {
12961 if (sched) {
12962 ast_sched_thread_del(sched, reg->expire);
12963 }
12964 if (reg->callno) {
12965 int callno = reg->callno;
12966 ast_mutex_lock(&iaxsl[callno]);
12967 if (iaxs[callno]) {
12968 iaxs[callno]->reg = NULL;
12969 iax2_destroy(callno);
12970 }
12971 ast_mutex_unlock(&iaxsl[callno]);
12972 }
12973 if (reg->dnsmgr)
12974 ast_dnsmgr_release(reg->dnsmgr);
12975 ast_free(reg);
12976 }
12977 AST_LIST_UNLOCK(®istrations);
12978
12979 ao2_callback(peers, 0, peer_delme_cb, NULL);
12980 }
12981
12982 static void prune_users(void)
12983 {
12984 struct iax2_user *user;
12985 struct ao2_iterator i;
12986
12987 i = ao2_iterator_init(users, 0);
12988 while ((user = ao2_iterator_next(&i))) {
12989 if (ast_test_flag64(user, IAX_DELME) || ast_test_flag64(user, IAX_RTCACHEFRIENDS)) {
12990 ao2_unlink(users, user);
12991 }
12992 user_unref(user);
12993 }
12994 ao2_iterator_destroy(&i);
12995 }
12996
12997
12998 static void prune_peers(void)
12999 {
13000 struct iax2_peer *peer;
13001 struct ao2_iterator i;
13002
13003 i = ao2_iterator_init(peers, 0);
13004 while ((peer = ao2_iterator_next(&i))) {
13005 if (ast_test_flag64(peer, IAX_DELME) || ast_test_flag64(peer, IAX_RTCACHEFRIENDS)) {
13006 unlink_peer(peer);
13007 }
13008 peer_unref(peer);
13009 }
13010 ao2_iterator_destroy(&i);
13011 }
13012
13013 static void set_config_destroy(void)
13014 {
13015 strcpy(accountcode, "");
13016 strcpy(language, "");
13017 strcpy(mohinterpret, "");
13018 strcpy(mohsuggest, "");
13019 trunkmaxsize = MAX_TRUNKDATA;
13020 amaflags = 0;
13021 delayreject = 0;
13022 ast_clear_flag64((&globalflags), IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF |
13023 IAX_FORCEJITTERBUF | IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13024 delete_users();
13025 ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
13026 ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
13027 }
13028
13029
13030 static int set_config(const char *config_file, int reload)
13031 {
13032 struct ast_config *cfg, *ucfg;
13033 format_t capability = iax2_capability;
13034 struct ast_variable *v;
13035 char *cat;
13036 const char *utype;
13037 const char *tosval;
13038 int format;
13039 int portno = IAX_DEFAULT_PORTNO;
13040 int x;
13041 int mtuv;
13042 int subscribe_network_change = 1;
13043 struct iax2_user *user;
13044 struct iax2_peer *peer;
13045 struct ast_netsock *ns;
13046 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
13047 #if 0
13048 static unsigned short int last_port=0;
13049 #endif
13050
13051 cfg = ast_config_load(config_file, config_flags);
13052
13053 if (!cfg) {
13054 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
13055 return -1;
13056 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
13057 ucfg = ast_config_load("users.conf", config_flags);
13058 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
13059 return 0;
13060
13061 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13062 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
13063 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13064 ast_config_destroy(ucfg);
13065 return 0;
13066 }
13067 if (!cfg) {
13068
13069 ast_log(LOG_ERROR, "Unable to load config %s again\n", config_file);
13070 return -1;
13071 }
13072 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
13073 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
13074 return 0;
13075 } else {
13076 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
13077 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
13078 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
13079 ast_config_destroy(cfg);
13080 return 0;
13081 }
13082 }
13083
13084 if (reload) {
13085 set_config_destroy();
13086 }
13087
13088
13089 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
13090
13091
13092 memset(&globalflags, 0, sizeof(globalflags));
13093 ast_set_flag64(&globalflags, IAX_RTUPDATE);
13094 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13095
13096 #ifdef SO_NO_CHECK
13097 nochecksums = 0;
13098 #endif
13099
13100 default_parkinglot[0] = '\0';
13101
13102 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13103 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
13104 global_max_trunk_mtu = MAX_TRUNK_MTU;
13105 global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
13106 global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
13107
13108 maxauthreq = 3;
13109
13110 srvlookup = 0;
13111
13112 v = ast_variable_browse(cfg, "general");
13113
13114
13115 tosval = ast_variable_retrieve(cfg, "general", "tos");
13116 if (tosval) {
13117 if (ast_str2tos(tosval, &qos.tos))
13118 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
13119 }
13120
13121 tosval = ast_variable_retrieve(cfg, "general", "cos");
13122 if (tosval) {
13123 if (ast_str2cos(tosval, &qos.cos))
13124 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
13125 }
13126 while(v) {
13127 if (!strcasecmp(v->name, "bindport")){
13128 if (reload)
13129 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
13130 else
13131 portno = atoi(v->value);
13132 } else if (!strcasecmp(v->name, "pingtime"))
13133 ping_time = atoi(v->value);
13134 else if (!strcasecmp(v->name, "iaxthreadcount")) {
13135 if (reload) {
13136 if (atoi(v->value) != iaxthreadcount)
13137 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
13138 } else {
13139 iaxthreadcount = atoi(v->value);
13140 if (iaxthreadcount < 1) {
13141 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
13142 iaxthreadcount = 1;
13143 } else if (iaxthreadcount > 256) {
13144 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
13145 iaxthreadcount = 256;
13146 }
13147 }
13148 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
13149 if (reload) {
13150 AST_LIST_LOCK(&dynamic_list);
13151 iaxmaxthreadcount = atoi(v->value);
13152 AST_LIST_UNLOCK(&dynamic_list);
13153 } else {
13154 iaxmaxthreadcount = atoi(v->value);
13155 if (iaxmaxthreadcount < 0) {
13156 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
13157 iaxmaxthreadcount = 0;
13158 } else if (iaxmaxthreadcount > 256) {
13159 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
13160 iaxmaxthreadcount = 256;
13161 }
13162 }
13163 } else if (!strcasecmp(v->name, "nochecksums")) {
13164 #ifdef SO_NO_CHECK
13165 if (ast_true(v->value))
13166 nochecksums = 1;
13167 else
13168 nochecksums = 0;
13169 #else
13170 if (ast_true(v->value))
13171 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
13172 #endif
13173 }
13174 else if (!strcasecmp(v->name, "maxjitterbuffer"))
13175 maxjitterbuffer = atoi(v->value);
13176 else if (!strcasecmp(v->name, "resyncthreshold"))
13177 resyncthreshold = atoi(v->value);
13178 else if (!strcasecmp(v->name, "maxjitterinterps"))
13179 maxjitterinterps = atoi(v->value);
13180 else if (!strcasecmp(v->name, "jittertargetextra"))
13181 jittertargetextra = atoi(v->value);
13182 else if (!strcasecmp(v->name, "lagrqtime"))
13183 lagrq_time = atoi(v->value);
13184 else if (!strcasecmp(v->name, "maxregexpire"))
13185 max_reg_expire = atoi(v->value);
13186 else if (!strcasecmp(v->name, "minregexpire"))
13187 min_reg_expire = atoi(v->value);
13188 else if (!strcasecmp(v->name, "bindaddr")) {
13189 if (reload) {
13190 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
13191 } else {
13192 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
13193 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
13194 } else {
13195 if (strchr(v->value, ':'))
13196 ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
13197 else
13198 ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
13199 if (defaultsockfd < 0)
13200 defaultsockfd = ast_netsock_sockfd(ns);
13201 ast_netsock_unref(ns);
13202 }
13203 }
13204 } else if (!strcasecmp(v->name, "authdebug")) {
13205 authdebug = ast_true(v->value);
13206 } else if (!strcasecmp(v->name, "encryption")) {
13207 iax2_encryption |= get_encrypt_methods(v->value);
13208 if (!iax2_encryption) {
13209 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13210 }
13211 } else if (!strcasecmp(v->name, "forceencryption")) {
13212 if (ast_false(v->value)) {
13213 ast_clear_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13214 } else {
13215 iax2_encryption |= get_encrypt_methods(v->value);
13216 if (iax2_encryption) {
13217 ast_set_flag64((&globalflags), IAX_FORCE_ENCRYPT);
13218 }
13219 }
13220 } else if (!strcasecmp(v->name, "transfer")) {
13221 if (!strcasecmp(v->value, "mediaonly")) {
13222 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
13223 } else if (ast_true(v->value)) {
13224 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
13225 } else
13226 ast_set_flags_to64((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
13227 } else if (!strcasecmp(v->name, "codecpriority")) {
13228 if(!strcasecmp(v->value, "caller"))
13229 ast_set_flag64((&globalflags), IAX_CODEC_USER_FIRST);
13230 else if(!strcasecmp(v->value, "disabled"))
13231 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13232 else if(!strcasecmp(v->value, "reqonly")) {
13233 ast_set_flag64((&globalflags), IAX_CODEC_NOCAP);
13234 ast_set_flag64((&globalflags), IAX_CODEC_NOPREFS);
13235 }
13236 } else if (!strcasecmp(v->name, "jitterbuffer"))
13237 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
13238 else if (!strcasecmp(v->name, "forcejitterbuffer"))
13239 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
13240 else if (!strcasecmp(v->name, "delayreject"))
13241 delayreject = ast_true(v->value);
13242 else if (!strcasecmp(v->name, "allowfwdownload"))
13243 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
13244 else if (!strcasecmp(v->name, "rtcachefriends"))
13245 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
13246 else if (!strcasecmp(v->name, "rtignoreregexpire"))
13247 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
13248 else if (!strcasecmp(v->name, "rtupdate"))
13249 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTUPDATE);
13250 else if (!strcasecmp(v->name, "rtsavesysname"))
13251 ast_set2_flag64((&globalflags), ast_true(v->value), IAX_RTSAVE_SYSNAME);
13252 else if (!strcasecmp(v->name, "trunktimestamps"))
13253 ast_set2_flag64(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
13254 else if (!strcasecmp(v->name, "rtautoclear")) {
13255 int i = atoi(v->value);
13256 if(i > 0)
13257 global_rtautoclear = i;
13258 else
13259 i = 0;
13260 ast_set2_flag64((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
13261 } else if (!strcasecmp(v->name, "trunkfreq")) {
13262 trunkfreq = atoi(v->value);
13263 if (trunkfreq < 10) {
13264 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 10ms instead.\n");
13265 trunkfreq = 10;
13266 } else if (trunkfreq > 1000) {
13267 ast_log(LOG_NOTICE, "trunkfreq must be between 10ms and 1000ms, using 1000ms instead.\n");
13268 trunkfreq = 1000;
13269 }
13270 if (timer) {
13271 ast_timer_set_rate(timer, 1000 / trunkfreq);
13272 }
13273 } else if (!strcasecmp(v->name, "trunkmtu")) {
13274 mtuv = atoi(v->value);
13275 if (mtuv == 0 )
13276 global_max_trunk_mtu = 0;
13277 else if (mtuv >= 172 && mtuv < 4000)
13278 global_max_trunk_mtu = mtuv;
13279 else
13280 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
13281 mtuv, v->lineno);
13282 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
13283 trunkmaxsize = atoi(v->value);
13284 if (trunkmaxsize == 0)
13285 trunkmaxsize = MAX_TRUNKDATA;
13286 } else if (!strcasecmp(v->name, "autokill")) {
13287 if (sscanf(v->value, "%30d", &x) == 1) {
13288 if (x >= 0)
13289 autokill = x;
13290 else
13291 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
13292 } else if (ast_true(v->value)) {
13293 autokill = DEFAULT_MAXMS;
13294 } else {
13295 autokill = 0;
13296 }
13297 } else if (!strcasecmp(v->name, "bandwidth")) {
13298 if (!strcasecmp(v->value, "low")) {
13299 capability = IAX_CAPABILITY_LOWBANDWIDTH;
13300 } else if (!strcasecmp(v->value, "medium")) {
13301 capability = IAX_CAPABILITY_MEDBANDWIDTH;
13302 } else if (!strcasecmp(v->value, "high")) {
13303 capability = IAX_CAPABILITY_FULLBANDWIDTH;
13304 } else
13305 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
13306 } else if (!strcasecmp(v->name, "allow")) {
13307 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
13308 } else if (!strcasecmp(v->name, "disallow")) {
13309 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
13310 } else if (!strcasecmp(v->name, "register")) {
13311 iax2_register(v->value, v->lineno);
13312 } else if (!strcasecmp(v->name, "iaxcompat")) {
13313 iaxcompat = ast_true(v->value);
13314 } else if (!strcasecmp(v->name, "regcontext")) {
13315 ast_copy_string(regcontext, v->value, sizeof(regcontext));
13316
13317 ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
13318 } else if (!strcasecmp(v->name, "tos")) {
13319 if (ast_str2tos(v->value, &qos.tos))
13320 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
13321 } else if (!strcasecmp(v->name, "cos")) {
13322 if (ast_str2cos(v->value, &qos.cos))
13323 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
13324 } else if (!strcasecmp(v->name, "parkinglot")) {
13325 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
13326 } else if (!strcasecmp(v->name, "accountcode")) {
13327 ast_copy_string(accountcode, v->value, sizeof(accountcode));
13328 } else if (!strcasecmp(v->name, "mohinterpret")) {
13329 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
13330 } else if (!strcasecmp(v->name, "mohsuggest")) {
13331 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
13332 } else if (!strcasecmp(v->name, "amaflags")) {
13333 format = ast_cdr_amaflags2int(v->value);
13334 if (format < 0) {
13335 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
13336 } else {
13337 amaflags = format;
13338 }
13339 } else if (!strcasecmp(v->name, "language")) {
13340 ast_copy_string(language, v->value, sizeof(language));
13341 } else if (!strcasecmp(v->name, "maxauthreq")) {
13342 maxauthreq = atoi(v->value);
13343 if (maxauthreq < 0)
13344 maxauthreq = 0;
13345 } else if (!strcasecmp(v->name, "adsi")) {
13346 adsi = ast_true(v->value);
13347 } else if (!strcasecmp(v->name, "srvlookup")) {
13348 srvlookup = ast_true(v->value);
13349 } else if (!strcasecmp(v->name, "connectedline")) {
13350 if (ast_true(v->value)) {
13351 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13352 } else if (!strcasecmp(v->value, "send")) {
13353 ast_clear_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13354 ast_set_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13355 } else if (!strcasecmp(v->value, "receive")) {
13356 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE);
13357 ast_set_flag64((&globalflags), IAX_RECVCONNECTEDLINE);
13358 } else {
13359 ast_clear_flag64((&globalflags), IAX_SENDCONNECTEDLINE | IAX_RECVCONNECTEDLINE);
13360 }
13361 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
13362 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
13363 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
13364 }
13365 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
13366 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
13367 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);
13368 }
13369 } else if (!strcasecmp(v->name, "calltokenoptional")) {
13370 if (add_calltoken_ignore(v->value)) {
13371 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
13372 }
13373 } else if (!strcasecmp(v->name, "subscribe_network_change_event")) {
13374 if (ast_true(v->value)) {
13375 subscribe_network_change = 1;
13376 } else if (ast_false(v->value)) {
13377 subscribe_network_change = 0;
13378 } else {
13379 ast_log(LOG_WARNING, "subscribe_network_change_event value %s is not valid at line %d.\n", v->value, v->lineno);
13380 }
13381 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
13382 if (ast_true(v->value)) {
13383 ast_set_flag64((&globalflags), IAX_SHRINKCALLERID);
13384 } else if (ast_false(v->value)) {
13385 ast_clear_flag64((&globalflags), IAX_SHRINKCALLERID);
13386 } else {
13387 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
13388 }
13389 }
13390
13391 v = v->next;
13392 }
13393
13394 if (subscribe_network_change) {
13395 network_change_event_subscribe();
13396 } else {
13397 network_change_event_unsubscribe();
13398 }
13399
13400 if (defaultsockfd < 0) {
13401 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
13402 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
13403 } else {
13404 ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
13405 defaultsockfd = ast_netsock_sockfd(ns);
13406 ast_netsock_unref(ns);
13407 }
13408 }
13409 if (reload) {
13410 ast_netsock_release(outsock);
13411 outsock = ast_netsock_list_alloc();
13412 if (!outsock) {
13413 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13414 return -1;
13415 }
13416 ast_netsock_init(outsock);
13417 }
13418
13419 if (min_reg_expire > max_reg_expire) {
13420 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
13421 min_reg_expire, max_reg_expire, max_reg_expire);
13422 min_reg_expire = max_reg_expire;
13423 }
13424 iax2_capability = capability;
13425
13426 if (ucfg) {
13427 struct ast_variable *gen;
13428 int genhasiax;
13429 int genregisteriax;
13430 const char *hasiax, *registeriax;
13431
13432 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
13433 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
13434 gen = ast_variable_browse(ucfg, "general");
13435 cat = ast_category_browse(ucfg, NULL);
13436 while (cat) {
13437 if (strcasecmp(cat, "general")) {
13438 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
13439 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
13440 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
13441
13442 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
13443 if (user) {
13444 ao2_link(users, user);
13445 user = user_unref(user);
13446 }
13447 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
13448 if (peer) {
13449 if (ast_test_flag64(peer, IAX_DYNAMIC))
13450 reg_source_db(peer);
13451 ao2_link(peers, peer);
13452 peer = peer_unref(peer);
13453 }
13454 }
13455 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
13456 char tmp[256];
13457 const char *host = ast_variable_retrieve(ucfg, cat, "host");
13458 const char *username = ast_variable_retrieve(ucfg, cat, "username");
13459 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
13460 if (!host)
13461 host = ast_variable_retrieve(ucfg, "general", "host");
13462 if (!username)
13463 username = ast_variable_retrieve(ucfg, "general", "username");
13464 if (!secret)
13465 secret = ast_variable_retrieve(ucfg, "general", "secret");
13466 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
13467 if (!ast_strlen_zero(secret))
13468 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
13469 else
13470 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
13471 iax2_register(tmp, 0);
13472 }
13473 }
13474 }
13475 cat = ast_category_browse(ucfg, cat);
13476 }
13477 ast_config_destroy(ucfg);
13478 }
13479
13480 cat = ast_category_browse(cfg, NULL);
13481 while(cat) {
13482 if (strcasecmp(cat, "general")) {
13483 utype = ast_variable_retrieve(cfg, cat, "type");
13484 if (!strcasecmp(cat, "callnumberlimits")) {
13485 build_callno_limits(ast_variable_browse(cfg, cat));
13486 } else if (utype) {
13487 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
13488 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
13489 if (user) {
13490 ao2_link(users, user);
13491 user = user_unref(user);
13492 }
13493 }
13494 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
13495 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
13496 if (peer) {
13497 if (ast_test_flag64(peer, IAX_DYNAMIC))
13498 reg_source_db(peer);
13499 ao2_link(peers, peer);
13500 peer = peer_unref(peer);
13501 }
13502 } else if (strcasecmp(utype, "user")) {
13503 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
13504 }
13505 } else
13506 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
13507 }
13508 cat = ast_category_browse(cfg, cat);
13509 }
13510 ast_config_destroy(cfg);
13511 return 1;
13512 }
13513
13514 static void poke_all_peers(void)
13515 {
13516 struct ao2_iterator i;
13517 struct iax2_peer *peer;
13518
13519 i = ao2_iterator_init(peers, 0);
13520 while ((peer = ao2_iterator_next(&i))) {
13521 iax2_poke_peer(peer, 0);
13522 peer_unref(peer);
13523 }
13524 ao2_iterator_destroy(&i);
13525 }
13526 static int reload_config(void)
13527 {
13528 static const char config[] = "iax.conf";
13529 struct iax2_registry *reg;
13530
13531 if (set_config(config, 1) > 0) {
13532 prune_peers();
13533 prune_users();
13534 ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13535 ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13536 ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13537 trunk_timed = trunk_untimed = 0;
13538 trunk_nmaxmtu = trunk_maxmtu = 0;
13539 memset(&debugaddr, '\0', sizeof(debugaddr));
13540
13541 AST_LIST_LOCK(®istrations);
13542 AST_LIST_TRAVERSE(®istrations, reg, entry)
13543 iax2_do_register(reg);
13544 AST_LIST_UNLOCK(®istrations);
13545
13546
13547 poke_all_peers();
13548 }
13549
13550 reload_firmware(0);
13551 iax_provision_reload(1);
13552 ast_unload_realtime("iaxpeers");
13553
13554 return 0;
13555 }
13556
13557 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13558 {
13559 switch (cmd) {
13560 case CLI_INIT:
13561 e->command = "iax2 reload";
13562 e->usage =
13563 "Usage: iax2 reload\n"
13564 " Reloads IAX configuration from iax.conf\n";
13565 return NULL;
13566 case CLI_GENERATE:
13567 return NULL;
13568 }
13569
13570 reload_config();
13571
13572 return CLI_SUCCESS;
13573 }
13574
13575 static int reload(void)
13576 {
13577 return reload_config();
13578 }
13579
13580 static int cache_get_callno_locked(const char *data)
13581 {
13582 struct sockaddr_in sin;
13583 int x;
13584 int callno;
13585 struct iax_ie_data ied;
13586 struct create_addr_info cai;
13587 struct parsed_dial_string pds;
13588 char *tmpstr;
13589
13590 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13591
13592
13593 if (!ast_mutex_trylock(&iaxsl[x])) {
13594 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13595 return x;
13596 ast_mutex_unlock(&iaxsl[x]);
13597 }
13598 }
13599
13600
13601
13602 memset(&cai, 0, sizeof(cai));
13603 memset(&ied, 0, sizeof(ied));
13604 memset(&pds, 0, sizeof(pds));
13605
13606 tmpstr = ast_strdupa(data);
13607 parse_dial_string(tmpstr, &pds);
13608
13609 if (ast_strlen_zero(pds.peer)) {
13610 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13611 return -1;
13612 }
13613
13614
13615 if (create_addr(pds.peer, NULL, &sin, &cai))
13616 return -1;
13617
13618 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13619 pds.peer, pds.username, pds.password, pds.context);
13620
13621 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13622 if (callno < 1) {
13623 ast_log(LOG_WARNING, "Unable to create call\n");
13624 return -1;
13625 }
13626
13627 ast_string_field_set(iaxs[callno], dproot, data);
13628 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13629
13630 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
13631 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
13632
13633
13634
13635 if (pds.exten)
13636 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
13637 if (pds.username)
13638 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
13639 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
13640 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
13641
13642 if (pds.password)
13643 ast_string_field_set(iaxs[callno], secret, pds.password);
13644 if (pds.key)
13645 ast_string_field_set(iaxs[callno], outkey, pds.key);
13646
13647 add_empty_calltoken_ie(iaxs[callno], &ied);
13648 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13649
13650 return callno;
13651 }
13652
13653 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13654 {
13655 struct iax2_dpcache *dp = NULL;
13656 struct timeval now = ast_tvnow();
13657 int x, com[2], timeout, old = 0, outfd, doabort, callno;
13658 struct ast_channel *c = NULL;
13659 struct ast_frame *f = NULL;
13660
13661 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13662 if (ast_tvcmp(now, dp->expiry) > 0) {
13663 AST_LIST_REMOVE_CURRENT(cache_list);
13664 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13665 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13666 else
13667 ast_free(dp);
13668 continue;
13669 }
13670 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13671 break;
13672 }
13673 AST_LIST_TRAVERSE_SAFE_END;
13674
13675 if (!dp) {
13676
13677
13678 if ((callno = cache_get_callno_locked(data)) < 0) {
13679 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13680 return NULL;
13681 }
13682 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13683 ast_mutex_unlock(&iaxsl[callno]);
13684 return NULL;
13685 }
13686 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13687 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13688 dp->expiry = ast_tvnow();
13689 dp->orig = dp->expiry;
13690
13691 dp->expiry.tv_sec += iaxdefaultdpcache;
13692 dp->flags = CACHE_FLAG_PENDING;
13693 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13694 dp->waiters[x] = -1;
13695
13696 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13697 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13698
13699 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13700 iax2_dprequest(dp, callno);
13701 ast_mutex_unlock(&iaxsl[callno]);
13702 }
13703
13704
13705 if (dp->flags & CACHE_FLAG_PENDING) {
13706
13707
13708 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13709
13710 if (dp->waiters[x] < 0)
13711 break;
13712 }
13713 if (x >= ARRAY_LEN(dp->waiters)) {
13714 ast_log(LOG_WARNING, "No more waiter positions available\n");
13715 return NULL;
13716 }
13717 if (pipe(com)) {
13718 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13719 return NULL;
13720 }
13721 dp->waiters[x] = com[1];
13722
13723 timeout = iaxdefaulttimeout * 1000;
13724
13725 AST_LIST_UNLOCK(&dpcache);
13726
13727 if (chan)
13728 old = ast_channel_defer_dtmf(chan);
13729 doabort = 0;
13730 while(timeout) {
13731 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
13732 if (outfd > -1)
13733 break;
13734 if (!c)
13735 continue;
13736 if (!(f = ast_read(c))) {
13737 doabort = 1;
13738 break;
13739 }
13740 ast_frfree(f);
13741 }
13742 if (!timeout) {
13743 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13744 }
13745 AST_LIST_LOCK(&dpcache);
13746 dp->waiters[x] = -1;
13747 close(com[1]);
13748 close(com[0]);
13749 if (doabort) {
13750
13751
13752 if (!old && chan)
13753 ast_channel_undefer_dtmf(chan);
13754 return NULL;
13755 }
13756 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13757
13758 if (dp->flags & CACHE_FLAG_PENDING) {
13759
13760
13761 dp->flags &= ~CACHE_FLAG_PENDING;
13762 dp->flags |= CACHE_FLAG_TIMEOUT;
13763
13764
13765 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
13766 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13767 if (dp->waiters[x] > -1) {
13768 if (write(dp->waiters[x], "asdf", 4) < 0) {
13769 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13770 }
13771 }
13772 }
13773 }
13774 }
13775
13776 if (!old && chan)
13777 ast_channel_undefer_dtmf(chan);
13778 }
13779 return dp;
13780 }
13781
13782
13783 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13784 {
13785 int res = 0;
13786 struct iax2_dpcache *dp = NULL;
13787 #if 0
13788 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13789 #endif
13790 if ((priority != 1) && (priority != 2))
13791 return 0;
13792
13793 AST_LIST_LOCK(&dpcache);
13794 if ((dp = find_cache(chan, data, context, exten, priority))) {
13795 if (dp->flags & CACHE_FLAG_EXISTS)
13796 res = 1;
13797 } else {
13798 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13799 }
13800 AST_LIST_UNLOCK(&dpcache);
13801
13802 return res;
13803 }
13804
13805
13806 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13807 {
13808 int res = 0;
13809 struct iax2_dpcache *dp = NULL;
13810 #if 0
13811 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13812 #endif
13813 if ((priority != 1) && (priority != 2))
13814 return 0;
13815
13816 AST_LIST_LOCK(&dpcache);
13817 if ((dp = find_cache(chan, data, context, exten, priority))) {
13818 if (dp->flags & CACHE_FLAG_CANEXIST)
13819 res = 1;
13820 } else {
13821 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13822 }
13823 AST_LIST_UNLOCK(&dpcache);
13824
13825 return res;
13826 }
13827
13828
13829 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13830 {
13831 int res = 0;
13832 struct iax2_dpcache *dp = NULL;
13833 #if 0
13834 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13835 #endif
13836 if ((priority != 1) && (priority != 2))
13837 return 0;
13838
13839 AST_LIST_LOCK(&dpcache);
13840 if ((dp = find_cache(chan, data, context, exten, priority))) {
13841 if (dp->flags & CACHE_FLAG_MATCHMORE)
13842 res = 1;
13843 } else {
13844 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13845 }
13846 AST_LIST_UNLOCK(&dpcache);
13847
13848 return res;
13849 }
13850
13851
13852 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13853 {
13854 char odata[256];
13855 char req[256];
13856 char *ncontext;
13857 struct iax2_dpcache *dp = NULL;
13858 struct ast_app *dial = NULL;
13859 #if 0
13860 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);
13861 #endif
13862 if (priority == 2) {
13863
13864 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
13865 if (dialstatus) {
13866 dial = pbx_findapp(dialstatus);
13867 if (dial)
13868 pbx_exec(chan, dial, "");
13869 }
13870 return -1;
13871 } else if (priority != 1)
13872 return -1;
13873
13874 AST_LIST_LOCK(&dpcache);
13875 if ((dp = find_cache(chan, data, context, exten, priority))) {
13876 if (dp->flags & CACHE_FLAG_EXISTS) {
13877 ast_copy_string(odata, data, sizeof(odata));
13878 ncontext = strchr(odata, '/');
13879 if (ncontext) {
13880 *ncontext = '\0';
13881 ncontext++;
13882 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
13883 } else {
13884 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
13885 }
13886 ast_verb(3, "Executing Dial('%s')\n", req);
13887 } else {
13888 AST_LIST_UNLOCK(&dpcache);
13889 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
13890 return -1;
13891 }
13892 }
13893 AST_LIST_UNLOCK(&dpcache);
13894
13895 if ((dial = pbx_findapp("Dial")))
13896 return pbx_exec(chan, dial, req);
13897 else
13898 ast_log(LOG_WARNING, "No dial application registered\n");
13899
13900 return -1;
13901 }
13902
13903 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
13904 {
13905 struct iax2_peer *peer;
13906 char *peername, *colname;
13907
13908 peername = ast_strdupa(data);
13909
13910
13911 if (!strcmp(peername,"CURRENTCHANNEL")) {
13912 unsigned short callno;
13913 if (chan->tech != &iax2_tech)
13914 return -1;
13915 callno = PTR_TO_CALLNO(chan->tech_pvt);
13916 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
13917 return 0;
13918 }
13919
13920 if ((colname = strchr(peername, ',')))
13921 *colname++ = '\0';
13922 else
13923 colname = "ip";
13924
13925 if (!(peer = find_peer(peername, 1)))
13926 return -1;
13927
13928 if (!strcasecmp(colname, "ip")) {
13929 ast_copy_string(buf, ast_sockaddr_stringify_addr(&peer->addr), len);
13930 } else if (!strcasecmp(colname, "status")) {
13931 peer_status(peer, buf, len);
13932 } else if (!strcasecmp(colname, "mailbox")) {
13933 ast_copy_string(buf, peer->mailbox, len);
13934 } else if (!strcasecmp(colname, "context")) {
13935 ast_copy_string(buf, peer->context, len);
13936 } else if (!strcasecmp(colname, "expire")) {
13937 snprintf(buf, len, "%d", peer->expire);
13938 } else if (!strcasecmp(colname, "dynamic")) {
13939 ast_copy_string(buf, (ast_test_flag64(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
13940 } else if (!strcasecmp(colname, "callerid_name")) {
13941 ast_copy_string(buf, peer->cid_name, len);
13942 } else if (!strcasecmp(colname, "callerid_num")) {
13943 ast_copy_string(buf, peer->cid_num, len);
13944 } else if (!strcasecmp(colname, "codecs")) {
13945 ast_getformatname_multiple(buf, len -1, peer->capability);
13946 } else if (!strncasecmp(colname, "codec[", 6)) {
13947 char *codecnum, *ptr;
13948 int codec = 0;
13949
13950
13951 codecnum = colname + 5;
13952 *codecnum = '\0';
13953 codecnum++;
13954 if ((ptr = strchr(codecnum, ']'))) {
13955 *ptr = '\0';
13956 }
13957 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
13958 ast_copy_string(buf, ast_getformatname(codec), len);
13959 } else {
13960 buf[0] = '\0';
13961 }
13962 } else {
13963 buf[0] = '\0';
13964 }
13965
13966 peer_unref(peer);
13967
13968 return 0;
13969 }
13970
13971 static struct ast_custom_function iaxpeer_function = {
13972 .name = "IAXPEER",
13973 .read = function_iaxpeer,
13974 };
13975
13976 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
13977 {
13978 struct chan_iax2_pvt *pvt;
13979 unsigned int callno;
13980 int res = 0;
13981
13982 if (!chan || chan->tech != &iax2_tech) {
13983 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
13984 return -1;
13985 }
13986
13987 callno = PTR_TO_CALLNO(chan->tech_pvt);
13988 ast_mutex_lock(&iaxsl[callno]);
13989 if (!(pvt = iaxs[callno])) {
13990 ast_mutex_unlock(&iaxsl[callno]);
13991 return -1;
13992 }
13993
13994 if (!strcasecmp(args, "osptoken")) {
13995 ast_copy_string(buf, pvt->osptoken, buflen);
13996 } else if (!strcasecmp(args, "peerip")) {
13997 ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
13998 } else if (!strcasecmp(args, "peername")) {
13999 ast_copy_string(buf, pvt->username, buflen);
14000 } else if (!strcasecmp(args, "secure_signaling") || !strcasecmp(args, "secure_media")) {
14001 snprintf(buf, buflen, "%s", IAX_CALLENCRYPTED(pvt) ? "1" : "");
14002 } else {
14003 res = -1;
14004 }
14005
14006 ast_mutex_unlock(&iaxsl[callno]);
14007
14008 return res;
14009 }
14010
14011
14012 static int iax2_devicestate(void *data)
14013 {
14014 struct parsed_dial_string pds;
14015 char *tmp = ast_strdupa(data);
14016 struct iax2_peer *p;
14017 int res = AST_DEVICE_INVALID;
14018
14019 memset(&pds, 0, sizeof(pds));
14020 parse_dial_string(tmp, &pds);
14021
14022 if (ast_strlen_zero(pds.peer)) {
14023 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
14024 return res;
14025 }
14026
14027 ast_debug(3, "Checking device state for device %s\n", pds.peer);
14028
14029
14030 if (!(p = find_peer(pds.peer, 1)))
14031 return res;
14032
14033 res = AST_DEVICE_UNAVAILABLE;
14034 ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
14035 pds.peer, ast_sockaddr_ipv4(&p->addr), p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
14036
14037 if ((ast_sockaddr_ipv4(&p->addr) || p->defaddr.sin_addr.s_addr) &&
14038 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
14039
14040
14041 if (p->historicms == 0 || p->historicms <= p->maxms)
14042
14043 res = AST_DEVICE_UNKNOWN;
14044 }
14045
14046 peer_unref(p);
14047
14048 return res;
14049 }
14050
14051 static struct ast_switch iax2_switch =
14052 {
14053 .name = "IAX2",
14054 .description = "IAX Remote Dialplan Switch",
14055 .exists = iax2_exists,
14056 .canmatch = iax2_canmatch,
14057 .exec = iax2_exec,
14058 .matchmore = iax2_matchmore,
14059 };
14060
14061
14062
14063
14064
14065
14066
14067
14068
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 static struct ast_cli_entry cli_iax2[] = {
14166 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
14167 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
14168 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
14169 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
14170 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
14171 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
14172 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
14173 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
14174 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
14175 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
14176 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
14177 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
14178 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
14179 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
14180 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
14181 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
14182 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
14183 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
14184 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
14185 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
14186 #ifdef IAXTESTS
14187 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
14188 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
14189 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
14190 #endif
14191 };
14192
14193 #ifdef TEST_FRAMEWORK
14194 AST_TEST_DEFINE(test_iax2_peers_get)
14195 {
14196 struct ast_data_query query = {
14197 .path = "/asterisk/channel/iax2/peers",
14198 .search = "peers/peer/name=test_peer_data_provider"
14199 };
14200 struct ast_data *node;
14201 struct iax2_peer *peer;
14202
14203 switch (cmd) {
14204 case TEST_INIT:
14205 info->name = "iax2_peers_get_data_test";
14206 info->category = "/main/data/iax2/peers/";
14207 info->summary = "IAX2 peers data providers unit test";
14208 info->description =
14209 "Tests whether the IAX2 peers data provider implementation works as expected.";
14210 return AST_TEST_NOT_RUN;
14211 case TEST_EXECUTE:
14212 break;
14213 }
14214
14215
14216 peer = build_peer("test_peer_data_provider", NULL, NULL, 0);
14217 if (!peer) {
14218 return AST_TEST_FAIL;
14219 }
14220 peer->expiry= 1010;
14221 ao2_link(peers, peer);
14222
14223 node = ast_data_get(&query);
14224 if (!node) {
14225 ao2_unlink(peers, peer);
14226 peer_unref(peer);
14227 return AST_TEST_FAIL;
14228 }
14229
14230
14231 if (strcmp(ast_data_retrieve_string(node, "peer/name"), "test_peer_data_provider")) {
14232 ao2_unlink(peers, peer);
14233 peer_unref(peer);
14234 ast_data_free(node);
14235 return AST_TEST_FAIL;
14236 }
14237
14238 if (ast_data_retrieve_int(node, "peer/expiry") != 1010) {
14239 ao2_unlink(peers, peer);
14240 peer_unref(peer);
14241 ast_data_free(node);
14242 return AST_TEST_FAIL;
14243 }
14244
14245
14246 ast_data_free(node);
14247
14248 ao2_unlink(peers, peer);
14249 peer_unref(peer);
14250
14251 return AST_TEST_PASS;
14252 }
14253
14254 AST_TEST_DEFINE(test_iax2_users_get)
14255 {
14256 struct ast_data_query query = {
14257 .path = "/asterisk/channel/iax2/users",
14258 .search = "users/user/name=test_user_data_provider"
14259 };
14260 struct ast_data *node;
14261 struct iax2_user *user;
14262
14263 switch (cmd) {
14264 case TEST_INIT:
14265 info->name = "iax2_users_get_data_test";
14266 info->category = "/main/data/iax2/users/";
14267 info->summary = "IAX2 users data providers unit test";
14268 info->description =
14269 "Tests whether the IAX2 users data provider implementation works as expected.";
14270 return AST_TEST_NOT_RUN;
14271 case TEST_EXECUTE:
14272 break;
14273 }
14274
14275 user = build_user("test_user_data_provider", NULL, NULL, 0);
14276 if (!user) {
14277 ast_test_status_update(test, "Failed to build a test user\n");
14278 return AST_TEST_FAIL;
14279 }
14280 user->amaflags = 1010;
14281 ao2_link(users, user);
14282
14283 node = ast_data_get(&query);
14284 if (!node) {
14285 ast_test_status_update(test, "The data query to find our test user failed\n");
14286 ao2_unlink(users, user);
14287 user_unref(user);
14288 return AST_TEST_FAIL;
14289 }
14290
14291 if (strcmp(ast_data_retrieve_string(node, "user/name"), "test_user_data_provider")) {
14292 ast_test_status_update(test, "Our data results did not return the test user created in the previous step.\n");
14293 ao2_unlink(users, user);
14294 user_unref(user);
14295 ast_data_free(node);
14296 return AST_TEST_FAIL;
14297 }
14298
14299 if (ast_data_retrieve_int(node, "user/amaflags/value") != 1010) {
14300 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"));
14301 ao2_unlink(users, user);
14302 user_unref(user);
14303 ast_data_free(node);
14304 return AST_TEST_FAIL;
14305 }
14306
14307 ast_data_free(node);
14308
14309 ao2_unlink(users, user);
14310 user_unref(user);
14311
14312 return AST_TEST_PASS;
14313 }
14314 #endif
14315
14316 static void cleanup_thread_list(void *head)
14317 {
14318 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
14319 struct iax2_thread_list *list_head = head;
14320 struct iax2_thread *thread;
14321
14322 AST_LIST_LOCK(list_head);
14323 while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list))) {
14324 pthread_t thread_id = thread->threadid;
14325
14326 thread->stop = 1;
14327 signal_condition(&thread->lock, &thread->cond);
14328
14329 AST_LIST_UNLOCK(list_head);
14330 pthread_join(thread_id, NULL);
14331 AST_LIST_LOCK(list_head);
14332 }
14333 AST_LIST_UNLOCK(list_head);
14334 }
14335
14336 static int __unload_module(void)
14337 {
14338 struct ast_context *con;
14339 int x;
14340
14341 network_change_event_unsubscribe();
14342
14343 ast_manager_unregister("IAXpeers");
14344 ast_manager_unregister("IAXpeerlist");
14345 ast_manager_unregister("IAXnetstats");
14346 ast_manager_unregister("IAXregistry");
14347 ast_unregister_application(papp);
14348 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14349 ast_unregister_switch(&iax2_switch);
14350 ast_channel_unregister(&iax2_tech);
14351
14352 if (netthreadid != AST_PTHREADT_NULL) {
14353 pthread_cancel(netthreadid);
14354 pthread_kill(netthreadid, SIGURG);
14355 pthread_join(netthreadid, NULL);
14356 }
14357
14358 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14359 if (iaxs[x]) {
14360 iax2_destroy(x);
14361 }
14362 }
14363
14364
14365 cleanup_thread_list(&idle_list);
14366 cleanup_thread_list(&active_list);
14367 cleanup_thread_list(&dynamic_list);
14368
14369 ast_netsock_release(netsock);
14370 ast_netsock_release(outsock);
14371 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
14372 if (iaxs[x]) {
14373 iax2_destroy(x);
14374 }
14375 }
14376 ast_manager_unregister( "IAXpeers" );
14377 ast_manager_unregister( "IAXpeerlist" );
14378 ast_manager_unregister( "IAXnetstats" );
14379 ast_manager_unregister( "IAXregistry" );
14380 ast_unregister_application(papp);
14381 #ifdef TEST_FRAMEWORK
14382 AST_TEST_UNREGISTER(test_iax2_peers_get);
14383 AST_TEST_UNREGISTER(test_iax2_users_get);
14384 #endif
14385 ast_data_unregister(NULL);
14386 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14387 ast_unregister_switch(&iax2_switch);
14388 ast_channel_unregister(&iax2_tech);
14389 delete_users();
14390 iax_provision_unload();
14391 reload_firmware(1);
14392
14393 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14394 ast_mutex_destroy(&iaxsl[x]);
14395 }
14396
14397 ao2_ref(peers, -1);
14398 ao2_ref(users, -1);
14399 ao2_ref(iax_peercallno_pvts, -1);
14400 ao2_ref(iax_transfercallno_pvts, -1);
14401 ao2_ref(peercnts, -1);
14402 ao2_ref(callno_limits, -1);
14403 ao2_ref(calltoken_ignores, -1);
14404 ao2_ref(callno_pool, -1);
14405 ao2_ref(callno_pool_trunk, -1);
14406 if (timer) {
14407 ast_timer_close(timer);
14408 }
14409 transmit_processor = ast_taskprocessor_unreference(transmit_processor);
14410 sched = ast_sched_thread_destroy(sched);
14411
14412 con = ast_context_find(regcontext);
14413 if (con)
14414 ast_context_destroy(con, "IAX2");
14415 ast_unload_realtime("iaxpeers");
14416 return 0;
14417 }
14418
14419 static int unload_module(void)
14420 {
14421 ast_custom_function_unregister(&iaxpeer_function);
14422 ast_custom_function_unregister(&iaxvar_function);
14423 return __unload_module();
14424 }
14425
14426 static int peer_set_sock_cb(void *obj, void *arg, int flags)
14427 {
14428 struct iax2_peer *peer = obj;
14429
14430 if (peer->sockfd < 0)
14431 peer->sockfd = defaultsockfd;
14432
14433 return 0;
14434 }
14435
14436 static int pvt_hash_cb(const void *obj, const int flags)
14437 {
14438 const struct chan_iax2_pvt *pvt = obj;
14439
14440 return pvt->peercallno;
14441 }
14442
14443 static int pvt_cmp_cb(void *obj, void *arg, int flags)
14444 {
14445 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14446
14447
14448
14449
14450 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
14451 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14452 }
14453
14454 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
14455 {
14456 const struct chan_iax2_pvt *pvt = obj;
14457
14458 return pvt->transfercallno;
14459 }
14460
14461 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
14462 {
14463 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
14464
14465
14466
14467
14468 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
14469 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
14470 }
14471
14472 static int load_objects(void)
14473 {
14474 peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
14475 peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
14476
14477 if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
14478 goto container_fail;
14479 } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
14480 goto container_fail;
14481 } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
14482 goto container_fail;
14483 } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
14484 goto container_fail;
14485 } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
14486 goto container_fail;
14487 } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14488 goto container_fail;
14489 } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
14490 goto container_fail;
14491 } else if (create_callno_pools()) {
14492 goto container_fail;
14493 } else if (!(transmit_processor = ast_taskprocessor_get("iax2_transmit", TPS_REF_DEFAULT))) {
14494 goto container_fail;
14495 }
14496
14497 return 0;
14498
14499 container_fail:
14500 if (peers) {
14501 ao2_ref(peers, -1);
14502 }
14503 if (users) {
14504 ao2_ref(users, -1);
14505 }
14506 if (iax_peercallno_pvts) {
14507 ao2_ref(iax_peercallno_pvts, -1);
14508 }
14509 if (iax_transfercallno_pvts) {
14510 ao2_ref(iax_transfercallno_pvts, -1);
14511 }
14512 if (peercnts) {
14513 ao2_ref(peercnts, -1);
14514 }
14515 if (callno_limits) {
14516 ao2_ref(callno_limits, -1);
14517 }
14518 if (calltoken_ignores) {
14519 ao2_ref(calltoken_ignores, -1);
14520 }
14521 if (callno_pool) {
14522 ao2_ref(callno_pool, -1);
14523 }
14524 if (callno_pool_trunk) {
14525 ao2_ref(callno_pool_trunk, -1);
14526 }
14527 return AST_MODULE_LOAD_FAILURE;
14528 }
14529
14530
14531 #define DATA_EXPORT_IAX2_PEER(MEMBER) \
14532 MEMBER(iax2_peer, name, AST_DATA_STRING) \
14533 MEMBER(iax2_peer, username, AST_DATA_STRING) \
14534 MEMBER(iax2_peer, secret, AST_DATA_PASSWORD) \
14535 MEMBER(iax2_peer, dbsecret, AST_DATA_PASSWORD) \
14536 MEMBER(iax2_peer, outkey, AST_DATA_STRING) \
14537 MEMBER(iax2_peer, regexten, AST_DATA_STRING) \
14538 MEMBER(iax2_peer, context, AST_DATA_STRING) \
14539 MEMBER(iax2_peer, peercontext, AST_DATA_STRING) \
14540 MEMBER(iax2_peer, mailbox, AST_DATA_STRING) \
14541 MEMBER(iax2_peer, mohinterpret, AST_DATA_STRING) \
14542 MEMBER(iax2_peer, mohsuggest, AST_DATA_STRING) \
14543 MEMBER(iax2_peer, inkeys, AST_DATA_STRING) \
14544 MEMBER(iax2_peer, cid_num, AST_DATA_STRING) \
14545 MEMBER(iax2_peer, cid_name, AST_DATA_STRING) \
14546 MEMBER(iax2_peer, zonetag, AST_DATA_STRING) \
14547 MEMBER(iax2_peer, parkinglot, AST_DATA_STRING) \
14548 MEMBER(iax2_peer, expiry, AST_DATA_SECONDS) \
14549 MEMBER(iax2_peer, callno, AST_DATA_INTEGER) \
14550 MEMBER(iax2_peer, lastms, AST_DATA_MILLISECONDS) \
14551 MEMBER(iax2_peer, maxms, AST_DATA_MILLISECONDS) \
14552 MEMBER(iax2_peer, pokefreqok, AST_DATA_MILLISECONDS) \
14553 MEMBER(iax2_peer, pokefreqnotok, AST_DATA_MILLISECONDS) \
14554 MEMBER(iax2_peer, historicms, AST_DATA_INTEGER) \
14555 MEMBER(iax2_peer, smoothing, AST_DATA_BOOLEAN) \
14556 MEMBER(iax2_peer, maxcallno, AST_DATA_INTEGER)
14557
14558 AST_DATA_STRUCTURE(iax2_peer, DATA_EXPORT_IAX2_PEER);
14559
14560 static int peers_data_provider_get(const struct ast_data_search *search,
14561 struct ast_data *data_root)
14562 {
14563 struct ast_data *data_peer;
14564 struct iax2_peer *peer;
14565 struct ao2_iterator i;
14566 char status[20];
14567 struct ast_str *encmethods = ast_str_alloca(256);
14568
14569 i = ao2_iterator_init(peers, 0);
14570 while ((peer = ao2_iterator_next(&i))) {
14571 data_peer = ast_data_add_node(data_root, "peer");
14572 if (!data_peer) {
14573 peer_unref(peer);
14574 continue;
14575 }
14576
14577 ast_data_add_structure(iax2_peer, data_peer, peer);
14578
14579 ast_data_add_codecs(data_peer, "codecs", peer->capability);
14580
14581 peer_status(peer, status, sizeof(status));
14582 ast_data_add_str(data_peer, "status", status);
14583
14584 ast_data_add_str(data_peer, "host", ast_sockaddr_stringify_host(&peer->addr));
14585
14586 ast_data_add_str(data_peer, "mask", ast_inet_ntoa(peer->mask));
14587
14588 ast_data_add_int(data_peer, "port", ast_sockaddr_port(&peer->addr));
14589
14590 ast_data_add_bool(data_peer, "trunk", ast_test_flag64(peer, IAX_TRUNK));
14591
14592 ast_data_add_bool(data_peer, "dynamic", ast_test_flag64(peer, IAX_DYNAMIC));
14593
14594 encmethods_to_str(peer->encmethods, encmethods);
14595 ast_data_add_str(data_peer, "encryption", peer->encmethods ? ast_str_buffer(encmethods) : "no");
14596
14597 peer_unref(peer);
14598
14599 if (!ast_data_search_match(search, data_peer)) {
14600 ast_data_remove_node(data_root, data_peer);
14601 }
14602 }
14603 ao2_iterator_destroy(&i);
14604
14605 return 0;
14606 }
14607
14608 #define DATA_EXPORT_IAX2_USER(MEMBER) \
14609 MEMBER(iax2_user, name, AST_DATA_STRING) \
14610 MEMBER(iax2_user, dbsecret, AST_DATA_PASSWORD) \
14611 MEMBER(iax2_user, accountcode, AST_DATA_STRING) \
14612 MEMBER(iax2_user, mohinterpret, AST_DATA_STRING) \
14613 MEMBER(iax2_user, mohsuggest, AST_DATA_STRING) \
14614 MEMBER(iax2_user, inkeys, AST_DATA_STRING) \
14615 MEMBER(iax2_user, language, AST_DATA_STRING) \
14616 MEMBER(iax2_user, cid_num, AST_DATA_STRING) \
14617 MEMBER(iax2_user, cid_name, AST_DATA_STRING) \
14618 MEMBER(iax2_user, parkinglot, AST_DATA_STRING) \
14619 MEMBER(iax2_user, maxauthreq, AST_DATA_INTEGER) \
14620 MEMBER(iax2_user, curauthreq, AST_DATA_INTEGER)
14621
14622 AST_DATA_STRUCTURE(iax2_user, DATA_EXPORT_IAX2_USER);
14623
14624 static int users_data_provider_get(const struct ast_data_search *search,
14625 struct ast_data *data_root)
14626 {
14627 struct ast_data *data_user, *data_authmethods, *data_enum_node;
14628 struct iax2_user *user;
14629 struct ao2_iterator i;
14630 char auth[90];
14631 char *pstr = "";
14632
14633 i = ao2_iterator_init(users, 0);
14634 for (; (user = ao2_iterator_next(&i)); user_unref(user)) {
14635 data_user = ast_data_add_node(data_root, "user");
14636 if (!data_user) {
14637 continue;
14638 }
14639
14640 ast_data_add_structure(iax2_user, data_user, user);
14641
14642 ast_data_add_codecs(data_user, "codecs", user->capability);
14643
14644 if (!ast_strlen_zero(user->secret)) {
14645 ast_copy_string(auth, user->secret, sizeof(auth));
14646 } else if (!ast_strlen_zero(user->inkeys)) {
14647 snprintf(auth, sizeof(auth), "Key: %s", user->inkeys);
14648 } else {
14649 ast_copy_string(auth, "no secret", sizeof(auth));
14650 }
14651 ast_data_add_password(data_user, "secret", auth);
14652
14653 ast_data_add_str(data_user, "context", user->contexts ? user->contexts->context : DEFAULT_CONTEXT);
14654
14655
14656 data_authmethods = ast_data_add_node(data_user, "authmethods");
14657 if (!data_authmethods) {
14658 ast_data_remove_node(data_root, data_user);
14659 continue;
14660 }
14661 ast_data_add_bool(data_authmethods, "rsa", user->authmethods & IAX_AUTH_RSA);
14662 ast_data_add_bool(data_authmethods, "md5", user->authmethods & IAX_AUTH_MD5);
14663 ast_data_add_bool(data_authmethods, "plaintext", user->authmethods & IAX_AUTH_PLAINTEXT);
14664
14665
14666 data_enum_node = ast_data_add_node(data_user, "amaflags");
14667 if (!data_enum_node) {
14668 ast_data_remove_node(data_root, data_user);
14669 continue;
14670 }
14671 ast_data_add_int(data_enum_node, "value", user->amaflags);
14672 ast_data_add_str(data_enum_node, "text", ast_cdr_flags2str(user->amaflags));
14673
14674 ast_data_add_bool(data_user, "access-control", user->ha ? 1 : 0);
14675
14676 if (ast_test_flag64(user, IAX_CODEC_NOCAP)) {
14677 pstr = "REQ only";
14678 } else if (ast_test_flag64(user, IAX_CODEC_NOPREFS)) {
14679 pstr = "disabled";
14680 } else {
14681 pstr = ast_test_flag64(user, IAX_CODEC_USER_FIRST) ? "caller" : "host";
14682 }
14683 ast_data_add_str(data_user, "codec-preferences", pstr);
14684
14685 if (!ast_data_search_match(search, data_user)) {
14686 ast_data_remove_node(data_root, data_user);
14687 }
14688 }
14689 ao2_iterator_destroy(&i);
14690
14691 return 0;
14692 }
14693
14694 static const struct ast_data_handler peers_data_provider = {
14695 .version = AST_DATA_HANDLER_VERSION,
14696 .get = peers_data_provider_get
14697 };
14698
14699 static const struct ast_data_handler users_data_provider = {
14700 .version = AST_DATA_HANDLER_VERSION,
14701 .get = users_data_provider_get
14702 };
14703
14704 static const struct ast_data_entry iax2_data_providers[] = {
14705 AST_DATA_ENTRY("asterisk/channel/iax2/peers", &peers_data_provider),
14706 AST_DATA_ENTRY("asterisk/channel/iax2/users", &users_data_provider),
14707 };
14708
14709
14710 static int load_module(void)
14711 {
14712 static const char config[] = "iax.conf";
14713 int x = 0;
14714 struct iax2_registry *reg = NULL;
14715
14716 if (load_objects()) {
14717 return AST_MODULE_LOAD_FAILURE;
14718 }
14719
14720 memset(iaxs, 0, sizeof(iaxs));
14721
14722 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
14723 ast_mutex_init(&iaxsl[x]);
14724 }
14725
14726 if (!(sched = ast_sched_thread_create())) {
14727 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
14728 return AST_MODULE_LOAD_FAILURE;
14729 }
14730
14731 if (!(io = io_context_create())) {
14732 ast_log(LOG_ERROR, "Failed to create I/O context\n");
14733 sched = ast_sched_thread_destroy(sched);
14734 return AST_MODULE_LOAD_FAILURE;
14735 }
14736
14737 if (!(netsock = ast_netsock_list_alloc())) {
14738 ast_log(LOG_ERROR, "Failed to create netsock list\n");
14739 io_context_destroy(io);
14740 sched = ast_sched_thread_destroy(sched);
14741 return AST_MODULE_LOAD_FAILURE;
14742 }
14743 ast_netsock_init(netsock);
14744
14745 outsock = ast_netsock_list_alloc();
14746 if (!outsock) {
14747 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
14748 io_context_destroy(io);
14749 sched = ast_sched_thread_destroy(sched);
14750 return AST_MODULE_LOAD_FAILURE;
14751 }
14752 ast_netsock_init(outsock);
14753
14754 randomcalltokendata = ast_random();
14755
14756 iax_set_output(iax_debug_output);
14757 iax_set_error(iax_error_output);
14758 jb_setoutput(jb_error_output, jb_warning_output, NULL);
14759
14760 if ((timer = ast_timer_open())) {
14761 ast_timer_set_rate(timer, 1000 / trunkfreq);
14762 }
14763
14764 if (set_config(config, 0) == -1) {
14765 if (timer) {
14766 ast_timer_close(timer);
14767 }
14768 return AST_MODULE_LOAD_DECLINE;
14769 }
14770
14771 #ifdef TEST_FRAMEWORK
14772 AST_TEST_REGISTER(test_iax2_peers_get);
14773 AST_TEST_REGISTER(test_iax2_users_get);
14774 #endif
14775
14776
14777 ast_data_register_multiple(iax2_data_providers, ARRAY_LEN(iax2_data_providers));
14778 ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
14779
14780 ast_register_application_xml(papp, iax2_prov_app);
14781
14782 ast_custom_function_register(&iaxpeer_function);
14783 ast_custom_function_register(&iaxvar_function);
14784
14785 ast_manager_register_xml("IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers);
14786 ast_manager_register_xml("IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list);
14787 ast_manager_register_xml("IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats);
14788 ast_manager_register_xml("IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry);
14789
14790 if (ast_channel_register(&iax2_tech)) {
14791 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
14792 __unload_module();
14793 return AST_MODULE_LOAD_FAILURE;
14794 }
14795
14796 if (ast_register_switch(&iax2_switch)) {
14797 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
14798 }
14799
14800 if (start_network_thread()) {
14801 ast_log(LOG_ERROR, "Unable to start network thread\n");
14802 __unload_module();
14803 return AST_MODULE_LOAD_FAILURE;
14804 } else {
14805 ast_verb(2, "IAX Ready and Listening\n");
14806 }
14807
14808 AST_LIST_LOCK(®istrations);
14809 AST_LIST_TRAVERSE(®istrations, reg, entry)
14810 iax2_do_register(reg);
14811 AST_LIST_UNLOCK(®istrations);
14812
14813 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
14814 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
14815
14816
14817 reload_firmware(0);
14818 iax_provision_reload(0);
14819
14820 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
14821
14822 network_change_event_subscribe();
14823
14824 return AST_MODULE_LOAD_SUCCESS;
14825 }
14826
14827 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Inter Asterisk eXchange (Ver 2)",
14828 .load = load_module,
14829 .unload = unload_module,
14830 .reload = reload,
14831 .load_pri = AST_MODPRI_CHANNEL_DRIVER,
14832 .nonoptreq = "res_crypto",
14833 );