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 #include "asterisk.h"
00039
00040 ASTERISK_FILE_VERSION(__FILE__, "$Revision: 288193 $")
00041
00042 #include <sys/mman.h>
00043 #include <dirent.h>
00044 #include <sys/socket.h>
00045 #include <netinet/in.h>
00046 #include <arpa/inet.h>
00047 #include <netinet/in_systm.h>
00048 #include <netinet/ip.h>
00049 #include <sys/time.h>
00050 #include <sys/signal.h>
00051 #include <signal.h>
00052 #include <strings.h>
00053 #include <netdb.h>
00054 #include <fcntl.h>
00055 #include <sys/stat.h>
00056 #include <regex.h>
00057
00058 #include "asterisk/paths.h"
00059
00060 #include "asterisk/lock.h"
00061 #include "asterisk/frame.h"
00062 #include "asterisk/channel.h"
00063 #include "asterisk/module.h"
00064 #include "asterisk/pbx.h"
00065 #include "asterisk/sched.h"
00066 #include "asterisk/io.h"
00067 #include "asterisk/config.h"
00068 #include "asterisk/cli.h"
00069 #include "asterisk/translate.h"
00070 #include "asterisk/md5.h"
00071 #include "asterisk/cdr.h"
00072 #include "asterisk/crypto.h"
00073 #include "asterisk/acl.h"
00074 #include "asterisk/manager.h"
00075 #include "asterisk/callerid.h"
00076 #include "asterisk/app.h"
00077 #include "asterisk/astdb.h"
00078 #include "asterisk/musiconhold.h"
00079 #include "asterisk/features.h"
00080 #include "asterisk/utils.h"
00081 #include "asterisk/causes.h"
00082 #include "asterisk/localtime.h"
00083 #include "asterisk/aes.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
00093 #include "iax2.h"
00094 #include "iax2-parser.h"
00095 #include "iax2-provision.h"
00096 #include "jitterbuf.h"
00097
00098
00099
00100
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 #define SCHED_MULTITHREADED
00183
00184
00185
00186 #define DEBUG_SCHED_MULTITHREAD
00187
00188
00189 #ifdef SO_NO_CHECK
00190 static int nochecksums = 0;
00191 #endif
00192
00193 #define PTR_TO_CALLNO(a) ((unsigned short)(unsigned long)(a))
00194 #define CALLNO_TO_PTR(a) ((void *)(unsigned long)(a))
00195
00196 #define DEFAULT_THREAD_COUNT 10
00197 #define DEFAULT_MAX_THREAD_COUNT 100
00198 #define DEFAULT_RETRY_TIME 1000
00199 #define MEMORY_SIZE 100
00200 #define DEFAULT_DROP 3
00201
00202 #define DEBUG_SUPPORT
00203
00204 #define MIN_REUSE_TIME 60
00205
00206
00207 #define GAMMA (0.01)
00208
00209 static struct ast_codec_pref prefs;
00210
00211 static const char tdesc[] = "Inter Asterisk eXchange Driver (Ver 2)";
00212
00213
00214
00215
00216 #define MAX_TRUNK_MTU 1240
00217
00218 static int global_max_trunk_mtu;
00219 static int trunk_timed, trunk_untimed, trunk_maxmtu, trunk_nmaxmtu ;
00220
00221 #define DEFAULT_CONTEXT "default"
00222
00223 static char default_parkinglot[AST_MAX_CONTEXT];
00224
00225 static char language[MAX_LANGUAGE] = "";
00226 static char regcontext[AST_MAX_CONTEXT] = "";
00227
00228 static int maxauthreq = 3;
00229 static int max_retries = 4;
00230 static int ping_time = 21;
00231 static int lagrq_time = 10;
00232 static int maxjitterbuffer=1000;
00233 static int resyncthreshold=1000;
00234 static int maxjitterinterps=10;
00235 static int jittertargetextra = 40;
00236
00237 #define MAX_TRUNKDATA 640 * 200
00238
00239 static int trunkfreq = 20;
00240 static int trunkmaxsize = MAX_TRUNKDATA;
00241
00242 static int authdebug = 1;
00243 static int autokill = 0;
00244 static int iaxcompat = 0;
00245 static int last_authmethod = 0;
00246
00247 static int iaxdefaultdpcache=10 * 60;
00248
00249 static int iaxdefaulttimeout = 5;
00250
00251 static struct {
00252 unsigned int tos;
00253 unsigned int cos;
00254 } qos = { 0, 0 };
00255
00256 static int min_reg_expire;
00257 static int max_reg_expire;
00258
00259 static int srvlookup = 0;
00260
00261 static struct ast_timer *timer;
00262
00263 static struct ast_netsock_list *netsock;
00264 static struct ast_netsock_list *outsock;
00265 static int defaultsockfd = -1;
00266
00267 int (*iax2_regfunk)(const char *username, int onoff) = NULL;
00268
00269
00270 #define IAX_CAPABILITY_FULLBANDWIDTH 0xFFFF
00271
00272 #define IAX_CAPABILITY_MEDBANDWIDTH (IAX_CAPABILITY_FULLBANDWIDTH & \
00273 ~AST_FORMAT_SLINEAR & \
00274 ~AST_FORMAT_SLINEAR16 & \
00275 ~AST_FORMAT_SIREN7 & \
00276 ~AST_FORMAT_SIREN14 & \
00277 ~AST_FORMAT_ULAW & \
00278 ~AST_FORMAT_ALAW & \
00279 ~AST_FORMAT_G722)
00280
00281 #define IAX_CAPABILITY_LOWBANDWIDTH (IAX_CAPABILITY_MEDBANDWIDTH & \
00282 ~AST_FORMAT_G726 & \
00283 ~AST_FORMAT_G726_AAL2 & \
00284 ~AST_FORMAT_ADPCM)
00285
00286 #define IAX_CAPABILITY_LOWFREE (IAX_CAPABILITY_LOWBANDWIDTH & \
00287 ~AST_FORMAT_G723_1)
00288
00289
00290 #define DEFAULT_MAXMS 2000
00291 #define DEFAULT_FREQ_OK 60 * 1000
00292 #define DEFAULT_FREQ_NOTOK 10 * 1000
00293
00294
00295 #define IAX_CALLENCRYPTED(pvt) \
00296 (ast_test_flag(pvt, IAX_ENCRYPTED) && ast_test_flag(pvt, IAX_KEYPOPULATED))
00297
00298 #define IAX_DEBUGDIGEST(msg, key) do { \
00299 int idx; \
00300 char digest[33] = ""; \
00301 \
00302 if (!iaxdebug) \
00303 break; \
00304 \
00305 for (idx = 0; idx < 16; idx++) \
00306 sprintf(digest + (idx << 1), "%2.2x", (unsigned char) key[idx]); \
00307 \
00308 ast_log(LOG_NOTICE, msg " IAX_COMMAND_RTKEY to rotate key to '%s'\n", digest); \
00309 } while(0)
00310
00311 static struct io_context *io;
00312 static struct ast_sched_thread *sched;
00313
00314 static int iax2_capability = IAX_CAPABILITY_FULLBANDWIDTH;
00315
00316 static int iaxdebug = 0;
00317
00318 static int iaxtrunkdebug = 0;
00319
00320 static int test_losspct = 0;
00321 #ifdef IAXTESTS
00322 static int test_late = 0;
00323 static int test_resync = 0;
00324 static int test_jit = 0;
00325 static int test_jitpct = 0;
00326 #endif
00327
00328 static char accountcode[AST_MAX_ACCOUNT_CODE];
00329 static char mohinterpret[MAX_MUSICCLASS];
00330 static char mohsuggest[MAX_MUSICCLASS];
00331 static int amaflags = 0;
00332 static int adsi = 0;
00333 static int delayreject = 0;
00334 static int iax2_encryption = 0;
00335
00336 static struct ast_flags globalflags = { 0 };
00337
00338 static pthread_t netthreadid = AST_PTHREADT_NULL;
00339
00340 enum iax2_state {
00341 IAX_STATE_STARTED = (1 << 0),
00342 IAX_STATE_AUTHENTICATED = (1 << 1),
00343 IAX_STATE_TBD = (1 << 2),
00344 };
00345
00346 struct iax2_context {
00347 char context[AST_MAX_CONTEXT];
00348 struct iax2_context *next;
00349 };
00350
00351 enum iax2_flags {
00352 IAX_HASCALLERID = (1 << 0),
00353 IAX_DELME = (1 << 1),
00354 IAX_TEMPONLY = (1 << 2),
00355 IAX_TRUNK = (1 << 3),
00356 IAX_NOTRANSFER = (1 << 4),
00357 IAX_USEJITTERBUF = (1 << 5),
00358 IAX_DYNAMIC = (1 << 6),
00359 IAX_SENDANI = (1 << 7),
00360
00361 IAX_ALREADYGONE = (1 << 9),
00362 IAX_PROVISION = (1 << 10),
00363 IAX_QUELCH = (1 << 11),
00364 IAX_ENCRYPTED = (1 << 12),
00365 IAX_KEYPOPULATED = (1 << 13),
00366 IAX_CODEC_USER_FIRST = (1 << 14),
00367 IAX_CODEC_NOPREFS = (1 << 15),
00368 IAX_CODEC_NOCAP = (1 << 16),
00369 IAX_RTCACHEFRIENDS = (1 << 17),
00370 IAX_RTUPDATE = (1 << 18),
00371 IAX_RTAUTOCLEAR = (1 << 19),
00372 IAX_FORCEJITTERBUF = (1 << 20),
00373 IAX_RTIGNOREREGEXPIRE = (1 << 21),
00374 IAX_TRUNKTIMESTAMPS = (1 << 22),
00375 IAX_TRANSFERMEDIA = (1 << 23),
00376 IAX_MAXAUTHREQ = (1 << 24),
00377 IAX_DELAYPBXSTART = (1 << 25),
00378
00379
00380 IAX_ALLOWFWDOWNLOAD = (1 << 26),
00381 IAX_IMMEDIATE = (1 << 27),
00382 IAX_FORCE_ENCRYPT = (1 << 28),
00383 IAX_SHRINKCALLERID = (1 << 29),
00384 };
00385
00386 static int global_rtautoclear = 120;
00387
00388 static int reload_config(void);
00389
00390
00391
00392
00393 enum calltoken_peer_enum {
00394
00395 CALLTOKEN_DEFAULT = 0,
00396
00397 CALLTOKEN_YES = 1,
00398
00399
00400 CALLTOKEN_AUTO = 2,
00401
00402 CALLTOKEN_NO = 3,
00403 };
00404
00405 struct iax2_user {
00406 AST_DECLARE_STRING_FIELDS(
00407 AST_STRING_FIELD(name);
00408 AST_STRING_FIELD(secret);
00409 AST_STRING_FIELD(dbsecret);
00410 AST_STRING_FIELD(accountcode);
00411 AST_STRING_FIELD(mohinterpret);
00412 AST_STRING_FIELD(mohsuggest);
00413 AST_STRING_FIELD(inkeys);
00414 AST_STRING_FIELD(language);
00415 AST_STRING_FIELD(cid_num);
00416 AST_STRING_FIELD(cid_name);
00417 AST_STRING_FIELD(parkinglot);
00418 );
00419
00420 int authmethods;
00421 int encmethods;
00422 int amaflags;
00423 int adsi;
00424 unsigned int flags;
00425 int capability;
00426 int maxauthreq;
00427 int curauthreq;
00428 struct ast_codec_pref prefs;
00429 struct ast_ha *ha;
00430 struct iax2_context *contexts;
00431 struct ast_variable *vars;
00432 enum calltoken_peer_enum calltoken_required;
00433 };
00434
00435 struct iax2_peer {
00436 AST_DECLARE_STRING_FIELDS(
00437 AST_STRING_FIELD(name);
00438 AST_STRING_FIELD(username);
00439 AST_STRING_FIELD(secret);
00440 AST_STRING_FIELD(dbsecret);
00441 AST_STRING_FIELD(outkey);
00442
00443 AST_STRING_FIELD(regexten);
00444 AST_STRING_FIELD(context);
00445 AST_STRING_FIELD(peercontext);
00446 AST_STRING_FIELD(mailbox);
00447 AST_STRING_FIELD(mohinterpret);
00448 AST_STRING_FIELD(mohsuggest);
00449 AST_STRING_FIELD(inkeys);
00450
00451 AST_STRING_FIELD(cid_num);
00452 AST_STRING_FIELD(cid_name);
00453 AST_STRING_FIELD(zonetag);
00454 AST_STRING_FIELD(parkinglot);
00455 );
00456 struct ast_codec_pref prefs;
00457 struct ast_dnsmgr_entry *dnsmgr;
00458 struct sockaddr_in addr;
00459 int formats;
00460 int sockfd;
00461 struct in_addr mask;
00462 int adsi;
00463 unsigned int flags;
00464
00465
00466 struct sockaddr_in defaddr;
00467 int authmethods;
00468 int encmethods;
00469
00470 int expire;
00471 int expiry;
00472 int capability;
00473
00474
00475 int callno;
00476 int pokeexpire;
00477 int lastms;
00478 int maxms;
00479
00480 int pokefreqok;
00481 int pokefreqnotok;
00482 int historicms;
00483 int smoothing;
00484 uint16_t maxcallno;
00485
00486 struct ast_event_sub *mwi_event_sub;
00487
00488 struct ast_ha *ha;
00489 enum calltoken_peer_enum calltoken_required;
00490 };
00491
00492 #define IAX2_TRUNK_PREFACE (sizeof(struct iax_frame) + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr))
00493
00494 struct iax2_trunk_peer {
00495 ast_mutex_t lock;
00496 int sockfd;
00497 struct sockaddr_in addr;
00498 struct timeval txtrunktime;
00499 struct timeval rxtrunktime;
00500 struct timeval lasttxtime;
00501 struct timeval trunkact;
00502 unsigned int lastsent;
00503
00504 unsigned char *trunkdata;
00505 unsigned int trunkdatalen;
00506 unsigned int trunkdataalloc;
00507 int trunkmaxmtu;
00508 int trunkerror;
00509 int calls;
00510 AST_LIST_ENTRY(iax2_trunk_peer) list;
00511 };
00512
00513 static AST_LIST_HEAD_STATIC(tpeers, iax2_trunk_peer);
00514
00515 struct iax_firmware {
00516 AST_LIST_ENTRY(iax_firmware) list;
00517 int fd;
00518 int mmaplen;
00519 int dead;
00520 struct ast_iax2_firmware_header *fwh;
00521 unsigned char *buf;
00522 };
00523
00524 enum iax_reg_state {
00525 REG_STATE_UNREGISTERED = 0,
00526 REG_STATE_REGSENT,
00527 REG_STATE_AUTHSENT,
00528 REG_STATE_REGISTERED,
00529 REG_STATE_REJECTED,
00530 REG_STATE_TIMEOUT,
00531 REG_STATE_NOAUTH
00532 };
00533
00534 enum iax_transfer_state {
00535 TRANSFER_NONE = 0,
00536 TRANSFER_BEGIN,
00537 TRANSFER_READY,
00538 TRANSFER_RELEASED,
00539 TRANSFER_PASSTHROUGH,
00540 TRANSFER_MBEGIN,
00541 TRANSFER_MREADY,
00542 TRANSFER_MRELEASED,
00543 TRANSFER_MPASSTHROUGH,
00544 TRANSFER_MEDIA,
00545 TRANSFER_MEDIAPASS
00546 };
00547
00548 struct iax2_registry {
00549 struct sockaddr_in addr;
00550 char username[80];
00551 char secret[80];
00552 int expire;
00553 int refresh;
00554 enum iax_reg_state regstate;
00555 int messages;
00556 int callno;
00557 struct sockaddr_in us;
00558 struct ast_dnsmgr_entry *dnsmgr;
00559 AST_LIST_ENTRY(iax2_registry) entry;
00560 };
00561
00562 static AST_LIST_HEAD_STATIC(registrations, iax2_registry);
00563
00564
00565 #define MIN_RETRY_TIME 100
00566 #define MAX_RETRY_TIME 10000
00567
00568 #define MAX_JITTER_BUFFER 50
00569 #define MIN_JITTER_BUFFER 10
00570
00571 #define DEFAULT_TRUNKDATA 640 * 10
00572
00573 #define MAX_TIMESTAMP_SKEW 160
00574
00575
00576 #define TS_GAP_FOR_JB_RESYNC 5000
00577
00578
00579 #define MARK_IAX_SUBCLASS_TX 0x8000
00580
00581 static int iaxthreadcount = DEFAULT_THREAD_COUNT;
00582 static int iaxmaxthreadcount = DEFAULT_MAX_THREAD_COUNT;
00583 static int iaxdynamicthreadcount = 0;
00584 static int iaxdynamicthreadnum = 0;
00585 static int iaxactivethreadcount = 0;
00586
00587 struct iax_rr {
00588 int jitter;
00589 int losspct;
00590 int losscnt;
00591 int packets;
00592 int delay;
00593 int dropped;
00594 int ooo;
00595 };
00596
00597 struct iax2_pvt_ref;
00598
00599 struct chan_iax2_pvt {
00600
00601 int sockfd;
00602
00603 int voiceformat;
00604
00605 int videoformat;
00606
00607 int svoiceformat;
00608
00609 int svideoformat;
00610
00611 int capability;
00612
00613 unsigned int last;
00614
00615 unsigned int lastsent;
00616
00617 unsigned int lastvsent;
00618
00619 unsigned int nextpred;
00620
00621 int first_iax_message;
00622
00623 int last_iax_message;
00624
00625 unsigned int notsilenttx:1;
00626
00627 unsigned int pingtime;
00628
00629 int maxtime;
00630
00631 struct sockaddr_in addr;
00632
00633 struct ast_codec_pref prefs;
00634
00635 struct ast_codec_pref rprefs;
00636
00637 unsigned short callno;
00638
00639 struct callno_entry *callno_entry;
00640
00641 unsigned short peercallno;
00642
00643
00644
00645 int chosenformat;
00646
00647 int peerformat;
00648
00649 int peercapability;
00650
00651 struct timeval offset;
00652
00653 struct timeval rxcore;
00654
00655 jitterbuf *jb;
00656
00657 int jbid;
00658
00659 int lag;
00660
00661 int error;
00662
00663 struct ast_channel *owner;
00664
00665 struct ast_flags state;
00666
00667 int expiry;
00668
00669 unsigned char oseqno;
00670
00671 unsigned char rseqno;
00672
00673 unsigned char iseqno;
00674
00675 unsigned char aseqno;
00676
00677 AST_DECLARE_STRING_FIELDS(
00678
00679 AST_STRING_FIELD(peer);
00680
00681 AST_STRING_FIELD(context);
00682
00683 AST_STRING_FIELD(cid_num);
00684 AST_STRING_FIELD(cid_name);
00685
00686 AST_STRING_FIELD(ani);
00687
00688 AST_STRING_FIELD(dnid);
00689
00690 AST_STRING_FIELD(rdnis);
00691
00692 AST_STRING_FIELD(exten);
00693
00694 AST_STRING_FIELD(username);
00695
00696 AST_STRING_FIELD(secret);
00697
00698 AST_STRING_FIELD(challenge);
00699
00700 AST_STRING_FIELD(inkeys);
00701
00702 AST_STRING_FIELD(outkey);
00703
00704 AST_STRING_FIELD(language);
00705
00706 AST_STRING_FIELD(host);
00707
00708 AST_STRING_FIELD(dproot);
00709 AST_STRING_FIELD(accountcode);
00710 AST_STRING_FIELD(mohinterpret);
00711 AST_STRING_FIELD(mohsuggest);
00712
00713 AST_STRING_FIELD(osptoken);
00714
00715 AST_STRING_FIELD(parkinglot);
00716 );
00717
00718 int authrej;
00719
00720 int authmethods;
00721
00722 int encmethods;
00723
00724 ast_aes_encrypt_key ecx;
00725
00726 ast_aes_decrypt_key mydcx;
00727
00728 ast_aes_decrypt_key dcx;
00729
00730
00731 int keyrotateid;
00732
00733 unsigned char semirand[32];
00734
00735 struct iax2_registry *reg;
00736
00737 struct iax2_peer *peerpoke;
00738
00739 unsigned int flags;
00740 int adsi;
00741
00742
00743 enum iax_transfer_state transferring;
00744
00745 int transferid;
00746
00747 struct sockaddr_in transfer;
00748
00749 unsigned short transfercallno;
00750
00751 ast_aes_encrypt_key tdcx;
00752
00753
00754 int peeradsicpe;
00755
00756
00757 unsigned short bridgecallno;
00758
00759 int pingid;
00760 int lagid;
00761 int autoid;
00762 int authid;
00763 int authfail;
00764 int initid;
00765 int calling_ton;
00766 int calling_tns;
00767 int calling_pres;
00768 int amaflags;
00769 AST_LIST_HEAD_NOLOCK(, iax2_dpcache) dpentries;
00770
00771 struct ast_variable *vars;
00772
00773 struct ast_variable *iaxvars;
00774
00775 struct iax_rr remote_rr;
00776
00777 int min;
00778
00779 int frames_dropped;
00780
00781 int frames_received;
00782
00783 unsigned char calltoken_ie_len;
00784
00785 char hold_signaling;
00786
00787 AST_LIST_HEAD_NOLOCK(signaling_queue, signaling_queue_entry) signaling_queue;
00788 };
00789
00790 struct signaling_queue_entry {
00791 struct ast_frame f;
00792 AST_LIST_ENTRY(signaling_queue_entry) next;
00793 };
00794
00795
00796 static struct ao2_container *callno_pool;
00797
00798
00799 static struct ao2_container *callno_pool_trunk;
00800
00801 static const unsigned int CALLNO_POOL_BUCKETS = 2699;
00802
00803
00804
00805
00806
00807
00808
00809
00810 static AST_LIST_HEAD_STATIC(frame_queue, iax_frame);
00811
00812 static int randomcalltokendata;
00813
00814 static const time_t MAX_CALLTOKEN_DELAY = 10;
00815
00816
00817
00818
00819
00820
00821
00822
00823 #ifdef LOW_MEMORY
00824 #define MAX_PEER_BUCKETS 17
00825 #else
00826 #define MAX_PEER_BUCKETS 563
00827 #endif
00828 static struct ao2_container *peers;
00829
00830 #define MAX_USER_BUCKETS MAX_PEER_BUCKETS
00831 static struct ao2_container *users;
00832
00833
00834 static struct ao2_container *peercnts;
00835
00836
00837 static struct ao2_container *callno_limits;
00838
00839
00840 static struct ao2_container *calltoken_ignores;
00841
00842 static uint16_t DEFAULT_MAXCALLNO_LIMIT = 2048;
00843
00844 static uint16_t DEFAULT_MAXCALLNO_LIMIT_NONVAL = 8192;
00845
00846 static uint16_t global_maxcallno;
00847
00848
00849 static uint16_t global_maxcallno_nonval;
00850
00851 static uint16_t total_nonval_callno_used = 0;
00852
00853
00854
00855 struct peercnt {
00856
00857 unsigned long addr;
00858
00859 uint16_t cur;
00860
00861 uint16_t limit;
00862
00863
00864 unsigned char reg;
00865 };
00866
00867
00868 struct addr_range {
00869
00870 struct ast_ha ha;
00871
00872 uint16_t limit;
00873
00874 unsigned char delme;
00875 };
00876
00877 struct callno_entry {
00878
00879 uint16_t callno;
00880
00881 unsigned char validated;
00882 };
00883
00884 static AST_LIST_HEAD_STATIC(firmwares, iax_firmware);
00885
00886 enum {
00887
00888 CACHE_FLAG_EXISTS = (1 << 0),
00889
00890 CACHE_FLAG_NONEXISTENT = (1 << 1),
00891
00892 CACHE_FLAG_CANEXIST = (1 << 2),
00893
00894 CACHE_FLAG_PENDING = (1 << 3),
00895
00896 CACHE_FLAG_TIMEOUT = (1 << 4),
00897
00898 CACHE_FLAG_TRANSMITTED = (1 << 5),
00899
00900 CACHE_FLAG_UNKNOWN = (1 << 6),
00901
00902 CACHE_FLAG_MATCHMORE = (1 << 7),
00903 };
00904
00905 struct iax2_dpcache {
00906 char peercontext[AST_MAX_CONTEXT];
00907 char exten[AST_MAX_EXTENSION];
00908 struct timeval orig;
00909 struct timeval expiry;
00910 int flags;
00911 unsigned short callno;
00912 int waiters[256];
00913 AST_LIST_ENTRY(iax2_dpcache) cache_list;
00914 AST_LIST_ENTRY(iax2_dpcache) peer_list;
00915 };
00916
00917 static AST_LIST_HEAD_STATIC(dpcache, iax2_dpcache);
00918
00919 static void reg_source_db(struct iax2_peer *p);
00920 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin);
00921 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin);
00922
00923 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt);
00924 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags);
00925 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state);
00926
00927 enum iax2_thread_iostate {
00928 IAX_IOSTATE_IDLE,
00929 IAX_IOSTATE_READY,
00930 IAX_IOSTATE_PROCESSING,
00931 IAX_IOSTATE_SCHEDREADY,
00932 };
00933
00934 enum iax2_thread_type {
00935 IAX_THREAD_TYPE_POOL,
00936 IAX_THREAD_TYPE_DYNAMIC,
00937 };
00938
00939 struct iax2_pkt_buf {
00940 AST_LIST_ENTRY(iax2_pkt_buf) entry;
00941 size_t len;
00942 unsigned char buf[1];
00943 };
00944
00945 struct iax2_thread {
00946 AST_LIST_ENTRY(iax2_thread) list;
00947 enum iax2_thread_type type;
00948 enum iax2_thread_iostate iostate;
00949 #ifdef SCHED_MULTITHREADED
00950 void (*schedfunc)(const void *);
00951 const void *scheddata;
00952 #endif
00953 #ifdef DEBUG_SCHED_MULTITHREAD
00954 char curfunc[80];
00955 #endif
00956 int actions;
00957 pthread_t threadid;
00958 int threadnum;
00959 struct sockaddr_in iosin;
00960 unsigned char readbuf[4096];
00961 unsigned char *buf;
00962 ssize_t buf_len;
00963 size_t buf_size;
00964 int iofd;
00965 time_t checktime;
00966 ast_mutex_t lock;
00967 ast_cond_t cond;
00968 ast_mutex_t init_lock;
00969 ast_cond_t init_cond;
00970
00971
00972
00973
00974 struct {
00975 unsigned short callno;
00976 struct sockaddr_in sin;
00977 unsigned char type;
00978 unsigned char csub;
00979 } ffinfo;
00980
00981
00982
00983 AST_LIST_HEAD_NOLOCK(, iax2_pkt_buf) full_frames;
00984 unsigned char stop;
00985 };
00986
00987
00988 static AST_LIST_HEAD_STATIC(idle_list, iax2_thread);
00989 static AST_LIST_HEAD_STATIC(active_list, iax2_thread);
00990 static AST_LIST_HEAD_STATIC(dynamic_list, iax2_thread);
00991
00992 static void *iax2_process_thread(void *data);
00993 static void iax2_destroy(int callno);
00994
00995 static void signal_condition(ast_mutex_t *lock, ast_cond_t *cond)
00996 {
00997 ast_mutex_lock(lock);
00998 ast_cond_signal(cond);
00999 ast_mutex_unlock(lock);
01000 }
01001
01002
01003
01004
01005
01006
01007
01008
01009
01010 static struct chan_iax2_pvt *iaxs[IAX_MAX_CALLS + 1];
01011
01012
01013
01014
01015
01016
01017
01018
01019
01020
01021 static struct ao2_container *iax_peercallno_pvts;
01022
01023
01024
01025
01026
01027
01028
01029
01030 static ast_mutex_t iaxsl[ARRAY_LEN(iaxs)];
01031
01032
01033
01034
01035
01036
01037 static struct ao2_container *iax_transfercallno_pvts;
01038
01039
01040
01041 #define TRUNK_CALL_START IAX_MAX_CALLS / 2
01042
01043
01044 static struct sockaddr_in debugaddr;
01045
01046 static void iax_outputframe(struct iax_frame *f, struct ast_iax2_full_hdr *fhi, int rx, struct sockaddr_in *sin, int datalen)
01047 {
01048 if (iaxdebug ||
01049 (sin && debugaddr.sin_addr.s_addr &&
01050 (!ntohs(debugaddr.sin_port) ||
01051 debugaddr.sin_port == sin->sin_port) &&
01052 debugaddr.sin_addr.s_addr == sin->sin_addr.s_addr)) {
01053 if (iaxdebug) {
01054 iax_showframe(f, fhi, rx, sin, datalen);
01055 } else {
01056 iaxdebug = 1;
01057 iax_showframe(f, fhi, rx, sin, datalen);
01058 iaxdebug = 0;
01059 }
01060 }
01061 }
01062
01063 static void iax_debug_output(const char *data)
01064 {
01065 if (iaxdebug)
01066 ast_verbose("%s", data);
01067 }
01068
01069 static void iax_error_output(const char *data)
01070 {
01071 ast_log(LOG_WARNING, "%s", data);
01072 }
01073
01074 static void __attribute__((format(printf, 1, 2))) jb_error_output(const char *fmt, ...)
01075 {
01076 va_list args;
01077 char buf[1024];
01078
01079 va_start(args, fmt);
01080 vsnprintf(buf, sizeof(buf), fmt, args);
01081 va_end(args);
01082
01083 ast_log(LOG_ERROR, "%s", buf);
01084 }
01085
01086 static void __attribute__((format(printf, 1, 2))) jb_warning_output(const char *fmt, ...)
01087 {
01088 va_list args;
01089 char buf[1024];
01090
01091 va_start(args, fmt);
01092 vsnprintf(buf, sizeof(buf), fmt, args);
01093 va_end(args);
01094
01095 ast_log(LOG_WARNING, "%s", buf);
01096 }
01097
01098 static void __attribute__((format(printf, 1, 2))) jb_debug_output(const char *fmt, ...)
01099 {
01100 va_list args;
01101 char buf[1024];
01102
01103 va_start(args, fmt);
01104 vsnprintf(buf, sizeof(buf), fmt, args);
01105 va_end(args);
01106
01107 ast_verbose("%s", buf);
01108 }
01109
01110 static int maxtrunkcall = TRUNK_CALL_START;
01111 static int maxnontrunkcall = 1;
01112
01113 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);
01114 static int expire_registry(const void *data);
01115 static int iax2_answer(struct ast_channel *c);
01116 static int iax2_call(struct ast_channel *c, char *dest, int timeout);
01117 static int iax2_devicestate(void *data);
01118 static int iax2_digit_begin(struct ast_channel *c, char digit);
01119 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration);
01120 static int iax2_do_register(struct iax2_registry *reg);
01121 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan);
01122 static int iax2_hangup(struct ast_channel *c);
01123 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen);
01124 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
01125 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
01126 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final);
01127 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen);
01128 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img);
01129 static int iax2_sendtext(struct ast_channel *c, const char *text);
01130 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen);
01131 static int iax2_transfer(struct ast_channel *c, const char *dest);
01132 static int iax2_write(struct ast_channel *c, struct ast_frame *f);
01133 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now);
01134 static int send_command(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01135 static int send_command_final(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01136 static int send_command_immediate(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int, int);
01137 static int send_command_locked(unsigned short callno, char, int, unsigned int, const unsigned char *, int, int);
01138 static int send_command_transfer(struct chan_iax2_pvt *, char, int, unsigned int, const unsigned char *, int);
01139 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause);
01140 static struct ast_frame *iax2_read(struct ast_channel *c);
01141 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01142 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly);
01143 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime);
01144 static void *iax2_dup_variable_datastore(void *);
01145 static void prune_peers(void);
01146 static void prune_users(void);
01147 static void iax2_free_variable_datastore(void *);
01148
01149 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
01150 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen);
01151 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen);
01152 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt);
01153 static void build_rand_pad(unsigned char *buf, ssize_t len);
01154 static struct callno_entry *get_unused_callno(int trunk, int validated);
01155 static int replace_callno(const void *obj);
01156 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry);
01157
01158 static const struct ast_channel_tech iax2_tech = {
01159 .type = "IAX2",
01160 .description = tdesc,
01161 .capabilities = IAX_CAPABILITY_FULLBANDWIDTH,
01162 .properties = AST_CHAN_TP_WANTSJITTER,
01163 .requester = iax2_request,
01164 .devicestate = iax2_devicestate,
01165 .send_digit_begin = iax2_digit_begin,
01166 .send_digit_end = iax2_digit_end,
01167 .send_text = iax2_sendtext,
01168 .send_image = iax2_sendimage,
01169 .send_html = iax2_sendhtml,
01170 .call = iax2_call,
01171 .hangup = iax2_hangup,
01172 .answer = iax2_answer,
01173 .read = iax2_read,
01174 .write = iax2_write,
01175 .write_video = iax2_write,
01176 .indicate = iax2_indicate,
01177 .setoption = iax2_setoption,
01178 .bridge = iax2_bridge,
01179 .transfer = iax2_transfer,
01180 .fixup = iax2_fixup,
01181 .func_channel_read = acf_channel_read,
01182 };
01183
01184
01185
01186
01187
01188
01189
01190
01191
01192
01193
01194
01195
01196
01197
01198
01199
01200
01201 static void iax2_lock_owner(int callno)
01202 {
01203 for (;;) {
01204 if (!iaxs[callno] || !iaxs[callno]->owner) {
01205
01206 break;
01207 }
01208 if (!ast_channel_trylock(iaxs[callno]->owner)) {
01209
01210 break;
01211 }
01212
01213 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
01214 }
01215 }
01216
01217 static void mwi_event_cb(const struct ast_event *event, void *userdata)
01218 {
01219
01220
01221
01222 }
01223
01224
01225
01226 static void iax2_ami_channelupdate(struct chan_iax2_pvt *pvt)
01227 {
01228 manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
01229 "Channel: %s\r\nChanneltype: IAX2\r\nIAX2-callno-local: %d\r\nIAX2-callno-remote: %d\r\nIAX2-peer: %s\r\n",
01230 pvt->owner ? pvt->owner->name : "",
01231 pvt->callno, pvt->peercallno, pvt->peer ? pvt->peer : "");
01232 }
01233
01234
01235 static struct ast_datastore_info iax2_variable_datastore_info = {
01236 .type = "IAX2_VARIABLE",
01237 .duplicate = iax2_dup_variable_datastore,
01238 .destroy = iax2_free_variable_datastore,
01239 };
01240
01241 static void *iax2_dup_variable_datastore(void *old)
01242 {
01243 AST_LIST_HEAD(, ast_var_t) *oldlist = old, *newlist;
01244 struct ast_var_t *oldvar, *newvar;
01245
01246 newlist = ast_calloc(sizeof(*newlist), 1);
01247 if (!newlist) {
01248 ast_log(LOG_ERROR, "Unable to duplicate iax2 variables\n");
01249 return NULL;
01250 }
01251
01252 AST_LIST_HEAD_INIT(newlist);
01253 AST_LIST_LOCK(oldlist);
01254 AST_LIST_TRAVERSE(oldlist, oldvar, entries) {
01255 newvar = ast_var_assign(ast_var_name(oldvar), ast_var_value(oldvar));
01256 if (newvar)
01257 AST_LIST_INSERT_TAIL(newlist, newvar, entries);
01258 else
01259 ast_log(LOG_ERROR, "Unable to duplicate iax2 variable '%s'\n", ast_var_name(oldvar));
01260 }
01261 AST_LIST_UNLOCK(oldlist);
01262 return newlist;
01263 }
01264
01265 static void iax2_free_variable_datastore(void *old)
01266 {
01267 AST_LIST_HEAD(, ast_var_t) *oldlist = old;
01268 struct ast_var_t *oldvar;
01269
01270 AST_LIST_LOCK(oldlist);
01271 while ((oldvar = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
01272 ast_free(oldvar);
01273 }
01274 AST_LIST_UNLOCK(oldlist);
01275 AST_LIST_HEAD_DESTROY(oldlist);
01276 ast_free(oldlist);
01277 }
01278
01279
01280
01281
01282
01283 static void insert_idle_thread(struct iax2_thread *thread)
01284 {
01285 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
01286 AST_LIST_LOCK(&dynamic_list);
01287 AST_LIST_INSERT_TAIL(&dynamic_list, thread, list);
01288 AST_LIST_UNLOCK(&dynamic_list);
01289 } else {
01290 AST_LIST_LOCK(&idle_list);
01291 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
01292 AST_LIST_UNLOCK(&idle_list);
01293 }
01294
01295 return;
01296 }
01297
01298 static struct iax2_thread *find_idle_thread(void)
01299 {
01300 struct iax2_thread *thread = NULL;
01301
01302
01303 AST_LIST_LOCK(&idle_list);
01304 thread = AST_LIST_REMOVE_HEAD(&idle_list, list);
01305 AST_LIST_UNLOCK(&idle_list);
01306
01307
01308 if (thread) {
01309 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01310 return thread;
01311 }
01312
01313
01314 AST_LIST_LOCK(&dynamic_list);
01315 thread = AST_LIST_REMOVE_HEAD(&dynamic_list, list);
01316 AST_LIST_UNLOCK(&dynamic_list);
01317
01318
01319 if (thread) {
01320 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01321 return thread;
01322 }
01323
01324
01325 if (iaxdynamicthreadcount >= iaxmaxthreadcount || !(thread = ast_calloc(1, sizeof(*thread))))
01326 return NULL;
01327
01328
01329 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, 1);
01330 thread->threadnum = ast_atomic_fetchadd_int(&iaxdynamicthreadnum, 1);
01331 thread->type = IAX_THREAD_TYPE_DYNAMIC;
01332
01333
01334 ast_mutex_init(&thread->lock);
01335 ast_cond_init(&thread->cond, NULL);
01336 ast_mutex_init(&thread->init_lock);
01337 ast_cond_init(&thread->init_cond, NULL);
01338 ast_mutex_lock(&thread->init_lock);
01339
01340
01341 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
01342 ast_cond_destroy(&thread->cond);
01343 ast_mutex_destroy(&thread->lock);
01344 ast_free(thread);
01345 return NULL;
01346 }
01347
01348
01349
01350 memset(&thread->ffinfo, 0, sizeof(thread->ffinfo));
01351
01352
01353 ast_cond_wait(&thread->init_cond, &thread->init_lock);
01354
01355
01356 ast_mutex_unlock(&thread->init_lock);
01357
01358 return thread;
01359 }
01360
01361 #ifdef SCHED_MULTITHREADED
01362 static int __schedule_action(void (*func)(const void *data), const void *data, const char *funcname)
01363 {
01364 struct iax2_thread *thread = NULL;
01365 static time_t lasterror;
01366 static time_t t;
01367
01368 thread = find_idle_thread();
01369
01370 if (thread != NULL) {
01371 thread->schedfunc = func;
01372 thread->scheddata = data;
01373 thread->iostate = IAX_IOSTATE_SCHEDREADY;
01374 #ifdef DEBUG_SCHED_MULTITHREAD
01375 ast_copy_string(thread->curfunc, funcname, sizeof(thread->curfunc));
01376 #endif
01377 signal_condition(&thread->lock, &thread->cond);
01378 return 0;
01379 }
01380 time(&t);
01381 if (t != lasterror)
01382 ast_debug(1, "Out of idle IAX2 threads for scheduling!\n");
01383 lasterror = t;
01384
01385 return -1;
01386 }
01387 #define schedule_action(func, data) __schedule_action(func, data, __PRETTY_FUNCTION__)
01388 #endif
01389
01390 static int iax2_sched_replace(int id, struct ast_sched_thread *st, int when,
01391 ast_sched_cb callback, const void *data)
01392 {
01393 ast_sched_thread_del(st, id);
01394
01395 return ast_sched_thread_add(st, when, callback, data);
01396 }
01397
01398 static int iax2_sched_add(struct ast_sched_thread *st, int when,
01399 ast_sched_cb callback, const void *data)
01400 {
01401 return ast_sched_thread_add(st, when, callback, data);
01402 }
01403
01404 static int send_ping(const void *data);
01405
01406 static void __send_ping(const void *data)
01407 {
01408 int callno = (long) data;
01409
01410 ast_mutex_lock(&iaxsl[callno]);
01411
01412 if (iaxs[callno]) {
01413 if (iaxs[callno]->peercallno) {
01414 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PING, 0, NULL, 0, -1);
01415 iaxs[callno]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, data);
01416 } else {
01417
01418 iaxs[callno]->pingid = -1;
01419 }
01420 } else {
01421 ast_debug(1, "I was supposed to send a PING with callno %d, but no such call exists.\n", callno);
01422 }
01423
01424 ast_mutex_unlock(&iaxsl[callno]);
01425 }
01426
01427 static int send_ping(const void *data)
01428 {
01429 #ifdef SCHED_MULTITHREADED
01430 if (schedule_action(__send_ping, data))
01431 #endif
01432 __send_ping(data);
01433
01434 return 0;
01435 }
01436
01437 static void encmethods_to_str(int e, struct ast_str *buf)
01438 {
01439 ast_str_set(&buf, 0, "(");
01440 if (e & IAX_ENCRYPT_AES128) {
01441 ast_str_append(&buf, 0, "aes128");
01442 }
01443 if (e & IAX_ENCRYPT_KEYROTATE) {
01444 ast_str_append(&buf, 0, ",keyrotate");
01445 }
01446 if (ast_str_strlen(buf) > 1) {
01447 ast_str_append(&buf, 0, ")");
01448 } else {
01449 ast_str_set(&buf, 0, "No");
01450 }
01451 }
01452
01453 static int get_encrypt_methods(const char *s)
01454 {
01455 int e;
01456 if (!strcasecmp(s, "aes128"))
01457 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01458 else if (ast_true(s))
01459 e = IAX_ENCRYPT_AES128 | IAX_ENCRYPT_KEYROTATE;
01460 else
01461 e = 0;
01462 return e;
01463 }
01464
01465 static int send_lagrq(const void *data);
01466
01467 static void __send_lagrq(const void *data)
01468 {
01469 int callno = (long) data;
01470
01471 ast_mutex_lock(&iaxsl[callno]);
01472
01473 if (iaxs[callno]) {
01474 if (iaxs[callno]->peercallno) {
01475 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_LAGRQ, 0, NULL, 0, -1);
01476 iaxs[callno]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, data);
01477 } else {
01478
01479 iaxs[callno]->lagid = -1;
01480 }
01481 } else {
01482 ast_debug(1, "I was supposed to send a LAGRQ with callno %d, but no such call exists.\n", callno);
01483 }
01484
01485 ast_mutex_unlock(&iaxsl[callno]);
01486 }
01487
01488 static int send_lagrq(const void *data)
01489 {
01490 #ifdef SCHED_MULTITHREADED
01491 if (schedule_action(__send_lagrq, data))
01492 #endif
01493 __send_lagrq(data);
01494
01495 return 0;
01496 }
01497
01498 static unsigned char compress_subclass(int subclass)
01499 {
01500 int x;
01501 int power=-1;
01502
01503 if (subclass < IAX_FLAG_SC_LOG)
01504 return subclass;
01505
01506 for (x = 0; x < IAX_MAX_SHIFT; x++) {
01507 if (subclass & (1 << x)) {
01508 if (power > -1) {
01509 ast_log(LOG_WARNING, "Can't compress subclass %d\n", subclass);
01510 return 0;
01511 } else
01512 power = x;
01513 }
01514 }
01515 return power | IAX_FLAG_SC_LOG;
01516 }
01517
01518 static int uncompress_subclass(unsigned char csub)
01519 {
01520
01521 if (csub & IAX_FLAG_SC_LOG) {
01522
01523 if (csub == 0xff)
01524 return -1;
01525 else
01526 return 1 << (csub & ~IAX_FLAG_SC_LOG & IAX_MAX_SHIFT);
01527 }
01528 else
01529 return csub;
01530 }
01531
01532
01533
01534
01535 static int peer_hash_cb(const void *obj, const int flags)
01536 {
01537 const struct iax2_peer *peer = obj;
01538
01539 return ast_str_hash(peer->name);
01540 }
01541
01542
01543
01544
01545 static int peer_cmp_cb(void *obj, void *arg, int flags)
01546 {
01547 struct iax2_peer *peer = obj, *peer2 = arg;
01548
01549 return !strcmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01550 }
01551
01552
01553
01554
01555 static int user_hash_cb(const void *obj, const int flags)
01556 {
01557 const struct iax2_user *user = obj;
01558
01559 return ast_str_hash(user->name);
01560 }
01561
01562
01563
01564
01565 static int user_cmp_cb(void *obj, void *arg, int flags)
01566 {
01567 struct iax2_user *user = obj, *user2 = arg;
01568
01569 return !strcmp(user->name, user2->name) ? CMP_MATCH | CMP_STOP : 0;
01570 }
01571
01572
01573
01574
01575
01576 static struct iax2_peer *find_peer(const char *name, int realtime)
01577 {
01578 struct iax2_peer *peer = NULL;
01579 struct iax2_peer tmp_peer = {
01580 .name = name,
01581 };
01582
01583 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
01584
01585
01586 if(!peer && realtime)
01587 peer = realtime_peer(name, NULL);
01588
01589 return peer;
01590 }
01591
01592 static struct iax2_peer *peer_ref(struct iax2_peer *peer)
01593 {
01594 ao2_ref(peer, +1);
01595 return peer;
01596 }
01597
01598 static inline struct iax2_peer *peer_unref(struct iax2_peer *peer)
01599 {
01600 ao2_ref(peer, -1);
01601 return NULL;
01602 }
01603
01604 static struct iax2_user *find_user(const char *name)
01605 {
01606 struct iax2_user tmp_user = {
01607 .name = name,
01608 };
01609
01610 return ao2_find(users, &tmp_user, OBJ_POINTER);
01611 }
01612 static inline struct iax2_user *user_ref(struct iax2_user *user)
01613 {
01614 ao2_ref(user, +1);
01615 return user;
01616 }
01617
01618 static inline struct iax2_user *user_unref(struct iax2_user *user)
01619 {
01620 ao2_ref(user, -1);
01621 return NULL;
01622 }
01623
01624 static int iax2_getpeername(struct sockaddr_in sin, char *host, int len)
01625 {
01626 struct iax2_peer *peer = NULL;
01627 int res = 0;
01628 struct ao2_iterator i;
01629
01630 i = ao2_iterator_init(peers, 0);
01631 while ((peer = ao2_iterator_next(&i))) {
01632 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
01633 (peer->addr.sin_port == sin.sin_port)) {
01634 ast_copy_string(host, peer->name, len);
01635 peer_unref(peer);
01636 res = 1;
01637 break;
01638 }
01639 peer_unref(peer);
01640 }
01641 ao2_iterator_destroy(&i);
01642
01643 if (!peer) {
01644 peer = realtime_peer(NULL, &sin);
01645 if (peer) {
01646 ast_copy_string(host, peer->name, len);
01647 peer_unref(peer);
01648 res = 1;
01649 }
01650 }
01651
01652 return res;
01653 }
01654
01655
01656
01657 static void iax2_destroy_helper(struct chan_iax2_pvt *pvt)
01658 {
01659
01660 if (ast_test_flag(pvt, IAX_MAXAUTHREQ)) {
01661 struct iax2_user *user;
01662 struct iax2_user tmp_user = {
01663 .name = pvt->username,
01664 };
01665
01666 user = ao2_find(users, &tmp_user, OBJ_POINTER);
01667 if (user) {
01668 ast_atomic_fetchadd_int(&user->curauthreq, -1);
01669 user_unref(user);
01670 }
01671
01672 ast_clear_flag(pvt, IAX_MAXAUTHREQ);
01673 }
01674
01675 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->pingid, &iaxsl[pvt->callno]);
01676 AST_SCHED_DEL_SPINLOCK(ast_sched_thread_get_context(sched), pvt->lagid, &iaxsl[pvt->callno]);
01677 ast_sched_thread_del(sched, pvt->autoid);
01678 ast_sched_thread_del(sched, pvt->authid);
01679 ast_sched_thread_del(sched, pvt->initid);
01680 ast_sched_thread_del(sched, pvt->jbid);
01681 ast_sched_thread_del(sched, pvt->keyrotateid);
01682 }
01683
01684 static void iax2_frame_free(struct iax_frame *fr)
01685 {
01686 ast_sched_thread_del(sched, fr->retrans);
01687 iax_frame_free(fr);
01688 }
01689
01690 static int scheduled_destroy(const void *vid)
01691 {
01692 unsigned short callno = PTR_TO_CALLNO(vid);
01693 ast_mutex_lock(&iaxsl[callno]);
01694 if (iaxs[callno]) {
01695 if (option_debug) {
01696 ast_log(LOG_DEBUG, "Really destroying %d now...\n", callno);
01697 }
01698 iax2_destroy(callno);
01699 }
01700 ast_mutex_unlock(&iaxsl[callno]);
01701 return 0;
01702 }
01703
01704 static void free_signaling_queue_entry(struct signaling_queue_entry *s)
01705 {
01706 ast_free(s->f.data.ptr);
01707 ast_free(s);
01708 }
01709
01710
01711
01712 static void send_signaling(struct chan_iax2_pvt *pvt)
01713 {
01714 struct signaling_queue_entry *s = NULL;
01715
01716 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01717 iax2_send(pvt, &s->f, 0, -1, 0, 0, 0);
01718 free_signaling_queue_entry(s);
01719 }
01720 pvt->hold_signaling = 0;
01721 }
01722
01723
01724
01725 static int queue_signalling(struct chan_iax2_pvt *pvt, struct ast_frame *f)
01726 {
01727 struct signaling_queue_entry *new;
01728
01729 if (f->frametype == AST_FRAME_IAX || !pvt->hold_signaling) {
01730 return 1;
01731 } else if (!(new = ast_calloc(1, sizeof(struct signaling_queue_entry)))) {
01732 return -1;
01733 }
01734
01735 memcpy(&new->f, f, sizeof(new->f));
01736
01737 if (new->f.datalen) {
01738 if (!(new->f.data.ptr = ast_calloc(1, new->f.datalen))) {
01739 free_signaling_queue_entry(new);
01740 return -1;
01741 }
01742 memcpy(new->f.data.ptr, f->data.ptr, sizeof(*new->f.data.ptr));
01743 }
01744 AST_LIST_INSERT_TAIL(&pvt->signaling_queue, new, next);
01745
01746 return 0;
01747 }
01748
01749 static void pvt_destructor(void *obj)
01750 {
01751 struct chan_iax2_pvt *pvt = obj;
01752 struct iax_frame *cur = NULL;
01753 struct signaling_queue_entry *s = NULL;
01754
01755 ast_mutex_lock(&iaxsl[pvt->callno]);
01756 iax2_destroy_helper(pvt);
01757 sched_delay_remove(&pvt->addr, pvt->callno_entry);
01758 pvt->callno_entry = NULL;
01759 ast_mutex_unlock(&iaxsl[pvt->callno]);
01760
01761
01762 ast_set_flag(pvt, IAX_ALREADYGONE);
01763
01764 AST_LIST_LOCK(&frame_queue);
01765 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
01766
01767 if (cur->callno == pvt->callno) {
01768 cur->retries = -1;
01769 }
01770 }
01771 AST_LIST_UNLOCK(&frame_queue);
01772
01773 while ((s = AST_LIST_REMOVE_HEAD(&pvt->signaling_queue, next))) {
01774 free_signaling_queue_entry(s);
01775 }
01776
01777 if (pvt->reg) {
01778 pvt->reg->callno = 0;
01779 }
01780
01781 if (!pvt->owner) {
01782 jb_frame frame;
01783 if (pvt->vars) {
01784 ast_variables_destroy(pvt->vars);
01785 pvt->vars = NULL;
01786 }
01787
01788 while (jb_getall(pvt->jb, &frame) == JB_OK) {
01789 iax2_frame_free(frame.data);
01790 }
01791
01792 jb_destroy(pvt->jb);
01793 ast_string_field_free_memory(pvt);
01794 }
01795 }
01796
01797 static struct chan_iax2_pvt *new_iax(struct sockaddr_in *sin, const char *host)
01798 {
01799 struct chan_iax2_pvt *tmp;
01800 jb_conf jbconf;
01801
01802 if (!(tmp = ao2_alloc(sizeof(*tmp), pvt_destructor))) {
01803 return NULL;
01804 }
01805
01806 if (ast_string_field_init(tmp, 32)) {
01807 ao2_ref(tmp, -1);
01808 tmp = NULL;
01809 return NULL;
01810 }
01811
01812 tmp->prefs = prefs;
01813 tmp->pingid = -1;
01814 tmp->lagid = -1;
01815 tmp->autoid = -1;
01816 tmp->authid = -1;
01817 tmp->initid = -1;
01818 tmp->keyrotateid = -1;
01819
01820 ast_string_field_set(tmp,exten, "s");
01821 ast_string_field_set(tmp,host, host);
01822
01823 tmp->jb = jb_new();
01824 tmp->jbid = -1;
01825 jbconf.max_jitterbuf = maxjitterbuffer;
01826 jbconf.resync_threshold = resyncthreshold;
01827 jbconf.max_contig_interp = maxjitterinterps;
01828 jbconf.target_extra = jittertargetextra;
01829 jb_setconf(tmp->jb,&jbconf);
01830
01831 AST_LIST_HEAD_INIT_NOLOCK(&tmp->dpentries);
01832
01833 tmp->hold_signaling = 1;
01834 AST_LIST_HEAD_INIT_NOLOCK(&tmp->signaling_queue);
01835
01836 return tmp;
01837 }
01838
01839 static struct iax_frame *iaxfrdup2(struct iax_frame *fr)
01840 {
01841 struct iax_frame *new = iax_frame_new(DIRECTION_INGRESS, fr->af.datalen, fr->cacheable);
01842 if (new) {
01843 size_t afdatalen = new->afdatalen;
01844 memcpy(new, fr, sizeof(*new));
01845 iax_frame_wrap(new, &fr->af);
01846 new->afdatalen = afdatalen;
01847 new->data = NULL;
01848 new->datalen = 0;
01849 new->direction = DIRECTION_INGRESS;
01850 new->retrans = -1;
01851 }
01852 return new;
01853 }
01854
01855
01856 enum {
01857
01858 NEW_PREVENT = 0,
01859
01860 NEW_ALLOW = 1,
01861
01862 NEW_FORCE = 2,
01863
01864
01865 NEW_ALLOW_CALLTOKEN_VALIDATED = 3,
01866 };
01867
01868 static int match(struct sockaddr_in *sin, unsigned short callno, unsigned short dcallno, const struct chan_iax2_pvt *cur, int check_dcallno)
01869 {
01870 if ((cur->addr.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01871 (cur->addr.sin_port == sin->sin_port)) {
01872
01873 if ( (cur->peercallno == 0 || cur->peercallno == callno) &&
01874 (check_dcallno ? dcallno == cur->callno : 1) ) {
01875
01876 return 1;
01877 }
01878 }
01879 if ((cur->transfer.sin_addr.s_addr == sin->sin_addr.s_addr) &&
01880 (cur->transfer.sin_port == sin->sin_port) && (cur->transferring)) {
01881
01882 if ((dcallno == cur->callno) || (cur->transferring == TRANSFER_MEDIAPASS && cur->transfercallno == callno))
01883 return 1;
01884 }
01885 return 0;
01886 }
01887
01888 static void update_max_trunk(void)
01889 {
01890 int max = TRUNK_CALL_START;
01891 int x;
01892
01893
01894 for (x = TRUNK_CALL_START; x < ARRAY_LEN(iaxs) - 1; x++) {
01895 if (iaxs[x]) {
01896 max = x + 1;
01897 }
01898 }
01899
01900 maxtrunkcall = max;
01901 if (iaxdebug)
01902 ast_debug(1, "New max trunk callno is %d\n", max);
01903 }
01904
01905 static void update_max_nontrunk(void)
01906 {
01907 int max = 1;
01908 int x;
01909
01910 for (x=1;x<TRUNK_CALL_START - 1; x++) {
01911 if (iaxs[x])
01912 max = x + 1;
01913 }
01914 maxnontrunkcall = max;
01915 if (iaxdebug)
01916 ast_debug(1, "New max nontrunk callno is %d\n", max);
01917 }
01918
01919 static int make_trunk(unsigned short callno, int locked)
01920 {
01921 int x;
01922 int res= 0;
01923 struct callno_entry *callno_entry;
01924 if (iaxs[callno]->oseqno) {
01925 ast_log(LOG_WARNING, "Can't make trunk once a call has started!\n");
01926 return -1;
01927 }
01928 if (callno & TRUNK_CALL_START) {
01929 ast_log(LOG_WARNING, "Call %d is already a trunk\n", callno);
01930 return -1;
01931 }
01932
01933 if (!(callno_entry = get_unused_callno(1, iaxs[callno]->callno_entry->validated))) {
01934 ast_log(LOG_WARNING, "Unable to trunk call: Insufficient space\n");
01935 return -1;
01936 }
01937
01938 x = callno_entry->callno;
01939 ast_mutex_lock(&iaxsl[x]);
01940
01941
01942
01943
01944
01945 ast_sched_thread_del(sched, iaxs[callno]->pingid);
01946 ast_sched_thread_del(sched, iaxs[callno]->lagid);
01947 iaxs[x] = iaxs[callno];
01948 iaxs[x]->callno = x;
01949
01950
01951
01952 if (iaxs[x]->callno_entry) {
01953 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, iaxs[x]->callno_entry);
01954 }
01955 iaxs[x]->callno_entry = callno_entry;
01956
01957 iaxs[callno] = NULL;
01958
01959 iaxs[x]->pingid = iax2_sched_add(sched,
01960 ping_time * 1000, send_ping, (void *)(long)x);
01961 iaxs[x]->lagid = iax2_sched_add(sched,
01962 lagrq_time * 1000, send_lagrq, (void *)(long)x);
01963
01964 if (locked)
01965 ast_mutex_unlock(&iaxsl[callno]);
01966 res = x;
01967 if (!locked)
01968 ast_mutex_unlock(&iaxsl[x]);
01969
01970 ast_debug(1, "Made call %d into trunk call %d\n", callno, x);
01971
01972 update_max_trunk();
01973 update_max_nontrunk();
01974 return res;
01975 }
01976
01977 static void store_by_transfercallno(struct chan_iax2_pvt *pvt)
01978 {
01979 if (!pvt->transfercallno) {
01980 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
01981 return;
01982 }
01983
01984 ao2_link(iax_transfercallno_pvts, pvt);
01985 }
01986
01987 static void remove_by_transfercallno(struct chan_iax2_pvt *pvt)
01988 {
01989 if (!pvt->transfercallno) {
01990 ast_log(LOG_ERROR, "This should not be called without a transfer call number.\n");
01991 return;
01992 }
01993
01994 ao2_unlink(iax_transfercallno_pvts, pvt);
01995 }
01996 static void store_by_peercallno(struct chan_iax2_pvt *pvt)
01997 {
01998 if (!pvt->peercallno) {
01999 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02000 return;
02001 }
02002
02003 ao2_link(iax_peercallno_pvts, pvt);
02004 }
02005
02006 static void remove_by_peercallno(struct chan_iax2_pvt *pvt)
02007 {
02008 if (!pvt->peercallno) {
02009 ast_log(LOG_ERROR, "This should not be called without a peer call number.\n");
02010 return;
02011 }
02012
02013 ao2_unlink(iax_peercallno_pvts, pvt);
02014 }
02015
02016 static int addr_range_delme_cb(void *obj, void *arg, int flags)
02017 {
02018 struct addr_range *lim = obj;
02019 lim->delme = 1;
02020 return 0;
02021 }
02022
02023 static int addr_range_hash_cb(const void *obj, const int flags)
02024 {
02025 const struct addr_range *lim = obj;
02026 return abs((int) lim->ha.netaddr.s_addr);
02027 }
02028
02029 static int addr_range_cmp_cb(void *obj, void *arg, int flags)
02030 {
02031 struct addr_range *lim1 = obj, *lim2 = arg;
02032 return ((lim1->ha.netaddr.s_addr == lim2->ha.netaddr.s_addr) &&
02033 (lim1->ha.netmask.s_addr == lim2->ha.netmask.s_addr)) ?
02034 CMP_MATCH | CMP_STOP : 0;
02035 }
02036
02037 static int peercnt_hash_cb(const void *obj, const int flags)
02038 {
02039 const struct peercnt *peercnt = obj;
02040 return abs((int) peercnt->addr);
02041 }
02042
02043 static int peercnt_cmp_cb(void *obj, void *arg, int flags)
02044 {
02045 struct peercnt *peercnt1 = obj, *peercnt2 = arg;
02046 return (peercnt1->addr == peercnt2->addr) ? CMP_MATCH | CMP_STOP : 0;
02047 }
02048
02049 static int addr_range_match_address_cb(void *obj, void *arg, int flags)
02050 {
02051 struct addr_range *addr_range = obj;
02052 struct sockaddr_in *sin = arg;
02053
02054 if ((sin->sin_addr.s_addr & addr_range->ha.netmask.s_addr) == addr_range->ha.netaddr.s_addr) {
02055 return CMP_MATCH | CMP_STOP;
02056 }
02057 return 0;
02058 }
02059
02060
02061
02062
02063
02064
02065 static int calltoken_required(struct sockaddr_in *sin, const char *name, int subclass)
02066 {
02067 struct addr_range *addr_range;
02068 struct iax2_peer *peer = NULL;
02069 struct iax2_user *user = NULL;
02070
02071 const char *find = S_OR(name, "guest");
02072 int res = 1;
02073 int optional = 0;
02074 enum calltoken_peer_enum calltoken_required = CALLTOKEN_DEFAULT;
02075
02076
02077
02078
02079
02080
02081
02082 if ((addr_range = ao2_callback(calltoken_ignores, 0, addr_range_match_address_cb, sin))) {
02083 ao2_ref(addr_range, -1);
02084 optional = 1;
02085 }
02086
02087
02088 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(find))) {
02089 calltoken_required = user->calltoken_required;
02090 } else if ((subclass == IAX_COMMAND_NEW) && (user = realtime_user(find, sin))) {
02091 calltoken_required = user->calltoken_required;
02092 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(find, 0))) {
02093 calltoken_required = peer->calltoken_required;
02094 } else if ((subclass != IAX_COMMAND_NEW) && (peer = realtime_peer(find, sin))) {
02095 calltoken_required = peer->calltoken_required;
02096 }
02097
02098 if (peer) {
02099 peer_unref(peer);
02100 }
02101 if (user) {
02102 user_unref(user);
02103 }
02104
02105 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);
02106 if (((calltoken_required == CALLTOKEN_NO) || (calltoken_required == CALLTOKEN_AUTO)) ||
02107 (optional && (calltoken_required == CALLTOKEN_DEFAULT))) {
02108 res = 0;
02109 }
02110
02111 return res;
02112 }
02113
02114
02115
02116
02117
02118
02119
02120
02121
02122
02123
02124 static void set_peercnt_limit(struct peercnt *peercnt)
02125 {
02126 uint16_t limit = global_maxcallno;
02127 struct addr_range *addr_range;
02128 struct sockaddr_in sin = {
02129 .sin_addr.s_addr = peercnt->addr,
02130 };
02131
02132
02133 if (peercnt->reg && peercnt->limit) {
02134 return;
02135 }
02136
02137 if ((addr_range = ao2_callback(callno_limits, 0, addr_range_match_address_cb, &sin))) {
02138 limit = addr_range->limit;
02139 ast_debug(1, "custom addr_range %d found for %s\n", limit, ast_inet_ntoa(sin.sin_addr));
02140 ao2_ref(addr_range, -1);
02141 }
02142
02143 peercnt->limit = limit;
02144 }
02145
02146
02147
02148
02149
02150 static int set_peercnt_limit_all_cb(void *obj, void *arg, int flags)
02151 {
02152 struct peercnt *peercnt = obj;
02153
02154 set_peercnt_limit(peercnt);
02155 ast_debug(1, "Reset limits for peercnts table\n");
02156
02157 return 0;
02158 }
02159
02160
02161
02162
02163
02164 static int prune_addr_range_cb(void *obj, void *arg, int flags)
02165 {
02166 struct addr_range *addr_range = obj;
02167
02168 return addr_range->delme ? CMP_MATCH : 0;
02169 }
02170
02171
02172
02173
02174
02175 static void peercnt_modify(unsigned char reg, uint16_t limit, struct sockaddr_in *sin)
02176 {
02177
02178 struct peercnt *peercnt;
02179 struct peercnt tmp = {
02180 .addr = sin->sin_addr.s_addr,
02181 };
02182
02183 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02184 peercnt->reg = reg;
02185 if (limit) {
02186 peercnt->limit = limit;
02187 } else {
02188 set_peercnt_limit(peercnt);
02189 }
02190 ast_debug(1, "peercnt entry %s modified limit:%d registered:%d", ast_inet_ntoa(sin->sin_addr), peercnt->limit, peercnt->reg);
02191 ao2_ref(peercnt, -1);
02192 }
02193 }
02194
02195
02196
02197
02198
02199
02200
02201
02202
02203 static int peercnt_add(struct sockaddr_in *sin)
02204 {
02205 struct peercnt *peercnt;
02206 unsigned long addr = sin->sin_addr.s_addr;
02207 int res = 0;
02208 struct peercnt tmp = {
02209 .addr = addr,
02210 };
02211
02212
02213
02214
02215
02216
02217
02218 ao2_lock(peercnts);
02219 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02220 ao2_lock(peercnt);
02221 } else if ((peercnt = ao2_alloc(sizeof(*peercnt), NULL))) {
02222 ao2_lock(peercnt);
02223
02224 peercnt->addr = addr;
02225 set_peercnt_limit(peercnt);
02226
02227
02228 ao2_link(peercnts, peercnt);
02229 } else {
02230 ao2_unlock(peercnts);
02231 return -1;
02232 }
02233
02234
02235 if (peercnt->limit > peercnt->cur) {
02236 peercnt->cur++;
02237 ast_debug(1, "ip callno count incremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin->sin_addr));
02238 } else {
02239 ast_log(LOG_ERROR, "maxcallnumber limit of %d for %s has been reached!\n", peercnt->limit, ast_inet_ntoa(sin->sin_addr));
02240 res = -1;
02241 }
02242
02243
02244 ao2_unlock(peercnt);
02245 ao2_unlock(peercnts);
02246 ao2_ref(peercnt, -1);
02247
02248 return res;
02249 }
02250
02251
02252
02253
02254
02255 static void peercnt_remove(struct peercnt *peercnt)
02256 {
02257 struct sockaddr_in sin = {
02258 .sin_addr.s_addr = peercnt->addr,
02259 };
02260
02261 if (peercnt) {
02262
02263
02264
02265 ao2_lock(peercnts);
02266 peercnt->cur--;
02267 ast_debug(1, "ip callno count decremented to %d for %s\n", peercnt->cur, ast_inet_ntoa(sin.sin_addr));
02268
02269 if (peercnt->cur == 0) {
02270 ao2_unlink(peercnts, peercnt);
02271 }
02272 ao2_unlock(peercnts);
02273 }
02274 }
02275
02276
02277
02278
02279
02280 static int peercnt_remove_cb(const void *obj)
02281 {
02282 struct peercnt *peercnt = (struct peercnt *) obj;
02283
02284 peercnt_remove(peercnt);
02285 ao2_ref(peercnt, -1);
02286
02287 return 0;
02288 }
02289
02290
02291
02292
02293
02294 static int peercnt_remove_by_addr(struct sockaddr_in *sin)
02295 {
02296 struct peercnt *peercnt;
02297 struct peercnt tmp = {
02298 .addr = sin->sin_addr.s_addr,
02299 };
02300
02301 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02302 peercnt_remove(peercnt);
02303 ao2_ref(peercnt, -1);
02304 }
02305 return 0;
02306 }
02307
02308
02309
02310
02311
02312 static void build_callno_limits(struct ast_variable *v)
02313 {
02314 struct addr_range *addr_range = NULL;
02315 struct addr_range tmp;
02316 struct ast_ha *ha;
02317 int limit;
02318 int error;
02319 int found;
02320
02321 for (; v; v = v->next) {
02322 limit = -1;
02323 error = 0;
02324 found = 0;
02325 ha = ast_append_ha("permit", v->name, NULL, &error);
02326
02327
02328 if (error) {
02329 ast_log(LOG_ERROR, "Call number limit for %s could not be added, Invalid address range\n.", v->name);
02330 continue;
02331 } else if ((sscanf(v->value, "%d", &limit) != 1) || (limit < 0)) {
02332 ast_log(LOG_ERROR, "Call number limit for %s could not be added. Invalid limit %s\n.", v->name, v->value);
02333 ast_free_ha(ha);
02334 continue;
02335 }
02336
02337 ast_copy_ha(ha, &tmp.ha);
02338
02339 if ((addr_range = ao2_find(callno_limits, &tmp, OBJ_POINTER))) {
02340 ao2_lock(addr_range);
02341 found = 1;
02342 } else if (!(addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02343 ast_free_ha(ha);
02344 return;
02345 }
02346
02347
02348 ast_copy_ha(ha, &addr_range->ha);
02349 ast_free_ha(ha);
02350 addr_range->limit = limit;
02351 addr_range->delme = 0;
02352
02353
02354 if (found) {
02355 ao2_unlock(addr_range);
02356 } else {
02357 ao2_link(callno_limits, addr_range);
02358 }
02359 ao2_ref(addr_range, -1);
02360 }
02361 }
02362
02363
02364
02365
02366
02367 static int add_calltoken_ignore(const char *addr)
02368 {
02369 struct addr_range tmp;
02370 struct addr_range *addr_range = NULL;
02371 struct ast_ha *ha = NULL;
02372 int error = 0;
02373
02374 if (ast_strlen_zero(addr)) {
02375 ast_log(LOG_WARNING, "invalid calltokenoptional %s\n", addr);
02376 return -1;
02377 }
02378
02379 ha = ast_append_ha("permit", addr, NULL, &error);
02380
02381
02382 if (error) {
02383 ast_log(LOG_WARNING, "Error %d creating calltokenoptional entry %s\n", error, addr);
02384 return -1;
02385 }
02386
02387 ast_copy_ha(ha, &tmp.ha);
02388
02389 if ((addr_range = ao2_find(calltoken_ignores, &tmp, OBJ_POINTER))) {
02390 ao2_lock(addr_range);
02391 addr_range->delme = 0;
02392 ao2_unlock(addr_range);
02393 } else if ((addr_range = ao2_alloc(sizeof(*addr_range), NULL))) {
02394
02395 ast_copy_ha(ha, &addr_range->ha);
02396 ao2_link(calltoken_ignores, addr_range);
02397 } else {
02398 ast_free_ha(ha);
02399 return -1;
02400 }
02401
02402 ast_free_ha(ha);
02403 ao2_ref(addr_range, -1);
02404
02405 return 0;
02406 }
02407
02408 static char *handle_cli_iax2_show_callno_limits(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
02409 {
02410 struct ao2_iterator i;
02411 struct peercnt *peercnt;
02412 struct sockaddr_in sin;
02413 int found = 0;
02414
02415 switch (cmd) {
02416 case CLI_INIT:
02417 e->command = "iax2 show callnumber usage";
02418 e->usage =
02419 "Usage: iax2 show callnumber usage <ip address (optional)>\n"
02420 " Shows current ip addresses which are consuming iax2 call numbers\n";
02421 return NULL;
02422 case CLI_GENERATE:
02423 return NULL;
02424 case CLI_HANDLER:
02425 if (a->argc < 4 || a->argc > 5)
02426 return CLI_SHOWUSAGE;
02427
02428 ast_cli(a->fd, "%-15s %-12s %-12s\n", "Address", "Callno Usage", "Callno Limit");
02429 i = ao2_iterator_init(peercnts, 0);
02430 while ((peercnt = ao2_iterator_next(&i))) {
02431 sin.sin_addr.s_addr = peercnt->addr;
02432 if (a->argc == 5 && (!strcasecmp(a->argv[4], ast_inet_ntoa(sin.sin_addr)))) {
02433 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02434 found = 1;
02435 break;
02436 } else {
02437 ast_cli(a->fd, "%-15s %-12d %-12d\n", ast_inet_ntoa(sin.sin_addr), peercnt->cur, peercnt->limit);
02438 }
02439 ao2_ref(peercnt, -1);
02440 }
02441 ao2_iterator_destroy(&i);
02442
02443 if (a->argc == 4) {
02444 ast_cli(a->fd, "\nNon-CallToken Validation Limit: %d\nNon-CallToken Validated: %d\n", global_maxcallno_nonval, total_nonval_callno_used);
02445 } else if (a->argc == 5 && !found) {
02446 ast_cli(a->fd, "No callnumber table entries for %s found\n", a->argv[4] );
02447 }
02448
02449 return CLI_SUCCESS;
02450 default:
02451 return NULL;
02452 }
02453 }
02454
02455 static struct callno_entry *get_unused_callno(int trunk, int validated)
02456 {
02457 struct callno_entry *callno_entry = NULL;
02458 if ((!ao2_container_count(callno_pool) && !trunk) || (!ao2_container_count(callno_pool_trunk) && trunk)) {
02459 ast_log(LOG_WARNING, "Out of CallNumbers\n");
02460
02461 return NULL;
02462 }
02463
02464
02465
02466 ao2_lock(callno_pool);
02467
02468
02469
02470
02471 if (!validated && (total_nonval_callno_used >= global_maxcallno_nonval)) {
02472 ast_log(LOG_WARNING, "NON-CallToken callnumber limit is reached. Current:%d Max:%d\n", total_nonval_callno_used, global_maxcallno_nonval);
02473 ao2_unlock(callno_pool);
02474 return NULL;
02475 }
02476
02477
02478
02479 callno_entry = ao2_find((trunk ? callno_pool_trunk : callno_pool), NULL, OBJ_POINTER | OBJ_UNLINK | OBJ_CONTINUE);
02480
02481 if (callno_entry) {
02482 callno_entry->validated = validated;
02483 if (!validated) {
02484 total_nonval_callno_used++;
02485 }
02486 }
02487
02488 ao2_unlock(callno_pool);
02489 return callno_entry;
02490 }
02491
02492 static int replace_callno(const void *obj)
02493 {
02494 struct callno_entry *callno_entry = (struct callno_entry *) obj;
02495
02496
02497
02498 ao2_lock(callno_pool);
02499
02500 if (!callno_entry->validated && (total_nonval_callno_used != 0)) {
02501 total_nonval_callno_used--;
02502 } else if (!callno_entry->validated && (total_nonval_callno_used == 0)) {
02503 ast_log(LOG_ERROR, "Attempted to decrement total non calltoken validated callnumbers below zero... Callno is:%d \n", callno_entry->callno);
02504 }
02505
02506 if (callno_entry->callno < TRUNK_CALL_START) {
02507 ao2_link(callno_pool, callno_entry);
02508 } else {
02509 ao2_link(callno_pool_trunk, callno_entry);
02510 }
02511 ao2_ref(callno_entry, -1);
02512
02513 ao2_unlock(callno_pool);
02514 return 0;
02515 }
02516
02517 static int callno_hash(const void *obj, const int flags)
02518 {
02519 return abs(ast_random());
02520 }
02521
02522 static int create_callno_pools(void)
02523 {
02524 uint16_t i;
02525
02526 if (!(callno_pool = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02527 return -1;
02528 }
02529
02530 if (!(callno_pool_trunk = ao2_container_alloc(CALLNO_POOL_BUCKETS, callno_hash, NULL))) {
02531 return -1;
02532 }
02533
02534
02535 for (i = 2; i <= IAX_MAX_CALLS; i++) {
02536 struct callno_entry *callno_entry;
02537
02538 if (!(callno_entry = ao2_alloc(sizeof(*callno_entry), NULL))) {
02539 return -1;
02540 }
02541
02542 callno_entry->callno = i;
02543
02544 if (i < TRUNK_CALL_START) {
02545 ao2_link(callno_pool, callno_entry);
02546 } else {
02547 ao2_link(callno_pool_trunk, callno_entry);
02548 }
02549
02550 ao2_ref(callno_entry, -1);
02551 }
02552
02553 return 0;
02554 }
02555
02556
02557
02558
02559
02560
02561
02562
02563
02564 static void sched_delay_remove(struct sockaddr_in *sin, struct callno_entry *callno_entry)
02565 {
02566 int i;
02567 struct peercnt *peercnt;
02568 struct peercnt tmp = {
02569 .addr = sin->sin_addr.s_addr,
02570 };
02571
02572 if ((peercnt = ao2_find(peercnts, &tmp, OBJ_POINTER))) {
02573
02574 ast_debug(1, "schedule decrement of callno used for %s in %d seconds\n", ast_inet_ntoa(sin->sin_addr), MIN_REUSE_TIME);
02575 i = iax2_sched_add(sched, MIN_REUSE_TIME * 1000, peercnt_remove_cb, peercnt);
02576 if (i == -1) {
02577 ao2_ref(peercnt, -1);
02578 }
02579 }
02580
02581 iax2_sched_add(sched, MIN_REUSE_TIME * 1000, replace_callno, callno_entry);
02582 }
02583
02584
02585
02586
02587
02588
02589
02590
02591 static inline int attribute_pure iax2_allow_new(int frametype, int subclass, int inbound)
02592 {
02593 if (frametype != AST_FRAME_IAX) {
02594 return 0;
02595 }
02596 switch (subclass) {
02597 case IAX_COMMAND_NEW:
02598 case IAX_COMMAND_REGREQ:
02599 case IAX_COMMAND_FWDOWNL:
02600 case IAX_COMMAND_REGREL:
02601 return 1;
02602 case IAX_COMMAND_POKE:
02603 if (!inbound) {
02604 return 1;
02605 }
02606 break;
02607 }
02608 return 0;
02609 }
02610
02611
02612
02613
02614 static int __find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int return_locked, int check_dcallno)
02615 {
02616 int res = 0;
02617 int x;
02618
02619
02620 int validated = (new > NEW_ALLOW) ? 1 : 0;
02621 char host[80];
02622
02623 if (new <= NEW_ALLOW) {
02624 if (callno) {
02625 struct chan_iax2_pvt *pvt;
02626 struct chan_iax2_pvt tmp_pvt = {
02627 .callno = dcallno,
02628 .peercallno = callno,
02629 .transfercallno = callno,
02630
02631 .frames_received = check_dcallno,
02632 };
02633
02634 memcpy(&tmp_pvt.addr, sin, sizeof(tmp_pvt.addr));
02635
02636 if ((pvt = ao2_find(iax_peercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02637 if (return_locked) {
02638 ast_mutex_lock(&iaxsl[pvt->callno]);
02639 }
02640 res = pvt->callno;
02641 ao2_ref(pvt, -1);
02642 pvt = NULL;
02643 return res;
02644 }
02645
02646 memset(&tmp_pvt.addr, 0, sizeof(tmp_pvt.addr));
02647 memcpy(&tmp_pvt.transfer, sin, sizeof(tmp_pvt.transfer));
02648 if ((pvt = ao2_find(iax_transfercallno_pvts, &tmp_pvt, OBJ_POINTER))) {
02649 if (return_locked) {
02650 ast_mutex_lock(&iaxsl[pvt->callno]);
02651 }
02652 res = pvt->callno;
02653 ao2_ref(pvt, -1);
02654 pvt = NULL;
02655 return res;
02656 }
02657 }
02658
02659
02660 if (dcallno) {
02661 ast_mutex_lock(&iaxsl[dcallno]);
02662 }
02663 if (callno && dcallno && iaxs[dcallno] && !iaxs[dcallno]->peercallno && match(sin, callno, dcallno, iaxs[dcallno], check_dcallno)) {
02664 iaxs[dcallno]->peercallno = callno;
02665 res = dcallno;
02666 store_by_peercallno(iaxs[dcallno]);
02667 if (!res || !return_locked) {
02668 ast_mutex_unlock(&iaxsl[dcallno]);
02669 }
02670 return res;
02671 }
02672 if (dcallno) {
02673 ast_mutex_unlock(&iaxsl[dcallno]);
02674 }
02675 #ifdef IAX_OLD_FIND
02676
02677
02678
02679
02680
02681
02682
02683
02684
02685
02686
02687 for (x = 1; !res && x < maxnontrunkcall; x++) {
02688 ast_mutex_lock(&iaxsl[x]);
02689 if (iaxs[x]) {
02690
02691 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02692 res = x;
02693 }
02694 }
02695 if (!res || !return_locked)
02696 ast_mutex_unlock(&iaxsl[x]);
02697 }
02698 for (x = TRUNK_CALL_START; !res && x < maxtrunkcall; x++) {
02699 ast_mutex_lock(&iaxsl[x]);
02700 if (iaxs[x]) {
02701
02702 if (match(sin, callno, dcallno, iaxs[x], check_dcallno)) {
02703 res = x;
02704 }
02705 }
02706 if (!res || !return_locked)
02707 ast_mutex_unlock(&iaxsl[x]);
02708 }
02709 #endif
02710 }
02711 if (!res && (new >= NEW_ALLOW)) {
02712 struct callno_entry *callno_entry;
02713
02714
02715
02716
02717
02718
02719 if (!iax2_getpeername(*sin, host, sizeof(host)))
02720 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
02721
02722 if (peercnt_add(sin)) {
02723
02724
02725 return 0;
02726 }
02727
02728 if (!(callno_entry = get_unused_callno(0, validated))) {
02729
02730
02731 peercnt_remove_by_addr(sin);
02732 ast_log(LOG_WARNING, "No more space\n");
02733 return 0;
02734 }
02735 x = callno_entry->callno;
02736 ast_mutex_lock(&iaxsl[x]);
02737
02738 iaxs[x] = new_iax(sin, host);
02739 update_max_nontrunk();
02740 if (iaxs[x]) {
02741 if (iaxdebug)
02742 ast_debug(1, "Creating new call structure %d\n", x);
02743 iaxs[x]->callno_entry = callno_entry;
02744 iaxs[x]->sockfd = sockfd;
02745 iaxs[x]->addr.sin_port = sin->sin_port;
02746 iaxs[x]->addr.sin_family = sin->sin_family;
02747 iaxs[x]->addr.sin_addr.s_addr = sin->sin_addr.s_addr;
02748 iaxs[x]->peercallno = callno;
02749 iaxs[x]->callno = x;
02750 iaxs[x]->pingtime = DEFAULT_RETRY_TIME;
02751 iaxs[x]->expiry = min_reg_expire;
02752 iaxs[x]->pingid = iax2_sched_add(sched, ping_time * 1000, send_ping, (void *)(long)x);
02753 iaxs[x]->lagid = iax2_sched_add(sched, lagrq_time * 1000, send_lagrq, (void *)(long)x);
02754 iaxs[x]->amaflags = amaflags;
02755 ast_copy_flags(iaxs[x], &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT);
02756 ast_string_field_set(iaxs[x], accountcode, accountcode);
02757 ast_string_field_set(iaxs[x], mohinterpret, mohinterpret);
02758 ast_string_field_set(iaxs[x], mohsuggest, mohsuggest);
02759 ast_string_field_set(iaxs[x], parkinglot, default_parkinglot);
02760
02761 if (iaxs[x]->peercallno) {
02762 store_by_peercallno(iaxs[x]);
02763 }
02764 } else {
02765 ast_log(LOG_WARNING, "Out of resources\n");
02766 ast_mutex_unlock(&iaxsl[x]);
02767 replace_callno(callno_entry);
02768 return 0;
02769 }
02770 if (!return_locked)
02771 ast_mutex_unlock(&iaxsl[x]);
02772 res = x;
02773 }
02774 return res;
02775 }
02776
02777 static int find_callno(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02778
02779 return __find_callno(callno, dcallno, sin, new, sockfd, 0, full_frame);
02780 }
02781
02782 static int find_callno_locked(unsigned short callno, unsigned short dcallno, struct sockaddr_in *sin, int new, int sockfd, int full_frame) {
02783
02784 return __find_callno(callno, dcallno, sin, new, sockfd, 1, full_frame);
02785 }
02786
02787
02788
02789
02790
02791
02792
02793
02794
02795
02796
02797 static int iax2_queue_frame(int callno, struct ast_frame *f)
02798 {
02799 iax2_lock_owner(callno);
02800 if (iaxs[callno] && iaxs[callno]->owner) {
02801 ast_queue_frame(iaxs[callno]->owner, f);
02802 ast_channel_unlock(iaxs[callno]->owner);
02803 }
02804 return 0;
02805 }
02806
02807
02808
02809
02810
02811
02812
02813
02814
02815
02816
02817
02818
02819
02820 static int iax2_queue_hangup(int callno)
02821 {
02822 iax2_lock_owner(callno);
02823 if (iaxs[callno] && iaxs[callno]->owner) {
02824 ast_queue_hangup(iaxs[callno]->owner);
02825 ast_channel_unlock(iaxs[callno]->owner);
02826 }
02827 return 0;
02828 }
02829
02830
02831
02832
02833
02834
02835
02836
02837
02838
02839
02840
02841
02842
02843 static int iax2_queue_control_data(int callno,
02844 enum ast_control_frame_type control, const void *data, size_t datalen)
02845 {
02846 iax2_lock_owner(callno);
02847 if (iaxs[callno] && iaxs[callno]->owner) {
02848 ast_queue_control_data(iaxs[callno]->owner, control, data, datalen);
02849 ast_channel_unlock(iaxs[callno]->owner);
02850 }
02851 return 0;
02852 }
02853 static void destroy_firmware(struct iax_firmware *cur)
02854 {
02855
02856 if (cur->fwh) {
02857 munmap((void*)cur->fwh, ntohl(cur->fwh->datalen) + sizeof(*(cur->fwh)));
02858 }
02859 close(cur->fd);
02860 ast_free(cur);
02861 }
02862
02863 static int try_firmware(char *s)
02864 {
02865 struct stat stbuf;
02866 struct iax_firmware *cur = NULL;
02867 int ifd, fd, res, len, chunk;
02868 struct ast_iax2_firmware_header *fwh, fwh2;
02869 struct MD5Context md5;
02870 unsigned char sum[16], buf[1024];
02871 char *s2, *last;
02872
02873 if (!(s2 = alloca(strlen(s) + 100))) {
02874 ast_log(LOG_WARNING, "Alloca failed!\n");
02875 return -1;
02876 }
02877
02878 last = strrchr(s, '/');
02879 if (last)
02880 last++;
02881 else
02882 last = s;
02883
02884 snprintf(s2, strlen(s) + 100, "/var/tmp/%s-%ld", last, (unsigned long)ast_random());
02885
02886 if ((res = stat(s, &stbuf) < 0)) {
02887 ast_log(LOG_WARNING, "Failed to stat '%s': %s\n", s, strerror(errno));
02888 return -1;
02889 }
02890
02891
02892 if (S_ISDIR(stbuf.st_mode))
02893 return -1;
02894 ifd = open(s, O_RDONLY);
02895 if (ifd < 0) {
02896 ast_log(LOG_WARNING, "Cannot open '%s': %s\n", s, strerror(errno));
02897 return -1;
02898 }
02899 fd = open(s2, O_RDWR | O_CREAT | O_EXCL, AST_FILE_MODE);
02900 if (fd < 0) {
02901 ast_log(LOG_WARNING, "Cannot open '%s' for writing: %s\n", s2, strerror(errno));
02902 close(ifd);
02903 return -1;
02904 }
02905
02906 unlink(s2);
02907
02908
02909 len = stbuf.st_size;
02910 while(len) {
02911 chunk = len;
02912 if (chunk > sizeof(buf))
02913 chunk = sizeof(buf);
02914 res = read(ifd, buf, chunk);
02915 if (res != chunk) {
02916 ast_log(LOG_WARNING, "Only read %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
02917 close(ifd);
02918 close(fd);
02919 return -1;
02920 }
02921 res = write(fd, buf, chunk);
02922 if (res != chunk) {
02923 ast_log(LOG_WARNING, "Only write %d of %d bytes of data :(: %s\n", res, chunk, strerror(errno));
02924 close(ifd);
02925 close(fd);
02926 return -1;
02927 }
02928 len -= chunk;
02929 }
02930 close(ifd);
02931
02932 lseek(fd, 0, SEEK_SET);
02933 if ((res = read(fd, &fwh2, sizeof(fwh2))) != sizeof(fwh2)) {
02934 ast_log(LOG_WARNING, "Unable to read firmware header in '%s'\n", s);
02935 close(fd);
02936 return -1;
02937 }
02938 if (ntohl(fwh2.magic) != IAX_FIRMWARE_MAGIC) {
02939 ast_log(LOG_WARNING, "'%s' is not a valid firmware file\n", s);
02940 close(fd);
02941 return -1;
02942 }
02943 if (ntohl(fwh2.datalen) != (stbuf.st_size - sizeof(fwh2))) {
02944 ast_log(LOG_WARNING, "Invalid data length in firmware '%s'\n", s);
02945 close(fd);
02946 return -1;
02947 }
02948 if (fwh2.devname[sizeof(fwh2.devname) - 1] || ast_strlen_zero((char *)fwh2.devname)) {
02949 ast_log(LOG_WARNING, "No or invalid device type specified for '%s'\n", s);
02950 close(fd);
02951 return -1;
02952 }
02953 fwh = (struct ast_iax2_firmware_header*)mmap(NULL, stbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
02954 if (fwh == (void *) -1) {
02955 ast_log(LOG_WARNING, "mmap failed: %s\n", strerror(errno));
02956 close(fd);
02957 return -1;
02958 }
02959 MD5Init(&md5);
02960 MD5Update(&md5, fwh->data, ntohl(fwh->datalen));
02961 MD5Final(sum, &md5);
02962 if (memcmp(sum, fwh->chksum, sizeof(sum))) {
02963 ast_log(LOG_WARNING, "Firmware file '%s' fails checksum\n", s);
02964 munmap((void*)fwh, stbuf.st_size);
02965 close(fd);
02966 return -1;
02967 }
02968
02969 AST_LIST_TRAVERSE(&firmwares, cur, list) {
02970 if (!strcmp((char *)cur->fwh->devname, (char *)fwh->devname)) {
02971
02972 if (cur->dead || (ntohs(cur->fwh->version) < ntohs(fwh->version)))
02973
02974 break;
02975
02976
02977 munmap((void*)fwh, stbuf.st_size);
02978 close(fd);
02979 return 0;
02980 }
02981 }
02982
02983 if (!cur && ((cur = ast_calloc(1, sizeof(*cur))))) {
02984 cur->fd = -1;
02985 AST_LIST_INSERT_TAIL(&firmwares, cur, list);
02986 }
02987
02988 if (cur) {
02989 if (cur->fwh)
02990 munmap((void*)cur->fwh, cur->mmaplen);
02991 if (cur->fd > -1)
02992 close(cur->fd);
02993 cur->fwh = fwh;
02994 cur->fd = fd;
02995 cur->mmaplen = stbuf.st_size;
02996 cur->dead = 0;
02997 }
02998
02999 return 0;
03000 }
03001
03002 static int iax_check_version(char *dev)
03003 {
03004 int res = 0;
03005 struct iax_firmware *cur = NULL;
03006
03007 if (ast_strlen_zero(dev))
03008 return 0;
03009
03010 AST_LIST_LOCK(&firmwares);
03011 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03012 if (!strcmp(dev, (char *)cur->fwh->devname)) {
03013 res = ntohs(cur->fwh->version);
03014 break;
03015 }
03016 }
03017 AST_LIST_UNLOCK(&firmwares);
03018
03019 return res;
03020 }
03021
03022 static int iax_firmware_append(struct iax_ie_data *ied, const unsigned char *dev, unsigned int desc)
03023 {
03024 int res = -1;
03025 unsigned int bs = desc & 0xff;
03026 unsigned int start = (desc >> 8) & 0xffffff;
03027 unsigned int bytes;
03028 struct iax_firmware *cur;
03029
03030 if (ast_strlen_zero((char *)dev) || !bs)
03031 return -1;
03032
03033 start *= bs;
03034
03035 AST_LIST_LOCK(&firmwares);
03036 AST_LIST_TRAVERSE(&firmwares, cur, list) {
03037 if (strcmp((char *)dev, (char *)cur->fwh->devname))
03038 continue;
03039 iax_ie_append_int(ied, IAX_IE_FWBLOCKDESC, desc);
03040 if (start < ntohl(cur->fwh->datalen)) {
03041 bytes = ntohl(cur->fwh->datalen) - start;
03042 if (bytes > bs)
03043 bytes = bs;
03044 iax_ie_append_raw(ied, IAX_IE_FWBLOCKDATA, cur->fwh->data + start, bytes);
03045 } else {
03046 bytes = 0;
03047 iax_ie_append(ied, IAX_IE_FWBLOCKDATA);
03048 }
03049 if (bytes == bs)
03050 res = 0;
03051 else
03052 res = 1;
03053 break;
03054 }
03055 AST_LIST_UNLOCK(&firmwares);
03056
03057 return res;
03058 }
03059
03060
03061 static void reload_firmware(int unload)
03062 {
03063 struct iax_firmware *cur = NULL;
03064 DIR *fwd;
03065 struct dirent *de;
03066 char dir[256], fn[256];
03067
03068 AST_LIST_LOCK(&firmwares);
03069
03070
03071 AST_LIST_TRAVERSE(&firmwares, cur, list)
03072 cur->dead = 1;
03073
03074
03075 if (!unload) {
03076 snprintf(dir, sizeof(dir), "%s/firmware/iax", ast_config_AST_DATA_DIR);
03077 fwd = opendir(dir);
03078 if (fwd) {
03079 while((de = readdir(fwd))) {
03080 if (de->d_name[0] != '.') {
03081 snprintf(fn, sizeof(fn), "%s/%s", dir, de->d_name);
03082 if (!try_firmware(fn)) {
03083 ast_verb(2, "Loaded firmware '%s'\n", de->d_name);
03084 }
03085 }
03086 }
03087 closedir(fwd);
03088 } else
03089 ast_log(LOG_WARNING, "Error opening firmware directory '%s': %s\n", dir, strerror(errno));
03090 }
03091
03092
03093 AST_LIST_TRAVERSE_SAFE_BEGIN(&firmwares, cur, list) {
03094 if (!cur->dead)
03095 continue;
03096 AST_LIST_REMOVE_CURRENT(list);
03097 destroy_firmware(cur);
03098 }
03099 AST_LIST_TRAVERSE_SAFE_END;
03100
03101 AST_LIST_UNLOCK(&firmwares);
03102 }
03103
03104
03105
03106
03107
03108
03109
03110
03111
03112 static int __do_deliver(void *data)
03113 {
03114
03115
03116 struct iax_frame *fr = data;
03117 fr->retrans = -1;
03118 ast_clear_flag(&fr->af, AST_FRFLAG_HAS_TIMING_INFO);
03119 if (iaxs[fr->callno] && !ast_test_flag(iaxs[fr->callno], IAX_ALREADYGONE))
03120 iax2_queue_frame(fr->callno, &fr->af);
03121
03122 iax2_frame_free(fr);
03123
03124 return 0;
03125 }
03126
03127 static int handle_error(void)
03128 {
03129
03130
03131
03132 #if 0
03133 struct sockaddr_in *sin;
03134 int res;
03135 struct msghdr m;
03136 struct sock_extended_err e;
03137 m.msg_name = NULL;
03138 m.msg_namelen = 0;
03139 m.msg_iov = NULL;
03140 m.msg_control = &e;
03141 m.msg_controllen = sizeof(e);
03142 m.msg_flags = 0;
03143 res = recvmsg(netsocket, &m, MSG_ERRQUEUE);
03144 if (res < 0)
03145 ast_log(LOG_WARNING, "Error detected, but unable to read error: %s\n", strerror(errno));
03146 else {
03147 if (m.msg_controllen) {
03148 sin = (struct sockaddr_in *)SO_EE_OFFENDER(&e);
03149 if (sin)
03150 ast_log(LOG_WARNING, "Receive error from %s\n", ast_inet_ntoa(sin->sin_addr));
03151 else
03152 ast_log(LOG_WARNING, "No address detected??\n");
03153 } else {
03154 ast_log(LOG_WARNING, "Local error: %s\n", strerror(e.ee_errno));
03155 }
03156 }
03157 #endif
03158 return 0;
03159 }
03160
03161 static int transmit_trunk(struct iax_frame *f, struct sockaddr_in *sin, int sockfd)
03162 {
03163 int res;
03164 res = sendto(sockfd, f->data, f->datalen, 0,(struct sockaddr *)sin,
03165 sizeof(*sin));
03166 if (res < 0) {
03167 ast_debug(1, "Received error: %s\n", strerror(errno));
03168 handle_error();
03169 } else
03170 res = 0;
03171 return res;
03172 }
03173
03174 static int send_packet(struct iax_frame *f)
03175 {
03176 int res;
03177 int callno = f->callno;
03178
03179
03180 if (!callno || !iaxs[callno] || iaxs[callno]->error)
03181 return -1;
03182
03183
03184 if (iaxdebug)
03185 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));
03186
03187 if (f->transfer) {
03188 if (iaxdebug)
03189 iax_showframe(f, NULL, 0, &iaxs[callno]->transfer, f->datalen - sizeof(struct ast_iax2_full_hdr));
03190 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->transfer, sizeof(iaxs[callno]->transfer));
03191 } else {
03192 if (iaxdebug)
03193 iax_showframe(f, NULL, 0, &iaxs[callno]->addr, f->datalen - sizeof(struct ast_iax2_full_hdr));
03194 res = sendto(iaxs[callno]->sockfd, f->data, f->datalen, 0,(struct sockaddr *)&iaxs[callno]->addr, sizeof(iaxs[callno]->addr));
03195 }
03196 if (res < 0) {
03197 if (iaxdebug)
03198 ast_debug(1, "Received error: %s\n", strerror(errno));
03199 handle_error();
03200 } else
03201 res = 0;
03202
03203 return res;
03204 }
03205
03206
03207
03208
03209
03210 static int iax2_predestroy(int callno)
03211 {
03212 struct ast_channel *c = NULL;
03213 struct chan_iax2_pvt *pvt = iaxs[callno];
03214
03215 if (!pvt)
03216 return -1;
03217
03218 if (!ast_test_flag(pvt, IAX_ALREADYGONE)) {
03219 iax2_destroy_helper(pvt);
03220 ast_set_flag(pvt, IAX_ALREADYGONE);
03221 }
03222
03223 if ((c = pvt->owner)) {
03224 c->tech_pvt = NULL;
03225 iax2_queue_hangup(callno);
03226 pvt->owner = NULL;
03227 ast_module_unref(ast_module_info->self);
03228 }
03229
03230 return 0;
03231 }
03232
03233 static void iax2_destroy(int callno)
03234 {
03235 struct chan_iax2_pvt *pvt = NULL;
03236 struct ast_channel *owner = NULL;
03237
03238 retry:
03239 if ((pvt = iaxs[callno])) {
03240 #if 0
03241
03242
03243
03244
03245
03246
03247
03248 iax2_destroy_helper(pvt);
03249 #endif
03250 }
03251
03252 owner = pvt ? pvt->owner : NULL;
03253
03254 if (owner) {
03255 if (ast_channel_trylock(owner)) {
03256 ast_debug(3, "Avoiding IAX destroy deadlock\n");
03257 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
03258 goto retry;
03259 }
03260 }
03261
03262 if (!owner) {
03263 iaxs[callno] = NULL;
03264 }
03265
03266 if (pvt) {
03267 if (!owner) {
03268 pvt->owner = NULL;
03269 } else {
03270
03271
03272
03273 ast_queue_hangup(owner);
03274 }
03275
03276 if (pvt->peercallno) {
03277 remove_by_peercallno(pvt);
03278 }
03279
03280 if (pvt->transfercallno) {
03281 remove_by_transfercallno(pvt);
03282 }
03283
03284 if (!owner) {
03285 ao2_ref(pvt, -1);
03286 pvt = NULL;
03287 }
03288 }
03289
03290 if (owner) {
03291 ast_channel_unlock(owner);
03292 }
03293
03294 if (callno & 0x4000) {
03295 update_max_trunk();
03296 }
03297 }
03298
03299 static int update_packet(struct iax_frame *f)
03300 {
03301
03302 struct ast_iax2_full_hdr *fh = f->data;
03303 struct ast_frame af;
03304
03305
03306 if (f->encmethods) {
03307 decode_frame(&f->mydcx, fh, &af, &f->datalen);
03308 }
03309
03310 fh->dcallno = ntohs(IAX_FLAG_RETRANS | f->dcallno);
03311
03312 f->iseqno = iaxs[f->callno]->iseqno;
03313 fh->iseqno = f->iseqno;
03314
03315
03316 if (f->encmethods) {
03317
03318
03319 build_rand_pad(f->semirand, sizeof(f->semirand));
03320 encrypt_frame(&f->ecx, fh, f->semirand, &f->datalen);
03321 }
03322 return 0;
03323 }
03324
03325 static int attempt_transmit(const void *data);
03326 static void __attempt_transmit(const void *data)
03327 {
03328
03329
03330 struct iax_frame *f = (struct iax_frame *)data;
03331 int freeme = 0;
03332 int callno = f->callno;
03333
03334 if (callno)
03335 ast_mutex_lock(&iaxsl[callno]);
03336 if (callno && iaxs[callno]) {
03337 if ((f->retries < 0) ||
03338 (f->retries >= max_retries) ) {
03339
03340 if (f->retries >= max_retries) {
03341 if (f->transfer) {
03342
03343 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
03344 } else if (f->final) {
03345 iax2_destroy(callno);
03346 } else {
03347 if (iaxs[callno]->owner)
03348 ast_log(LOG_WARNING, "Max retries exceeded to host %s on %s (type = %d, subclass = %d, ts=%d, seqno=%d)\n", ast_inet_ntoa(iaxs[f->callno]->addr.sin_addr),iaxs[f->callno]->owner->name , f->af.frametype, f->af.subclass, f->ts, f->oseqno);
03349 iaxs[callno]->error = ETIMEDOUT;
03350 if (iaxs[callno]->owner) {
03351 struct ast_frame fr = { AST_FRAME_CONTROL, AST_CONTROL_HANGUP, .data.uint32 = AST_CAUSE_DESTINATION_OUT_OF_ORDER };
03352
03353 iax2_queue_frame(callno, &fr);
03354
03355 if (iaxs[callno] && iaxs[callno]->owner)
03356 iaxs[callno]->owner->hangupcause = AST_CAUSE_DESTINATION_OUT_OF_ORDER;
03357 } else {
03358 if (iaxs[callno]->reg) {
03359 memset(&iaxs[callno]->reg->us, 0, sizeof(iaxs[callno]->reg->us));
03360 iaxs[callno]->reg->regstate = REG_STATE_TIMEOUT;
03361 iaxs[callno]->reg->refresh = IAX_DEFAULT_REG_EXPIRE;
03362 }
03363 iax2_destroy(callno);
03364 }
03365 }
03366
03367 }
03368 freeme = 1;
03369 } else {
03370
03371 update_packet(f);
03372
03373 send_packet(f);
03374 f->retries++;
03375
03376 f->retrytime *= 10;
03377 if (f->retrytime > MAX_RETRY_TIME)
03378 f->retrytime = MAX_RETRY_TIME;
03379
03380 if (f->transfer && (f->retrytime > 1000))
03381 f->retrytime = 1000;
03382 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
03383 }
03384 } else {
03385
03386 f->retries = -1;
03387 freeme = 1;
03388 }
03389 if (callno)
03390 ast_mutex_unlock(&iaxsl[callno]);
03391
03392 if (freeme) {
03393
03394 AST_LIST_LOCK(&frame_queue);
03395 AST_LIST_REMOVE(&frame_queue, f, list);
03396 AST_LIST_UNLOCK(&frame_queue);
03397 f->retrans = -1;
03398
03399 iax2_frame_free(f);
03400 }
03401 }
03402
03403 static int attempt_transmit(const void *data)
03404 {
03405 #ifdef SCHED_MULTITHREADED
03406 if (schedule_action(__attempt_transmit, data))
03407 #endif
03408 __attempt_transmit(data);
03409 return 0;
03410 }
03411
03412 static char *handle_cli_iax2_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03413 {
03414 struct iax2_peer *peer = NULL;
03415 struct iax2_user *user = NULL;
03416 static char *choices[] = { "all", NULL };
03417 char *cmplt;
03418
03419 switch (cmd) {
03420 case CLI_INIT:
03421 e->command = "iax2 prune realtime";
03422 e->usage =
03423 "Usage: iax2 prune realtime [<peername>|all]\n"
03424 " Prunes object(s) from the cache\n";
03425 return NULL;
03426 case CLI_GENERATE:
03427 if (a->pos == 3) {
03428 cmplt = ast_cli_complete(a->word, choices, a->n);
03429 if (!cmplt)
03430 cmplt = complete_iax2_peers(a->line, a->word, a->pos, a->n - sizeof(choices), IAX_RTCACHEFRIENDS);
03431 return cmplt;
03432 }
03433 return NULL;
03434 }
03435 if (a->argc != 4)
03436 return CLI_SHOWUSAGE;
03437 if (!strcmp(a->argv[3], "all")) {
03438 prune_users();
03439 prune_peers();
03440 ast_cli(a->fd, "Cache flushed successfully.\n");
03441 return CLI_SUCCESS;
03442 }
03443 peer = find_peer(a->argv[3], 0);
03444 user = find_user(a->argv[3]);
03445 if (peer || user) {
03446 if (peer) {
03447 if (ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
03448 ast_set_flag(peer, IAX_RTAUTOCLEAR);
03449 expire_registry(peer_ref(peer));
03450 ast_cli(a->fd, "Peer %s was removed from the cache.\n", a->argv[3]);
03451 } else {
03452 ast_cli(a->fd, "Peer %s is not eligible for this operation.\n", a->argv[3]);
03453 }
03454 peer_unref(peer);
03455 }
03456 if (user) {
03457 if (ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
03458 ast_set_flag(user, IAX_RTAUTOCLEAR);
03459 ast_cli(a->fd, "User %s was removed from the cache.\n", a->argv[3]);
03460 } else {
03461 ast_cli(a->fd, "User %s is not eligible for this operation.\n", a->argv[3]);
03462 }
03463 ao2_unlink(users,user);
03464 user_unref(user);
03465 }
03466 } else {
03467 ast_cli(a->fd, "%s was not found in the cache.\n", a->argv[3]);
03468 }
03469
03470 return CLI_SUCCESS;
03471 }
03472
03473 static char *handle_cli_iax2_test_losspct(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03474 {
03475 switch (cmd) {
03476 case CLI_INIT:
03477 e->command = "iax2 test losspct";
03478 e->usage =
03479 "Usage: iax2 test losspct <percentage>\n"
03480 " For testing, throws away <percentage> percent of incoming packets\n";
03481 return NULL;
03482 case CLI_GENERATE:
03483 return NULL;
03484 }
03485 if (a->argc != 4)
03486 return CLI_SHOWUSAGE;
03487
03488 test_losspct = atoi(a->argv[3]);
03489
03490 return CLI_SUCCESS;
03491 }
03492
03493 #ifdef IAXTESTS
03494 static char *handle_cli_iax2_test_late(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03495 {
03496 switch (cmd) {
03497 case CLI_INIT:
03498 e->command = "iax2 test late";
03499 e->usage =
03500 "Usage: iax2 test late <ms>\n"
03501 " For testing, count the next frame as <ms> ms late\n";
03502 return NULL;
03503 case CLI_GENERATE:
03504 return NULL;
03505 }
03506
03507 if (a->argc != 4)
03508 return CLI_SHOWUSAGE;
03509
03510 test_late = atoi(a->argv[3]);
03511
03512 return CLI_SUCCESS;
03513 }
03514
03515 static char *handle_cli_iax2_test_resync(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03516 {
03517 switch (cmd) {
03518 case CLI_INIT:
03519 e->command = "iax2 test resync";
03520 e->usage =
03521 "Usage: iax2 test resync <ms>\n"
03522 " For testing, adjust all future frames by <ms> ms\n";
03523 return NULL;
03524 case CLI_GENERATE:
03525 return NULL;
03526 }
03527
03528 if (a->argc != 4)
03529 return CLI_SHOWUSAGE;
03530
03531 test_resync = atoi(a->argv[3]);
03532
03533 return CLI_SUCCESS;
03534 }
03535
03536 static char *handle_cli_iax2_test_jitter(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03537 {
03538 switch (cmd) {
03539 case CLI_INIT:
03540 e->command = "iax2 test jitter";
03541 e->usage =
03542 "Usage: iax2 test jitter <ms> <pct>\n"
03543 " For testing, simulate maximum jitter of +/- <ms> on <pct>\n"
03544 " percentage of packets. If <pct> is not specified, adds\n"
03545 " jitter to all packets.\n";
03546 return NULL;
03547 case CLI_GENERATE:
03548 return NULL;
03549 }
03550
03551 if (a->argc < 4 || a->argc > 5)
03552 return CLI_SHOWUSAGE;
03553
03554 test_jit = atoi(a->argv[3]);
03555 if (a->argc == 5)
03556 test_jitpct = atoi(a->argv[4]);
03557
03558 return CLI_SUCCESS;
03559 }
03560 #endif
03561
03562
03563
03564 static int peer_status(struct iax2_peer *peer, char *status, int statuslen)
03565 {
03566 int res = 0;
03567 if (peer->maxms) {
03568 if (peer->lastms < 0) {
03569 ast_copy_string(status, "UNREACHABLE", statuslen);
03570 } else if (peer->lastms > peer->maxms) {
03571 snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
03572 res = 1;
03573 } else if (peer->lastms) {
03574 snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
03575 res = 1;
03576 } else {
03577 ast_copy_string(status, "UNKNOWN", statuslen);
03578 }
03579 } else {
03580 ast_copy_string(status, "Unmonitored", statuslen);
03581 res = -1;
03582 }
03583 return res;
03584 }
03585
03586
03587 static char *handle_cli_iax2_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03588 {
03589 char status[30];
03590 char cbuf[256];
03591 struct iax2_peer *peer;
03592 char codec_buf[512];
03593 struct ast_str *encmethods = ast_str_alloca(256);
03594 int x = 0, codec = 0, load_realtime = 0;
03595
03596 switch (cmd) {
03597 case CLI_INIT:
03598 e->command = "iax2 show peer";
03599 e->usage =
03600 "Usage: iax2 show peer <name>\n"
03601 " Display details on specific IAX peer\n";
03602 return NULL;
03603 case CLI_GENERATE:
03604 if (a->pos == 3)
03605 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
03606 return NULL;
03607 }
03608
03609 if (a->argc < 4)
03610 return CLI_SHOWUSAGE;
03611
03612 load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? 1 : 0;
03613
03614 peer = find_peer(a->argv[3], load_realtime);
03615 if (peer) {
03616 encmethods_to_str(peer->encmethods, encmethods);
03617 ast_cli(a->fd, "\n\n");
03618 ast_cli(a->fd, " * Name : %s\n", peer->name);
03619 ast_cli(a->fd, " Secret : %s\n", ast_strlen_zero(peer->secret) ? "<Not set>" : "<Set>");
03620 ast_cli(a->fd, " Context : %s\n", peer->context);
03621 ast_cli(a->fd, " Parking lot : %s\n", peer->parkinglot);
03622 ast_cli(a->fd, " Mailbox : %s\n", peer->mailbox);
03623 ast_cli(a->fd, " Dynamic : %s\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
03624 ast_cli(a->fd, " Callnum limit: %d\n", peer->maxcallno);
03625 ast_cli(a->fd, " Calltoken req: %s\n", (peer->calltoken_required == CALLTOKEN_YES) ? "Yes" : ((peer->calltoken_required == CALLTOKEN_AUTO) ? "Auto" : "No"));
03626 ast_cli(a->fd, " Trunk : %s\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
03627 ast_cli(a->fd, " Encryption : %s\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
03628 ast_cli(a->fd, " Callerid : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
03629 ast_cli(a->fd, " Expire : %d\n", peer->expire);
03630 ast_cli(a->fd, " ACL : %s\n", (peer->ha ? "Yes" : "No"));
03631 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));
03632 ast_cli(a->fd, " Defaddr->IP : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
03633 ast_cli(a->fd, " Username : %s\n", peer->username);
03634 ast_cli(a->fd, " Codecs : ");
03635 ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
03636 ast_cli(a->fd, "%s\n", codec_buf);
03637
03638 ast_cli(a->fd, " Codec Order : (");
03639 for(x = 0; x < 32 ; x++) {
03640 codec = ast_codec_pref_index(&peer->prefs,x);
03641 if(!codec)
03642 break;
03643 ast_cli(a->fd, "%s", ast_getformatname(codec));
03644 if(x < 31 && ast_codec_pref_index(&peer->prefs,x+1))
03645 ast_cli(a->fd, "|");
03646 }
03647
03648 if (!x)
03649 ast_cli(a->fd, "none");
03650 ast_cli(a->fd, ")\n");
03651
03652 ast_cli(a->fd, " Status : ");
03653 peer_status(peer, status, sizeof(status));
03654 ast_cli(a->fd, "%s\n",status);
03655 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");
03656 ast_cli(a->fd, "\n");
03657 peer_unref(peer);
03658 } else {
03659 ast_cli(a->fd, "Peer %s not found.\n", a->argv[3]);
03660 ast_cli(a->fd, "\n");
03661 }
03662
03663 return CLI_SUCCESS;
03664 }
03665
03666 static char *complete_iax2_peers(const char *line, const char *word, int pos, int state, int flags)
03667 {
03668 int which = 0;
03669 struct iax2_peer *peer;
03670 char *res = NULL;
03671 int wordlen = strlen(word);
03672 struct ao2_iterator i;
03673
03674 i = ao2_iterator_init(peers, 0);
03675 while ((peer = ao2_iterator_next(&i))) {
03676 if (!strncasecmp(peer->name, word, wordlen) && ++which > state
03677 && (!flags || ast_test_flag(peer, flags))) {
03678 res = ast_strdup(peer->name);
03679 peer_unref(peer);
03680 break;
03681 }
03682 peer_unref(peer);
03683 }
03684 ao2_iterator_destroy(&i);
03685
03686 return res;
03687 }
03688
03689 static char *handle_cli_iax2_show_stats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03690 {
03691 struct iax_frame *cur;
03692 int cnt = 0, dead = 0, final = 0;
03693
03694 switch (cmd) {
03695 case CLI_INIT:
03696 e->command = "iax2 show stats";
03697 e->usage =
03698 "Usage: iax2 show stats\n"
03699 " Display statistics on IAX channel driver.\n";
03700 return NULL;
03701 case CLI_GENERATE:
03702 return NULL;
03703 }
03704
03705 if (a->argc != 3)
03706 return CLI_SHOWUSAGE;
03707
03708 AST_LIST_LOCK(&frame_queue);
03709 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
03710 if (cur->retries < 0)
03711 dead++;
03712 if (cur->final)
03713 final++;
03714 cnt++;
03715 }
03716 AST_LIST_UNLOCK(&frame_queue);
03717
03718 ast_cli(a->fd, " IAX Statistics\n");
03719 ast_cli(a->fd, "---------------------\n");
03720 ast_cli(a->fd, "Outstanding frames: %d (%d ingress, %d egress)\n", iax_get_frames(), iax_get_iframes(), iax_get_oframes());
03721 ast_cli(a->fd, "%d timed and %d untimed transmits; MTU %d/%d/%d\n", trunk_timed, trunk_untimed,
03722 trunk_maxmtu, trunk_nmaxmtu, global_max_trunk_mtu);
03723 ast_cli(a->fd, "Packets in transmit queue: %d dead, %d final, %d total\n\n", dead, final, cnt);
03724
03725 trunk_timed = trunk_untimed = 0;
03726 if (trunk_maxmtu > trunk_nmaxmtu)
03727 trunk_nmaxmtu = trunk_maxmtu;
03728
03729 return CLI_SUCCESS;
03730 }
03731
03732
03733 static char *handle_cli_iax2_set_mtu(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03734 {
03735 int mtuv;
03736
03737 switch (cmd) {
03738 case CLI_INIT:
03739 e->command = "iax2 set mtu";
03740 e->usage =
03741 "Usage: iax2 set mtu <value>\n"
03742 " Set the system-wide IAX IP mtu to <value> bytes net or\n"
03743 " zero to disable. Disabling means that the operating system\n"
03744 " must handle fragmentation of UDP packets when the IAX2 trunk\n"
03745 " packet exceeds the UDP payload size. This is substantially\n"
03746 " below the IP mtu. Try 1240 on ethernets. Must be 172 or\n"
03747 " greater for G.711 samples.\n";
03748 return NULL;
03749 case CLI_GENERATE:
03750 return NULL;
03751 }
03752
03753 if (a->argc != 4)
03754 return CLI_SHOWUSAGE;
03755 if (strncasecmp(a->argv[3], "default", strlen(a->argv[3])) == 0)
03756 mtuv = MAX_TRUNK_MTU;
03757 else
03758 mtuv = atoi(a->argv[3]);
03759
03760 if (mtuv == 0) {
03761 ast_cli(a->fd, "Trunk MTU control disabled (mtu was %d)\n", global_max_trunk_mtu);
03762 global_max_trunk_mtu = 0;
03763 return CLI_SUCCESS;
03764 }
03765 if (mtuv < 172 || mtuv > 4000) {
03766 ast_cli(a->fd, "Trunk MTU must be between 172 and 4000\n");
03767 return CLI_SHOWUSAGE;
03768 }
03769 ast_cli(a->fd, "Trunk MTU changed from %d to %d\n", global_max_trunk_mtu, mtuv);
03770 global_max_trunk_mtu = mtuv;
03771 return CLI_SUCCESS;
03772 }
03773
03774 static char *handle_cli_iax2_show_cache(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
03775 {
03776 struct iax2_dpcache *dp = NULL;
03777 char tmp[1024], *pc = NULL;
03778 int s, x, y;
03779 struct timeval now = ast_tvnow();
03780
03781 switch (cmd) {
03782 case CLI_INIT:
03783 e->command = "iax2 show cache";
03784 e->usage =
03785 "Usage: iax2 show cache\n"
03786 " Display currently cached IAX Dialplan results.\n";
03787 return NULL;
03788 case CLI_GENERATE:
03789 return NULL;
03790 }
03791
03792 AST_LIST_LOCK(&dpcache);
03793
03794 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8.8s %s\n", "Peer/Context", "Exten", "Exp.", "Wait.", "Flags");
03795
03796 AST_LIST_TRAVERSE(&dpcache, dp, cache_list) {
03797 s = dp->expiry.tv_sec - now.tv_sec;
03798 tmp[0] = '\0';
03799 if (dp->flags & CACHE_FLAG_EXISTS)
03800 strncat(tmp, "EXISTS|", sizeof(tmp) - strlen(tmp) - 1);
03801 if (dp->flags & CACHE_FLAG_NONEXISTENT)
03802 strncat(tmp, "NONEXISTENT|", sizeof(tmp) - strlen(tmp) - 1);
03803 if (dp->flags & CACHE_FLAG_CANEXIST)
03804 strncat(tmp, "CANEXIST|", sizeof(tmp) - strlen(tmp) - 1);
03805 if (dp->flags & CACHE_FLAG_PENDING)
03806 strncat(tmp, "PENDING|", sizeof(tmp) - strlen(tmp) - 1);
03807 if (dp->flags & CACHE_FLAG_TIMEOUT)
03808 strncat(tmp, "TIMEOUT|", sizeof(tmp) - strlen(tmp) - 1);
03809 if (dp->flags & CACHE_FLAG_TRANSMITTED)
03810 strncat(tmp, "TRANSMITTED|", sizeof(tmp) - strlen(tmp) - 1);
03811 if (dp->flags & CACHE_FLAG_MATCHMORE)
03812 strncat(tmp, "MATCHMORE|", sizeof(tmp) - strlen(tmp) - 1);
03813 if (dp->flags & CACHE_FLAG_UNKNOWN)
03814 strncat(tmp, "UNKNOWN|", sizeof(tmp) - strlen(tmp) - 1);
03815
03816 if (!ast_strlen_zero(tmp)) {
03817 tmp[strlen(tmp) - 1] = '\0';
03818 } else {
03819 ast_copy_string(tmp, "(none)", sizeof(tmp));
03820 }
03821 y = 0;
03822 pc = strchr(dp->peercontext, '@');
03823 if (!pc) {
03824 pc = dp->peercontext;
03825 } else {
03826 pc++;
03827 }
03828 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
03829 if (dp->waiters[x] > -1)
03830 y++;
03831 }
03832 if (s > 0) {
03833 ast_cli(a->fd, "%-20.20s %-12.12s %-9d %-8d %s\n", pc, dp->exten, s, y, tmp);
03834 } else {
03835 ast_cli(a->fd, "%-20.20s %-12.12s %-9.9s %-8d %s\n", pc, dp->exten, "(expired)", y, tmp);
03836 }
03837 }
03838
03839 AST_LIST_UNLOCK(&dpcache);
03840
03841 return CLI_SUCCESS;
03842 }
03843
03844 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset);
03845
03846 static void unwrap_timestamp(struct iax_frame *fr)
03847 {
03848
03849
03850 const int ts_shift = (fr->af.frametype == AST_FRAME_VIDEO) ? 15 : 16;
03851 const int lower_mask = (1 << ts_shift) - 1;
03852 const int upper_mask = ~lower_mask;
03853 const int last_upper = iaxs[fr->callno]->last & upper_mask;
03854
03855 if ( (fr->ts & upper_mask) == last_upper ) {
03856 const int x = fr->ts - iaxs[fr->callno]->last;
03857 const int threshold = (ts_shift == 15) ? 25000 : 50000;
03858
03859 if (x < -threshold) {
03860
03861
03862
03863
03864 fr->ts = (last_upper + (1 << ts_shift)) | (fr->ts & lower_mask);
03865 if (iaxdebug)
03866 ast_debug(1, "schedule_delivery: pushed forward timestamp\n");
03867 } else if (x > threshold) {
03868
03869
03870
03871
03872 fr->ts = (last_upper - (1 << ts_shift)) | (fr->ts & lower_mask);
03873 if (iaxdebug)
03874 ast_debug(1, "schedule_delivery: pushed back timestamp\n");
03875 }
03876 }
03877 }
03878
03879 static int get_from_jb(const void *p);
03880
03881 static void update_jbsched(struct chan_iax2_pvt *pvt)
03882 {
03883 int when;
03884
03885 when = ast_tvdiff_ms(ast_tvnow(), pvt->rxcore);
03886
03887 when = jb_next(pvt->jb) - when;
03888
03889 if (when <= 0) {
03890
03891 when = 1;
03892 }
03893
03894 pvt->jbid = iax2_sched_replace(pvt->jbid, sched, when, get_from_jb,
03895 CALLNO_TO_PTR(pvt->callno));
03896 }
03897
03898 static void __get_from_jb(const void *p)
03899 {
03900 int callno = PTR_TO_CALLNO(p);
03901 struct chan_iax2_pvt *pvt = NULL;
03902 struct iax_frame *fr;
03903 jb_frame frame;
03904 int ret;
03905 long ms;
03906 long next;
03907 struct timeval now = ast_tvnow();
03908
03909
03910 ast_mutex_lock(&iaxsl[callno]);
03911 pvt = iaxs[callno];
03912 if (!pvt) {
03913
03914 ast_mutex_unlock(&iaxsl[callno]);
03915 return;
03916 }
03917
03918 pvt->jbid = -1;
03919
03920
03921
03922
03923 now.tv_usec += 1000;
03924
03925 ms = ast_tvdiff_ms(now, pvt->rxcore);
03926
03927 if(ms >= (next = jb_next(pvt->jb))) {
03928 ret = jb_get(pvt->jb,&frame,ms,ast_codec_interp_len(pvt->voiceformat));
03929 switch(ret) {
03930 case JB_OK:
03931 fr = frame.data;
03932 __do_deliver(fr);
03933
03934 pvt = iaxs[callno];
03935 break;
03936 case JB_INTERP:
03937 {
03938 struct ast_frame af = { 0, };
03939
03940
03941 af.frametype = AST_FRAME_VOICE;
03942 af.subclass = pvt->voiceformat;
03943 af.samples = frame.ms * (ast_format_rate(pvt->voiceformat) / 1000);
03944 af.src = "IAX2 JB interpolation";
03945 af.delivery = ast_tvadd(pvt->rxcore, ast_samp2tv(next, 1000));
03946 af.offset = AST_FRIENDLY_OFFSET;
03947
03948
03949
03950 if (!ast_test_flag(iaxs[callno], IAX_ALREADYGONE)) {
03951 iax2_queue_frame(callno, &af);
03952
03953 pvt = iaxs[callno];
03954 }
03955 }
03956 break;
03957 case JB_DROP:
03958 iax2_frame_free(frame.data);
03959 break;
03960 case JB_NOFRAME:
03961 case JB_EMPTY:
03962
03963 break;
03964 default:
03965
03966 break;
03967 }
03968 }
03969 if (pvt)
03970 update_jbsched(pvt);
03971 ast_mutex_unlock(&iaxsl[callno]);
03972 }
03973
03974 static int get_from_jb(const void *data)
03975 {
03976 #ifdef SCHED_MULTITHREADED
03977 if (schedule_action(__get_from_jb, data))
03978 #endif
03979 __get_from_jb(data);
03980 return 0;
03981 }
03982
03983
03984
03985
03986
03987
03988
03989 static int schedule_delivery(struct iax_frame *fr, int updatehistory, int fromtrunk, unsigned int *tsout)
03990 {
03991 int type, len;
03992 int ret;
03993 int needfree = 0;
03994 struct ast_channel *owner = NULL;
03995 struct ast_channel *bridge = NULL;
03996
03997
03998 unwrap_timestamp(fr);
03999
04000
04001 if ( !fromtrunk && !ast_tvzero(iaxs[fr->callno]->rxcore))
04002 fr->af.delivery = ast_tvadd(iaxs[fr->callno]->rxcore, ast_samp2tv(fr->ts, 1000));
04003 else {
04004 #if 0
04005 ast_debug(1, "schedule_delivery: set delivery to 0 as we don't have an rxcore yet, or frame is from trunk.\n");
04006 #endif
04007 fr->af.delivery = ast_tv(0,0);
04008 }
04009
04010 type = JB_TYPE_CONTROL;
04011 len = 0;
04012
04013 if(fr->af.frametype == AST_FRAME_VOICE) {
04014 type = JB_TYPE_VOICE;
04015 len = ast_codec_get_samples(&fr->af) / (ast_format_rate(fr->af.subclass) / 1000);
04016 } else if(fr->af.frametype == AST_FRAME_CNG) {
04017 type = JB_TYPE_SILENCE;
04018 }
04019
04020 if ( (!ast_test_flag(iaxs[fr->callno], IAX_USEJITTERBUF)) ) {
04021 if (tsout)
04022 *tsout = fr->ts;
04023 __do_deliver(fr);
04024 return -1;
04025 }
04026
04027 iax2_lock_owner(fr->callno);
04028 if (!iaxs[fr->callno]) {
04029
04030 iax2_frame_free(fr);
04031 return -1;
04032 }
04033 if ((owner = iaxs[fr->callno]->owner))
04034 bridge = ast_bridged_channel(owner);
04035
04036
04037
04038 if ( (!ast_test_flag(iaxs[fr->callno], IAX_FORCEJITTERBUF)) && owner && bridge && (bridge->tech->properties & AST_CHAN_TP_WANTSJITTER) ) {
04039 jb_frame frame;
04040
04041 ast_channel_unlock(owner);
04042
04043
04044 while (jb_getall(iaxs[fr->callno]->jb, &frame) == JB_OK) {
04045 __do_deliver(frame.data);
04046
04047 if (!iaxs[fr->callno])
04048 return -1;
04049 }
04050
04051 jb_reset(iaxs[fr->callno]->jb);
04052
04053 ast_sched_thread_del(sched, iaxs[fr->callno]->jbid);
04054
04055
04056 if (tsout)
04057 *tsout = fr->ts;
04058 __do_deliver(fr);
04059 return -1;
04060 }
04061 if (owner) {
04062 ast_channel_unlock(owner);
04063 }
04064
04065
04066
04067 ret = jb_put(iaxs[fr->callno]->jb, fr, type, len, fr->ts,
04068 calc_rxstamp(iaxs[fr->callno],fr->ts));
04069 if (ret == JB_DROP) {
04070 needfree++;
04071 } else if (ret == JB_SCHED) {
04072 update_jbsched(iaxs[fr->callno]);
04073 }
04074 if (tsout)
04075 *tsout = fr->ts;
04076 if (needfree) {
04077
04078 iax2_frame_free(fr);
04079 return -1;
04080 }
04081 return 0;
04082 }
04083
04084 static int iax2_transmit(struct iax_frame *fr)
04085 {
04086
04087
04088
04089 fr->sentyet = 0;
04090 AST_LIST_LOCK(&frame_queue);
04091 AST_LIST_INSERT_TAIL(&frame_queue, fr, list);
04092 AST_LIST_UNLOCK(&frame_queue);
04093
04094 if (netthreadid != AST_PTHREADT_NULL)
04095 pthread_kill(netthreadid, SIGURG);
04096 ast_sched_thread_poke(sched);
04097 return 0;
04098 }
04099
04100
04101
04102 static int iax2_digit_begin(struct ast_channel *c, char digit)
04103 {
04104 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_BEGIN, digit, 0, NULL, 0, -1);
04105 }
04106
04107 static int iax2_digit_end(struct ast_channel *c, char digit, unsigned int duration)
04108 {
04109 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_DTMF_END, digit, 0, NULL, 0, -1);
04110 }
04111
04112 static int iax2_sendtext(struct ast_channel *c, const char *text)
04113 {
04114
04115 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_TEXT,
04116 0, 0, (unsigned char *)text, strlen(text) + 1, -1);
04117 }
04118
04119 static int iax2_sendimage(struct ast_channel *c, struct ast_frame *img)
04120 {
04121 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_IMAGE, img->subclass, 0, img->data.ptr, img->datalen, -1);
04122 }
04123
04124 static int iax2_sendhtml(struct ast_channel *c, int subclass, const char *data, int datalen)
04125 {
04126 return send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_HTML, subclass, 0, (unsigned char *)data, datalen, -1);
04127 }
04128
04129 static int iax2_fixup(struct ast_channel *oldchannel, struct ast_channel *newchan)
04130 {
04131 unsigned short callno = PTR_TO_CALLNO(newchan->tech_pvt);
04132 ast_mutex_lock(&iaxsl[callno]);
04133 if (iaxs[callno])
04134 iaxs[callno]->owner = newchan;
04135 else
04136 ast_log(LOG_WARNING, "Uh, this isn't a good sign...\n");
04137 ast_mutex_unlock(&iaxsl[callno]);
04138 return 0;
04139 }
04140
04141
04142
04143
04144
04145 static struct iax2_peer *realtime_peer(const char *peername, struct sockaddr_in *sin)
04146 {
04147 struct ast_variable *var = NULL;
04148 struct ast_variable *tmp;
04149 struct iax2_peer *peer=NULL;
04150 time_t regseconds = 0, nowtime;
04151 int dynamic=0;
04152
04153 if (peername) {
04154 var = ast_load_realtime("iaxpeers", "name", peername, "host", "dynamic", SENTINEL);
04155 if (!var && sin)
04156 var = ast_load_realtime("iaxpeers", "name", peername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04157 } else if (sin) {
04158 char porta[25];
04159 sprintf(porta, "%d", ntohs(sin->sin_port));
04160 var = ast_load_realtime("iaxpeers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04161 if (var) {
04162
04163 for (tmp = var; tmp; tmp = tmp->next) {
04164 if (!strcasecmp(tmp->name, "name"))
04165 peername = tmp->value;
04166 }
04167 }
04168 }
04169 if (!var && peername) {
04170 var = ast_load_realtime("iaxpeers", "name", peername, SENTINEL);
04171
04172
04173
04174
04175
04176
04177 if (var && sin) {
04178 for (tmp = var; tmp; tmp = tmp->next) {
04179 if (!strcasecmp(tmp->name, "host")) {
04180 struct ast_hostent ahp;
04181 struct hostent *hp;
04182 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04183
04184 ast_variables_destroy(var);
04185 var = NULL;
04186 }
04187 break;
04188 }
04189 }
04190 }
04191 }
04192 if (!var)
04193 return NULL;
04194
04195 peer = build_peer(peername, var, NULL, ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS) ? 0 : 1);
04196
04197 if (!peer) {
04198 ast_variables_destroy(var);
04199 return NULL;
04200 }
04201
04202 for (tmp = var; tmp; tmp = tmp->next) {
04203
04204 if (!strcasecmp(tmp->name, "type")) {
04205 if (strcasecmp(tmp->value, "friend") &&
04206 strcasecmp(tmp->value, "peer")) {
04207
04208 peer = peer_unref(peer);
04209 break;
04210 }
04211 } else if (!strcasecmp(tmp->name, "regseconds")) {
04212 ast_get_time_t(tmp->value, ®seconds, 0, NULL);
04213 } else if (!strcasecmp(tmp->name, "ipaddr")) {
04214 inet_aton(tmp->value, &(peer->addr.sin_addr));
04215 } else if (!strcasecmp(tmp->name, "port")) {
04216 peer->addr.sin_port = htons(atoi(tmp->value));
04217 } else if (!strcasecmp(tmp->name, "host")) {
04218 if (!strcasecmp(tmp->value, "dynamic"))
04219 dynamic = 1;
04220 }
04221 }
04222
04223 ast_variables_destroy(var);
04224
04225 if (!peer)
04226 return NULL;
04227
04228 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
04229 ast_copy_flags(peer, &globalflags, IAX_RTAUTOCLEAR|IAX_RTCACHEFRIENDS);
04230 if (ast_test_flag(peer, IAX_RTAUTOCLEAR)) {
04231 if (peer->expire > -1) {
04232 if (!ast_sched_thread_del(sched, peer->expire)) {
04233 peer->expire = -1;
04234 peer_unref(peer);
04235 }
04236 }
04237 peer->expire = iax2_sched_add(sched, (global_rtautoclear) * 1000, expire_registry, peer_ref(peer));
04238 if (peer->expire == -1)
04239 peer_unref(peer);
04240 }
04241 ao2_link(peers, peer);
04242 if (ast_test_flag(peer, IAX_DYNAMIC))
04243 reg_source_db(peer);
04244 } else {
04245 ast_set_flag(peer, IAX_TEMPONLY);
04246 }
04247
04248 if (!ast_test_flag(&globalflags, IAX_RTIGNOREREGEXPIRE) && dynamic) {
04249 time(&nowtime);
04250 if ((nowtime - regseconds) > IAX_DEFAULT_REG_EXPIRE) {
04251 memset(&peer->addr, 0, sizeof(peer->addr));
04252 realtime_update_peer(peer->name, &peer->addr, 0);
04253 ast_debug(1, "realtime_peer: Bah, '%s' is expired (%d/%d/%d)!\n",
04254 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04255 }
04256 else {
04257 ast_debug(1, "realtime_peer: Registration for '%s' still active (%d/%d/%d)!\n",
04258 peername, (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
04259 }
04260 }
04261
04262 return peer;
04263 }
04264
04265 static struct iax2_user *realtime_user(const char *username, struct sockaddr_in *sin)
04266 {
04267 struct ast_variable *var;
04268 struct ast_variable *tmp;
04269 struct iax2_user *user=NULL;
04270
04271 var = ast_load_realtime("iaxusers", "name", username, "host", "dynamic", SENTINEL);
04272 if (!var)
04273 var = ast_load_realtime("iaxusers", "name", username, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04274 if (!var && sin) {
04275 char porta[6];
04276 snprintf(porta, sizeof(porta), "%d", ntohs(sin->sin_port));
04277 var = ast_load_realtime("iaxusers", "name", username, "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04278 if (!var)
04279 var = ast_load_realtime("iaxusers", "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", porta, SENTINEL);
04280 }
04281 if (!var) {
04282 var = ast_load_realtime("iaxusers", "name", username, SENTINEL);
04283
04284
04285
04286
04287
04288
04289 if (var) {
04290 for (tmp = var; tmp; tmp = tmp->next) {
04291 if (!strcasecmp(tmp->name, "host")) {
04292 struct ast_hostent ahp;
04293 struct hostent *hp;
04294 if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04295
04296 ast_variables_destroy(var);
04297 var = NULL;
04298 }
04299 break;
04300 }
04301 }
04302 }
04303 }
04304 if (!var)
04305 return NULL;
04306
04307 tmp = var;
04308 while(tmp) {
04309
04310 if (!strcasecmp(tmp->name, "type")) {
04311 if (strcasecmp(tmp->value, "friend") &&
04312 strcasecmp(tmp->value, "user")) {
04313 return NULL;
04314 }
04315 }
04316 tmp = tmp->next;
04317 }
04318
04319 user = build_user(username, var, NULL, !ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS));
04320
04321 ast_variables_destroy(var);
04322
04323 if (!user)
04324 return NULL;
04325
04326 if (ast_test_flag((&globalflags), IAX_RTCACHEFRIENDS)) {
04327 ast_set_flag(user, IAX_RTCACHEFRIENDS);
04328 ao2_link(users, user);
04329 } else {
04330 ast_set_flag(user, IAX_TEMPONLY);
04331 }
04332
04333 return user;
04334 }
04335
04336 static void realtime_update_peer(const char *peername, struct sockaddr_in *sin, time_t regtime)
04337 {
04338 char port[10];
04339 char regseconds[20];
04340
04341 snprintf(regseconds, sizeof(regseconds), "%d", (int)regtime);
04342 snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04343 ast_update_realtime("iaxpeers", "name", peername,
04344 "ipaddr", ast_inet_ntoa(sin->sin_addr), "port", port,
04345 "regseconds", regseconds, SENTINEL);
04346 }
04347
04348 struct create_addr_info {
04349 int capability;
04350 unsigned int flags;
04351 int maxtime;
04352 int encmethods;
04353 int found;
04354 int sockfd;
04355 int adsi;
04356 char username[80];
04357 char secret[80];
04358 char outkey[80];
04359 char timezone[80];
04360 char prefs[32];
04361 char context[AST_MAX_CONTEXT];
04362 char peercontext[AST_MAX_CONTEXT];
04363 char mohinterpret[MAX_MUSICCLASS];
04364 char mohsuggest[MAX_MUSICCLASS];
04365 };
04366
04367 static int create_addr(const char *peername, struct ast_channel *c, struct sockaddr_in *sin, struct create_addr_info *cai)
04368 {
04369 struct iax2_peer *peer;
04370 int res = -1;
04371 struct ast_codec_pref ourprefs;
04372
04373 ast_clear_flag(cai, IAX_SENDANI | IAX_TRUNK);
04374 cai->sockfd = defaultsockfd;
04375 cai->maxtime = 0;
04376 sin->sin_family = AF_INET;
04377
04378 if (!(peer = find_peer(peername, 1))) {
04379 cai->found = 0;
04380 if (ast_get_ip_or_srv(sin, peername, srvlookup ? "_iax._udp" : NULL)) {
04381 ast_log(LOG_WARNING, "No such host: %s\n", peername);
04382 return -1;
04383 }
04384 sin->sin_port = htons(IAX_DEFAULT_PORTNO);
04385
04386
04387 memcpy(&ourprefs, &prefs, sizeof(ourprefs));
04388 if (c)
04389 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04390 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04391 return 0;
04392 }
04393
04394 cai->found = 1;
04395
04396
04397 if (!(peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr))
04398 goto return_unref;
04399
04400
04401 if (peer->maxms && ((peer->lastms > peer->maxms) || (peer->lastms < 0)))
04402 goto return_unref;
04403
04404 ast_copy_flags(cai, peer, IAX_SENDANI | IAX_TRUNK | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT);
04405 cai->maxtime = peer->maxms;
04406 cai->capability = peer->capability;
04407 cai->encmethods = peer->encmethods;
04408 cai->sockfd = peer->sockfd;
04409 cai->adsi = peer->adsi;
04410 memcpy(&ourprefs, &peer->prefs, sizeof(ourprefs));
04411
04412 if (c) {
04413 ast_debug(1, "prepending %x to prefs\n", c->nativeformats);
04414 ast_codec_pref_prepend(&ourprefs, c->nativeformats, 1);
04415 }
04416 ast_codec_pref_convert(&ourprefs, cai->prefs, sizeof(cai->prefs), 1);
04417 ast_copy_string(cai->context, peer->context, sizeof(cai->context));
04418 ast_copy_string(cai->peercontext, peer->peercontext, sizeof(cai->peercontext));
04419 ast_copy_string(cai->username, peer->username, sizeof(cai->username));
04420 ast_copy_string(cai->timezone, peer->zonetag, sizeof(cai->timezone));
04421 ast_copy_string(cai->outkey, peer->outkey, sizeof(cai->outkey));
04422 ast_copy_string(cai->mohinterpret, peer->mohinterpret, sizeof(cai->mohinterpret));
04423 ast_copy_string(cai->mohsuggest, peer->mohsuggest, sizeof(cai->mohsuggest));
04424 if (ast_strlen_zero(peer->dbsecret)) {
04425 ast_copy_string(cai->secret, peer->secret, sizeof(cai->secret));
04426 } else {
04427 char *family;
04428 char *key = NULL;
04429
04430 family = ast_strdupa(peer->dbsecret);
04431 key = strchr(family, '/');
04432 if (key)
04433 *key++ = '\0';
04434 if (!key || ast_db_get(family, key, cai->secret, sizeof(cai->secret))) {
04435 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", peer->dbsecret);
04436 goto return_unref;
04437 }
04438 }
04439
04440 if (peer->addr.sin_addr.s_addr) {
04441 sin->sin_addr = peer->addr.sin_addr;
04442 sin->sin_port = peer->addr.sin_port;
04443 } else {
04444 sin->sin_addr = peer->defaddr.sin_addr;
04445 sin->sin_port = peer->defaddr.sin_port;
04446 }
04447
04448 res = 0;
04449
04450 return_unref:
04451 peer_unref(peer);
04452
04453 return res;
04454 }
04455
04456 static void __auto_congest(const void *nothing)
04457 {
04458 int callno = PTR_TO_CALLNO(nothing);
04459 struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_CONGESTION };
04460 ast_mutex_lock(&iaxsl[callno]);
04461 if (iaxs[callno]) {
04462 iaxs[callno]->initid = -1;
04463 iax2_queue_frame(callno, &f);
04464 ast_log(LOG_NOTICE, "Auto-congesting call due to slow response\n");
04465 }
04466 ast_mutex_unlock(&iaxsl[callno]);
04467 }
04468
04469 static int auto_congest(const void *data)
04470 {
04471 #ifdef SCHED_MULTITHREADED
04472 if (schedule_action(__auto_congest, data))
04473 #endif
04474 __auto_congest(data);
04475 return 0;
04476 }
04477
04478 static unsigned int iax2_datetime(const char *tz)
04479 {
04480 struct timeval t = ast_tvnow();
04481 struct ast_tm tm;
04482 unsigned int tmp;
04483 ast_localtime(&t, &tm, ast_strlen_zero(tz) ? NULL : tz);
04484 tmp = (tm.tm_sec >> 1) & 0x1f;
04485 tmp |= (tm.tm_min & 0x3f) << 5;
04486 tmp |= (tm.tm_hour & 0x1f) << 11;
04487 tmp |= (tm.tm_mday & 0x1f) << 16;
04488 tmp |= ((tm.tm_mon + 1) & 0xf) << 21;
04489 tmp |= ((tm.tm_year - 100) & 0x7f) << 25;
04490 return tmp;
04491 }
04492
04493 struct parsed_dial_string {
04494 char *username;
04495 char *password;
04496 char *key;
04497 char *peer;
04498 char *port;
04499 char *exten;
04500 char *context;
04501 char *options;
04502 };
04503
04504 static int send_apathetic_reply(unsigned short callno, unsigned short dcallno,
04505 struct sockaddr_in *sin, int command, int ts, unsigned char seqno,
04506 int sockfd, struct iax_ie_data *ied)
04507 {
04508 struct {
04509 struct ast_iax2_full_hdr f;
04510 struct iax_ie_data ied;
04511 } data;
04512 size_t size = sizeof(struct ast_iax2_full_hdr);
04513
04514 if (ied) {
04515 size += ied->pos;
04516 memcpy(&data.ied, ied->buf, ied->pos);
04517 }
04518
04519 data.f.scallno = htons(0x8000 | callno);
04520 data.f.dcallno = htons(dcallno);
04521 data.f.ts = htonl(ts);
04522 data.f.iseqno = seqno;
04523 data.f.oseqno = 0;
04524 data.f.type = AST_FRAME_IAX;
04525 data.f.csub = compress_subclass(command);
04526
04527 return sendto(sockfd, &data, size, 0, (struct sockaddr *)sin, sizeof(*sin));
04528 }
04529
04530 static void add_empty_calltoken_ie(struct chan_iax2_pvt *pvt, struct iax_ie_data *ied)
04531 {
04532
04533 if (pvt && ied && (2 < ((int) sizeof(ied->buf) - ied->pos))) {
04534 ied->buf[ied->pos++] = IAX_IE_CALLTOKEN;
04535 ied->buf[ied->pos++] = 0;
04536 pvt->calltoken_ie_len = 2;
04537 }
04538 }
04539
04540 static void resend_with_token(int callno, struct iax_frame *f, const char *newtoken)
04541 {
04542 struct chan_iax2_pvt *pvt = iaxs[callno];
04543 int frametype = f->af.frametype;
04544 int subclass = f->af.subclass;
04545 struct {
04546 struct ast_iax2_full_hdr fh;
04547 struct iax_ie_data ied;
04548 } data = {
04549 .ied.buf = { 0 },
04550 .ied.pos = 0,
04551 };
04552
04553 int ie_data_pos = f->datalen - sizeof(struct ast_iax2_full_hdr);
04554
04555 if (!pvt) {
04556 return;
04557 }
04558
04559
04560
04561
04562
04563
04564
04565
04566
04567
04568
04569
04570 if (f->encmethods || f->dcallno || !iax2_allow_new(frametype, subclass, 0)
04571 || !pvt->calltoken_ie_len || (pvt->calltoken_ie_len > ie_data_pos) ||
04572 (f->datalen > sizeof(data))) {
04573
04574 return;
04575 }
04576
04577
04578
04579
04580
04581
04582
04583
04584
04585
04586
04587
04588
04589
04590
04591 memcpy(&data, f->data, f->datalen);
04592 data.ied.pos = ie_data_pos;
04593
04594
04595
04596 data.ied.pos -= pvt->calltoken_ie_len;
04597 iax_ie_append_str(&data.ied, IAX_IE_CALLTOKEN, newtoken);
04598
04599
04600 pvt->calltoken_ie_len = data.ied.pos - ie_data_pos;
04601
04602
04603 AST_LIST_LOCK(&frame_queue);
04604 AST_LIST_REMOVE(&frame_queue, f, list);
04605 AST_LIST_UNLOCK(&frame_queue);
04606
04607
04608 iax2_frame_free(f);
04609
04610
04611 pvt->oseqno = 0;
04612 pvt->rseqno = 0;
04613 pvt->iseqno = 0;
04614 pvt->aseqno = 0;
04615 if (pvt->peercallno) {
04616 remove_by_peercallno(pvt);
04617 pvt->peercallno = 0;
04618 }
04619
04620
04621 send_command(pvt, AST_FRAME_IAX, subclass, 0, data.ied.buf, data.ied.pos, -1);
04622 }
04623
04624 static void requirecalltoken_mark_auto(const char *name, int subclass)
04625 {
04626 struct iax2_user *user = NULL;
04627 struct iax2_peer *peer = NULL;
04628
04629 if (ast_strlen_zero(name)) {
04630 return;
04631 }
04632
04633 if ((subclass == IAX_COMMAND_NEW) && (user = find_user(name)) && (user->calltoken_required == CALLTOKEN_AUTO)) {
04634 user->calltoken_required = CALLTOKEN_YES;
04635 } else if ((subclass != IAX_COMMAND_NEW) && (peer = find_peer(name, 1)) && (peer->calltoken_required == CALLTOKEN_AUTO)) {
04636 peer->calltoken_required = CALLTOKEN_YES;
04637 }
04638
04639 if (peer) {
04640 peer_unref(peer);
04641 }
04642 if (user) {
04643 user_unref(user);
04644 }
04645 }
04646
04647
04648
04649
04650
04651
04652
04653
04654
04655
04656
04657
04658
04659
04660
04661
04662
04663
04664 static int handle_call_token(struct ast_iax2_full_hdr *fh, struct iax_ies *ies,
04665 struct sockaddr_in *sin, int fd)
04666 {
04667 #define CALLTOKEN_HASH_FORMAT "%s%d%u%d"
04668 #define CALLTOKEN_IE_FORMAT "%u?%s"
04669 struct ast_str *buf = ast_str_alloca(256);
04670 time_t t = time(NULL);
04671 char hash[41];
04672 int subclass = uncompress_subclass(fh->csub);
04673
04674
04675 if (ies->calltoken && !ies->calltokendata) {
04676 struct iax_ie_data ied = {
04677 .buf = { 0 },
04678 .pos = 0,
04679 };
04680
04681
04682 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) t, randomcalltokendata);
04683 ast_sha1_hash(hash, ast_str_buffer(buf));
04684
04685 ast_str_set(&buf, 0, CALLTOKEN_IE_FORMAT, (unsigned int) t, hash);
04686 iax_ie_append_str(&ied, IAX_IE_CALLTOKEN, ast_str_buffer(buf));
04687 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_CALLTOKEN, ntohl(fh->ts), fh->iseqno + 1, fd, &ied);
04688
04689 return 1;
04690
04691
04692 } else if (ies->calltoken && ies->calltokendata) {
04693 char *rec_hash = NULL;
04694 char *rec_ts = NULL;
04695 unsigned int rec_time;
04696
04697
04698 rec_hash = strchr((char *) ies->calltokendata, '?');
04699 if (rec_hash) {
04700 *rec_hash++ = '\0';
04701 rec_ts = (char *) ies->calltokendata;
04702 }
04703
04704
04705 if (!rec_hash || !rec_ts) {
04706 goto reject;
04707 } else if (sscanf(rec_ts, "%u", &rec_time) != 1) {
04708 goto reject;
04709 }
04710
04711
04712 ast_str_set(&buf, 0, CALLTOKEN_HASH_FORMAT, ast_inet_ntoa(sin->sin_addr), sin->sin_port, (unsigned int) rec_time, randomcalltokendata);
04713 ast_sha1_hash(hash, ast_str_buffer(buf));
04714
04715
04716 if (strcmp(hash, rec_hash)) {
04717 ast_log(LOG_WARNING, "Address %s failed CallToken hash inspection\n", ast_inet_ntoa(sin->sin_addr));
04718 goto reject;
04719 } else if ((t < rec_time) || ((t - rec_time) >= MAX_CALLTOKEN_DELAY)) {
04720 ast_log(LOG_WARNING, "Too much delay in IAX2 calltoken timestamp from address %s\n", ast_inet_ntoa(sin->sin_addr));
04721 goto reject;
04722 }
04723
04724
04725
04726 requirecalltoken_mark_auto(ies->username, subclass);
04727 return 0;
04728
04729
04730 } else {
04731 if (calltoken_required(sin, ies->username, subclass)) {
04732 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"));
04733 goto reject;
04734 }
04735 return 0;
04736 }
04737
04738 reject:
04739
04740 if (subclass == IAX_COMMAND_REGREQ || subclass == IAX_COMMAND_REGREL) {
04741 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04742 } else {
04743 send_apathetic_reply(1, ntohs(fh->scallno), sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
04744 }
04745
04746 return 1;
04747 }
04748
04749
04750
04751
04752
04753
04754
04755
04756
04757
04758
04759
04760
04761
04762
04763
04764
04765
04766
04767 static void parse_dial_string(char *data, struct parsed_dial_string *pds)
04768 {
04769 if (ast_strlen_zero(data))
04770 return;
04771
04772 pds->peer = strsep(&data, "/");
04773 pds->exten = strsep(&data, "/");
04774 pds->options = data;
04775
04776 if (pds->exten) {
04777 data = pds->exten;
04778 pds->exten = strsep(&data, "@");
04779 pds->context = data;
04780 }
04781
04782 if (strchr(pds->peer, '@')) {
04783 data = pds->peer;
04784 pds->username = strsep(&data, "@");
04785 pds->peer = data;
04786 }
04787
04788 if (pds->username) {
04789 data = pds->username;
04790 pds->username = strsep(&data, ":");
04791 pds->password = data;
04792 }
04793
04794 data = pds->peer;
04795 pds->peer = strsep(&data, ":");
04796 pds->port = data;
04797
04798
04799
04800
04801 if (pds->password && (pds->password[0] == '[')) {
04802 pds->key = ast_strip_quoted(pds->password, "[", "]");
04803 pds->password = NULL;
04804 }
04805 }
04806
04807 static int iax2_call(struct ast_channel *c, char *dest, int timeout)
04808 {
04809 struct sockaddr_in sin;
04810 char *l=NULL, *n=NULL, *tmpstr;
04811 struct iax_ie_data ied;
04812 char *defaultrdest = "s";
04813 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
04814 struct parsed_dial_string pds;
04815 struct create_addr_info cai;
04816 struct ast_var_t *var;
04817 struct ast_datastore *variablestore = ast_channel_datastore_find(c, &iax2_variable_datastore_info, NULL);
04818 const char* osp_token_ptr;
04819 unsigned int osp_token_length;
04820 unsigned char osp_block_index;
04821 unsigned int osp_block_length;
04822 unsigned char osp_buffer[256];
04823
04824 if ((c->_state != AST_STATE_DOWN) && (c->_state != AST_STATE_RESERVED)) {
04825 ast_log(LOG_WARNING, "Channel is already in use (%s)?\n", c->name);
04826 return -1;
04827 }
04828
04829 memset(&cai, 0, sizeof(cai));
04830 cai.encmethods = iax2_encryption;
04831
04832 memset(&pds, 0, sizeof(pds));
04833 tmpstr = ast_strdupa(dest);
04834 parse_dial_string(tmpstr, &pds);
04835
04836 if (ast_strlen_zero(pds.peer)) {
04837 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", dest);
04838 return -1;
04839 }
04840 if (!pds.exten) {
04841 pds.exten = defaultrdest;
04842 }
04843 if (create_addr(pds.peer, c, &sin, &cai)) {
04844 ast_log(LOG_WARNING, "No address associated with '%s'\n", pds.peer);
04845 return -1;
04846 }
04847 if (ast_strlen_zero(cai.secret) && ast_test_flag(iaxs[callno], IAX_FORCE_ENCRYPT)) {
04848 ast_log(LOG_WARNING, "Call terminated. No secret given and force encrypt enabled\n");
04849 return -1;
04850 }
04851 if (!pds.username && !ast_strlen_zero(cai.username))
04852 pds.username = cai.username;
04853 if (!pds.password && !ast_strlen_zero(cai.secret))
04854 pds.password = cai.secret;
04855 if (!pds.key && !ast_strlen_zero(cai.outkey))
04856 pds.key = cai.outkey;
04857 if (!pds.context && !ast_strlen_zero(cai.peercontext))
04858 pds.context = cai.peercontext;
04859
04860
04861 ast_copy_string(c->context, cai.context, sizeof(c->context));
04862
04863 if (pds.port)
04864 sin.sin_port = htons(atoi(pds.port));
04865
04866 l = c->cid.cid_num;
04867 n = c->cid.cid_name;
04868
04869
04870 memset(&ied, 0, sizeof(ied));
04871
04872
04873 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
04874 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, pds.exten);
04875 if (pds.options && strchr(pds.options, 'a')) {
04876
04877 iax_ie_append(&ied, IAX_IE_AUTOANSWER);
04878 }
04879
04880 iax_ie_append_str(&ied, IAX_IE_CODEC_PREFS, cai.prefs);
04881
04882 if (l) {
04883 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, l);
04884 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
04885 } else {
04886 if (n)
04887 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, c->cid.cid_pres);
04888 else
04889 iax_ie_append_byte(&ied, IAX_IE_CALLINGPRES, AST_PRES_NUMBER_NOT_AVAILABLE);
04890 }
04891
04892 iax_ie_append_byte(&ied, IAX_IE_CALLINGTON, c->cid.cid_ton);
04893 iax_ie_append_short(&ied, IAX_IE_CALLINGTNS, c->cid.cid_tns);
04894
04895 if (n)
04896 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, n);
04897 if (ast_test_flag(iaxs[callno], IAX_SENDANI) && c->cid.cid_ani)
04898 iax_ie_append_str(&ied, IAX_IE_CALLING_ANI, c->cid.cid_ani);
04899
04900 if (!ast_strlen_zero(c->language))
04901 iax_ie_append_str(&ied, IAX_IE_LANGUAGE, c->language);
04902 if (!ast_strlen_zero(c->cid.cid_dnid))
04903 iax_ie_append_str(&ied, IAX_IE_DNID, c->cid.cid_dnid);
04904 if (!ast_strlen_zero(c->cid.cid_rdnis))
04905 iax_ie_append_str(&ied, IAX_IE_RDNIS, c->cid.cid_rdnis);
04906
04907 if (pds.context)
04908 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.context);
04909
04910 if (pds.username)
04911 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
04912
04913 if (cai.encmethods)
04914 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, cai.encmethods);
04915
04916 ast_mutex_lock(&iaxsl[callno]);
04917
04918 if (!ast_strlen_zero(c->context))
04919 ast_string_field_set(iaxs[callno], context, c->context);
04920
04921 if (pds.username)
04922 ast_string_field_set(iaxs[callno], username, pds.username);
04923
04924 iaxs[callno]->encmethods = cai.encmethods;
04925
04926 iaxs[callno]->adsi = cai.adsi;
04927
04928 ast_string_field_set(iaxs[callno], mohinterpret, cai.mohinterpret);
04929 ast_string_field_set(iaxs[callno], mohsuggest, cai.mohsuggest);
04930
04931 if (pds.key)
04932 ast_string_field_set(iaxs[callno], outkey, pds.key);
04933 if (pds.password)
04934 ast_string_field_set(iaxs[callno], secret, pds.password);
04935
04936 iax_ie_append_int(&ied, IAX_IE_FORMAT, c->nativeformats);
04937 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, iaxs[callno]->capability);
04938 iax_ie_append_short(&ied, IAX_IE_ADSICPE, c->adsicpe);
04939 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(cai.timezone));
04940
04941 if (iaxs[callno]->maxtime) {
04942
04943 iaxs[callno]->pingtime = iaxs[callno]->maxtime / 2;
04944 iaxs[callno]->initid = iax2_sched_add(sched, iaxs[callno]->maxtime * 2, auto_congest, CALLNO_TO_PTR(callno));
04945 } else if (autokill) {
04946 iaxs[callno]->pingtime = autokill / 2;
04947 iaxs[callno]->initid = iax2_sched_add(sched, autokill * 2, auto_congest, CALLNO_TO_PTR(callno));
04948 }
04949
04950
04951 osp_token_ptr = pbx_builtin_getvar_helper(c, "IAX2OSPTOKEN");
04952 if (!ast_strlen_zero(osp_token_ptr)) {
04953 if ((osp_token_length = strlen(osp_token_ptr)) <= IAX_MAX_OSPTOKEN_SIZE) {
04954 osp_block_index = 0;
04955 while (osp_token_length > 0) {
04956 osp_block_length = IAX_MAX_OSPBLOCK_SIZE < osp_token_length ? IAX_MAX_OSPBLOCK_SIZE : osp_token_length;
04957 osp_buffer[0] = osp_block_index;
04958 memcpy(osp_buffer + 1, osp_token_ptr, osp_block_length);
04959 iax_ie_append_raw(&ied, IAX_IE_OSPTOKEN, osp_buffer, osp_block_length + 1);
04960 osp_block_index++;
04961 osp_token_ptr += osp_block_length;
04962 osp_token_length -= osp_block_length;
04963 }
04964 } else
04965 ast_log(LOG_WARNING, "OSP token is too long\n");
04966 } else if (iaxdebug)
04967 ast_debug(1, "OSP token is undefined\n");
04968
04969
04970 iaxs[callno]->sockfd = cai.sockfd;
04971
04972
04973 if (variablestore) {
04974 AST_LIST_HEAD(, ast_var_t) *variablelist = variablestore->data;
04975 ast_debug(1, "Found an IAX variable store on this channel\n");
04976 AST_LIST_LOCK(variablelist);
04977 AST_LIST_TRAVERSE(variablelist, var, entries) {
04978 char tmp[256];
04979 int i;
04980 ast_debug(1, "Found IAXVAR '%s' with value '%s' (to transmit)\n", ast_var_name(var), ast_var_value(var));
04981
04982 for (i = 0; i < strlen(ast_var_value(var)); i += 255 - (strlen(ast_var_name(var)) + 1)) {
04983 snprintf(tmp, sizeof(tmp), "%s=%s", ast_var_name(var), ast_var_value(var) + i);
04984 iax_ie_append_str(&ied, IAX_IE_VARIABLE, tmp);
04985 }
04986 }
04987 AST_LIST_UNLOCK(variablelist);
04988 }
04989
04990
04991 add_empty_calltoken_ie(iaxs[callno], &ied);
04992 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
04993
04994 ast_mutex_unlock(&iaxsl[callno]);
04995 ast_setstate(c, AST_STATE_RINGING);
04996
04997 return 0;
04998 }
04999
05000 static int iax2_hangup(struct ast_channel *c)
05001 {
05002 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05003 struct iax_ie_data ied;
05004 int alreadygone;
05005 memset(&ied, 0, sizeof(ied));
05006 ast_mutex_lock(&iaxsl[callno]);
05007 if (callno && iaxs[callno]) {
05008 ast_debug(1, "We're hanging up %s now...\n", c->name);
05009 alreadygone = ast_test_flag(iaxs[callno], IAX_ALREADYGONE);
05010
05011 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, (unsigned char)c->hangupcause);
05012 if (!iaxs[callno]->error && !alreadygone) {
05013 if (send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1)) {
05014 ast_log(LOG_WARNING, "No final packet could be sent for callno %d\n", callno);
05015 }
05016 if (!iaxs[callno]) {
05017 ast_mutex_unlock(&iaxsl[callno]);
05018 return 0;
05019 }
05020 }
05021
05022 iax2_predestroy(callno);
05023
05024 if (iaxs[callno] && alreadygone) {
05025 ast_debug(1, "Really destroying %s now...\n", c->name);
05026 iax2_destroy(callno);
05027 } else if (iaxs[callno]) {
05028 if (ast_sched_thread_add(sched, 10000, scheduled_destroy, CALLNO_TO_PTR(callno)) < 0) {
05029 ast_log(LOG_ERROR, "Unable to schedule iax2 callno %d destruction?!! Destroying immediately.\n", callno);
05030 iax2_destroy(callno);
05031 }
05032 }
05033 } else if (c->tech_pvt) {
05034
05035
05036
05037
05038 c->tech_pvt = NULL;
05039 }
05040 ast_mutex_unlock(&iaxsl[callno]);
05041 ast_verb(3, "Hungup '%s'\n", c->name);
05042 return 0;
05043 }
05044
05045
05046
05047
05048 static int wait_for_peercallno(struct chan_iax2_pvt *pvt)
05049 {
05050 unsigned short callno = pvt->callno;
05051
05052 if (!pvt->peercallno) {
05053
05054 int count = 10;
05055 while (count-- && pvt && !pvt->peercallno) {
05056 DEADLOCK_AVOIDANCE(&iaxsl[callno]);
05057 pvt = iaxs[callno];
05058 }
05059 if (!pvt->peercallno) {
05060 return -1;
05061 }
05062 }
05063
05064 return 0;
05065 }
05066
05067 static int iax2_setoption(struct ast_channel *c, int option, void *data, int datalen)
05068 {
05069 struct ast_option_header *h;
05070 int res;
05071
05072 switch (option) {
05073 case AST_OPTION_TXGAIN:
05074 case AST_OPTION_RXGAIN:
05075
05076 errno = ENOSYS;
05077 return -1;
05078 case AST_OPTION_OPRMODE:
05079 errno = EINVAL;
05080 return -1;
05081 default:
05082 {
05083 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05084 struct chan_iax2_pvt *pvt;
05085
05086 ast_mutex_lock(&iaxsl[callno]);
05087 pvt = iaxs[callno];
05088
05089 if (wait_for_peercallno(pvt)) {
05090 ast_mutex_unlock(&iaxsl[callno]);
05091 return -1;
05092 }
05093
05094 ast_mutex_unlock(&iaxsl[callno]);
05095
05096 if (!(h = ast_malloc(datalen + sizeof(*h)))) {
05097 return -1;
05098 }
05099
05100 h->flag = AST_OPTION_FLAG_REQUEST;
05101 h->option = htons(option);
05102 memcpy(h->data, data, datalen);
05103 res = send_command_locked(PTR_TO_CALLNO(c->tech_pvt), AST_FRAME_CONTROL,
05104 AST_CONTROL_OPTION, 0, (unsigned char *) h,
05105 datalen + sizeof(*h), -1);
05106 ast_free(h);
05107 return res;
05108 }
05109 }
05110 }
05111
05112 static struct ast_frame *iax2_read(struct ast_channel *c)
05113 {
05114 ast_log(LOG_NOTICE, "I should never be called!\n");
05115 return &ast_null_frame;
05116 }
05117
05118 static int iax2_key_rotate(const void *vpvt)
05119 {
05120 int res = 0;
05121 struct chan_iax2_pvt *pvt = (void *) vpvt;
05122 struct MD5Context md5;
05123 char key[17] = "";
05124 struct iax_ie_data ied = {
05125 .pos = 0,
05126 };
05127
05128 ast_mutex_lock(&iaxsl[pvt->callno]);
05129 pvt->keyrotateid =
05130 ast_sched_thread_add(sched, 120000 + (ast_random() % 180001), iax2_key_rotate, vpvt);
05131
05132 snprintf(key, sizeof(key), "%lX", ast_random());
05133
05134 MD5Init(&md5);
05135 MD5Update(&md5, (unsigned char *) key, strlen(key));
05136 MD5Final((unsigned char *) key, &md5);
05137
05138 IAX_DEBUGDIGEST("Sending", key);
05139
05140 iax_ie_append_raw(&ied, IAX_IE_CHALLENGE, key, 16);
05141
05142 res = send_command(pvt, AST_FRAME_IAX, IAX_COMMAND_RTKEY, 0, ied.buf, ied.pos, -1);
05143
05144 build_ecx_key((unsigned char *) key, pvt);
05145
05146 ast_mutex_unlock(&iaxsl[pvt->callno]);
05147
05148 return res;
05149 }
05150
05151 static int iax2_start_transfer(unsigned short callno0, unsigned short callno1, int mediaonly)
05152 {
05153 int res;
05154 struct iax_ie_data ied0;
05155 struct iax_ie_data ied1;
05156 unsigned int transferid = (unsigned int)ast_random();
05157
05158 if (IAX_CALLENCRYPTED(iaxs[callno0]) || IAX_CALLENCRYPTED(iaxs[callno1])) {
05159 ast_debug(1, "transfers are not supported for encrypted calls at this time");
05160 ast_set_flag(iaxs[callno0], IAX_NOTRANSFER);
05161 ast_set_flag(iaxs[callno1], IAX_NOTRANSFER);
05162 return 0;
05163 }
05164
05165 memset(&ied0, 0, sizeof(ied0));
05166 iax_ie_append_addr(&ied0, IAX_IE_APPARENT_ADDR, &iaxs[callno1]->addr);
05167 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[callno1]->peercallno);
05168 iax_ie_append_int(&ied0, IAX_IE_TRANSFERID, transferid);
05169
05170 memset(&ied1, 0, sizeof(ied1));
05171 iax_ie_append_addr(&ied1, IAX_IE_APPARENT_ADDR, &iaxs[callno0]->addr);
05172 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[callno0]->peercallno);
05173 iax_ie_append_int(&ied1, IAX_IE_TRANSFERID, transferid);
05174
05175 res = send_command(iaxs[callno0], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied0.buf, ied0.pos, -1);
05176 if (res)
05177 return -1;
05178 res = send_command(iaxs[callno1], AST_FRAME_IAX, IAX_COMMAND_TXREQ, 0, ied1.buf, ied1.pos, -1);
05179 if (res)
05180 return -1;
05181 iaxs[callno0]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05182 iaxs[callno1]->transferring = mediaonly ? TRANSFER_MBEGIN : TRANSFER_BEGIN;
05183 return 0;
05184 }
05185
05186 static void lock_both(unsigned short callno0, unsigned short callno1)
05187 {
05188 ast_mutex_lock(&iaxsl[callno0]);
05189 while (ast_mutex_trylock(&iaxsl[callno1])) {
05190 DEADLOCK_AVOIDANCE(&iaxsl[callno0]);
05191 }
05192 }
05193
05194 static void unlock_both(unsigned short callno0, unsigned short callno1)
05195 {
05196 ast_mutex_unlock(&iaxsl[callno1]);
05197 ast_mutex_unlock(&iaxsl[callno0]);
05198 }
05199
05200 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)
05201 {
05202 struct ast_channel *cs[3];
05203 struct ast_channel *who, *other;
05204 int to = -1;
05205 int res = -1;
05206 int transferstarted=0;
05207 struct ast_frame *f;
05208 unsigned short callno0 = PTR_TO_CALLNO(c0->tech_pvt);
05209 unsigned short callno1 = PTR_TO_CALLNO(c1->tech_pvt);
05210 struct timeval waittimer = {0, 0};
05211
05212
05213 if (timeoutms > 0) {
05214 return AST_BRIDGE_FAILED;
05215 }
05216
05217 timeoutms = -1;
05218
05219 lock_both(callno0, callno1);
05220 if (!iaxs[callno0] || !iaxs[callno1]) {
05221 unlock_both(callno0, callno1);
05222 return AST_BRIDGE_FAILED;
05223 }
05224
05225 if (!(flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
05226 iaxs[callno0]->bridgecallno = callno1;
05227 iaxs[callno1]->bridgecallno = callno0;
05228 }
05229 unlock_both(callno0, callno1);
05230
05231
05232 cs[0] = c0;
05233 cs[1] = c1;
05234 for (;;) {
05235
05236 if ((c0->tech != &iax2_tech) || (c1->tech != &iax2_tech)) {
05237 ast_verb(3, "Can't masquerade, we're different...\n");
05238
05239 if (c0->tech == &iax2_tech) {
05240 ast_mutex_lock(&iaxsl[callno0]);
05241 iaxs[callno0]->bridgecallno = 0;
05242 ast_mutex_unlock(&iaxsl[callno0]);
05243 }
05244 if (c1->tech == &iax2_tech) {
05245 ast_mutex_lock(&iaxsl[callno1]);
05246 iaxs[callno1]->bridgecallno = 0;
05247 ast_mutex_unlock(&iaxsl[callno1]);
05248 }
05249 return AST_BRIDGE_FAILED_NOWARN;
05250 }
05251 if (c0->nativeformats != c1->nativeformats) {
05252 char buf0[255];
05253 char buf1[255];
05254 ast_getformatname_multiple(buf0, sizeof(buf0) -1, c0->nativeformats);
05255 ast_getformatname_multiple(buf1, sizeof(buf1) -1, c1->nativeformats);
05256 ast_verb(3, "Operating with different codecs %d[%s] %d[%s] , can't native bridge...\n", c0->nativeformats, buf0, c1->nativeformats, buf1);
05257
05258 lock_both(callno0, callno1);
05259 if (iaxs[callno0])
05260 iaxs[callno0]->bridgecallno = 0;
05261 if (iaxs[callno1])
05262 iaxs[callno1]->bridgecallno = 0;
05263 unlock_both(callno0, callno1);
05264 return AST_BRIDGE_FAILED_NOWARN;
05265 }
05266
05267 if (!transferstarted && !ast_test_flag(iaxs[callno0], IAX_NOTRANSFER) && !ast_test_flag(iaxs[callno1], IAX_NOTRANSFER)) {
05268
05269 if (iax2_start_transfer(callno0, callno1, (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1)) ||
05270 ast_test_flag(iaxs[callno0], IAX_TRANSFERMEDIA) | ast_test_flag(iaxs[callno1], IAX_TRANSFERMEDIA)))
05271 ast_log(LOG_WARNING, "Unable to start the transfer\n");
05272 transferstarted = 1;
05273 }
05274 if ((iaxs[callno0]->transferring == TRANSFER_RELEASED) && (iaxs[callno1]->transferring == TRANSFER_RELEASED)) {
05275
05276 struct timeval now = ast_tvnow();
05277 if (ast_tvzero(waittimer)) {
05278 waittimer = now;
05279 } else if (now.tv_sec - waittimer.tv_sec > IAX_LINGER_TIMEOUT) {
05280 c0->_softhangup |= AST_SOFTHANGUP_DEV;
05281 c1->_softhangup |= AST_SOFTHANGUP_DEV;
05282 *fo = NULL;
05283 *rc = c0;
05284 res = AST_BRIDGE_COMPLETE;
05285 break;
05286 }
05287 }
05288 to = 1000;
05289 who = ast_waitfor_n(cs, 2, &to);
05290 if (timeoutms > -1) {
05291 timeoutms -= (1000 - to);
05292 if (timeoutms < 0)
05293 timeoutms = 0;
05294 }
05295 if (!who) {
05296 if (!timeoutms) {
05297 res = AST_BRIDGE_RETRY;
05298 break;
05299 }
05300 if (ast_check_hangup(c0) || ast_check_hangup(c1)) {
05301 res = AST_BRIDGE_FAILED;
05302 break;
05303 }
05304 continue;
05305 }
05306 f = ast_read(who);
05307 if (!f) {
05308 *fo = NULL;
05309 *rc = who;
05310 res = AST_BRIDGE_COMPLETE;
05311 break;
05312 }
05313 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS) && (f->subclass != AST_CONTROL_SRCUPDATE)) {
05314 *fo = f;
05315 *rc = who;
05316 res = AST_BRIDGE_COMPLETE;
05317 break;
05318 }
05319 other = (who == c0) ? c1 : c0;
05320 if ((f->frametype == AST_FRAME_VOICE) ||
05321 (f->frametype == AST_FRAME_TEXT) ||
05322 (f->frametype == AST_FRAME_VIDEO) ||
05323 (f->frametype == AST_FRAME_IMAGE) ||
05324 (f->frametype == AST_FRAME_DTMF) ||
05325 (f->frametype == AST_FRAME_CONTROL)) {
05326
05327
05328
05329 int monitored_source = (who == c0) ? AST_BRIDGE_DTMF_CHANNEL_0 : AST_BRIDGE_DTMF_CHANNEL_1;
05330 if (f->frametype == AST_FRAME_DTMF && (flags & monitored_source)) {
05331 *rc = who;
05332 *fo = f;
05333 res = AST_BRIDGE_COMPLETE;
05334
05335 break;
05336 }
05337
05338 ast_write(other, f);
05339 }
05340 ast_frfree(f);
05341
05342 cs[2] = cs[0];
05343 cs[0] = cs[1];
05344 cs[1] = cs[2];
05345 }
05346 lock_both(callno0, callno1);
05347 if(iaxs[callno0])
05348 iaxs[callno0]->bridgecallno = 0;
05349 if(iaxs[callno1])
05350 iaxs[callno1]->bridgecallno = 0;
05351 unlock_both(callno0, callno1);
05352 return res;
05353 }
05354
05355 static int iax2_answer(struct ast_channel *c)
05356 {
05357 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05358 ast_debug(1, "Answering IAX2 call\n");
05359 ast_mutex_lock(&iaxsl[callno]);
05360 if (iaxs[callno])
05361 iax2_ami_channelupdate(iaxs[callno]);
05362 ast_mutex_unlock(&iaxsl[callno]);
05363 return send_command_locked(callno, AST_FRAME_CONTROL, AST_CONTROL_ANSWER, 0, NULL, 0, -1);
05364 }
05365
05366 static int iax2_indicate(struct ast_channel *c, int condition, const void *data, size_t datalen)
05367 {
05368 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05369 struct chan_iax2_pvt *pvt;
05370 int res = 0;
05371
05372 if (iaxdebug)
05373 ast_debug(1, "Indicating condition %d\n", condition);
05374
05375 ast_mutex_lock(&iaxsl[callno]);
05376 pvt = iaxs[callno];
05377
05378 if (wait_for_peercallno(pvt)) {
05379 res = -1;
05380 goto done;
05381 }
05382
05383 switch (condition) {
05384 case AST_CONTROL_HOLD:
05385 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05386 ast_moh_start(c, data, pvt->mohinterpret);
05387 goto done;
05388 }
05389 break;
05390 case AST_CONTROL_UNHOLD:
05391 if (strcasecmp(pvt->mohinterpret, "passthrough")) {
05392 ast_moh_stop(c);
05393 goto done;
05394 }
05395 }
05396
05397 res = send_command(pvt, AST_FRAME_CONTROL, condition, 0, data, datalen, -1);
05398
05399 done:
05400 ast_mutex_unlock(&iaxsl[callno]);
05401
05402 return res;
05403 }
05404
05405 static int iax2_transfer(struct ast_channel *c, const char *dest)
05406 {
05407 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
05408 struct iax_ie_data ied = { "", };
05409 char tmp[256], *context;
05410 ast_copy_string(tmp, dest, sizeof(tmp));
05411 context = strchr(tmp, '@');
05412 if (context) {
05413 *context = '\0';
05414 context++;
05415 }
05416 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, tmp);
05417 if (context)
05418 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, context);
05419 ast_debug(1, "Transferring '%s' to '%s'\n", c->name, dest);
05420 return send_command_locked(callno, AST_FRAME_IAX, IAX_COMMAND_TRANSFER, 0, ied.buf, ied.pos, -1);
05421 }
05422
05423 static int iax2_getpeertrunk(struct sockaddr_in sin)
05424 {
05425 struct iax2_peer *peer;
05426 int res = 0;
05427 struct ao2_iterator i;
05428
05429 i = ao2_iterator_init(peers, 0);
05430 while ((peer = ao2_iterator_next(&i))) {
05431 if ((peer->addr.sin_addr.s_addr == sin.sin_addr.s_addr) &&
05432 (peer->addr.sin_port == sin.sin_port)) {
05433 res = ast_test_flag(peer, IAX_TRUNK);
05434 peer_unref(peer);
05435 break;
05436 }
05437 peer_unref(peer);
05438 }
05439 ao2_iterator_destroy(&i);
05440
05441 return res;
05442 }
05443
05444
05445 static struct ast_channel *ast_iax2_new(int callno, int state, int capability)
05446 {
05447 struct ast_channel *tmp;
05448 struct chan_iax2_pvt *i;
05449 struct ast_variable *v = NULL;
05450
05451 if (!(i = iaxs[callno])) {
05452 ast_log(LOG_WARNING, "No IAX2 pvt found for callno '%d' !\n", callno);
05453 return NULL;
05454 }
05455
05456
05457 ast_mutex_unlock(&iaxsl[callno]);
05458 tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "IAX2/%s-%d", i->host, i->callno);
05459 ast_mutex_lock(&iaxsl[callno]);
05460 if (i != iaxs[callno]) {
05461 if (tmp) {
05462
05463 ast_mutex_unlock(&iaxsl[callno]);
05464 ast_channel_free(tmp);
05465 ast_mutex_lock(&iaxsl[callno]);
05466 }
05467 return NULL;
05468 }
05469 iax2_ami_channelupdate(i);
05470 if (!tmp)
05471 return NULL;
05472 tmp->tech = &iax2_tech;
05473
05474 tmp->nativeformats = capability;
05475 tmp->readformat = tmp->rawreadformat = ast_best_codec(capability);
05476 tmp->writeformat = tmp->rawwriteformat = ast_best_codec(capability);
05477 tmp->tech_pvt = CALLNO_TO_PTR(i->callno);
05478
05479 if (!ast_strlen_zero(i->parkinglot))
05480 ast_string_field_set(tmp, parkinglot, i->parkinglot);
05481
05482
05483 if (!ast_strlen_zero(i->ani))
05484 tmp->cid.cid_ani = ast_strdup(i->ani);
05485 else
05486 tmp->cid.cid_ani = ast_strdup(i->cid_num);
05487 tmp->cid.cid_dnid = ast_strdup(i->dnid);
05488 tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
05489 tmp->cid.cid_pres = i->calling_pres;
05490 tmp->cid.cid_ton = i->calling_ton;
05491 tmp->cid.cid_tns = i->calling_tns;
05492 if (!ast_strlen_zero(i->language))
05493 ast_string_field_set(tmp, language, i->language);
05494 if (!ast_strlen_zero(i->accountcode))
05495 ast_string_field_set(tmp, accountcode, i->accountcode);
05496 if (i->amaflags)
05497 tmp->amaflags = i->amaflags;
05498 ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
05499 ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
05500 if (i->adsi)
05501 tmp->adsicpe = i->peeradsicpe;
05502 else
05503 tmp->adsicpe = AST_ADSI_UNAVAILABLE;
05504 i->owner = tmp;
05505 i->capability = capability;
05506
05507
05508 if (i->vars) {
05509 for (v = i->vars ; v ; v = v->next)
05510 pbx_builtin_setvar_helper(tmp, v->name, v->value);
05511 }
05512 if (i->iaxvars) {
05513 struct ast_datastore *variablestore;
05514 struct ast_variable *var, *prev = NULL;
05515 AST_LIST_HEAD(, ast_var_t) *varlist;
05516 ast_debug(1, "Loading up the channel with IAXVARs\n");
05517 varlist = ast_calloc(1, sizeof(*varlist));
05518 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
05519 if (variablestore && varlist) {
05520 variablestore->data = varlist;
05521 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
05522 AST_LIST_HEAD_INIT(varlist);
05523 for (var = i->iaxvars; var; var = var->next) {
05524 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
05525 if (prev)
05526 ast_free(prev);
05527 prev = var;
05528 if (!newvar) {
05529
05530 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
05531 } else {
05532 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
05533 }
05534 }
05535 if (prev)
05536 ast_free(prev);
05537 i->iaxvars = NULL;
05538 ast_channel_datastore_add(i->owner, variablestore);
05539 } else {
05540 if (variablestore) {
05541 ast_datastore_free(variablestore);
05542 }
05543 if (varlist) {
05544 ast_free(varlist);
05545 }
05546 }
05547 }
05548
05549 if (state != AST_STATE_DOWN) {
05550 if (ast_pbx_start(tmp)) {
05551 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
05552 ast_hangup(tmp);
05553 i->owner = NULL;
05554 return NULL;
05555 }
05556 }
05557
05558 ast_module_ref(ast_module_info->self);
05559 return tmp;
05560 }
05561
05562 static unsigned int calc_txpeerstamp(struct iax2_trunk_peer *tpeer, int sampms, struct timeval *now)
05563 {
05564 unsigned long int mssincetx;
05565 long int ms, pred;
05566
05567 tpeer->trunkact = *now;
05568 mssincetx = ast_tvdiff_ms(*now, tpeer->lasttxtime);
05569 if (mssincetx > 5000 || ast_tvzero(tpeer->txtrunktime)) {
05570
05571 tpeer->txtrunktime = *now;
05572 tpeer->lastsent = 999999;
05573 }
05574
05575 tpeer->lasttxtime = *now;
05576
05577
05578 ms = ast_tvdiff_ms(*now, tpeer->txtrunktime);
05579
05580 pred = tpeer->lastsent + sampms;
05581 if (abs(ms - pred) < MAX_TIMESTAMP_SKEW)
05582 ms = pred;
05583
05584
05585 if (ms == tpeer->lastsent)
05586 ms = tpeer->lastsent + 1;
05587 tpeer->lastsent = ms;
05588 return ms;
05589 }
05590
05591 static unsigned int fix_peerts(struct timeval *rxtrunktime, int callno, unsigned int ts)
05592 {
05593 long ms;
05594 if (ast_tvzero(iaxs[callno]->rxcore)) {
05595
05596 iaxs[callno]->rxcore = ast_tvnow();
05597
05598 iaxs[callno]->rxcore.tv_usec -= iaxs[callno]->rxcore.tv_usec % 20000;
05599 }
05600
05601 ms = ast_tvdiff_ms(*rxtrunktime, iaxs[callno]->rxcore);
05602
05603 return ms + ts;
05604 }
05605
05606 static unsigned int calc_timestamp(struct chan_iax2_pvt *p, unsigned int ts, struct ast_frame *f)
05607 {
05608 int ms;
05609 int voice = 0;
05610 int genuine = 0;
05611 int adjust;
05612 int rate = ast_format_rate(f->subclass) / 1000;
05613 struct timeval *delivery = NULL;
05614
05615
05616
05617
05618
05619
05620
05621
05622 if (f) {
05623 if (f->frametype == AST_FRAME_VOICE) {
05624 voice = 1;
05625 delivery = &f->delivery;
05626 } else if (f->frametype == AST_FRAME_IAX) {
05627 genuine = 1;
05628 } else if (f->frametype == AST_FRAME_CNG) {
05629 p->notsilenttx = 0;
05630 }
05631 }
05632 if (ast_tvzero(p->offset)) {
05633 p->offset = ast_tvnow();
05634
05635 p->offset.tv_usec -= p->offset.tv_usec % 20000;
05636 }
05637
05638 if (ts)
05639 return ts;
05640
05641 if (delivery && !ast_tvzero(*delivery)) {
05642 ms = ast_tvdiff_ms(*delivery, p->offset);
05643 if (ms < 0) {
05644 ms = 0;
05645 }
05646 if (iaxdebug)
05647 ast_debug(3, "calc_timestamp: call %d/%d: Timestamp slaved to delivery time\n", p->callno, iaxs[p->callno]->peercallno);
05648 } else {
05649 ms = ast_tvdiff_ms(ast_tvnow(), p->offset);
05650 if (ms < 0)
05651 ms = 0;
05652 if (voice) {
05653
05654 if (p->notsilenttx && abs(ms - p->nextpred) <= MAX_TIMESTAMP_SKEW) {
05655
05656
05657
05658
05659
05660
05661
05662
05663
05664
05665
05666
05667
05668
05669
05670
05671
05672
05673 adjust = (ms - p->nextpred);
05674 if (adjust < 0)
05675 p->offset = ast_tvsub(p->offset, ast_samp2tv(abs(adjust), 10000));
05676 else if (adjust > 0)
05677 p->offset = ast_tvadd(p->offset, ast_samp2tv(adjust, 10000));
05678
05679 if (!p->nextpred) {
05680 p->nextpred = ms;
05681 if (p->nextpred <= p->lastsent)
05682 p->nextpred = p->lastsent + 3;
05683 }
05684 ms = p->nextpred;
05685 } else {
05686
05687
05688
05689
05690
05691
05692
05693
05694
05695 if (iaxdebug && abs(ms - p->nextpred) > MAX_TIMESTAMP_SKEW )
05696 ast_debug(1, "predicted timestamp skew (%u) > max (%u), using real ts instead.\n",
05697 abs(ms - p->nextpred), MAX_TIMESTAMP_SKEW);
05698
05699 if (f->samples >= rate)
05700 {
05701 int diff = ms % (f->samples / rate);
05702 if (diff)
05703 ms += f->samples/rate - diff;
05704 }
05705
05706 p->nextpred = ms;
05707 p->notsilenttx = 1;
05708 }
05709 } else if ( f->frametype == AST_FRAME_VIDEO ) {
05710
05711
05712
05713
05714
05715
05716
05717
05718 if ( (unsigned int)ms < p->lastsent )
05719 ms = p->lastsent;
05720 } else {
05721
05722
05723 if (genuine) {
05724
05725 if (ms <= p->lastsent)
05726 ms = p->lastsent + 3;
05727 } else if (abs(ms - p->lastsent) <= MAX_TIMESTAMP_SKEW) {
05728
05729 ms = p->lastsent + 3;
05730 }
05731 }
05732 }
05733 p->lastsent = ms;
05734 if (voice)
05735 p->nextpred = p->nextpred + f->samples / rate;
05736 return ms;
05737 }
05738
05739 static unsigned int calc_rxstamp(struct chan_iax2_pvt *p, unsigned int offset)
05740 {
05741
05742
05743 int ms;
05744 #ifdef IAXTESTS
05745 int jit;
05746 #endif
05747
05748 if (ast_tvzero(p->rxcore)) {
05749 p->rxcore = ast_tvnow();
05750 if (iaxdebug)
05751 ast_debug(1, "calc_rxstamp: call=%d: rxcore set to %d.%6.6d - %dms\n",
05752 p->callno, (int)(p->rxcore.tv_sec), (int)(p->rxcore.tv_usec), offset);
05753 p->rxcore = ast_tvsub(p->rxcore, ast_samp2tv(offset, 1000));
05754 #if 1
05755 if (iaxdebug)
05756 ast_debug(1, "calc_rxstamp: call=%d: works out as %d.%6.6d\n",
05757 p->callno, (int)(p->rxcore.tv_sec),(int)( p->rxcore.tv_usec));
05758 #endif
05759 }
05760
05761 ms = ast_tvdiff_ms(ast_tvnow(), p->rxcore);
05762 #ifdef IAXTESTS
05763 if (test_jit) {
05764 if (!test_jitpct || ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_jitpct)) {
05765 jit = (int)((float)test_jit * ast_random() / (RAND_MAX + 1.0));
05766 if ((int)(2.0 * ast_random() / (RAND_MAX + 1.0)))
05767 jit = -jit;
05768 ms += jit;
05769 }
05770 }
05771 if (test_late) {
05772 ms += test_late;
05773 test_late = 0;
05774 }
05775 #endif
05776 return ms;
05777 }
05778
05779 static struct iax2_trunk_peer *find_tpeer(struct sockaddr_in *sin, int fd)
05780 {
05781 struct iax2_trunk_peer *tpeer = NULL;
05782
05783
05784 AST_LIST_LOCK(&tpeers);
05785
05786 AST_LIST_TRAVERSE(&tpeers, tpeer, list) {
05787 if (!inaddrcmp(&tpeer->addr, sin)) {
05788 ast_mutex_lock(&tpeer->lock);
05789 break;
05790 }
05791 }
05792
05793 if (!tpeer) {
05794 if ((tpeer = ast_calloc(1, sizeof(*tpeer)))) {
05795 ast_mutex_init(&tpeer->lock);
05796 tpeer->lastsent = 9999;
05797 memcpy(&tpeer->addr, sin, sizeof(tpeer->addr));
05798 tpeer->trunkact = ast_tvnow();
05799 ast_mutex_lock(&tpeer->lock);
05800 tpeer->sockfd = fd;
05801 #ifdef SO_NO_CHECK
05802 setsockopt(tpeer->sockfd, SOL_SOCKET, SO_NO_CHECK, &nochecksums, sizeof(nochecksums));
05803 #endif
05804 ast_debug(1, "Created trunk peer for '%s:%d'\n", ast_inet_ntoa(tpeer->addr.sin_addr), ntohs(tpeer->addr.sin_port));
05805 AST_LIST_INSERT_TAIL(&tpeers, tpeer, list);
05806 }
05807 }
05808
05809 AST_LIST_UNLOCK(&tpeers);
05810
05811 return tpeer;
05812 }
05813
05814 static int iax2_trunk_queue(struct chan_iax2_pvt *pvt, struct iax_frame *fr)
05815 {
05816 struct ast_frame *f;
05817 struct iax2_trunk_peer *tpeer;
05818 void *tmp, *ptr;
05819 struct timeval now;
05820 int res;
05821 struct ast_iax2_meta_trunk_entry *met;
05822 struct ast_iax2_meta_trunk_mini *mtm;
05823
05824 f = &fr->af;
05825 tpeer = find_tpeer(&pvt->addr, pvt->sockfd);
05826 if (tpeer) {
05827 if (tpeer->trunkdatalen + f->datalen + 4 >= tpeer->trunkdataalloc) {
05828
05829 if (tpeer->trunkdataalloc < trunkmaxsize) {
05830 if (!(tmp = ast_realloc(tpeer->trunkdata, tpeer->trunkdataalloc + DEFAULT_TRUNKDATA + IAX2_TRUNK_PREFACE))) {
05831 ast_mutex_unlock(&tpeer->lock);
05832 return -1;
05833 }
05834
05835 tpeer->trunkdataalloc += DEFAULT_TRUNKDATA;
05836 tpeer->trunkdata = tmp;
05837 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);
05838 } else {
05839 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));
05840 ast_mutex_unlock(&tpeer->lock);
05841 return -1;
05842 }
05843 }
05844
05845
05846 ptr = tpeer->trunkdata + IAX2_TRUNK_PREFACE + tpeer->trunkdatalen;
05847 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS)) {
05848 mtm = (struct ast_iax2_meta_trunk_mini *)ptr;
05849 mtm->len = htons(f->datalen);
05850 mtm->mini.callno = htons(pvt->callno);
05851 mtm->mini.ts = htons(0xffff & fr->ts);
05852 ptr += sizeof(struct ast_iax2_meta_trunk_mini);
05853 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_mini);
05854 } else {
05855 met = (struct ast_iax2_meta_trunk_entry *)ptr;
05856
05857 met->callno = htons(pvt->callno);
05858 met->len = htons(f->datalen);
05859
05860 ptr += sizeof(struct ast_iax2_meta_trunk_entry);
05861 tpeer->trunkdatalen += sizeof(struct ast_iax2_meta_trunk_entry);
05862 }
05863
05864 memcpy(ptr, f->data.ptr, f->datalen);
05865 tpeer->trunkdatalen += f->datalen;
05866
05867 tpeer->calls++;
05868
05869
05870 if (tpeer->trunkdatalen + f->datalen + 4 > trunk_maxmtu)
05871 trunk_maxmtu = tpeer->trunkdatalen + f->datalen + 4 ;
05872
05873
05874 if (global_max_trunk_mtu > 0 && tpeer->trunkdatalen + f->datalen + 4 >= global_max_trunk_mtu) {
05875 now = ast_tvnow();
05876 res = send_trunk(tpeer, &now);
05877 trunk_untimed ++;
05878 }
05879
05880 ast_mutex_unlock(&tpeer->lock);
05881 }
05882 return 0;
05883 }
05884
05885
05886
05887 static void build_rand_pad(unsigned char *buf, ssize_t len)
05888 {
05889 long tmp;
05890 for (tmp = ast_random(); len > 0; tmp = ast_random()) {
05891 memcpy(buf, (unsigned char *) &tmp, (len > sizeof(tmp)) ? sizeof(tmp) : len);
05892 buf += sizeof(tmp);
05893 len -= sizeof(tmp);
05894 }
05895 }
05896
05897 static void build_encryption_keys(const unsigned char *digest, struct chan_iax2_pvt *pvt)
05898 {
05899 build_ecx_key(digest, pvt);
05900 ast_aes_decrypt_key(digest, &pvt->dcx);
05901 }
05902
05903 static void build_ecx_key(const unsigned char *digest, struct chan_iax2_pvt *pvt)
05904 {
05905
05906
05907
05908 build_rand_pad(pvt->semirand, sizeof(pvt->semirand));
05909 ast_aes_encrypt_key(digest, &pvt->ecx);
05910 ast_aes_decrypt_key(digest, &pvt->mydcx);
05911 }
05912
05913 static void memcpy_decrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_decrypt_key *dcx)
05914 {
05915 #if 0
05916
05917 int x;
05918 if (len % 16)
05919 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
05920 for (x=0;x<len;x++)
05921 dst[x] = src[x] ^ 0xff;
05922 #else
05923 unsigned char lastblock[16] = { 0 };
05924 int x;
05925 while(len > 0) {
05926 ast_aes_decrypt(src, dst, dcx);
05927 for (x=0;x<16;x++)
05928 dst[x] ^= lastblock[x];
05929 memcpy(lastblock, src, sizeof(lastblock));
05930 dst += 16;
05931 src += 16;
05932 len -= 16;
05933 }
05934 #endif
05935 }
05936
05937 static void memcpy_encrypt(unsigned char *dst, const unsigned char *src, int len, ast_aes_encrypt_key *ecx)
05938 {
05939 #if 0
05940
05941 int x;
05942 if (len % 16)
05943 ast_log(LOG_WARNING, "len should be multiple of 16, not %d!\n", len);
05944 for (x=0;x<len;x++)
05945 dst[x] = src[x] ^ 0xff;
05946 #else
05947 unsigned char curblock[16] = { 0 };
05948 int x;
05949 while(len > 0) {
05950 for (x=0;x<16;x++)
05951 curblock[x] ^= src[x];
05952 ast_aes_encrypt(curblock, dst, ecx);
05953 memcpy(curblock, dst, sizeof(curblock));
05954 dst += 16;
05955 src += 16;
05956 len -= 16;
05957 }
05958 #endif
05959 }
05960
05961 static int decode_frame(ast_aes_decrypt_key *dcx, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
05962 {
05963 int padding;
05964 unsigned char *workspace;
05965
05966 workspace = alloca(*datalen);
05967 memset(f, 0, sizeof(*f));
05968 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
05969 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
05970 if (*datalen < 16 + sizeof(struct ast_iax2_full_hdr))
05971 return -1;
05972
05973 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr), dcx);
05974
05975 padding = 16 + (workspace[15] & 0x0f);
05976 if (iaxdebug)
05977 ast_debug(1, "Decoding full frame with length %d (padding = %d) (15=%02x)\n", *datalen, padding, workspace[15]);
05978 if (*datalen < padding + sizeof(struct ast_iax2_full_hdr))
05979 return -1;
05980
05981 *datalen -= padding;
05982 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
05983 f->frametype = fh->type;
05984 if (f->frametype == AST_FRAME_VIDEO) {
05985 f->subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
05986 } else {
05987 f->subclass = uncompress_subclass(fh->csub);
05988 }
05989 } else {
05990 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
05991 if (iaxdebug)
05992 ast_debug(1, "Decoding mini with length %d\n", *datalen);
05993 if (*datalen < 16 + sizeof(struct ast_iax2_mini_hdr))
05994 return -1;
05995
05996 memcpy_decrypt(workspace, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), dcx);
05997 padding = 16 + (workspace[15] & 0x0f);
05998 if (*datalen < padding + sizeof(struct ast_iax2_mini_hdr))
05999 return -1;
06000 *datalen -= padding;
06001 memcpy(efh->encdata, workspace + padding, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06002 }
06003 return 0;
06004 }
06005
06006 static int encrypt_frame(ast_aes_encrypt_key *ecx, struct ast_iax2_full_hdr *fh, unsigned char *poo, int *datalen)
06007 {
06008 int padding;
06009 unsigned char *workspace;
06010 workspace = alloca(*datalen + 32);
06011 if (!workspace)
06012 return -1;
06013 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
06014 struct ast_iax2_full_enc_hdr *efh = (struct ast_iax2_full_enc_hdr *)fh;
06015 if (iaxdebug)
06016 ast_debug(1, "Encoding full frame %d/%d with length %d\n", fh->type, fh->csub, *datalen);
06017 padding = 16 - ((*datalen - sizeof(struct ast_iax2_full_enc_hdr)) % 16);
06018 padding = 16 + (padding & 0xf);
06019 memcpy(workspace, poo, padding);
06020 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_full_enc_hdr));
06021 workspace[15] &= 0xf0;
06022 workspace[15] |= (padding & 0xf);
06023 if (iaxdebug)
06024 ast_debug(1, "Encoding full frame %d/%d with length %d + %d padding (15=%02x)\n", fh->type, fh->csub, *datalen, padding, workspace[15]);
06025 *datalen += padding;
06026 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_full_enc_hdr), ecx);
06027 if (*datalen >= 32 + sizeof(struct ast_iax2_full_enc_hdr))
06028 memcpy(poo, workspace + *datalen - 32, 32);
06029 } else {
06030 struct ast_iax2_mini_enc_hdr *efh = (struct ast_iax2_mini_enc_hdr *)fh;
06031 if (iaxdebug)
06032 ast_debug(1, "Encoding mini frame with length %d\n", *datalen);
06033 padding = 16 - ((*datalen - sizeof(struct ast_iax2_mini_enc_hdr)) % 16);
06034 padding = 16 + (padding & 0xf);
06035 memcpy(workspace, poo, padding);
06036 memcpy(workspace + padding, efh->encdata, *datalen - sizeof(struct ast_iax2_mini_enc_hdr));
06037 workspace[15] &= 0xf0;
06038 workspace[15] |= (padding & 0x0f);
06039 *datalen += padding;
06040 memcpy_encrypt(efh->encdata, workspace, *datalen - sizeof(struct ast_iax2_mini_enc_hdr), ecx);
06041 if (*datalen >= 32 + sizeof(struct ast_iax2_mini_enc_hdr))
06042 memcpy(poo, workspace + *datalen - 32, 32);
06043 }
06044 return 0;
06045 }
06046
06047 static int decrypt_frame(int callno, struct ast_iax2_full_hdr *fh, struct ast_frame *f, int *datalen)
06048 {
06049 int res=-1;
06050 if (!ast_test_flag(iaxs[callno], IAX_KEYPOPULATED)) {
06051
06052 struct MD5Context md5;
06053 unsigned char digest[16];
06054 char *tmppw, *stringp;
06055
06056 tmppw = ast_strdupa(iaxs[callno]->secret);
06057 stringp = tmppw;
06058 while ((tmppw = strsep(&stringp, ";"))) {
06059 MD5Init(&md5);
06060 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
06061 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
06062 MD5Final(digest, &md5);
06063 build_encryption_keys(digest, iaxs[callno]);
06064 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06065 if (!res) {
06066 ast_set_flag(iaxs[callno], IAX_KEYPOPULATED);
06067 break;
06068 }
06069 }
06070 } else
06071 res = decode_frame(&iaxs[callno]->dcx, fh, f, datalen);
06072 return res;
06073 }
06074
06075 static int iax2_send(struct chan_iax2_pvt *pvt, struct ast_frame *f, unsigned int ts, int seqno, int now, int transfer, int final)
06076 {
06077
06078
06079
06080 struct ast_iax2_full_hdr *fh;
06081 struct ast_iax2_mini_hdr *mh;
06082 struct ast_iax2_video_hdr *vh;
06083 struct {
06084 struct iax_frame fr2;
06085 unsigned char buffer[4096];
06086 } frb;
06087 struct iax_frame *fr;
06088 int res;
06089 int sendmini=0;
06090 unsigned int lastsent;
06091 unsigned int fts;
06092
06093 frb.fr2.afdatalen = sizeof(frb.buffer);
06094
06095 if (!pvt) {
06096 ast_log(LOG_WARNING, "No private structure for packet?\n");
06097 return -1;
06098 }
06099
06100 lastsent = pvt->lastsent;
06101
06102
06103 fts = calc_timestamp(pvt, ts, f);
06104
06105
06106
06107
06108 if(f->frametype == AST_FRAME_VOICE && f->datalen == 0)
06109 return 0;
06110 #if 0
06111 ast_log(LOG_NOTICE,
06112 "f->frametype %c= AST_FRAME_VOICE, %sencrypted, %srotation scheduled...\n",
06113 *("=!" + (f->frametype == AST_FRAME_VOICE)),
06114 IAX_CALLENCRYPTED(pvt) ? "" : "not ",
06115 pvt->keyrotateid != -1 ? "" : "no "
06116 );
06117 #endif
06118 if (pvt->keyrotateid == -1 && f->frametype == AST_FRAME_VOICE && IAX_CALLENCRYPTED(pvt)) {
06119 iax2_key_rotate(pvt);
06120 }
06121
06122 if ((ast_test_flag(pvt, IAX_TRUNK) ||
06123 (((fts & 0xFFFF0000L) == (lastsent & 0xFFFF0000L)) ||
06124 ((fts & 0xFFFF0000L) == ((lastsent + 0x10000) & 0xFFFF0000L))))
06125 &&
06126 (f->frametype == AST_FRAME_VOICE)
06127 &&
06128 (f->subclass == pvt->svoiceformat)
06129 ) {
06130
06131 now = 1;
06132
06133 sendmini = 1;
06134 }
06135 if ( f->frametype == AST_FRAME_VIDEO ) {
06136
06137
06138
06139
06140
06141 if (((fts & 0xFFFF8000L) == (pvt->lastvsent & 0xFFFF8000L)) &&
06142 ((f->subclass & ~0x1) == pvt->svideoformat)
06143 ) {
06144 now = 1;
06145 sendmini = 1;
06146 } else {
06147 now = 0;
06148 sendmini = 0;
06149 }
06150 pvt->lastvsent = fts;
06151 }
06152 if (f->frametype == AST_FRAME_IAX) {
06153
06154 pvt->last_iax_message = f->subclass | MARK_IAX_SUBCLASS_TX;
06155 if (!pvt->first_iax_message) {
06156 pvt->first_iax_message = pvt->last_iax_message;
06157 }
06158 }
06159
06160 if (now) {
06161 fr = &frb.fr2;
06162 } else
06163 fr = iax_frame_new(DIRECTION_OUTGRESS, ast_test_flag(pvt, IAX_ENCRYPTED) ? f->datalen + 32 : f->datalen, (f->frametype == AST_FRAME_VOICE) || (f->frametype == AST_FRAME_VIDEO));
06164 if (!fr) {
06165 ast_log(LOG_WARNING, "Out of memory\n");
06166 return -1;
06167 }
06168
06169 iax_frame_wrap(fr, f);
06170
06171 fr->ts = fts;
06172 fr->callno = pvt->callno;
06173 fr->transfer = transfer;
06174 fr->final = final;
06175 fr->encmethods = 0;
06176 if (!sendmini) {
06177
06178 if (seqno > -1)
06179 fr->oseqno = seqno;
06180 else
06181 fr->oseqno = pvt->oseqno++;
06182 fr->iseqno = pvt->iseqno;
06183 fh = (struct ast_iax2_full_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_full_hdr));
06184 fh->scallno = htons(fr->callno | IAX_FLAG_FULL);
06185 fh->ts = htonl(fr->ts);
06186 fh->oseqno = fr->oseqno;
06187 if (transfer) {
06188 fh->iseqno = 0;
06189 } else
06190 fh->iseqno = fr->iseqno;
06191
06192 if (!transfer)
06193 pvt->aseqno = fr->iseqno;
06194 fh->type = fr->af.frametype & 0xFF;
06195 if (fr->af.frametype == AST_FRAME_VIDEO)
06196 fh->csub = compress_subclass(fr->af.subclass & ~0x1) | ((fr->af.subclass & 0x1) << 6);
06197 else
06198 fh->csub = compress_subclass(fr->af.subclass);
06199 if (transfer) {
06200 fr->dcallno = pvt->transfercallno;
06201 } else
06202 fr->dcallno = pvt->peercallno;
06203 fh->dcallno = htons(fr->dcallno);
06204 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_full_hdr);
06205 fr->data = fh;
06206 fr->retries = 0;
06207
06208 fr->retrytime = pvt->pingtime * 2;
06209 if (fr->retrytime < MIN_RETRY_TIME)
06210 fr->retrytime = MIN_RETRY_TIME;
06211 if (fr->retrytime > MAX_RETRY_TIME)
06212 fr->retrytime = MAX_RETRY_TIME;
06213
06214 if ((f->frametype == AST_FRAME_IAX) && (f->subclass == IAX_COMMAND_ACK))
06215 fr->retries = -1;
06216 else if (f->frametype == AST_FRAME_VOICE)
06217 pvt->svoiceformat = f->subclass;
06218 else if (f->frametype == AST_FRAME_VIDEO)
06219 pvt->svideoformat = f->subclass & ~0x1;
06220 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
06221 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
06222 if (fr->transfer)
06223 iax_outputframe(fr, NULL, 2, &pvt->transfer, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06224 else
06225 iax_outputframe(fr, NULL, 2, &pvt->addr, fr->datalen - sizeof(struct ast_iax2_full_hdr));
06226 encrypt_frame(&pvt->ecx, fh, pvt->semirand, &fr->datalen);
06227 fr->encmethods = pvt->encmethods;
06228 fr->ecx = pvt->ecx;
06229 fr->mydcx = pvt->mydcx;
06230 memcpy(fr->semirand, pvt->semirand, sizeof(fr->semirand));
06231 } else
06232 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06233 }
06234
06235 if (now) {
06236 res = send_packet(fr);
06237 } else
06238 res = iax2_transmit(fr);
06239 } else {
06240 if (ast_test_flag(pvt, IAX_TRUNK)) {
06241 iax2_trunk_queue(pvt, fr);
06242 res = 0;
06243 } else if (fr->af.frametype == AST_FRAME_VIDEO) {
06244
06245 fr->oseqno = -1;
06246 fr->iseqno = -1;
06247 vh = (struct ast_iax2_video_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_video_hdr));
06248 vh->zeros = 0;
06249 vh->callno = htons(0x8000 | fr->callno);
06250 vh->ts = htons((fr->ts & 0x7FFF) | (fr->af.subclass & 0x1 ? 0x8000 : 0));
06251 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_video_hdr);
06252 fr->data = vh;
06253 fr->retries = -1;
06254 res = send_packet(fr);
06255 } else {
06256
06257 fr->oseqno = -1;
06258 fr->iseqno = -1;
06259
06260 mh = (struct ast_iax2_mini_hdr *)(fr->af.data.ptr - sizeof(struct ast_iax2_mini_hdr));
06261 mh->callno = htons(fr->callno);
06262 mh->ts = htons(fr->ts & 0xFFFF);
06263 fr->datalen = fr->af.datalen + sizeof(struct ast_iax2_mini_hdr);
06264 fr->data = mh;
06265 fr->retries = -1;
06266 if (pvt->transferring == TRANSFER_MEDIAPASS)
06267 fr->transfer = 1;
06268 if (ast_test_flag(pvt, IAX_ENCRYPTED)) {
06269 if (ast_test_flag(pvt, IAX_KEYPOPULATED)) {
06270 encrypt_frame(&pvt->ecx, (struct ast_iax2_full_hdr *)mh, pvt->semirand, &fr->datalen);
06271 } else
06272 ast_log(LOG_WARNING, "Supposed to send packet encrypted, but no key?\n");
06273 }
06274 res = send_packet(fr);
06275 }
06276 }
06277 return res;
06278 }
06279
06280 static char *handle_cli_iax2_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06281 {
06282 regex_t regexbuf;
06283 int havepattern = 0;
06284
06285 #define FORMAT "%-15.15s %-20.20s %-15.15s %-15.15s %-5.5s %-5.10s\n"
06286 #define FORMAT2 "%-15.15s %-20.20s %-15.15d %-15.15s %-5.5s %-5.10s\n"
06287
06288 struct iax2_user *user = NULL;
06289 char auth[90];
06290 char *pstr = "";
06291 struct ao2_iterator i;
06292
06293 switch (cmd) {
06294 case CLI_INIT:
06295 e->command = "iax2 show users [like]";
06296 e->usage =
06297 "Usage: iax2 show users [like <pattern>]\n"
06298 " Lists all known IAX2 users.\n"
06299 " Optional regular expression pattern is used to filter the user list.\n";
06300 return NULL;
06301 case CLI_GENERATE:
06302 return NULL;
06303 }
06304
06305 switch (a->argc) {
06306 case 5:
06307 if (!strcasecmp(a->argv[3], "like")) {
06308 if (regcomp(®exbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
06309 return CLI_SHOWUSAGE;
06310 havepattern = 1;
06311 } else
06312 return CLI_SHOWUSAGE;
06313 case 3:
06314 break;
06315 default:
06316 return CLI_SHOWUSAGE;
06317 }
06318
06319 ast_cli(a->fd, FORMAT, "Username", "Secret", "Authen", "Def.Context", "A/C","Codec Pref");
06320 i = ao2_iterator_init(users, 0);
06321 for (user = ao2_iterator_next(&i); user;
06322 user_unref(user), user = ao2_iterator_next(&i)) {
06323 if (havepattern && regexec(®exbuf, user->name, 0, NULL, 0))
06324 continue;
06325
06326 if (!ast_strlen_zero(user->secret)) {
06327 ast_copy_string(auth,user->secret, sizeof(auth));
06328 } else if (!ast_strlen_zero(user->inkeys)) {
06329 snprintf(auth, sizeof(auth), "Key: %-15.15s ", user->inkeys);
06330 } else
06331 ast_copy_string(auth, "-no secret-", sizeof(auth));
06332
06333 if(ast_test_flag(user,IAX_CODEC_NOCAP))
06334 pstr = "REQ Only";
06335 else if(ast_test_flag(user,IAX_CODEC_NOPREFS))
06336 pstr = "Disabled";
06337 else
06338 pstr = ast_test_flag(user,IAX_CODEC_USER_FIRST) ? "Caller" : "Host";
06339
06340 ast_cli(a->fd, FORMAT2, user->name, auth, user->authmethods,
06341 user->contexts ? user->contexts->context : DEFAULT_CONTEXT,
06342 user->ha ? "Yes" : "No", pstr);
06343 }
06344 ao2_iterator_destroy(&i);
06345
06346 if (havepattern)
06347 regfree(®exbuf);
06348
06349 return CLI_SUCCESS;
06350 #undef FORMAT
06351 #undef FORMAT2
06352 }
06353
06354 static int __iax2_show_peers(int manager, int fd, struct mansession *s, int argc, char *argv[])
06355 {
06356 regex_t regexbuf;
06357 int havepattern = 0;
06358 int total_peers = 0;
06359 int online_peers = 0;
06360 int offline_peers = 0;
06361 int unmonitored_peers = 0;
06362 struct ao2_iterator i;
06363
06364 #define FORMAT2 "%-15.15s %-15.15s %s %-15.15s %-8s %s %-10s%s"
06365 #define FORMAT "%-15.15s %-15.15s %s %-15.15s %-5d%s %s %-10s%s"
06366
06367 struct iax2_peer *peer = NULL;
06368 char name[256];
06369 struct ast_str *encmethods = ast_str_alloca(256);
06370 int registeredonly=0;
06371 char *term = manager ? "\r\n" : "\n";
06372 char idtext[256] = "";
06373 switch (argc) {
06374 case 6:
06375 if (!strcasecmp(argv[3], "registered"))
06376 registeredonly = 1;
06377 else
06378 return RESULT_SHOWUSAGE;
06379 if (!strcasecmp(argv[4], "like")) {
06380 if (regcomp(®exbuf, argv[5], REG_EXTENDED | REG_NOSUB))
06381 return RESULT_SHOWUSAGE;
06382 havepattern = 1;
06383 } else
06384 return RESULT_SHOWUSAGE;
06385 break;
06386 case 5:
06387 if (!strcasecmp(argv[3], "like")) {
06388 if (regcomp(®exbuf, argv[4], REG_EXTENDED | REG_NOSUB))
06389 return RESULT_SHOWUSAGE;
06390 havepattern = 1;
06391 } else
06392 return RESULT_SHOWUSAGE;
06393 break;
06394 case 4:
06395 if (!strcasecmp(argv[3], "registered"))
06396 registeredonly = 1;
06397 else
06398 return RESULT_SHOWUSAGE;
06399 break;
06400 case 3:
06401 break;
06402 default:
06403 return RESULT_SHOWUSAGE;
06404 }
06405
06406
06407 if (!s)
06408 ast_cli(fd, FORMAT2, "Name/Username", "Host", " ", "Mask", "Port", " ", "Status", term);
06409
06410 i = ao2_iterator_init(peers, 0);
06411 for (peer = ao2_iterator_next(&i); peer;
06412 peer_unref(peer), peer = ao2_iterator_next(&i)) {
06413 char nm[20];
06414 char status[20];
06415 int retstatus;
06416
06417 if (registeredonly && !peer->addr.sin_addr.s_addr)
06418 continue;
06419 if (havepattern && regexec(®exbuf, peer->name, 0, NULL, 0))
06420 continue;
06421
06422 if (!ast_strlen_zero(peer->username))
06423 snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
06424 else
06425 ast_copy_string(name, peer->name, sizeof(name));
06426
06427 encmethods_to_str(peer->encmethods, encmethods);
06428 retstatus = peer_status(peer, status, sizeof(status));
06429 if (retstatus > 0)
06430 online_peers++;
06431 else if (!retstatus)
06432 offline_peers++;
06433 else
06434 unmonitored_peers++;
06435
06436 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06437
06438 if (s) {
06439 astman_append(s,
06440 "Event: PeerEntry\r\n%s"
06441 "Channeltype: IAX2\r\n"
06442 "ChanObjectType: peer\r\n"
06443 "ObjectName: %s\r\n"
06444 "IPaddress: %s\r\n"
06445 "IPport: %d\r\n"
06446 "Dynamic: %s\r\n"
06447 "Trunk: %s\r\n"
06448 "Encryption: %s\r\n"
06449 "Status: %s\r\n\r\n",
06450 idtext,
06451 name,
06452 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
06453 ntohs(peer->addr.sin_port),
06454 ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no",
06455 ast_test_flag(peer, IAX_TRUNK) ? "yes" : "no",
06456 peer->encmethods ? ast_str_buffer(encmethods) : "no",
06457 status);
06458 } else {
06459 ast_cli(fd, FORMAT, name,
06460 peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
06461 ast_test_flag(peer, IAX_DYNAMIC) ? "(D)" : "(S)",
06462 nm,
06463 ntohs(peer->addr.sin_port),
06464 ast_test_flag(peer, IAX_TRUNK) ? "(T)" : " ",
06465 peer->encmethods ? "(E)" : " ",
06466 status,
06467 term);
06468 }
06469 total_peers++;
06470 }
06471 ao2_iterator_destroy(&i);
06472
06473 if (!s)
06474 ast_cli(fd,"%d iax2 peers [%d online, %d offline, %d unmonitored]%s", total_peers, online_peers, offline_peers, unmonitored_peers, term);
06475
06476 if (havepattern)
06477 regfree(®exbuf);
06478
06479 return RESULT_SUCCESS;
06480 #undef FORMAT
06481 #undef FORMAT2
06482 }
06483
06484 static char *handle_cli_iax2_show_threads(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06485 {
06486 struct iax2_thread *thread = NULL;
06487 time_t t;
06488 int threadcount = 0, dynamiccount = 0;
06489 char type;
06490
06491 switch (cmd) {
06492 case CLI_INIT:
06493 e->command = "iax2 show threads";
06494 e->usage =
06495 "Usage: iax2 show threads\n"
06496 " Lists status of IAX helper threads\n";
06497 return NULL;
06498 case CLI_GENERATE:
06499 return NULL;
06500 }
06501 if (a->argc != 3)
06502 return CLI_SHOWUSAGE;
06503
06504 ast_cli(a->fd, "IAX2 Thread Information\n");
06505 time(&t);
06506 ast_cli(a->fd, "Idle Threads:\n");
06507 AST_LIST_LOCK(&idle_list);
06508 AST_LIST_TRAVERSE(&idle_list, thread, list) {
06509 #ifdef DEBUG_SCHED_MULTITHREAD
06510 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06511 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06512 #else
06513 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06514 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06515 #endif
06516 threadcount++;
06517 }
06518 AST_LIST_UNLOCK(&idle_list);
06519 ast_cli(a->fd, "Active Threads:\n");
06520 AST_LIST_LOCK(&active_list);
06521 AST_LIST_TRAVERSE(&active_list, thread, list) {
06522 if (thread->type == IAX_THREAD_TYPE_DYNAMIC)
06523 type = 'D';
06524 else
06525 type = 'P';
06526 #ifdef DEBUG_SCHED_MULTITHREAD
06527 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d, func='%s'\n",
06528 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06529 #else
06530 ast_cli(a->fd, "Thread %c%d: state=%d, update=%d, actions=%d\n",
06531 type, thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06532 #endif
06533 threadcount++;
06534 }
06535 AST_LIST_UNLOCK(&active_list);
06536 ast_cli(a->fd, "Dynamic Threads:\n");
06537 AST_LIST_LOCK(&dynamic_list);
06538 AST_LIST_TRAVERSE(&dynamic_list, thread, list) {
06539 #ifdef DEBUG_SCHED_MULTITHREAD
06540 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d, func='%s'\n",
06541 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions, thread->curfunc);
06542 #else
06543 ast_cli(a->fd, "Thread %d: state=%d, update=%d, actions=%d\n",
06544 thread->threadnum, thread->iostate, (int)(t - thread->checktime), thread->actions);
06545 #endif
06546 dynamiccount++;
06547 }
06548 AST_LIST_UNLOCK(&dynamic_list);
06549 ast_cli(a->fd, "%d of %d threads accounted for with %d dynamic threads\n", threadcount, iaxthreadcount, dynamiccount);
06550 return CLI_SUCCESS;
06551 }
06552
06553 static char *handle_cli_iax2_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06554 {
06555 struct iax2_peer *p;
06556
06557 switch (cmd) {
06558 case CLI_INIT:
06559 e->command = "iax2 unregister";
06560 e->usage =
06561 "Usage: iax2 unregister <peername>\n"
06562 " Unregister (force expiration) an IAX2 peer from the registry.\n";
06563 return NULL;
06564 case CLI_GENERATE:
06565 return complete_iax2_unregister(a->line, a->word, a->pos, a->n);
06566 }
06567
06568 if (a->argc != 3)
06569 return CLI_SHOWUSAGE;
06570
06571 p = find_peer(a->argv[2], 1);
06572 if (p) {
06573 if (p->expire > 0) {
06574 struct iax2_peer tmp_peer = {
06575 .name = a->argv[2],
06576 };
06577 struct iax2_peer *peer;
06578
06579 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
06580 if (peer) {
06581 expire_registry(peer_ref(peer));
06582 peer_unref(peer);
06583 ast_cli(a->fd, "Peer %s unregistered\n", a->argv[2]);
06584 } else {
06585 ast_cli(a->fd, "Peer %s not found\n", a->argv[2]);
06586 }
06587 } else {
06588 ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
06589 }
06590 } else {
06591 ast_cli(a->fd, "Peer unknown: %s. Not unregistered\n", a->argv[2]);
06592 }
06593 return CLI_SUCCESS;
06594 }
06595
06596 static char *complete_iax2_unregister(const char *line, const char *word, int pos, int state)
06597 {
06598 int which = 0;
06599 struct iax2_peer *p = NULL;
06600 char *res = NULL;
06601 int wordlen = strlen(word);
06602
06603
06604 if (pos == 2) {
06605 struct ao2_iterator i = ao2_iterator_init(peers, 0);
06606 while ((p = ao2_iterator_next(&i))) {
06607 if (!strncasecmp(p->name, word, wordlen) &&
06608 ++which > state && p->expire > 0) {
06609 res = ast_strdup(p->name);
06610 peer_unref(p);
06611 break;
06612 }
06613 peer_unref(p);
06614 }
06615 ao2_iterator_destroy(&i);
06616 }
06617
06618 return res;
06619 }
06620
06621 static char *handle_cli_iax2_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06622 {
06623 switch (cmd) {
06624 case CLI_INIT:
06625 e->command = "iax2 show peers";
06626 e->usage =
06627 "Usage: iax2 show peers [registered] [like <pattern>]\n"
06628 " Lists all known IAX2 peers.\n"
06629 " Optional 'registered' argument lists only peers with known addresses.\n"
06630 " Optional regular expression pattern is used to filter the peer list.\n";
06631 return NULL;
06632 case CLI_GENERATE:
06633 return NULL;
06634 }
06635
06636 switch (__iax2_show_peers(0, a->fd, NULL, a->argc, a->argv)) {
06637 case RESULT_SHOWUSAGE:
06638 return CLI_SHOWUSAGE;
06639 case RESULT_FAILURE:
06640 return CLI_FAILURE;
06641 default:
06642 return CLI_SUCCESS;
06643 }
06644 }
06645
06646 static int manager_iax2_show_netstats(struct mansession *s, const struct message *m)
06647 {
06648 ast_cli_netstats(s, -1, 0);
06649 astman_append(s, "\r\n");
06650 return RESULT_SUCCESS;
06651 }
06652
06653 static char *handle_cli_iax2_show_firmware(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06654 {
06655 struct iax_firmware *cur = NULL;
06656
06657 switch (cmd) {
06658 case CLI_INIT:
06659 e->command = "iax2 show firmware";
06660 e->usage =
06661 "Usage: iax2 show firmware\n"
06662 " Lists all known IAX firmware images.\n";
06663 return NULL;
06664 case CLI_GENERATE:
06665 return NULL;
06666 }
06667
06668 if (a->argc != 3 && a->argc != 4)
06669 return CLI_SHOWUSAGE;
06670
06671 ast_cli(a->fd, "%-15.15s %-15.15s %-15.15s\n", "Device", "Version", "Size");
06672 AST_LIST_LOCK(&firmwares);
06673 AST_LIST_TRAVERSE(&firmwares, cur, list) {
06674 if ((a->argc == 3) || (!strcasecmp(a->argv[3], (char *) cur->fwh->devname))) {
06675 ast_cli(a->fd, "%-15.15s %-15d %-15d\n", cur->fwh->devname,
06676 ntohs(cur->fwh->version), (int)ntohl(cur->fwh->datalen));
06677 }
06678 }
06679 AST_LIST_UNLOCK(&firmwares);
06680
06681 return CLI_SUCCESS;
06682 }
06683
06684
06685 static int manager_iax2_show_peers(struct mansession *s, const struct message *m)
06686 {
06687 char *a[] = { "iax2", "show", "users" };
06688 const char *id = astman_get_header(m,"ActionID");
06689 char idtext[256] = "";
06690
06691 if (!ast_strlen_zero(id))
06692 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06693 astman_send_ack(s, m, "Peer status list will follow");
06694 return __iax2_show_peers(1, -1, s, 3, a );
06695 }
06696
06697
06698 static int manager_iax2_show_peer_list(struct mansession *s, const struct message *m)
06699 {
06700 struct iax2_peer *peer = NULL;
06701 int peer_count = 0;
06702 char nm[20];
06703 char status[20];
06704 const char *id = astman_get_header(m,"ActionID");
06705 char idtext[256] = "";
06706 struct ast_str *encmethods = ast_str_alloca(256);
06707 struct ao2_iterator i;
06708
06709 if (!ast_strlen_zero(id))
06710 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06711
06712 astman_append(s, "Response: Success\r\n%sMessage: IAX Peer status list will follow\r\n\r\n", idtext);
06713
06714
06715 i = ao2_iterator_init(peers, 0);
06716 for (peer = ao2_iterator_next(&i); peer; peer_unref(peer), peer = ao2_iterator_next(&i)) {
06717 encmethods_to_str(peer->encmethods, encmethods);
06718 astman_append(s, "Event: PeerEntry\r\n%sChanneltype: IAX\r\n", idtext);
06719 if (!ast_strlen_zero(peer->username)) {
06720 astman_append(s, "ObjectName: %s\r\nObjectUsername: %s\r\n", peer->name, peer->username);
06721 } else {
06722 astman_append(s, "ObjectName: %s\r\n", peer->name);
06723 }
06724 astman_append(s, "ChanObjectType: peer\r\n");
06725 astman_append(s, "IPaddress: %s\r\n", peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-");
06726 ast_copy_string(nm, ast_inet_ntoa(peer->mask), sizeof(nm));
06727 astman_append(s, "Mask: %s\r\n", nm);
06728 astman_append(s, "Port: %d\r\n", ntohs(peer->addr.sin_port));
06729 astman_append(s, "Dynamic: %s\r\n", ast_test_flag(peer, IAX_DYNAMIC) ? "Yes" : "No");
06730 astman_append(s, "Trunk: %s\r\n", ast_test_flag(peer, IAX_TRUNK) ? "Yes" : "No");
06731 astman_append(s, "Encryption: %s\r\n", peer->encmethods ? ast_str_buffer(encmethods) : "No");
06732 peer_status(peer, status, sizeof(status));
06733 astman_append(s, "Status: %s\r\n\r\n", status);
06734 peer_count++;
06735 }
06736 ao2_iterator_destroy(&i);
06737
06738 astman_append(s, "Event: PeerlistComplete\r\n%sListItems: %d\r\n\r\n", idtext, peer_count);
06739 return RESULT_SUCCESS;
06740 }
06741
06742
06743 static char *regstate2str(int regstate)
06744 {
06745 switch(regstate) {
06746 case REG_STATE_UNREGISTERED:
06747 return "Unregistered";
06748 case REG_STATE_REGSENT:
06749 return "Request Sent";
06750 case REG_STATE_AUTHSENT:
06751 return "Auth. Sent";
06752 case REG_STATE_REGISTERED:
06753 return "Registered";
06754 case REG_STATE_REJECTED:
06755 return "Rejected";
06756 case REG_STATE_TIMEOUT:
06757 return "Timeout";
06758 case REG_STATE_NOAUTH:
06759 return "No Authentication";
06760 default:
06761 return "Unknown";
06762 }
06763 }
06764
06765 static char *handle_cli_iax2_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06766 {
06767 #define FORMAT2 "%-20.20s %-6.6s %-10.10s %-20.20s %8.8s %s\n"
06768 #define FORMAT "%-20.20s %-6.6s %-10.10s %-20.20s %8d %s\n"
06769 struct iax2_registry *reg = NULL;
06770 char host[80];
06771 char perceived[80];
06772 int counter = 0;
06773
06774 switch (cmd) {
06775 case CLI_INIT:
06776 e->command = "iax2 show registry";
06777 e->usage =
06778 "Usage: iax2 show registry\n"
06779 " Lists all registration requests and status.\n";
06780 return NULL;
06781 case CLI_GENERATE:
06782 return NULL;
06783 }
06784 if (a->argc != 3)
06785 return CLI_SHOWUSAGE;
06786 ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Perceived", "Refresh", "State");
06787 AST_LIST_LOCK(®istrations);
06788 AST_LIST_TRAVERSE(®istrations, reg, entry) {
06789 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
06790 if (reg->us.sin_addr.s_addr)
06791 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
06792 else
06793 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
06794 ast_cli(a->fd, FORMAT, host,
06795 (reg->dnsmgr) ? "Y" : "N",
06796 reg->username, perceived, reg->refresh, regstate2str(reg->regstate));
06797 counter++;
06798 }
06799 AST_LIST_UNLOCK(®istrations);
06800 ast_cli(a->fd, "%d IAX2 registrations.\n", counter);
06801 return CLI_SUCCESS;
06802 #undef FORMAT
06803 #undef FORMAT2
06804 }
06805
06806 static int manager_iax2_show_registry(struct mansession *s, const struct message *m)
06807 {
06808 const char *id = astman_get_header(m, "ActionID");
06809 struct iax2_registry *reg = NULL;
06810 char idtext[256] = "";
06811 char host[80] = "";
06812 char perceived[80] = "";
06813 int total = 0;
06814
06815 if (!ast_strlen_zero(id))
06816 snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
06817
06818 astman_send_listack(s, m, "Registrations will follow", "start");
06819
06820 AST_LIST_LOCK(®istrations);
06821 AST_LIST_TRAVERSE(®istrations, reg, entry) {
06822 snprintf(host, sizeof(host), "%s:%d", ast_inet_ntoa(reg->addr.sin_addr), ntohs(reg->addr.sin_port));
06823
06824 if (reg->us.sin_addr.s_addr) {
06825 snprintf(perceived, sizeof(perceived), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
06826 } else {
06827 ast_copy_string(perceived, "<Unregistered>", sizeof(perceived));
06828 }
06829
06830 astman_append(s,
06831 "Event: RegistryEntry\r\n"
06832 "%s"
06833 "Host: %s\r\n"
06834 "DNSmanager: %s\r\n"
06835 "Username: %s\r\n"
06836 "Perceived: %s\r\n"
06837 "Refresh: %d\r\n"
06838 "State: %s\r\n"
06839 "\r\n", idtext, host, (reg->dnsmgr) ? "Y" : "N", reg->username, perceived,
06840 reg->refresh, regstate2str(reg->regstate));
06841
06842 total++;
06843 }
06844 AST_LIST_UNLOCK(®istrations);
06845
06846 astman_append(s,
06847 "Event: RegistrationsComplete\r\n"
06848 "EventList: Complete\r\n"
06849 "ListItems: %d\r\n"
06850 "%s"
06851 "\r\n", total, idtext);
06852
06853 return 0;
06854 }
06855
06856 static char *handle_cli_iax2_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
06857 {
06858 #define FORMAT2 "%-20.20s %-15.15s %-10.10s %-11.11s %-11.11s %-7.7s %-6.6s %-6.6s %s %s %9s\n"
06859 #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"
06860 #define FORMATB "%-20.20s %-15.15s %-10.10s %5.5d/%5.5d %5.5d/%5.5d [Native Bridged to ID=%5.5d]\n"
06861 int x;
06862 int numchans = 0;
06863 char first_message[10] = { 0, };
06864 char last_message[10] = { 0, };
06865
06866 switch (cmd) {
06867 case CLI_INIT:
06868 e->command = "iax2 show channels";
06869 e->usage =
06870 "Usage: iax2 show channels\n"
06871 " Lists all currently active IAX channels.\n";
06872 return NULL;
06873 case CLI_GENERATE:
06874 return NULL;
06875 }
06876
06877 if (a->argc != 3)
06878 return CLI_SHOWUSAGE;
06879 ast_cli(a->fd, FORMAT2, "Channel", "Peer", "Username", "ID (Lo/Rem)", "Seq (Tx/Rx)", "Lag", "Jitter", "JitBuf", "Format", "FirstMsg", "LastMsg");
06880 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
06881 ast_mutex_lock(&iaxsl[x]);
06882 if (iaxs[x]) {
06883 int lag, jitter, localdelay;
06884 jb_info jbinfo;
06885 if (ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
06886 jb_getinfo(iaxs[x]->jb, &jbinfo);
06887 jitter = jbinfo.jitter;
06888 localdelay = jbinfo.current - jbinfo.min;
06889 } else {
06890 jitter = -1;
06891 localdelay = 0;
06892 }
06893
06894 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
06895 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
06896 lag = iaxs[x]->remote_rr.delay;
06897 ast_cli(a->fd, FORMAT,
06898 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
06899 ast_inet_ntoa(iaxs[x]->addr.sin_addr),
06900 S_OR(iaxs[x]->username, "(None)"),
06901 iaxs[x]->callno, iaxs[x]->peercallno,
06902 iaxs[x]->oseqno, iaxs[x]->iseqno,
06903 lag,
06904 jitter,
06905 localdelay,
06906 ast_getformatname(iaxs[x]->voiceformat),
06907 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06908 first_message,
06909 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06910 last_message);
06911 numchans++;
06912 }
06913 ast_mutex_unlock(&iaxsl[x]);
06914 }
06915 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
06916 return CLI_SUCCESS;
06917 #undef FORMAT
06918 #undef FORMAT2
06919 #undef FORMATB
06920 }
06921
06922 static int ast_cli_netstats(struct mansession *s, int fd, int limit_fmt)
06923 {
06924 int x;
06925 int numchans = 0;
06926 char first_message[10] = { 0, };
06927 char last_message[10] = { 0, };
06928 #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"
06929 #define ACN_FORMAT2 "%s %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %s%s %s%s\n"
06930 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
06931 ast_mutex_lock(&iaxsl[x]);
06932 if (iaxs[x]) {
06933 int localjitter, localdelay, locallost, locallosspct, localdropped, localooo;
06934 jb_info jbinfo;
06935 iax_frame_subclass2str(iaxs[x]->first_iax_message & ~MARK_IAX_SUBCLASS_TX, first_message, sizeof(first_message));
06936 iax_frame_subclass2str(iaxs[x]->last_iax_message & ~MARK_IAX_SUBCLASS_TX, last_message, sizeof(last_message));
06937
06938 if(ast_test_flag(iaxs[x], IAX_USEJITTERBUF)) {
06939 jb_getinfo(iaxs[x]->jb, &jbinfo);
06940 localjitter = jbinfo.jitter;
06941 localdelay = jbinfo.current - jbinfo.min;
06942 locallost = jbinfo.frames_lost;
06943 locallosspct = jbinfo.losspct/1000;
06944 localdropped = jbinfo.frames_dropped;
06945 localooo = jbinfo.frames_ooo;
06946 } else {
06947 localjitter = -1;
06948 localdelay = 0;
06949 locallost = -1;
06950 locallosspct = -1;
06951 localdropped = 0;
06952 localooo = -1;
06953 }
06954 if (s)
06955 astman_append(s, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
06956 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
06957 iaxs[x]->pingtime,
06958 localjitter,
06959 localdelay,
06960 locallost,
06961 locallosspct,
06962 localdropped,
06963 localooo,
06964 iaxs[x]->frames_received/1000,
06965 iaxs[x]->remote_rr.jitter,
06966 iaxs[x]->remote_rr.delay,
06967 iaxs[x]->remote_rr.losscnt,
06968 iaxs[x]->remote_rr.losspct,
06969 iaxs[x]->remote_rr.dropped,
06970 iaxs[x]->remote_rr.ooo,
06971 iaxs[x]->remote_rr.packets/1000,
06972 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06973 first_message,
06974 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06975 last_message);
06976 else
06977 ast_cli(fd, limit_fmt ? ACN_FORMAT1 : ACN_FORMAT2,
06978 iaxs[x]->owner ? iaxs[x]->owner->name : "(None)",
06979 iaxs[x]->pingtime,
06980 localjitter,
06981 localdelay,
06982 locallost,
06983 locallosspct,
06984 localdropped,
06985 localooo,
06986 iaxs[x]->frames_received/1000,
06987 iaxs[x]->remote_rr.jitter,
06988 iaxs[x]->remote_rr.delay,
06989 iaxs[x]->remote_rr.losscnt,
06990 iaxs[x]->remote_rr.losspct,
06991 iaxs[x]->remote_rr.dropped,
06992 iaxs[x]->remote_rr.ooo,
06993 iaxs[x]->remote_rr.packets/1000,
06994 (iaxs[x]->first_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06995 first_message,
06996 (iaxs[x]->last_iax_message & MARK_IAX_SUBCLASS_TX) ? "Tx:" : "Rx:",
06997 last_message);
06998 numchans++;
06999 }
07000 ast_mutex_unlock(&iaxsl[x]);
07001 }
07002
07003 return numchans;
07004 }
07005
07006 static char *handle_cli_iax2_show_netstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07007 {
07008 int numchans = 0;
07009
07010 switch (cmd) {
07011 case CLI_INIT:
07012 e->command = "iax2 show netstats";
07013 e->usage =
07014 "Usage: iax2 show netstats\n"
07015 " Lists network status for all currently active IAX channels.\n";
07016 return NULL;
07017 case CLI_GENERATE:
07018 return NULL;
07019 }
07020 if (a->argc != 3)
07021 return CLI_SHOWUSAGE;
07022 ast_cli(a->fd, " -------- LOCAL --------------------- -------- REMOTE --------------------\n");
07023 ast_cli(a->fd, "Channel RTT Jit Del Lost %% Drop OOO Kpkts Jit Del Lost %% Drop OOO Kpkts FirstMsg LastMsg\n");
07024 numchans = ast_cli_netstats(NULL, a->fd, 1);
07025 ast_cli(a->fd, "%d active IAX channel%s\n", numchans, (numchans != 1) ? "s" : "");
07026 return CLI_SUCCESS;
07027 }
07028
07029 static char *handle_cli_iax2_set_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07030 {
07031 switch (cmd) {
07032 case CLI_INIT:
07033 e->command = "iax2 set debug {on|off|peer}";
07034 e->usage =
07035 "Usage: iax2 set debug {on|off|peer peername}\n"
07036 " Enables/Disables dumping of IAX packets for debugging purposes.\n";
07037 return NULL;
07038 case CLI_GENERATE:
07039 if (a->pos == 4 && !strcasecmp(a->argv[3], "peer"))
07040 return complete_iax2_peers(a->line, a->word, a->pos, a->n, 0);
07041 return NULL;
07042 }
07043
07044 if (a->argc < e->args || a->argc > e->args + 1)
07045 return CLI_SHOWUSAGE;
07046
07047 if (!strcasecmp(a->argv[3], "peer")) {
07048 struct iax2_peer *peer;
07049
07050 if (a->argc != e->args + 1)
07051 return CLI_SHOWUSAGE;
07052
07053 peer = find_peer(a->argv[4], 1);
07054
07055 if (!peer) {
07056 ast_cli(a->fd, "IAX2 peer '%s' does not exist\n", a->argv[e->args-1]);
07057 return CLI_FAILURE;
07058 }
07059
07060 debugaddr.sin_addr = peer->addr.sin_addr;
07061 debugaddr.sin_port = peer->addr.sin_port;
07062
07063 ast_cli(a->fd, "IAX2 Debugging Enabled for IP: %s:%d\n",
07064 ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
07065
07066 ao2_ref(peer, -1);
07067 } else if (!strncasecmp(a->argv[3], "on", 2)) {
07068 iaxdebug = 1;
07069 ast_cli(a->fd, "IAX2 Debugging Enabled\n");
07070 } else {
07071 iaxdebug = 0;
07072 memset(&debugaddr, 0, sizeof(debugaddr));
07073 ast_cli(a->fd, "IAX2 Debugging Disabled\n");
07074 }
07075 return CLI_SUCCESS;
07076 }
07077
07078 static char *handle_cli_iax2_set_debug_trunk(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07079 {
07080 switch (cmd) {
07081 case CLI_INIT:
07082 e->command = "iax2 set debug trunk {on|off}";
07083 e->usage =
07084 "Usage: iax2 set debug trunk {on|off}\n"
07085 " Enables/Disables debugging of IAX trunking\n";
07086 return NULL;
07087 case CLI_GENERATE:
07088 return NULL;
07089 }
07090
07091 if (a->argc != e->args)
07092 return CLI_SHOWUSAGE;
07093
07094 if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
07095 iaxtrunkdebug = 1;
07096 ast_cli(a->fd, "IAX2 Trunk Debugging Enabled\n");
07097 } else {
07098 iaxtrunkdebug = 0;
07099 ast_cli(a->fd, "IAX2 Trunk Debugging Disabled\n");
07100 }
07101 return CLI_SUCCESS;
07102 }
07103
07104 static char *handle_cli_iax2_set_debug_jb(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
07105 {
07106 switch (cmd) {
07107 case CLI_INIT:
07108 e->command = "iax2 set debug jb {on|off}";
07109 e->usage =
07110 "Usage: iax2 set debug jb {on|off}\n"
07111 " Enables/Disables jitterbuffer debugging information\n";
07112 return NULL;
07113 case CLI_GENERATE:
07114 return NULL;
07115 }
07116
07117 if (a->argc != e->args)
07118 return CLI_SHOWUSAGE;
07119
07120 if (!strncasecmp(a->argv[e->args -1], "on", 2)) {
07121 jb_setoutput(jb_error_output, jb_warning_output, jb_debug_output);
07122 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Enabled\n");
07123 } else {
07124 jb_setoutput(jb_error_output, jb_warning_output, NULL);
07125 ast_cli(a->fd, "IAX2 Jitterbuffer Debugging Disabled\n");
07126 }
07127 return CLI_SUCCESS;
07128 }
07129
07130 static int iax2_write(struct ast_channel *c, struct ast_frame *f)
07131 {
07132 unsigned short callno = PTR_TO_CALLNO(c->tech_pvt);
07133 int res = -1;
07134 ast_mutex_lock(&iaxsl[callno]);
07135 if (iaxs[callno]) {
07136
07137 if (!iaxs[callno]->error) {
07138 if (ast_test_flag(iaxs[callno], IAX_ALREADYGONE))
07139 res = 0;
07140
07141 else if (f->frametype == AST_FRAME_NULL)
07142 res = 0;
07143 else if ((f->frametype == AST_FRAME_VOICE) && ast_test_flag(iaxs[callno], IAX_QUELCH))
07144 res = 0;
07145 else if (!ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
07146 res = 0;
07147 else
07148
07149 res = iax2_send(iaxs[callno], f, 0, -1, 0, 0, 0);
07150 } else {
07151 ast_debug(1, "Write error: %s\n", strerror(errno));
07152 }
07153 }
07154
07155 ast_mutex_unlock(&iaxsl[callno]);
07156 return res;
07157 }
07158
07159 static int __send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno,
07160 int now, int transfer, int final)
07161 {
07162 struct ast_frame f = { 0, };
07163 int res = 0;
07164
07165 f.frametype = type;
07166 f.subclass = command;
07167 f.datalen = datalen;
07168 f.src = __FUNCTION__;
07169 f.data.ptr = (void *) data;
07170
07171 if ((res = queue_signalling(i, &f)) <= 0) {
07172 return res;
07173 }
07174
07175 return iax2_send(i, &f, ts, seqno, now, transfer, final);
07176 }
07177
07178 static int send_command(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07179 {
07180 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 0);
07181 }
07182
07183 static int send_command_locked(unsigned short callno, char type, int command, unsigned int ts, const unsigned char *data, int datalen, int seqno)
07184 {
07185 int res;
07186 ast_mutex_lock(&iaxsl[callno]);
07187 res = send_command(iaxs[callno], type, command, ts, data, datalen, seqno);
07188 ast_mutex_unlock(&iaxsl[callno]);
07189 return res;
07190 }
07191
07192
07193
07194
07195
07196
07197 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)
07198 {
07199 int call_num = i->callno;
07200
07201 iax2_predestroy(i->callno);
07202 if (!iaxs[call_num])
07203 return -1;
07204 return __send_command(i, type, command, ts, data, datalen, seqno, 0, 0, 1);
07205 }
07206
07207 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)
07208 {
07209 return __send_command(i, type, command, ts, data, datalen, seqno, 1, 0, 0);
07210 }
07211
07212 static int send_command_transfer(struct chan_iax2_pvt *i, char type, int command, unsigned int ts, const unsigned char *data, int datalen)
07213 {
07214 return __send_command(i, type, command, ts, data, datalen, 0, 0, 1, 0);
07215 }
07216
07217 static int apply_context(struct iax2_context *con, const char *context)
07218 {
07219 while(con) {
07220 if (!strcmp(con->context, context) || !strcmp(con->context, "*"))
07221 return -1;
07222 con = con->next;
07223 }
07224 return 0;
07225 }
07226
07227
07228 static int check_access(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07229 {
07230
07231 int res = -1;
07232 int version = 2;
07233 struct iax2_user *user = NULL, *best = NULL;
07234 int bestscore = 0;
07235 int gotcapability = 0;
07236 struct ast_variable *v = NULL, *tmpvar = NULL;
07237 struct ao2_iterator i;
07238
07239 if (!iaxs[callno])
07240 return res;
07241 if (ies->called_number)
07242 ast_string_field_set(iaxs[callno], exten, ies->called_number);
07243 if (ies->calling_number) {
07244 if (ast_test_flag(&globalflags, IAX_SHRINKCALLERID)) {
07245 ast_shrink_phone_number(ies->calling_number);
07246 }
07247 ast_string_field_set(iaxs[callno], cid_num, ies->calling_number);
07248 }
07249 if (ies->calling_name)
07250 ast_string_field_set(iaxs[callno], cid_name, ies->calling_name);
07251 if (ies->calling_ani)
07252 ast_string_field_set(iaxs[callno], ani, ies->calling_ani);
07253 if (ies->dnid)
07254 ast_string_field_set(iaxs[callno], dnid, ies->dnid);
07255 if (ies->rdnis)
07256 ast_string_field_set(iaxs[callno], rdnis, ies->rdnis);
07257 if (ies->called_context)
07258 ast_string_field_set(iaxs[callno], context, ies->called_context);
07259 if (ies->language)
07260 ast_string_field_set(iaxs[callno], language, ies->language);
07261 if (ies->username)
07262 ast_string_field_set(iaxs[callno], username, ies->username);
07263 if (ies->calling_ton > -1)
07264 iaxs[callno]->calling_ton = ies->calling_ton;
07265 if (ies->calling_tns > -1)
07266 iaxs[callno]->calling_tns = ies->calling_tns;
07267 if (ies->calling_pres > -1)
07268 iaxs[callno]->calling_pres = ies->calling_pres;
07269 if (ies->format)
07270 iaxs[callno]->peerformat = ies->format;
07271 if (ies->adsicpe)
07272 iaxs[callno]->peeradsicpe = ies->adsicpe;
07273 if (ies->capability) {
07274 gotcapability = 1;
07275 iaxs[callno]->peercapability = ies->capability;
07276 }
07277 if (ies->version)
07278 version = ies->version;
07279
07280
07281 if(ies->codec_prefs) {
07282 ast_codec_pref_convert(&iaxs[callno]->rprefs, ies->codec_prefs, 32, 0);
07283 ast_codec_pref_convert(&iaxs[callno]->prefs, ies->codec_prefs, 32, 0);
07284 }
07285
07286 if (!gotcapability)
07287 iaxs[callno]->peercapability = iaxs[callno]->peerformat;
07288 if (version > IAX_PROTO_VERSION) {
07289 ast_log(LOG_WARNING, "Peer '%s' has too new a protocol version (%d) for me\n",
07290 ast_inet_ntoa(sin->sin_addr), version);
07291 return res;
07292 }
07293
07294 i = ao2_iterator_init(users, 0);
07295 while ((user = ao2_iterator_next(&i))) {
07296 if ((ast_strlen_zero(iaxs[callno]->username) ||
07297 !strcmp(iaxs[callno]->username, user->name))
07298 && ast_apply_ha(user->ha, sin)
07299 && (ast_strlen_zero(iaxs[callno]->context) ||
07300 apply_context(user->contexts, iaxs[callno]->context))) {
07301 if (!ast_strlen_zero(iaxs[callno]->username)) {
07302
07303 if (best)
07304 user_unref(best);
07305 best = user;
07306 break;
07307 } else if (ast_strlen_zero(user->secret) && ast_strlen_zero(user->dbsecret) && ast_strlen_zero(user->inkeys)) {
07308
07309 if (user->ha) {
07310
07311 if (bestscore < 4) {
07312 bestscore = 4;
07313 if (best)
07314 user_unref(best);
07315 best = user;
07316 continue;
07317 }
07318 } else {
07319
07320 if (bestscore < 3) {
07321 bestscore = 3;
07322 if (best)
07323 user_unref(best);
07324 best = user;
07325 continue;
07326 }
07327 }
07328 } else {
07329 if (user->ha) {
07330
07331 if (bestscore < 2) {
07332 bestscore = 2;
07333 if (best)
07334 user_unref(best);
07335 best = user;
07336 continue;
07337 }
07338 } else {
07339
07340 if (bestscore < 1) {
07341 bestscore = 1;
07342 if (best)
07343 user_unref(best);
07344 best = user;
07345 continue;
07346 }
07347 }
07348 }
07349 }
07350 user_unref(user);
07351 }
07352 ao2_iterator_destroy(&i);
07353 user = best;
07354 if (!user && !ast_strlen_zero(iaxs[callno]->username)) {
07355 user = realtime_user(iaxs[callno]->username, sin);
07356 if (user && !ast_strlen_zero(iaxs[callno]->context) &&
07357 !apply_context(user->contexts, iaxs[callno]->context)) {
07358 user = user_unref(user);
07359 }
07360 }
07361 if (user) {
07362
07363
07364 for (v = user->vars ; v ; v = v->next) {
07365 if((tmpvar = ast_variable_new(v->name, v->value, v->file))) {
07366 tmpvar->next = iaxs[callno]->vars;
07367 iaxs[callno]->vars = tmpvar;
07368 }
07369 }
07370
07371 if (user->maxauthreq > 0)
07372 ast_set_flag(iaxs[callno], IAX_MAXAUTHREQ);
07373 iaxs[callno]->prefs = user->prefs;
07374 ast_copy_flags(iaxs[callno], user, IAX_CODEC_USER_FIRST | IAX_IMMEDIATE | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
07375 iaxs[callno]->encmethods = user->encmethods;
07376
07377 if (ast_strlen_zero(iaxs[callno]->username))
07378 ast_string_field_set(iaxs[callno], username, user->name);
07379
07380 ast_copy_flags(iaxs[callno], user, IAX_TRUNK);
07381 iaxs[callno]->capability = user->capability;
07382
07383 if (ast_strlen_zero(iaxs[callno]->context)) {
07384 if (user->contexts)
07385 ast_string_field_set(iaxs[callno], context, user->contexts->context);
07386 else
07387 ast_string_field_set(iaxs[callno], context, DEFAULT_CONTEXT);
07388 }
07389
07390 ast_string_field_set(iaxs[callno], inkeys, user->inkeys);
07391
07392 iaxs[callno]->authmethods = user->authmethods;
07393 iaxs[callno]->adsi = user->adsi;
07394
07395 if (ast_test_flag(user, IAX_HASCALLERID)) {
07396 iaxs[callno]->calling_tns = 0;
07397 iaxs[callno]->calling_ton = 0;
07398 ast_string_field_set(iaxs[callno], cid_num, user->cid_num);
07399 ast_string_field_set(iaxs[callno], cid_name, user->cid_name);
07400 ast_string_field_set(iaxs[callno], ani, user->cid_num);
07401 iaxs[callno]->calling_pres = AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN;
07402 } else if (ast_strlen_zero(iaxs[callno]->cid_num) && ast_strlen_zero(iaxs[callno]->cid_name)) {
07403 iaxs[callno]->calling_pres = AST_PRES_NUMBER_NOT_AVAILABLE;
07404 }
07405 if (!ast_strlen_zero(user->accountcode))
07406 ast_string_field_set(iaxs[callno], accountcode, user->accountcode);
07407 if (!ast_strlen_zero(user->mohinterpret))
07408 ast_string_field_set(iaxs[callno], mohinterpret, user->mohinterpret);
07409 if (!ast_strlen_zero(user->mohsuggest))
07410 ast_string_field_set(iaxs[callno], mohsuggest, user->mohsuggest);
07411 if (!ast_strlen_zero(user->parkinglot))
07412 ast_string_field_set(iaxs[callno], parkinglot, user->parkinglot);
07413 if (user->amaflags)
07414 iaxs[callno]->amaflags = user->amaflags;
07415 if (!ast_strlen_zero(user->language))
07416 ast_string_field_set(iaxs[callno], language, user->language);
07417 ast_copy_flags(iaxs[callno], user, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
07418
07419 if (!ast_strlen_zero(user->dbsecret)) {
07420 char *family, *key=NULL;
07421 char buf[80];
07422 family = ast_strdupa(user->dbsecret);
07423 key = strchr(family, '/');
07424 if (key) {
07425 *key = '\0';
07426 key++;
07427 }
07428 if (!key || ast_db_get(family, key, buf, sizeof(buf)))
07429 ast_log(LOG_WARNING, "Unable to retrieve database password for family/key '%s'!\n", user->dbsecret);
07430 else
07431 ast_string_field_set(iaxs[callno], secret, buf);
07432 } else
07433 ast_string_field_set(iaxs[callno], secret, user->secret);
07434 res = 0;
07435 user = user_unref(user);
07436 } else {
07437
07438
07439
07440
07441 iaxs[callno]->authmethods = last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
07442 ast_string_field_set(iaxs[callno], secret, "badsecret");
07443 iaxs[callno]->authrej = 1;
07444 if (!ast_strlen_zero(iaxs[callno]->username)) {
07445
07446 res = 0;
07447 }
07448 }
07449 ast_set2_flag(iaxs[callno], iax2_getpeertrunk(*sin), IAX_TRUNK);
07450 return res;
07451 }
07452
07453 static int raw_hangup(struct sockaddr_in *sin, unsigned short src, unsigned short dst, int sockfd)
07454 {
07455 struct ast_iax2_full_hdr fh;
07456 fh.scallno = htons(src | IAX_FLAG_FULL);
07457 fh.dcallno = htons(dst);
07458 fh.ts = 0;
07459 fh.oseqno = 0;
07460 fh.iseqno = 0;
07461 fh.type = AST_FRAME_IAX;
07462 fh.csub = compress_subclass(IAX_COMMAND_INVAL);
07463 iax_outputframe(NULL, &fh, 0, sin, 0);
07464 #if 0
07465 if (option_debug)
07466 #endif
07467 ast_debug(1, "Raw Hangup %s:%d, src=%d, dst=%d\n",
07468 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), src, dst);
07469 return sendto(sockfd, &fh, sizeof(fh), 0, (struct sockaddr *)sin, sizeof(*sin));
07470 }
07471
07472 static void merge_encryption(struct chan_iax2_pvt *p, unsigned int enc)
07473 {
07474
07475 p->encmethods &= enc;
07476 if (p->encmethods) {
07477 if (!(p->encmethods & IAX_ENCRYPT_KEYROTATE)){
07478 p->keyrotateid = -2;
07479 }
07480 if (p->encmethods & IAX_ENCRYPT_AES128)
07481 p->encmethods = IAX_ENCRYPT_AES128;
07482 else
07483 p->encmethods = 0;
07484 }
07485 }
07486
07487
07488
07489
07490
07491
07492
07493 static int authenticate_request(int call_num)
07494 {
07495 struct iax_ie_data ied;
07496 int res = -1, authreq_restrict = 0;
07497 char challenge[10];
07498 struct chan_iax2_pvt *p = iaxs[call_num];
07499
07500 memset(&ied, 0, sizeof(ied));
07501
07502
07503 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
07504 struct iax2_user *user, tmp_user = {
07505 .name = p->username,
07506 };
07507
07508 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07509 if (user) {
07510 if (user->curauthreq == user->maxauthreq)
07511 authreq_restrict = 1;
07512 else
07513 user->curauthreq++;
07514 user = user_unref(user);
07515 }
07516 }
07517
07518
07519 if (authreq_restrict) {
07520 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Unauthenticated call limit reached");
07521 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_CALL_REJECTED);
07522 send_command_final(p, AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied.buf, ied.pos, -1);
07523 return 0;
07524 }
07525
07526 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, p->authmethods);
07527 if (p->authmethods & (IAX_AUTH_MD5 | IAX_AUTH_RSA)) {
07528 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
07529 ast_string_field_set(p, challenge, challenge);
07530
07531 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, p->challenge);
07532 }
07533 if (p->encmethods)
07534 iax_ie_append_short(&ied, IAX_IE_ENCRYPTION, p->encmethods);
07535
07536 iax_ie_append_str(&ied,IAX_IE_USERNAME, p->username);
07537
07538 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREQ, 0, ied.buf, ied.pos, -1);
07539
07540 if (p->encmethods)
07541 ast_set_flag(p, IAX_ENCRYPTED);
07542
07543 return res;
07544 }
07545
07546 static int authenticate_verify(struct chan_iax2_pvt *p, struct iax_ies *ies)
07547 {
07548 char requeststr[256];
07549 char md5secret[256] = "";
07550 char secret[256] = "";
07551 char rsasecret[256] = "";
07552 int res = -1;
07553 int x;
07554 struct iax2_user *user, tmp_user = {
07555 .name = p->username,
07556 };
07557
07558 if (p->authrej) {
07559 return res;
07560 }
07561 user = ao2_find(users, &tmp_user, OBJ_POINTER);
07562 if (user) {
07563 if (ast_test_flag(p, IAX_MAXAUTHREQ)) {
07564 ast_atomic_fetchadd_int(&user->curauthreq, -1);
07565 ast_clear_flag(p, IAX_MAXAUTHREQ);
07566 }
07567 ast_string_field_set(p, host, user->name);
07568 user = user_unref(user);
07569 }
07570 if (ast_test_flag(p, IAX_FORCE_ENCRYPT) && !p->encmethods) {
07571 ast_log(LOG_NOTICE, "Call Terminated, Incoming call is unencrypted while force encrypt is enabled.");
07572 return res;
07573 }
07574 if (!ast_test_flag(&p->state, IAX_STATE_AUTHENTICATED))
07575 return res;
07576 if (ies->password)
07577 ast_copy_string(secret, ies->password, sizeof(secret));
07578 if (ies->md5_result)
07579 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07580 if (ies->rsa_result)
07581 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07582 if ((p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(rsasecret) && !ast_strlen_zero(p->inkeys)) {
07583 struct ast_key *key;
07584 char *keyn;
07585 char tmpkey[256];
07586 char *stringp=NULL;
07587 ast_copy_string(tmpkey, p->inkeys, sizeof(tmpkey));
07588 stringp=tmpkey;
07589 keyn = strsep(&stringp, ":");
07590 while(keyn) {
07591 key = ast_key_get(keyn, AST_KEY_PUBLIC);
07592 if (key && !ast_check_signature(key, p->challenge, rsasecret)) {
07593 res = 0;
07594 break;
07595 } else if (!key)
07596 ast_log(LOG_WARNING, "requested inkey '%s' for RSA authentication does not exist\n", keyn);
07597 keyn = strsep(&stringp, ":");
07598 }
07599 } else if (p->authmethods & IAX_AUTH_MD5) {
07600 struct MD5Context md5;
07601 unsigned char digest[16];
07602 char *tmppw, *stringp;
07603
07604 tmppw = ast_strdupa(p->secret);
07605 stringp = tmppw;
07606 while((tmppw = strsep(&stringp, ";"))) {
07607 MD5Init(&md5);
07608 MD5Update(&md5, (unsigned char *)p->challenge, strlen(p->challenge));
07609 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07610 MD5Final(digest, &md5);
07611
07612 for (x=0;x<16;x++)
07613 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
07614 if (!strcasecmp(requeststr, md5secret)) {
07615 res = 0;
07616 break;
07617 }
07618 }
07619 } else if (p->authmethods & IAX_AUTH_PLAINTEXT) {
07620 if (!strcmp(secret, p->secret))
07621 res = 0;
07622 }
07623 return res;
07624 }
07625
07626
07627 static int register_verify(int callno, struct sockaddr_in *sin, struct iax_ies *ies)
07628 {
07629 char requeststr[256] = "";
07630 char peer[256] = "";
07631 char md5secret[256] = "";
07632 char rsasecret[256] = "";
07633 char secret[256] = "";
07634 struct iax2_peer *p = NULL;
07635 struct ast_key *key;
07636 char *keyn;
07637 int x;
07638 int expire = 0;
07639 int res = -1;
07640
07641 ast_clear_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07642
07643 if (ies->username)
07644 ast_copy_string(peer, ies->username, sizeof(peer));
07645 if (ies->password)
07646 ast_copy_string(secret, ies->password, sizeof(secret));
07647 if (ies->md5_result)
07648 ast_copy_string(md5secret, ies->md5_result, sizeof(md5secret));
07649 if (ies->rsa_result)
07650 ast_copy_string(rsasecret, ies->rsa_result, sizeof(rsasecret));
07651 if (ies->refresh)
07652 expire = ies->refresh;
07653
07654 if (ast_strlen_zero(peer)) {
07655 ast_log(LOG_NOTICE, "Empty registration from %s\n", ast_inet_ntoa(sin->sin_addr));
07656 return -1;
07657 }
07658
07659
07660 ast_mutex_unlock(&iaxsl[callno]);
07661 p = find_peer(peer, 1);
07662 ast_mutex_lock(&iaxsl[callno]);
07663 if (!p || !iaxs[callno]) {
07664 if (iaxs[callno]) {
07665 int plaintext = ((last_authmethod & IAX_AUTH_PLAINTEXT) | (iaxs[callno]->authmethods & IAX_AUTH_PLAINTEXT));
07666
07667 ast_string_field_set(iaxs[callno], secret, "badsecret");
07668
07669
07670
07671
07672
07673
07674
07675
07676
07677 if (ast_strlen_zero(iaxs[callno]->challenge) &&
07678 !(!ast_strlen_zero(secret) && plaintext)) {
07679
07680 res = 0;
07681 }
07682 }
07683 if (authdebug && !p)
07684 ast_log(LOG_NOTICE, "No registration for peer '%s' (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
07685 goto return_unref;
07686 }
07687
07688 if (!ast_test_flag(p, IAX_DYNAMIC)) {
07689 if (authdebug)
07690 ast_log(LOG_NOTICE, "Peer '%s' is not dynamic (from %s)\n", peer, ast_inet_ntoa(sin->sin_addr));
07691 goto return_unref;
07692 }
07693
07694 if (!ast_apply_ha(p->ha, sin)) {
07695 if (authdebug)
07696 ast_log(LOG_NOTICE, "Host %s denied access to register peer '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
07697 goto return_unref;
07698 }
07699 ast_string_field_set(iaxs[callno], secret, p->secret);
07700 ast_string_field_set(iaxs[callno], inkeys, p->inkeys);
07701
07702 if (!ast_strlen_zero(rsasecret) && (p->authmethods & IAX_AUTH_RSA) && !ast_strlen_zero(iaxs[callno]->challenge)) {
07703 if (!ast_strlen_zero(p->inkeys)) {
07704 char tmpkeys[256];
07705 char *stringp=NULL;
07706 ast_copy_string(tmpkeys, p->inkeys, sizeof(tmpkeys));
07707 stringp=tmpkeys;
07708 keyn = strsep(&stringp, ":");
07709 while(keyn) {
07710 key = ast_key_get(keyn, AST_KEY_PUBLIC);
07711 if (key && !ast_check_signature(key, iaxs[callno]->challenge, rsasecret)) {
07712 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07713 break;
07714 } else if (!key)
07715 ast_log(LOG_WARNING, "requested inkey '%s' does not exist\n", keyn);
07716 keyn = strsep(&stringp, ":");
07717 }
07718 if (!keyn) {
07719 if (authdebug)
07720 ast_log(LOG_NOTICE, "Host %s failed RSA authentication with inkeys '%s'\n", peer, p->inkeys);
07721 goto return_unref;
07722 }
07723 } else {
07724 if (authdebug)
07725 ast_log(LOG_NOTICE, "Host '%s' trying to do RSA authentication, but we have no inkeys\n", peer);
07726 goto return_unref;
07727 }
07728 } else if (!ast_strlen_zero(md5secret) && (p->authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(iaxs[callno]->challenge)) {
07729 struct MD5Context md5;
07730 unsigned char digest[16];
07731 char *tmppw, *stringp;
07732
07733 tmppw = ast_strdupa(p->secret);
07734 stringp = tmppw;
07735 while((tmppw = strsep(&stringp, ";"))) {
07736 MD5Init(&md5);
07737 MD5Update(&md5, (unsigned char *)iaxs[callno]->challenge, strlen(iaxs[callno]->challenge));
07738 MD5Update(&md5, (unsigned char *)tmppw, strlen(tmppw));
07739 MD5Final(digest, &md5);
07740 for (x=0;x<16;x++)
07741 sprintf(requeststr + (x << 1), "%2.2x", digest[x]);
07742 if (!strcasecmp(requeststr, md5secret))
07743 break;
07744 }
07745 if (tmppw) {
07746 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07747 } else {
07748 if (authdebug)
07749 ast_log(LOG_NOTICE, "Host %s failed MD5 authentication for '%s' (%s != %s)\n", ast_inet_ntoa(sin->sin_addr), p->name, requeststr, md5secret);
07750 goto return_unref;
07751 }
07752 } else if (!ast_strlen_zero(secret) && (p->authmethods & IAX_AUTH_PLAINTEXT)) {
07753
07754 if (strcmp(secret, p->secret)) {
07755 if (authdebug)
07756 ast_log(LOG_NOTICE, "Host %s did not provide proper plaintext password for '%s'\n", ast_inet_ntoa(sin->sin_addr), p->name);
07757 goto return_unref;
07758 } else
07759 ast_set_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED);
07760 } else if (!ast_strlen_zero(iaxs[callno]->challenge) && ast_strlen_zero(md5secret) && ast_strlen_zero(rsasecret)) {
07761
07762 goto return_unref;
07763 }
07764 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
07765
07766
07767 res = 0;
07768
07769 return_unref:
07770 if (iaxs[callno]) {
07771 ast_string_field_set(iaxs[callno], peer, peer);
07772
07773
07774 if (expire && (expire < iaxs[callno]->expiry)) {
07775 iaxs[callno]->expiry = expire;
07776 }
07777 }
07778
07779 if (p) {
07780 peer_unref(p);
07781 }
07782 return res;
07783 }
07784
07785 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)
07786 {
07787 int res = -1;
07788 int x;
07789 if (!ast_strlen_zero(keyn)) {
07790 if (!(authmethods & IAX_AUTH_RSA)) {
07791 if (ast_strlen_zero(secret))
07792 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));
07793 } else if (ast_strlen_zero(challenge)) {
07794 ast_log(LOG_NOTICE, "No challenge provided for RSA authentication to %s\n", ast_inet_ntoa(sin->sin_addr));
07795 } else {
07796 char sig[256];
07797 struct ast_key *key;
07798 key = ast_key_get(keyn, AST_KEY_PRIVATE);
07799 if (!key) {
07800 ast_log(LOG_NOTICE, "Unable to find private key '%s'\n", keyn);
07801 } else {
07802 if (ast_sign(key, (char*)challenge, sig)) {
07803 ast_log(LOG_NOTICE, "Unable to sign challenge with key\n");
07804 res = -1;
07805 } else {
07806 iax_ie_append_str(ied, IAX_IE_RSA_RESULT, sig);
07807 res = 0;
07808 }
07809 }
07810 }
07811 }
07812
07813 if (res && !ast_strlen_zero(secret)) {
07814 if ((authmethods & IAX_AUTH_MD5) && !ast_strlen_zero(challenge)) {
07815 struct MD5Context md5;
07816 unsigned char digest[16];
07817 char digres[128];
07818 MD5Init(&md5);
07819 MD5Update(&md5, (unsigned char *)challenge, strlen(challenge));
07820 MD5Update(&md5, (unsigned char *)secret, strlen(secret));
07821 MD5Final(digest, &md5);
07822
07823 for (x=0;x<16;x++)
07824 sprintf(digres + (x << 1), "%2.2x", digest[x]);
07825 if (pvt) {
07826 build_encryption_keys(digest, pvt);
07827 }
07828 iax_ie_append_str(ied, IAX_IE_MD5_RESULT, digres);
07829 res = 0;
07830 } else if (authmethods & IAX_AUTH_PLAINTEXT) {
07831 iax_ie_append_str(ied, IAX_IE_PASSWORD, secret);
07832 res = 0;
07833 } else
07834 ast_log(LOG_NOTICE, "No way to send secret to peer '%s' (their methods: %d)\n", ast_inet_ntoa(sin->sin_addr), authmethods);
07835 }
07836 return res;
07837 }
07838
07839
07840
07841
07842
07843 static int authenticate_reply(struct chan_iax2_pvt *p, struct sockaddr_in *sin, struct iax_ies *ies, const char *override, const char *okey)
07844 {
07845 struct iax2_peer *peer = NULL;
07846
07847 int res = -1;
07848 int authmethods = 0;
07849 struct iax_ie_data ied;
07850 uint16_t callno = p->callno;
07851
07852 memset(&ied, 0, sizeof(ied));
07853
07854 if (ies->username)
07855 ast_string_field_set(p, username, ies->username);
07856 if (ies->challenge)
07857 ast_string_field_set(p, challenge, ies->challenge);
07858 if (ies->authmethods)
07859 authmethods = ies->authmethods;
07860 if (authmethods & IAX_AUTH_MD5)
07861 merge_encryption(p, ies->encmethods);
07862 else
07863 p->encmethods = 0;
07864
07865
07866 if (!ast_strlen_zero(override) || !ast_strlen_zero(okey)) {
07867
07868 res = authenticate(p->challenge, override, okey, authmethods, &ied, sin, p);
07869 } else {
07870 struct ao2_iterator i = ao2_iterator_init(peers, 0);
07871 while ((peer = ao2_iterator_next(&i))) {
07872 if ((ast_strlen_zero(p->peer) || !strcmp(p->peer, peer->name))
07873
07874 && (ast_strlen_zero(peer->username) || (!strcmp(peer->username, p->username)))
07875
07876 && (!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)))
07877
07878 ) {
07879 res = authenticate(p->challenge, peer->secret, peer->outkey, authmethods, &ied, sin, p);
07880 if (!res) {
07881 peer_unref(peer);
07882 break;
07883 }
07884 }
07885 peer_unref(peer);
07886 }
07887 ao2_iterator_destroy(&i);
07888 if (!peer) {
07889
07890
07891 const char *peer_name = ast_strdupa(p->peer);
07892 ast_mutex_unlock(&iaxsl[callno]);
07893 if ((peer = realtime_peer(peer_name, NULL))) {
07894 ast_mutex_lock(&iaxsl[callno]);
07895 if (!(p = iaxs[callno])) {
07896 peer_unref(peer);
07897 return -1;
07898 }
07899 res = authenticate(p->challenge, peer->secret,peer->outkey, authmethods, &ied, sin, p);
07900 peer_unref(peer);
07901 }
07902 if (!peer) {
07903 ast_mutex_lock(&iaxsl[callno]);
07904 if (!(p = iaxs[callno]))
07905 return -1;
07906 }
07907 }
07908 }
07909
07910 if (ies->encmethods) {
07911 ast_set_flag(p, IAX_ENCRYPTED | IAX_KEYPOPULATED);
07912 } else if (ast_test_flag(iaxs[callno], IAX_FORCE_ENCRYPT)) {
07913 ast_log(LOG_NOTICE, "Call initiated without encryption while forceencryption=yes option is set");
07914 return -1;
07915 }
07916 if (!res) {
07917 struct ast_datastore *variablestore;
07918 struct ast_variable *var, *prev = NULL;
07919 AST_LIST_HEAD(, ast_var_t) *varlist;
07920 varlist = ast_calloc(1, sizeof(*varlist));
07921 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
07922 if (variablestore && varlist && p->owner) {
07923 variablestore->data = varlist;
07924 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
07925 AST_LIST_HEAD_INIT(varlist);
07926 for (var = ies->vars; var; var = var->next) {
07927 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
07928 if (prev)
07929 ast_free(prev);
07930 prev = var;
07931 if (!newvar) {
07932
07933 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
07934 } else {
07935 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
07936 }
07937 }
07938 if (prev)
07939 ast_free(prev);
07940 ies->vars = NULL;
07941 ast_channel_datastore_add(p->owner, variablestore);
07942 } else {
07943 if (p->owner)
07944 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
07945 if (variablestore)
07946 ast_datastore_free(variablestore);
07947 if (varlist)
07948 ast_free(varlist);
07949 }
07950 }
07951
07952 if (!res)
07953 res = send_command(p, AST_FRAME_IAX, IAX_COMMAND_AUTHREP, 0, ied.buf, ied.pos, -1);
07954 return res;
07955 }
07956
07957 static int iax2_do_register(struct iax2_registry *reg);
07958
07959 static void __iax2_do_register_s(const void *data)
07960 {
07961 struct iax2_registry *reg = (struct iax2_registry *)data;
07962 reg->expire = -1;
07963 iax2_do_register(reg);
07964 }
07965
07966 static int iax2_do_register_s(const void *data)
07967 {
07968 #ifdef SCHED_MULTITHREADED
07969 if (schedule_action(__iax2_do_register_s, data))
07970 #endif
07971 __iax2_do_register_s(data);
07972 return 0;
07973 }
07974
07975 static int try_transfer(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
07976 {
07977 int newcall = 0;
07978 char newip[256];
07979 struct iax_ie_data ied;
07980 struct sockaddr_in new;
07981
07982
07983 memset(&ied, 0, sizeof(ied));
07984 if (ies->apparent_addr)
07985 memmove(&new, ies->apparent_addr, sizeof(new));
07986 if (ies->callno)
07987 newcall = ies->callno;
07988 if (!newcall || !new.sin_addr.s_addr || !new.sin_port) {
07989 ast_log(LOG_WARNING, "Invalid transfer request\n");
07990 return -1;
07991 }
07992 pvt->transfercallno = newcall;
07993 memcpy(&pvt->transfer, &new, sizeof(pvt->transfer));
07994 inet_aton(newip, &pvt->transfer.sin_addr);
07995 pvt->transfer.sin_family = AF_INET;
07996 pvt->transferid = ies->transferid;
07997
07998
07999 if (pvt->transferring == TRANSFER_NONE) {
08000 store_by_transfercallno(pvt);
08001 }
08002 pvt->transferring = TRANSFER_BEGIN;
08003
08004 if (ies->transferid)
08005 iax_ie_append_int(&ied, IAX_IE_TRANSFERID, ies->transferid);
08006 send_command_transfer(pvt, AST_FRAME_IAX, IAX_COMMAND_TXCNT, 0, ied.buf, ied.pos);
08007 return 0;
08008 }
08009
08010 static int complete_dpreply(struct chan_iax2_pvt *pvt, struct iax_ies *ies)
08011 {
08012 char exten[256] = "";
08013 int status = CACHE_FLAG_UNKNOWN, expiry = iaxdefaultdpcache, x, matchmore = 0;
08014 struct iax2_dpcache *dp = NULL;
08015
08016 if (ies->called_number)
08017 ast_copy_string(exten, ies->called_number, sizeof(exten));
08018
08019 if (ies->dpstatus & IAX_DPSTATUS_EXISTS)
08020 status = CACHE_FLAG_EXISTS;
08021 else if (ies->dpstatus & IAX_DPSTATUS_CANEXIST)
08022 status = CACHE_FLAG_CANEXIST;
08023 else if (ies->dpstatus & IAX_DPSTATUS_NONEXISTENT)
08024 status = CACHE_FLAG_NONEXISTENT;
08025
08026 if (ies->refresh)
08027 expiry = ies->refresh;
08028 if (ies->dpstatus & IAX_DPSTATUS_MATCHMORE)
08029 matchmore = CACHE_FLAG_MATCHMORE;
08030
08031 AST_LIST_LOCK(&dpcache);
08032 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, peer_list) {
08033 if (strcmp(dp->exten, exten))
08034 continue;
08035 AST_LIST_REMOVE_CURRENT(peer_list);
08036 dp->callno = 0;
08037 dp->expiry.tv_sec = dp->orig.tv_sec + expiry;
08038 if (dp->flags & CACHE_FLAG_PENDING) {
08039 dp->flags &= ~CACHE_FLAG_PENDING;
08040 dp->flags |= status;
08041 dp->flags |= matchmore;
08042 }
08043
08044 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
08045 if (dp->waiters[x] > -1) {
08046 if (write(dp->waiters[x], "asdf", 4) < 0) {
08047 }
08048 }
08049 }
08050 }
08051 AST_LIST_TRAVERSE_SAFE_END;
08052 AST_LIST_UNLOCK(&dpcache);
08053
08054 return 0;
08055 }
08056
08057 static int complete_transfer(int callno, struct iax_ies *ies)
08058 {
08059 int peercallno = 0;
08060 struct chan_iax2_pvt *pvt = iaxs[callno];
08061 struct iax_frame *cur;
08062 jb_frame frame;
08063
08064 if (ies->callno)
08065 peercallno = ies->callno;
08066
08067 if (peercallno < 1) {
08068 ast_log(LOG_WARNING, "Invalid transfer request\n");
08069 return -1;
08070 }
08071 remove_by_transfercallno(pvt);
08072
08073
08074
08075 peercnt_remove_by_addr(&pvt->addr);
08076 peercnt_add(&pvt->transfer);
08077
08078 memcpy(&pvt->addr, &pvt->transfer, sizeof(pvt->addr));
08079 memset(&pvt->transfer, 0, sizeof(pvt->transfer));
08080
08081 pvt->oseqno = 0;
08082 pvt->rseqno = 0;
08083 pvt->iseqno = 0;
08084 pvt->aseqno = 0;
08085
08086 if (pvt->peercallno) {
08087 remove_by_peercallno(pvt);
08088 }
08089 pvt->peercallno = peercallno;
08090
08091 store_by_peercallno(pvt);
08092 pvt->transferring = TRANSFER_NONE;
08093 pvt->svoiceformat = -1;
08094 pvt->voiceformat = 0;
08095 pvt->svideoformat = -1;
08096 pvt->videoformat = 0;
08097 pvt->transfercallno = 0;
08098 memset(&pvt->rxcore, 0, sizeof(pvt->rxcore));
08099 memset(&pvt->offset, 0, sizeof(pvt->offset));
08100
08101 while(jb_getall(pvt->jb,&frame) == JB_OK)
08102 iax2_frame_free(frame.data);
08103 jb_reset(pvt->jb);
08104 pvt->lag = 0;
08105 pvt->last = 0;
08106 pvt->lastsent = 0;
08107 pvt->nextpred = 0;
08108 pvt->pingtime = DEFAULT_RETRY_TIME;
08109 AST_LIST_LOCK(&frame_queue);
08110 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
08111
08112
08113
08114 if (callno == cur->callno)
08115 cur->retries = -1;
08116 }
08117 AST_LIST_UNLOCK(&frame_queue);
08118 return 0;
08119 }
08120
08121
08122 static int iax2_ack_registry(struct iax_ies *ies, struct sockaddr_in *sin, int callno)
08123 {
08124 struct iax2_registry *reg;
08125
08126 char peer[256] = "";
08127 char msgstatus[60];
08128 int refresh = 60;
08129 char ourip[256] = "<Unspecified>";
08130 struct sockaddr_in oldus;
08131 struct sockaddr_in us;
08132 int oldmsgs;
08133
08134 memset(&us, 0, sizeof(us));
08135 if (ies->apparent_addr)
08136 memmove(&us, ies->apparent_addr, sizeof(us));
08137 if (ies->username)
08138 ast_copy_string(peer, ies->username, sizeof(peer));
08139 if (ies->refresh)
08140 refresh = ies->refresh;
08141 if (ies->calling_number) {
08142
08143 }
08144 reg = iaxs[callno]->reg;
08145 if (!reg) {
08146 ast_log(LOG_WARNING, "Registry acknowledge on unknown registry '%s'\n", peer);
08147 return -1;
08148 }
08149 memcpy(&oldus, ®->us, sizeof(oldus));
08150 oldmsgs = reg->messages;
08151 if (inaddrcmp(®->addr, sin)) {
08152 ast_log(LOG_WARNING, "Received unsolicited registry ack from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08153 return -1;
08154 }
08155 memcpy(®->us, &us, sizeof(reg->us));
08156 if (ies->msgcount >= 0)
08157 reg->messages = ies->msgcount & 0xffff;
08158
08159
08160
08161 reg->refresh = refresh;
08162 reg->expire = iax2_sched_replace(reg->expire, sched,
08163 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
08164 if (inaddrcmp(&oldus, ®->us) || (reg->messages != oldmsgs)) {
08165 if (reg->messages > 255)
08166 snprintf(msgstatus, sizeof(msgstatus), " with %d new and %d old messages waiting", reg->messages & 0xff, reg->messages >> 8);
08167 else if (reg->messages > 1)
08168 snprintf(msgstatus, sizeof(msgstatus), " with %d new messages waiting\n", reg->messages);
08169 else if (reg->messages > 0)
08170 ast_copy_string(msgstatus, " with 1 new message waiting\n", sizeof(msgstatus));
08171 else
08172 ast_copy_string(msgstatus, " with no messages waiting\n", sizeof(msgstatus));
08173 snprintf(ourip, sizeof(ourip), "%s:%d", ast_inet_ntoa(reg->us.sin_addr), ntohs(reg->us.sin_port));
08174 ast_verb(3, "Registered IAX2 to '%s', who sees us as %s%s\n", ast_inet_ntoa(sin->sin_addr), ourip, msgstatus);
08175 manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: IAX2\r\nDomain: %s\r\nStatus: Registered\r\n", ast_inet_ntoa(sin->sin_addr));
08176 }
08177 reg->regstate = REG_STATE_REGISTERED;
08178 return 0;
08179 }
08180
08181 static int iax2_append_register(const char *hostname, const char *username,
08182 const char *secret, const char *porta)
08183 {
08184 struct iax2_registry *reg;
08185
08186 if (!(reg = ast_calloc(1, sizeof(*reg))))
08187 return -1;
08188
08189 if (ast_dnsmgr_lookup(hostname, ®->addr, ®->dnsmgr, srvlookup ? "_iax._udp" : NULL) < 0) {
08190 ast_free(reg);
08191 return -1;
08192 }
08193
08194 ast_copy_string(reg->username, username, sizeof(reg->username));
08195
08196 if (secret)
08197 ast_copy_string(reg->secret, secret, sizeof(reg->secret));
08198
08199 reg->expire = -1;
08200 reg->refresh = IAX_DEFAULT_REG_EXPIRE;
08201 reg->addr.sin_family = AF_INET;
08202 reg->addr.sin_port = porta ? htons(atoi(porta)) : htons(IAX_DEFAULT_PORTNO);
08203
08204 AST_LIST_LOCK(®istrations);
08205 AST_LIST_INSERT_HEAD(®istrations, reg, entry);
08206 AST_LIST_UNLOCK(®istrations);
08207
08208 return 0;
08209 }
08210
08211 static int iax2_register(const char *value, int lineno)
08212 {
08213 char copy[256];
08214 char *username, *hostname, *secret;
08215 char *porta;
08216 char *stringp=NULL;
08217
08218 if (!value)
08219 return -1;
08220
08221 ast_copy_string(copy, value, sizeof(copy));
08222 stringp = copy;
08223 username = strsep(&stringp, "@");
08224 hostname = strsep(&stringp, "@");
08225
08226 if (!hostname) {
08227 ast_log(LOG_WARNING, "Format for registration is user[:secret]@host[:port] at line %d\n", lineno);
08228 return -1;
08229 }
08230
08231 stringp = username;
08232 username = strsep(&stringp, ":");
08233 secret = strsep(&stringp, ":");
08234 stringp = hostname;
08235 hostname = strsep(&stringp, ":");
08236 porta = strsep(&stringp, ":");
08237
08238 if (porta && !atoi(porta)) {
08239 ast_log(LOG_WARNING, "%s is not a valid port number at line %d\n", porta, lineno);
08240 return -1;
08241 }
08242
08243 return iax2_append_register(hostname, username, secret, porta);
08244 }
08245
08246
08247 static void register_peer_exten(struct iax2_peer *peer, int onoff)
08248 {
08249 char multi[256];
08250 char *stringp, *ext;
08251 if (!ast_strlen_zero(regcontext)) {
08252 ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
08253 stringp = multi;
08254 while((ext = strsep(&stringp, "&"))) {
08255 if (onoff) {
08256 if (!ast_exists_extension(NULL, regcontext, ext, 1, NULL))
08257 ast_add_extension(regcontext, 1, ext, 1, NULL, NULL,
08258 "Noop", ast_strdup(peer->name), ast_free_ptr, "IAX2");
08259 } else
08260 ast_context_remove_extension(regcontext, ext, 1, NULL);
08261 }
08262 }
08263 }
08264 static void prune_peers(void);
08265
08266 static void unlink_peer(struct iax2_peer *peer)
08267 {
08268 if (peer->expire > -1) {
08269 if (!ast_sched_thread_del(sched, peer->expire)) {
08270 peer->expire = -1;
08271 peer_unref(peer);
08272 }
08273 }
08274
08275 if (peer->pokeexpire > -1) {
08276 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
08277 peer->pokeexpire = -1;
08278 peer_unref(peer);
08279 }
08280 }
08281
08282 ao2_unlink(peers, peer);
08283 }
08284
08285 static void __expire_registry(const void *data)
08286 {
08287 struct iax2_peer *peer = (struct iax2_peer *) data;
08288
08289 if (!peer)
08290 return;
08291
08292 peer->expire = -1;
08293
08294 ast_debug(1, "Expiring registration for peer '%s'\n", peer->name);
08295 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(peer, IAX_TEMPONLY|IAX_RTCACHEFRIENDS)))
08296 realtime_update_peer(peer->name, &peer->addr, 0);
08297 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
08298
08299 peercnt_modify(0, 0, &peer->addr);
08300
08301 memset(&peer->addr, 0, sizeof(peer->addr));
08302
08303 peer->expiry = min_reg_expire;
08304 if (!ast_test_flag(peer, IAX_TEMPONLY))
08305 ast_db_del("IAX/Registry", peer->name);
08306 register_peer_exten(peer, 0);
08307 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
08308 if (iax2_regfunk)
08309 iax2_regfunk(peer->name, 0);
08310
08311 if (ast_test_flag(peer, IAX_RTAUTOCLEAR))
08312 unlink_peer(peer);
08313
08314 peer_unref(peer);
08315 }
08316
08317 static int expire_registry(const void *data)
08318 {
08319 #ifdef SCHED_MULTITHREADED
08320 if (schedule_action(__expire_registry, data))
08321 #endif
08322 __expire_registry(data);
08323 return 0;
08324 }
08325
08326 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall);
08327
08328 static void reg_source_db(struct iax2_peer *p)
08329 {
08330 char data[80];
08331 struct in_addr in;
08332 char *c, *d;
08333 if (!ast_test_flag(p, IAX_TEMPONLY) && (!ast_db_get("IAX/Registry", p->name, data, sizeof(data)))) {
08334 c = strchr(data, ':');
08335 if (c) {
08336 *c = '\0';
08337 c++;
08338 if (inet_aton(data, &in)) {
08339 d = strchr(c, ':');
08340 if (d) {
08341 *d = '\0';
08342 d++;
08343 ast_verb(3, "Seeding '%s' at %s:%d for %d\n", p->name,
08344 ast_inet_ntoa(in), atoi(c), atoi(d));
08345 iax2_poke_peer(p, 0);
08346 p->expiry = atoi(d);
08347 memset(&p->addr, 0, sizeof(p->addr));
08348 p->addr.sin_family = AF_INET;
08349 p->addr.sin_addr = in;
08350 p->addr.sin_port = htons(atoi(c));
08351 if (p->expire > -1) {
08352 if (!ast_sched_thread_del(sched, p->expire)) {
08353 p->expire = -1;
08354 peer_unref(p);
08355 }
08356 }
08357 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08358 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08359 if (p->expire == -1)
08360 peer_unref(p);
08361 if (iax2_regfunk)
08362 iax2_regfunk(p->name, 1);
08363 register_peer_exten(p, 1);
08364 }
08365
08366 }
08367 }
08368 }
08369 }
08370
08371
08372
08373
08374
08375
08376
08377 static int update_registry(struct sockaddr_in *sin, int callno, char *devtype, int fd, unsigned short refresh)
08378 {
08379
08380 struct iax_ie_data ied;
08381 struct iax2_peer *p;
08382 int msgcount;
08383 char data[80];
08384 int version;
08385 const char *peer_name;
08386 int res = -1;
08387
08388 memset(&ied, 0, sizeof(ied));
08389
08390 peer_name = ast_strdupa(iaxs[callno]->peer);
08391
08392
08393 ast_mutex_unlock(&iaxsl[callno]);
08394 if (!(p = find_peer(peer_name, 1))) {
08395 ast_mutex_lock(&iaxsl[callno]);
08396 ast_log(LOG_WARNING, "No such peer '%s'\n", peer_name);
08397 return -1;
08398 }
08399 ast_mutex_lock(&iaxsl[callno]);
08400 if (!iaxs[callno])
08401 goto return_unref;
08402
08403 if (ast_test_flag((&globalflags), IAX_RTUPDATE) && (ast_test_flag(p, IAX_TEMPONLY|IAX_RTCACHEFRIENDS))) {
08404 if (sin->sin_addr.s_addr) {
08405 time_t nowtime;
08406 time(&nowtime);
08407 realtime_update_peer(peer_name, sin, nowtime);
08408 } else {
08409 realtime_update_peer(peer_name, sin, 0);
08410 }
08411 }
08412 if (inaddrcmp(&p->addr, sin)) {
08413 if (iax2_regfunk)
08414 iax2_regfunk(p->name, 1);
08415
08416
08417 peercnt_modify(0, 0, &p->addr);
08418
08419
08420 memcpy(&p->addr, sin, sizeof(p->addr));
08421
08422 snprintf(data, sizeof(data), "%s:%d:%d", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port), p->expiry);
08423 if (!ast_test_flag(p, IAX_TEMPONLY) && sin->sin_addr.s_addr) {
08424 ast_db_put("IAX/Registry", p->name, data);
08425 ast_verb(3, "Registered IAX2 '%s' (%s) at %s:%d\n", p->name,
08426 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
08427 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Registered\r\n", p->name);
08428 register_peer_exten(p, 1);
08429 ast_devstate_changed(AST_DEVICE_UNKNOWN, "IAX2/%s", p->name);
08430 } else if (!ast_test_flag(p, IAX_TEMPONLY)) {
08431 ast_verb(3, "Unregistered IAX2 '%s' (%s)\n", p->name,
08432 ast_test_flag(&iaxs[callno]->state, IAX_STATE_AUTHENTICATED) ? "AUTHENTICATED" : "UNAUTHENTICATED");
08433 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unregistered\r\n", p->name);
08434 register_peer_exten(p, 0);
08435 ast_db_del("IAX/Registry", p->name);
08436 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", p->name);
08437 }
08438
08439
08440 iax2_poke_peer(p, callno);
08441 }
08442
08443
08444 if (p->maxcallno) {
08445 peercnt_modify(1, p->maxcallno, &p->addr);
08446 }
08447
08448
08449 if (!iaxs[callno]) {
08450 res = -1;
08451 goto return_unref;
08452 }
08453
08454
08455 p->sockfd = fd;
08456
08457 if (p->expire > -1) {
08458 if (!ast_sched_thread_del(sched, p->expire)) {
08459 p->expire = -1;
08460 peer_unref(p);
08461 }
08462 }
08463
08464 if (!refresh)
08465 refresh = min_reg_expire;
08466 if (refresh > max_reg_expire) {
08467 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08468 p->name, max_reg_expire, refresh);
08469 p->expiry = max_reg_expire;
08470 } else if (refresh < min_reg_expire) {
08471 ast_log(LOG_NOTICE, "Restricting registration for peer '%s' to %d seconds (requested %d)\n",
08472 p->name, min_reg_expire, refresh);
08473 p->expiry = min_reg_expire;
08474 } else {
08475 p->expiry = refresh;
08476 }
08477 if (p->expiry && sin->sin_addr.s_addr) {
08478 p->expire = iax2_sched_add(sched, (p->expiry + 10) * 1000, expire_registry, peer_ref(p));
08479 if (p->expire == -1)
08480 peer_unref(p);
08481 }
08482 iax_ie_append_str(&ied, IAX_IE_USERNAME, p->name);
08483 iax_ie_append_int(&ied, IAX_IE_DATETIME, iax2_datetime(p->zonetag));
08484 if (sin->sin_addr.s_addr) {
08485 iax_ie_append_short(&ied, IAX_IE_REFRESH, p->expiry);
08486 iax_ie_append_addr(&ied, IAX_IE_APPARENT_ADDR, &p->addr);
08487 if (!ast_strlen_zero(p->mailbox)) {
08488 struct ast_event *event;
08489 int new, old;
08490 char *mailbox, *context;
08491
08492 context = mailbox = ast_strdupa(p->mailbox);
08493 strsep(&context, "@");
08494 if (ast_strlen_zero(context))
08495 context = "default";
08496
08497 event = ast_event_get_cached(AST_EVENT_MWI,
08498 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
08499 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
08500 AST_EVENT_IE_END);
08501 if (event) {
08502 new = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
08503 old = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
08504 ast_event_destroy(event);
08505 } else {
08506 ast_app_inboxcount(p->mailbox, &new, &old);
08507 }
08508
08509 if (new > 255) {
08510 new = 255;
08511 }
08512 if (old > 255) {
08513 old = 255;
08514 }
08515 msgcount = (old << 8) | new;
08516
08517 iax_ie_append_short(&ied, IAX_IE_MSGCOUNT, msgcount);
08518 }
08519 if (ast_test_flag(p, IAX_HASCALLERID)) {
08520 iax_ie_append_str(&ied, IAX_IE_CALLING_NUMBER, p->cid_num);
08521 iax_ie_append_str(&ied, IAX_IE_CALLING_NAME, p->cid_name);
08522 }
08523 }
08524 version = iax_check_version(devtype);
08525 if (version)
08526 iax_ie_append_short(&ied, IAX_IE_FIRMWAREVER, version);
08527
08528 res = 0;
08529
08530 return_unref:
08531 peer_unref(p);
08532
08533 return res ? res : send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGACK, 0, ied.buf, ied.pos, -1);
08534 }
08535
08536 static int registry_authrequest(int callno)
08537 {
08538 struct iax_ie_data ied;
08539 struct iax2_peer *p;
08540 char challenge[10];
08541 const char *peer_name;
08542 int sentauthmethod;
08543
08544 peer_name = ast_strdupa(iaxs[callno]->peer);
08545
08546
08547 ast_mutex_unlock(&iaxsl[callno]);
08548 if ((p = find_peer(peer_name, 1))) {
08549 last_authmethod = p->authmethods;
08550 }
08551
08552 ast_mutex_lock(&iaxsl[callno]);
08553 if (!iaxs[callno])
08554 goto return_unref;
08555
08556 memset(&ied, 0, sizeof(ied));
08557
08558
08559
08560
08561
08562
08563 sentauthmethod = p ? p->authmethods : last_authmethod ? last_authmethod : (IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT);
08564 if (!p) {
08565 iaxs[callno]->authmethods = sentauthmethod;
08566 }
08567 iax_ie_append_short(&ied, IAX_IE_AUTHMETHODS, sentauthmethod);
08568 if (sentauthmethod & (IAX_AUTH_RSA | IAX_AUTH_MD5)) {
08569
08570 snprintf(challenge, sizeof(challenge), "%d", (int)ast_random());
08571 ast_string_field_set(iaxs[callno], challenge, challenge);
08572 iax_ie_append_str(&ied, IAX_IE_CHALLENGE, iaxs[callno]->challenge);
08573 }
08574 iax_ie_append_str(&ied, IAX_IE_USERNAME, peer_name);
08575
08576 return_unref:
08577 if (p) {
08578 peer_unref(p);
08579 }
08580
08581 return iaxs[callno] ? send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGAUTH, 0, ied.buf, ied.pos, -1) : -1;
08582 }
08583
08584 static int registry_rerequest(struct iax_ies *ies, int callno, struct sockaddr_in *sin)
08585 {
08586 struct iax2_registry *reg;
08587
08588 struct iax_ie_data ied;
08589 char peer[256] = "";
08590 char challenge[256] = "";
08591 int res;
08592 int authmethods = 0;
08593 if (ies->authmethods)
08594 authmethods = ies->authmethods;
08595 if (ies->username)
08596 ast_copy_string(peer, ies->username, sizeof(peer));
08597 if (ies->challenge)
08598 ast_copy_string(challenge, ies->challenge, sizeof(challenge));
08599 memset(&ied, 0, sizeof(ied));
08600 reg = iaxs[callno]->reg;
08601 if (reg) {
08602 if (inaddrcmp(®->addr, sin)) {
08603 ast_log(LOG_WARNING, "Received unsolicited registry authenticate request from '%s'\n", ast_inet_ntoa(sin->sin_addr));
08604 return -1;
08605 }
08606 if (ast_strlen_zero(reg->secret)) {
08607 ast_log(LOG_NOTICE, "No secret associated with peer '%s'\n", reg->username);
08608 reg->regstate = REG_STATE_NOAUTH;
08609 return -1;
08610 }
08611 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
08612 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
08613 if (reg->secret[0] == '[') {
08614 char tmpkey[256];
08615 ast_copy_string(tmpkey, reg->secret + 1, sizeof(tmpkey));
08616 tmpkey[strlen(tmpkey) - 1] = '\0';
08617 res = authenticate(challenge, NULL, tmpkey, authmethods, &ied, sin, NULL);
08618 } else
08619 res = authenticate(challenge, reg->secret, NULL, authmethods, &ied, sin, NULL);
08620 if (!res) {
08621 reg->regstate = REG_STATE_AUTHSENT;
08622 add_empty_calltoken_ie(iaxs[callno], &ied);
08623 return send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
08624 } else
08625 return -1;
08626 ast_log(LOG_WARNING, "Registry acknowledge on unknown registery '%s'\n", peer);
08627 } else
08628 ast_log(LOG_NOTICE, "Can't reregister without a reg\n");
08629 return -1;
08630 }
08631
08632 static void stop_stuff(int callno)
08633 {
08634 iax2_destroy_helper(iaxs[callno]);
08635 }
08636
08637 static void __auth_reject(const void *nothing)
08638 {
08639
08640 int callno = (int)(long)(nothing);
08641 struct iax_ie_data ied;
08642 ast_mutex_lock(&iaxsl[callno]);
08643 if (iaxs[callno]) {
08644 memset(&ied, 0, sizeof(ied));
08645 if (iaxs[callno]->authfail == IAX_COMMAND_REGREJ) {
08646 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Registration Refused");
08647 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_REJECTED);
08648 } else if (iaxs[callno]->authfail == IAX_COMMAND_REJECT) {
08649 iax_ie_append_str(&ied, IAX_IE_CAUSE, "No authority found");
08650 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
08651 }
08652 send_command_final(iaxs[callno], AST_FRAME_IAX, iaxs[callno]->authfail, 0, ied.buf, ied.pos, -1);
08653 }
08654 ast_mutex_unlock(&iaxsl[callno]);
08655 }
08656
08657 static int auth_reject(const void *data)
08658 {
08659 int callno = (int)(long)(data);
08660 ast_mutex_lock(&iaxsl[callno]);
08661 if (iaxs[callno])
08662 iaxs[callno]->authid = -1;
08663 ast_mutex_unlock(&iaxsl[callno]);
08664 #ifdef SCHED_MULTITHREADED
08665 if (schedule_action(__auth_reject, data))
08666 #endif
08667 __auth_reject(data);
08668 return 0;
08669 }
08670
08671 static int auth_fail(int callno, int failcode)
08672 {
08673
08674
08675 if (iaxs[callno]) {
08676 iaxs[callno]->authfail = failcode;
08677 if (delayreject) {
08678 iaxs[callno]->authid = iax2_sched_replace(iaxs[callno]->authid,
08679 sched, 1000, auth_reject, (void *)(long)callno);
08680 } else
08681 auth_reject((void *)(long)callno);
08682 }
08683 return 0;
08684 }
08685
08686 static void __auto_hangup(const void *nothing)
08687 {
08688
08689 int callno = (int)(long)(nothing);
08690 struct iax_ie_data ied;
08691 ast_mutex_lock(&iaxsl[callno]);
08692 if (iaxs[callno]) {
08693 memset(&ied, 0, sizeof(ied));
08694 iax_ie_append_str(&ied, IAX_IE_CAUSE, "Timeout");
08695 iax_ie_append_byte(&ied, IAX_IE_CAUSECODE, AST_CAUSE_NO_USER_RESPONSE);
08696 send_command_final(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_HANGUP, 0, ied.buf, ied.pos, -1);
08697 }
08698 ast_mutex_unlock(&iaxsl[callno]);
08699 }
08700
08701 static int auto_hangup(const void *data)
08702 {
08703 int callno = (int)(long)(data);
08704 ast_mutex_lock(&iaxsl[callno]);
08705 if (iaxs[callno]) {
08706 iaxs[callno]->autoid = -1;
08707 }
08708 ast_mutex_unlock(&iaxsl[callno]);
08709 #ifdef SCHED_MULTITHREADED
08710 if (schedule_action(__auto_hangup, data))
08711 #endif
08712 __auto_hangup(data);
08713 return 0;
08714 }
08715
08716 static void iax2_dprequest(struct iax2_dpcache *dp, int callno)
08717 {
08718 struct iax_ie_data ied;
08719
08720 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
08721 sched, 30000, auto_hangup, (void *)(long)callno);
08722 memset(&ied, 0, sizeof(ied));
08723 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, dp->exten);
08724 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREQ, 0, ied.buf, ied.pos, -1);
08725 dp->flags |= CACHE_FLAG_TRANSMITTED;
08726 }
08727
08728 static int iax2_vnak(int callno)
08729 {
08730 return send_command_immediate(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_VNAK, 0, NULL, 0, iaxs[callno]->iseqno);
08731 }
08732
08733 static void vnak_retransmit(int callno, int last)
08734 {
08735 struct iax_frame *f;
08736
08737 AST_LIST_LOCK(&frame_queue);
08738 AST_LIST_TRAVERSE(&frame_queue, f, list) {
08739
08740 if ((f->callno == callno) && iaxs[f->callno] &&
08741 ((unsigned char ) (f->oseqno - last) < 128) &&
08742 (f->retries >= 0)) {
08743 send_packet(f);
08744 }
08745 }
08746 AST_LIST_UNLOCK(&frame_queue);
08747 }
08748
08749 static void __iax2_poke_peer_s(const void *data)
08750 {
08751 struct iax2_peer *peer = (struct iax2_peer *)data;
08752 iax2_poke_peer(peer, 0);
08753 peer_unref(peer);
08754 }
08755
08756 static int iax2_poke_peer_s(const void *data)
08757 {
08758 struct iax2_peer *peer = (struct iax2_peer *)data;
08759 peer->pokeexpire = -1;
08760 #ifdef SCHED_MULTITHREADED
08761 if (schedule_action(__iax2_poke_peer_s, data))
08762 #endif
08763 __iax2_poke_peer_s(data);
08764 return 0;
08765 }
08766
08767 static int send_trunk(struct iax2_trunk_peer *tpeer, struct timeval *now)
08768 {
08769 int res = 0;
08770 struct iax_frame *fr;
08771 struct ast_iax2_meta_hdr *meta;
08772 struct ast_iax2_meta_trunk_hdr *mth;
08773 int calls = 0;
08774
08775
08776 fr = (struct iax_frame *)tpeer->trunkdata;
08777
08778 meta = (struct ast_iax2_meta_hdr *)fr->afdata;
08779 mth = (struct ast_iax2_meta_trunk_hdr *)meta->data;
08780 if (tpeer->trunkdatalen) {
08781
08782 meta->zeros = 0;
08783 meta->metacmd = IAX_META_TRUNK;
08784 if (ast_test_flag(&globalflags, IAX_TRUNKTIMESTAMPS))
08785 meta->cmddata = IAX_META_TRUNK_MINI;
08786 else
08787 meta->cmddata = IAX_META_TRUNK_SUPERMINI;
08788 mth->ts = htonl(calc_txpeerstamp(tpeer, trunkfreq, now));
08789
08790 fr->direction = DIRECTION_OUTGRESS;
08791 fr->retrans = -1;
08792 fr->transfer = 0;
08793
08794 fr->data = fr->afdata;
08795 fr->datalen = tpeer->trunkdatalen + sizeof(struct ast_iax2_meta_hdr) + sizeof(struct ast_iax2_meta_trunk_hdr);
08796 res = transmit_trunk(fr, &tpeer->addr, tpeer->sockfd);
08797 calls = tpeer->calls;
08798 #if 0
08799 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));
08800 #endif
08801
08802 tpeer->trunkdatalen = 0;
08803 tpeer->calls = 0;
08804 }
08805 if (res < 0)
08806 return res;
08807 return calls;
08808 }
08809
08810 static inline int iax2_trunk_expired(struct iax2_trunk_peer *tpeer, struct timeval *now)
08811 {
08812
08813 if (now->tv_sec > tpeer->trunkact.tv_sec + 5)
08814 return 1;
08815 return 0;
08816 }
08817
08818 static int timing_read(int *id, int fd, short events, void *cbdata)
08819 {
08820 int res, processed = 0, totalcalls = 0;
08821 struct iax2_trunk_peer *tpeer = NULL, *drop = NULL;
08822 struct timeval now = ast_tvnow();
08823
08824 if (iaxtrunkdebug)
08825 ast_verbose("Beginning trunk processing. Trunk queue ceiling is %d bytes per host\n", trunkmaxsize);
08826
08827 if (timer) {
08828 ast_timer_ack(timer, 1);
08829 }
08830
08831
08832 AST_LIST_LOCK(&tpeers);
08833 AST_LIST_TRAVERSE_SAFE_BEGIN(&tpeers, tpeer, list) {
08834 processed++;
08835 res = 0;
08836 ast_mutex_lock(&tpeer->lock);
08837
08838
08839 if (!drop && iax2_trunk_expired(tpeer, &now)) {
08840
08841
08842 AST_LIST_REMOVE_CURRENT(list);
08843 drop = tpeer;
08844 } else {
08845 res = send_trunk(tpeer, &now);
08846 trunk_timed++;
08847 if (iaxtrunkdebug)
08848 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);
08849 }
08850 totalcalls += res;
08851 res = 0;
08852 ast_mutex_unlock(&tpeer->lock);
08853 }
08854 AST_LIST_TRAVERSE_SAFE_END;
08855 AST_LIST_UNLOCK(&tpeers);
08856
08857 if (drop) {
08858 ast_mutex_lock(&drop->lock);
08859
08860
08861 ast_debug(1, "Dropping unused iax2 trunk peer '%s:%d'\n", ast_inet_ntoa(drop->addr.sin_addr), ntohs(drop->addr.sin_port));
08862 if (drop->trunkdata) {
08863 ast_free(drop->trunkdata);
08864 drop->trunkdata = NULL;
08865 }
08866 ast_mutex_unlock(&drop->lock);
08867 ast_mutex_destroy(&drop->lock);
08868 ast_free(drop);
08869
08870 }
08871
08872 if (iaxtrunkdebug)
08873 ast_verbose("Ending trunk processing with %d peers and %d call chunks processed\n", processed, totalcalls);
08874 iaxtrunkdebug = 0;
08875
08876 return 1;
08877 }
08878
08879 struct dpreq_data {
08880 int callno;
08881 char context[AST_MAX_EXTENSION];
08882 char callednum[AST_MAX_EXTENSION];
08883 char *callerid;
08884 };
08885
08886 static void dp_lookup(int callno, const char *context, const char *callednum, const char *callerid, int skiplock)
08887 {
08888 unsigned short dpstatus = 0;
08889 struct iax_ie_data ied1;
08890 int mm;
08891
08892 memset(&ied1, 0, sizeof(ied1));
08893 mm = ast_matchmore_extension(NULL, context, callednum, 1, callerid);
08894
08895 if (!strcmp(callednum, ast_parking_ext()) || ast_exists_extension(NULL, context, callednum, 1, callerid)) {
08896 dpstatus = IAX_DPSTATUS_EXISTS;
08897 } else if (ast_canmatch_extension(NULL, context, callednum, 1, callerid)) {
08898 dpstatus = IAX_DPSTATUS_CANEXIST;
08899 } else {
08900 dpstatus = IAX_DPSTATUS_NONEXISTENT;
08901 }
08902 if (ast_ignore_pattern(context, callednum))
08903 dpstatus |= IAX_DPSTATUS_IGNOREPAT;
08904 if (mm)
08905 dpstatus |= IAX_DPSTATUS_MATCHMORE;
08906 if (!skiplock)
08907 ast_mutex_lock(&iaxsl[callno]);
08908 if (iaxs[callno]) {
08909 iax_ie_append_str(&ied1, IAX_IE_CALLED_NUMBER, callednum);
08910 iax_ie_append_short(&ied1, IAX_IE_DPSTATUS, dpstatus);
08911 iax_ie_append_short(&ied1, IAX_IE_REFRESH, iaxdefaultdpcache);
08912 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_DPREP, 0, ied1.buf, ied1.pos, -1);
08913 }
08914 if (!skiplock)
08915 ast_mutex_unlock(&iaxsl[callno]);
08916 }
08917
08918 static void *dp_lookup_thread(void *data)
08919 {
08920
08921 struct dpreq_data *dpr = data;
08922 dp_lookup(dpr->callno, dpr->context, dpr->callednum, dpr->callerid, 0);
08923 if (dpr->callerid)
08924 ast_free(dpr->callerid);
08925 ast_free(dpr);
08926 return NULL;
08927 }
08928
08929 static void spawn_dp_lookup(int callno, const char *context, const char *callednum, const char *callerid)
08930 {
08931 pthread_t newthread;
08932 struct dpreq_data *dpr;
08933
08934 if (!(dpr = ast_calloc(1, sizeof(*dpr))))
08935 return;
08936
08937 dpr->callno = callno;
08938 ast_copy_string(dpr->context, context, sizeof(dpr->context));
08939 ast_copy_string(dpr->callednum, callednum, sizeof(dpr->callednum));
08940 if (callerid)
08941 dpr->callerid = ast_strdup(callerid);
08942 if (ast_pthread_create_detached(&newthread, NULL, dp_lookup_thread, dpr)) {
08943 ast_log(LOG_WARNING, "Unable to start lookup thread!\n");
08944 }
08945 }
08946
08947 struct iax_dual {
08948 struct ast_channel *chan1;
08949 struct ast_channel *chan2;
08950 };
08951
08952 static void *iax_park_thread(void *stuff)
08953 {
08954 struct ast_channel *chan1, *chan2;
08955 struct iax_dual *d;
08956 struct ast_frame *f;
08957 int ext;
08958 int res;
08959 d = stuff;
08960 chan1 = d->chan1;
08961 chan2 = d->chan2;
08962 ast_free(d);
08963 f = ast_read(chan1);
08964 if (f)
08965 ast_frfree(f);
08966 res = ast_park_call(chan1, chan2, 0, &ext);
08967 ast_hangup(chan2);
08968 ast_log(LOG_NOTICE, "Parked on extension '%d'\n", ext);
08969 return NULL;
08970 }
08971
08972 static int iax_park(struct ast_channel *chan1, struct ast_channel *chan2)
08973 {
08974 struct iax_dual *d;
08975 struct ast_channel *chan1m, *chan2m;
08976 pthread_t th;
08977 chan1m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
08978 chan2m = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "IAXPeer/%s",chan2->name);
08979 if (chan2m && chan1m) {
08980
08981 chan1m->readformat = chan1->readformat;
08982 chan1m->writeformat = chan1->writeformat;
08983 ast_channel_masquerade(chan1m, chan1);
08984
08985 ast_copy_string(chan1m->context, chan1->context, sizeof(chan1m->context));
08986 ast_copy_string(chan1m->exten, chan1->exten, sizeof(chan1m->exten));
08987 chan1m->priority = chan1->priority;
08988
08989
08990
08991
08992 chan2m->readformat = chan2->readformat;
08993 chan2m->writeformat = chan2->writeformat;
08994 ast_channel_masquerade(chan2m, chan2);
08995
08996 ast_copy_string(chan2m->context, chan2->context, sizeof(chan2m->context));
08997 ast_copy_string(chan2m->exten, chan2->exten, sizeof(chan2m->exten));
08998 chan2m->priority = chan2->priority;
08999 if (ast_do_masquerade(chan2m)) {
09000 ast_log(LOG_WARNING, "Masquerade failed :(\n");
09001 ast_hangup(chan2m);
09002 return -1;
09003 }
09004 } else {
09005 if (chan1m)
09006 ast_hangup(chan1m);
09007 if (chan2m)
09008 ast_hangup(chan2m);
09009 return -1;
09010 }
09011 if ((d = ast_calloc(1, sizeof(*d)))) {
09012 d->chan1 = chan1m;
09013 d->chan2 = chan2m;
09014 if (!ast_pthread_create_detached_background(&th, NULL, iax_park_thread, d)) {
09015 return 0;
09016 }
09017 ast_free(d);
09018 }
09019 return -1;
09020 }
09021
09022
09023 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force);
09024
09025 static int check_provisioning(struct sockaddr_in *sin, int sockfd, char *si, unsigned int ver)
09026 {
09027 unsigned int ourver;
09028 char rsi[80];
09029 snprintf(rsi, sizeof(rsi), "si-%s", si);
09030 if (iax_provision_version(&ourver, rsi, 1))
09031 return 0;
09032 ast_debug(1, "Service identifier '%s', we think '%08x', they think '%08x'\n", si, ourver, ver);
09033 if (ourver != ver)
09034 iax2_provision(sin, sockfd, NULL, rsi, 1);
09035 return 0;
09036 }
09037
09038 static void construct_rr(struct chan_iax2_pvt *pvt, struct iax_ie_data *iep)
09039 {
09040 jb_info stats;
09041 jb_getinfo(pvt->jb, &stats);
09042
09043 memset(iep, 0, sizeof(*iep));
09044
09045 iax_ie_append_int(iep,IAX_IE_RR_JITTER, stats.jitter);
09046 if(stats.frames_in == 0) stats.frames_in = 1;
09047 iax_ie_append_int(iep,IAX_IE_RR_LOSS, ((0xff & (stats.losspct/1000)) << 24 | (stats.frames_lost & 0x00ffffff)));
09048 iax_ie_append_int(iep,IAX_IE_RR_PKTS, stats.frames_in);
09049 iax_ie_append_short(iep,IAX_IE_RR_DELAY, stats.current - stats.min);
09050 iax_ie_append_int(iep,IAX_IE_RR_DROPPED, stats.frames_dropped);
09051 iax_ie_append_int(iep,IAX_IE_RR_OOO, stats.frames_ooo);
09052 }
09053
09054 static void save_rr(struct iax_frame *fr, struct iax_ies *ies)
09055 {
09056 iaxs[fr->callno]->remote_rr.jitter = ies->rr_jitter;
09057 iaxs[fr->callno]->remote_rr.losspct = ies->rr_loss >> 24;
09058 iaxs[fr->callno]->remote_rr.losscnt = ies->rr_loss & 0xffffff;
09059 iaxs[fr->callno]->remote_rr.packets = ies->rr_pkts;
09060 iaxs[fr->callno]->remote_rr.delay = ies->rr_delay;
09061 iaxs[fr->callno]->remote_rr.dropped = ies->rr_dropped;
09062 iaxs[fr->callno]->remote_rr.ooo = ies->rr_ooo;
09063 }
09064
09065 static void save_osptoken(struct iax_frame *fr, struct iax_ies *ies)
09066 {
09067 int i;
09068 unsigned int length, offset = 0;
09069 char full_osptoken[IAX_MAX_OSPBUFF_SIZE];
09070
09071 for (i = 0; i < IAX_MAX_OSPBLOCK_NUM; i++) {
09072 length = ies->ospblocklength[i];
09073 if (length != 0) {
09074 if (length > IAX_MAX_OSPBLOCK_SIZE) {
09075
09076 offset = 0;
09077 break;
09078 } else {
09079 memcpy(full_osptoken + offset, ies->osptokenblock[i], length);
09080 offset += length;
09081 }
09082 } else {
09083 break;
09084 }
09085 }
09086 *(full_osptoken + offset) = '\0';
09087 if (strlen(full_osptoken) != offset) {
09088
09089 *full_osptoken = '\0';
09090 }
09091
09092 ast_string_field_set(iaxs[fr->callno], osptoken, full_osptoken);
09093 }
09094
09095 static void log_jitterstats(unsigned short callno)
09096 {
09097 int localjitter = -1, localdelay = 0, locallost = -1, locallosspct = -1, localdropped = 0, localooo = -1, localpackets = -1;
09098 jb_info jbinfo;
09099
09100 ast_mutex_lock(&iaxsl[callno]);
09101 if (iaxs[callno] && iaxs[callno]->owner && iaxs[callno]->owner->name) {
09102 if(ast_test_flag(iaxs[callno], IAX_USEJITTERBUF)) {
09103 jb_getinfo(iaxs[callno]->jb, &jbinfo);
09104 localjitter = jbinfo.jitter;
09105 localdelay = jbinfo.current - jbinfo.min;
09106 locallost = jbinfo.frames_lost;
09107 locallosspct = jbinfo.losspct/1000;
09108 localdropped = jbinfo.frames_dropped;
09109 localooo = jbinfo.frames_ooo;
09110 localpackets = jbinfo.frames_in;
09111 }
09112 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",
09113 iaxs[callno]->owner->name,
09114 iaxs[callno]->pingtime,
09115 localjitter,
09116 localdelay,
09117 locallost,
09118 locallosspct,
09119 localdropped,
09120 localooo,
09121 localpackets,
09122 iaxs[callno]->remote_rr.jitter,
09123 iaxs[callno]->remote_rr.delay,
09124 iaxs[callno]->remote_rr.losscnt,
09125 iaxs[callno]->remote_rr.losspct/1000,
09126 iaxs[callno]->remote_rr.dropped,
09127 iaxs[callno]->remote_rr.ooo,
09128 iaxs[callno]->remote_rr.packets);
09129 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",
09130 iaxs[callno]->owner->name,
09131 iaxs[callno]->pingtime,
09132 localjitter,
09133 localdelay,
09134 locallost,
09135 locallosspct,
09136 localdropped,
09137 localooo,
09138 localpackets,
09139 iaxs[callno]->remote_rr.jitter,
09140 iaxs[callno]->remote_rr.delay,
09141 iaxs[callno]->remote_rr.losscnt,
09142 iaxs[callno]->remote_rr.losspct/1000,
09143 iaxs[callno]->remote_rr.dropped,
09144 iaxs[callno]->remote_rr.ooo,
09145 iaxs[callno]->remote_rr.packets);
09146 }
09147 ast_mutex_unlock(&iaxsl[callno]);
09148 }
09149
09150 static int socket_process(struct iax2_thread *thread);
09151
09152
09153
09154
09155 static void handle_deferred_full_frames(struct iax2_thread *thread)
09156 {
09157 struct iax2_pkt_buf *pkt_buf;
09158
09159 ast_mutex_lock(&thread->lock);
09160
09161 while ((pkt_buf = AST_LIST_REMOVE_HEAD(&thread->full_frames, entry))) {
09162 ast_mutex_unlock(&thread->lock);
09163
09164 thread->buf = pkt_buf->buf;
09165 thread->buf_len = pkt_buf->len;
09166 thread->buf_size = pkt_buf->len + 1;
09167
09168 socket_process(thread);
09169
09170 thread->buf = NULL;
09171 ast_free(pkt_buf);
09172
09173 ast_mutex_lock(&thread->lock);
09174 }
09175
09176 ast_mutex_unlock(&thread->lock);
09177 }
09178
09179
09180
09181
09182
09183
09184
09185 static void defer_full_frame(struct iax2_thread *from_here, struct iax2_thread *to_here)
09186 {
09187 struct iax2_pkt_buf *pkt_buf, *cur_pkt_buf;
09188 struct ast_iax2_full_hdr *fh, *cur_fh;
09189
09190 if (!(pkt_buf = ast_calloc(1, sizeof(*pkt_buf) + from_here->buf_len)))
09191 return;
09192
09193 pkt_buf->len = from_here->buf_len;
09194 memcpy(pkt_buf->buf, from_here->buf, pkt_buf->len);
09195
09196 fh = (struct ast_iax2_full_hdr *) pkt_buf->buf;
09197 ast_mutex_lock(&to_here->lock);
09198 AST_LIST_TRAVERSE_SAFE_BEGIN(&to_here->full_frames, cur_pkt_buf, entry) {
09199 cur_fh = (struct ast_iax2_full_hdr *) cur_pkt_buf->buf;
09200 if (fh->oseqno < cur_fh->oseqno) {
09201 AST_LIST_INSERT_BEFORE_CURRENT(pkt_buf, entry);
09202 break;
09203 }
09204 }
09205 AST_LIST_TRAVERSE_SAFE_END
09206
09207 if (!cur_pkt_buf)
09208 AST_LIST_INSERT_TAIL(&to_here->full_frames, pkt_buf, entry);
09209
09210 ast_mutex_unlock(&to_here->lock);
09211 }
09212
09213 static int socket_read(int *id, int fd, short events, void *cbdata)
09214 {
09215 struct iax2_thread *thread;
09216 socklen_t len;
09217 time_t t;
09218 static time_t last_errtime = 0;
09219 struct ast_iax2_full_hdr *fh;
09220
09221 if (!(thread = find_idle_thread())) {
09222 time(&t);
09223 if (t != last_errtime)
09224 ast_debug(1, "Out of idle IAX2 threads for I/O, pausing!\n");
09225 last_errtime = t;
09226 usleep(1);
09227 return 1;
09228 }
09229
09230 len = sizeof(thread->iosin);
09231 thread->iofd = fd;
09232 thread->buf_len = recvfrom(fd, thread->readbuf, sizeof(thread->readbuf), 0, (struct sockaddr *) &thread->iosin, &len);
09233 thread->buf_size = sizeof(thread->readbuf);
09234 thread->buf = thread->readbuf;
09235 if (thread->buf_len < 0) {
09236 if (errno != ECONNREFUSED && errno != EAGAIN)
09237 ast_log(LOG_WARNING, "Error: %s\n", strerror(errno));
09238 handle_error();
09239 thread->iostate = IAX_IOSTATE_IDLE;
09240 signal_condition(&thread->lock, &thread->cond);
09241 return 1;
09242 }
09243 if (test_losspct && ((100.0 * ast_random() / (RAND_MAX + 1.0)) < test_losspct)) {
09244 thread->iostate = IAX_IOSTATE_IDLE;
09245 signal_condition(&thread->lock, &thread->cond);
09246 return 1;
09247 }
09248
09249
09250
09251
09252 fh = (struct ast_iax2_full_hdr *) thread->buf;
09253 if (ntohs(fh->scallno) & IAX_FLAG_FULL) {
09254 struct iax2_thread *cur = NULL;
09255 uint16_t callno = ntohs(fh->scallno) & ~IAX_FLAG_FULL;
09256
09257 AST_LIST_LOCK(&active_list);
09258 AST_LIST_TRAVERSE(&active_list, cur, list) {
09259 if ((cur->ffinfo.callno == callno) &&
09260 !inaddrcmp(&cur->ffinfo.sin, &thread->iosin))
09261 break;
09262 }
09263 if (cur) {
09264
09265
09266 defer_full_frame(thread, cur);
09267 AST_LIST_UNLOCK(&active_list);
09268 thread->iostate = IAX_IOSTATE_IDLE;
09269 signal_condition(&thread->lock, &thread->cond);
09270 return 1;
09271 } else {
09272
09273 thread->ffinfo.callno = callno;
09274 memcpy(&thread->ffinfo.sin, &thread->iosin, sizeof(thread->ffinfo.sin));
09275 thread->ffinfo.type = fh->type;
09276 thread->ffinfo.csub = fh->csub;
09277 AST_LIST_INSERT_HEAD(&active_list, thread, list);
09278 }
09279 AST_LIST_UNLOCK(&active_list);
09280 }
09281
09282
09283 thread->iostate = IAX_IOSTATE_READY;
09284 #ifdef DEBUG_SCHED_MULTITHREAD
09285 ast_copy_string(thread->curfunc, "socket_process", sizeof(thread->curfunc));
09286 #endif
09287 signal_condition(&thread->lock, &thread->cond);
09288
09289 return 1;
09290 }
09291
09292 static int socket_process_meta(int packet_len, struct ast_iax2_meta_hdr *meta, struct sockaddr_in *sin, int sockfd,
09293 struct iax_frame *fr)
09294 {
09295 unsigned char metatype;
09296 struct ast_iax2_meta_trunk_mini *mtm;
09297 struct ast_iax2_meta_trunk_hdr *mth;
09298 struct ast_iax2_meta_trunk_entry *mte;
09299 struct iax2_trunk_peer *tpeer;
09300 unsigned int ts;
09301 void *ptr;
09302 struct timeval rxtrunktime;
09303 struct ast_frame f = { 0, };
09304
09305 if (packet_len < sizeof(*meta)) {
09306 ast_log(LOG_WARNING, "Rejecting packet from '%s.%d' that is flagged as a meta frame but is too short\n",
09307 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09308 return 1;
09309 }
09310
09311 if (meta->metacmd != IAX_META_TRUNK)
09312 return 1;
09313
09314 if (packet_len < (sizeof(*meta) + sizeof(*mth))) {
09315 ast_log(LOG_WARNING, "midget meta trunk packet received (%d of %d min)\n", packet_len,
09316 (int) (sizeof(*meta) + sizeof(*mth)));
09317 return 1;
09318 }
09319 mth = (struct ast_iax2_meta_trunk_hdr *)(meta->data);
09320 ts = ntohl(mth->ts);
09321 metatype = meta->cmddata;
09322 packet_len -= (sizeof(*meta) + sizeof(*mth));
09323 ptr = mth->data;
09324 tpeer = find_tpeer(sin, sockfd);
09325 if (!tpeer) {
09326 ast_log(LOG_WARNING, "Unable to accept trunked packet from '%s:%d': No matching peer\n",
09327 ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09328 return 1;
09329 }
09330 tpeer->trunkact = ast_tvnow();
09331 if (!ts || ast_tvzero(tpeer->rxtrunktime))
09332 tpeer->rxtrunktime = tpeer->trunkact;
09333 rxtrunktime = tpeer->rxtrunktime;
09334 ast_mutex_unlock(&tpeer->lock);
09335 while (packet_len >= sizeof(*mte)) {
09336
09337 unsigned short callno, trunked_ts, len;
09338
09339 if (metatype == IAX_META_TRUNK_MINI) {
09340 mtm = (struct ast_iax2_meta_trunk_mini *) ptr;
09341 ptr += sizeof(*mtm);
09342 packet_len -= sizeof(*mtm);
09343 len = ntohs(mtm->len);
09344 callno = ntohs(mtm->mini.callno);
09345 trunked_ts = ntohs(mtm->mini.ts);
09346 } else if (metatype == IAX_META_TRUNK_SUPERMINI) {
09347 mte = (struct ast_iax2_meta_trunk_entry *)ptr;
09348 ptr += sizeof(*mte);
09349 packet_len -= sizeof(*mte);
09350 len = ntohs(mte->len);
09351 callno = ntohs(mte->callno);
09352 trunked_ts = 0;
09353 } else {
09354 ast_log(LOG_WARNING, "Unknown meta trunk cmd from '%s:%d': dropping\n", ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
09355 break;
09356 }
09357
09358 if (len > packet_len)
09359 break;
09360 fr->callno = find_callno_locked(callno & ~IAX_FLAG_FULL, 0, sin, NEW_PREVENT, sockfd, 0);
09361 if (!fr->callno)
09362 continue;
09363
09364
09365
09366
09367 memset(&f, 0, sizeof(f));
09368 f.frametype = AST_FRAME_VOICE;
09369 if (!iaxs[fr->callno]) {
09370
09371 } else if (iaxs[fr->callno]->voiceformat == 0) {
09372 ast_log(LOG_WARNING, "Received trunked frame before first full voice frame\n");
09373 iax2_vnak(fr->callno);
09374 } else {
09375 f.subclass = iaxs[fr->callno]->voiceformat;
09376 f.datalen = len;
09377 if (f.datalen >= 0) {
09378 if (f.datalen)
09379 f.data.ptr = ptr;
09380 else
09381 f.data.ptr = NULL;
09382 if (trunked_ts)
09383 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | (trunked_ts & 0xffff);
09384 else
09385 fr->ts = fix_peerts(&rxtrunktime, fr->callno, ts);
09386
09387 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
09388 struct iax_frame *duped_fr;
09389
09390
09391 f.src = "IAX2";
09392 f.mallocd = 0;
09393 f.offset = 0;
09394 if (f.datalen && (f.frametype == AST_FRAME_VOICE))
09395 f.samples = ast_codec_get_samples(&f);
09396 else
09397 f.samples = 0;
09398 fr->outoforder = 0;
09399 iax_frame_wrap(fr, &f);
09400 duped_fr = iaxfrdup2(fr);
09401 if (duped_fr)
09402 schedule_delivery(duped_fr, 1, 1, &fr->ts);
09403 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts)
09404 iaxs[fr->callno]->last = fr->ts;
09405 }
09406 } else {
09407 ast_log(LOG_WARNING, "Datalen < 0?\n");
09408 }
09409 }
09410 ast_mutex_unlock(&iaxsl[fr->callno]);
09411 ptr += len;
09412 packet_len -= len;
09413 }
09414
09415 return 1;
09416 }
09417
09418 static int acf_iaxvar_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
09419 {
09420 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09421 AST_LIST_HEAD(, ast_var_t) *varlist;
09422 struct ast_var_t *var;
09423
09424 if (!variablestore) {
09425 *buf = '\0';
09426 return 0;
09427 }
09428 varlist = variablestore->data;
09429
09430 AST_LIST_LOCK(varlist);
09431 AST_LIST_TRAVERSE(varlist, var, entries) {
09432 if (strcmp(var->name, data) == 0) {
09433 ast_copy_string(buf, var->value, len);
09434 break;
09435 }
09436 }
09437 AST_LIST_UNLOCK(varlist);
09438 return 0;
09439 }
09440
09441 static int acf_iaxvar_write(struct ast_channel *chan, const char *cmd, char *data, const char *value)
09442 {
09443 struct ast_datastore *variablestore = ast_channel_datastore_find(chan, &iax2_variable_datastore_info, NULL);
09444 AST_LIST_HEAD(, ast_var_t) *varlist;
09445 struct ast_var_t *var;
09446
09447 if (!variablestore) {
09448 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09449 if (!variablestore) {
09450 ast_log(LOG_ERROR, "Memory allocation error\n");
09451 return -1;
09452 }
09453 varlist = ast_calloc(1, sizeof(*varlist));
09454 if (!varlist) {
09455 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09456 return -1;
09457 }
09458
09459 AST_LIST_HEAD_INIT(varlist);
09460 variablestore->data = varlist;
09461 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09462 ast_channel_datastore_add(chan, variablestore);
09463 } else
09464 varlist = variablestore->data;
09465
09466 AST_LIST_LOCK(varlist);
09467 AST_LIST_TRAVERSE_SAFE_BEGIN(varlist, var, entries) {
09468 if (strcmp(var->name, data) == 0) {
09469 AST_LIST_REMOVE_CURRENT(entries);
09470 ast_var_delete(var);
09471 break;
09472 }
09473 }
09474 AST_LIST_TRAVERSE_SAFE_END;
09475 var = ast_var_assign(data, value);
09476 if (var)
09477 AST_LIST_INSERT_TAIL(varlist, var, entries);
09478 else
09479 ast_log(LOG_ERROR, "Unable to assign new variable '%s'\n", data);
09480 AST_LIST_UNLOCK(varlist);
09481 return 0;
09482 }
09483
09484 static struct ast_custom_function iaxvar_function = {
09485 .name = "IAXVAR",
09486 .read = acf_iaxvar_read,
09487 .write = acf_iaxvar_write,
09488 };
09489
09490 static int socket_process(struct iax2_thread *thread)
09491 {
09492 struct sockaddr_in sin;
09493 int res;
09494 int updatehistory=1;
09495 int new = NEW_PREVENT;
09496 int dcallno = 0;
09497 char decrypted = 0;
09498 struct ast_iax2_full_hdr *fh = (struct ast_iax2_full_hdr *)thread->buf;
09499 struct ast_iax2_mini_hdr *mh = (struct ast_iax2_mini_hdr *)thread->buf;
09500 struct ast_iax2_meta_hdr *meta = (struct ast_iax2_meta_hdr *)thread->buf;
09501 struct ast_iax2_video_hdr *vh = (struct ast_iax2_video_hdr *)thread->buf;
09502 struct iax_frame *fr;
09503 struct iax_frame *cur;
09504 struct ast_frame f = { 0, };
09505 struct ast_channel *c = NULL;
09506 struct iax2_dpcache *dp;
09507 struct iax2_peer *peer;
09508 struct iax_ies ies;
09509 struct iax_ie_data ied0, ied1;
09510 int format;
09511 int fd;
09512 int exists;
09513 int minivid = 0;
09514 char empty[32]="";
09515 struct iax_frame *duped_fr;
09516 char host_pref_buf[128];
09517 char caller_pref_buf[128];
09518 struct ast_codec_pref pref;
09519 char *using_prefs = "mine";
09520
09521
09522 fr = alloca(sizeof(*fr) + 4096);
09523 memset(fr, 0, sizeof(*fr));
09524 fr->afdatalen = 4096;
09525
09526
09527 res = thread->buf_len;
09528 fd = thread->iofd;
09529 memcpy(&sin, &thread->iosin, sizeof(sin));
09530
09531 if (res < sizeof(*mh)) {
09532 ast_log(LOG_WARNING, "midget packet received (%d of %d min)\n", res, (int) sizeof(*mh));
09533 return 1;
09534 }
09535 if ((vh->zeros == 0) && (ntohs(vh->callno) & 0x8000)) {
09536 if (res < sizeof(*vh)) {
09537 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));
09538 return 1;
09539 }
09540
09541
09542 fr->callno = find_callno(ntohs(vh->callno) & ~0x8000, dcallno, &sin, new, fd, 0);
09543 minivid = 1;
09544 } else if ((meta->zeros == 0) && !(ntohs(meta->metacmd) & 0x8000))
09545 return socket_process_meta(res, meta, &sin, fd, fr);
09546
09547 #ifdef DEBUG_SUPPORT
09548 if (res >= sizeof(*fh))
09549 iax_outputframe(NULL, fh, 1, &sin, res - sizeof(*fh));
09550 #endif
09551 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09552 if (res < sizeof(*fh)) {
09553 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));
09554 return 1;
09555 }
09556
09557
09558 dcallno = ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS;
09559
09560
09561
09562
09563
09564
09565 if ((dcallno != 1) && (fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, NEW_PREVENT, fd, 1))) {
09566 ast_mutex_lock(&iaxsl[fr->callno]);
09567 if (iaxs[fr->callno] && ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED)) {
09568 if (decrypt_frame(fr->callno, fh, &f, &res)) {
09569 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09570 ast_mutex_unlock(&iaxsl[fr->callno]);
09571 return 1;
09572 }
09573 decrypted = 1;
09574 }
09575 ast_mutex_unlock(&iaxsl[fr->callno]);
09576 }
09577
09578
09579 f.frametype = fh->type;
09580 if (f.frametype == AST_FRAME_VIDEO) {
09581 f.subclass = uncompress_subclass(fh->csub & ~0x40) | ((fh->csub >> 6) & 0x1);
09582 } else {
09583 f.subclass = uncompress_subclass(fh->csub);
09584 }
09585
09586
09587 if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_POKE) {
09588
09589 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_PONG, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09590 return 1;
09591 } else if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_ACK && dcallno == 1) {
09592
09593 return 1;
09594 }
09595
09596 f.datalen = res - sizeof(*fh);
09597 if (f.datalen) {
09598 if (f.frametype == AST_FRAME_IAX) {
09599 if (iax_parse_ies(&ies, thread->buf + sizeof(struct ast_iax2_full_hdr), f.datalen)) {
09600 ast_log(LOG_WARNING, "Undecodable frame received from '%s'\n", ast_inet_ntoa(sin.sin_addr));
09601 ast_variables_destroy(ies.vars);
09602 return 1;
09603 }
09604 f.data.ptr = NULL;
09605 f.datalen = 0;
09606 } else {
09607 f.data.ptr = thread->buf + sizeof(struct ast_iax2_full_hdr);
09608 memset(&ies, 0, sizeof(ies));
09609 }
09610 } else {
09611 if (f.frametype == AST_FRAME_IAX)
09612 f.data.ptr = NULL;
09613 else
09614 f.data.ptr = empty;
09615 memset(&ies, 0, sizeof(ies));
09616 }
09617
09618 if (!dcallno && iax2_allow_new(f.frametype, f.subclass, 1)) {
09619
09620 if (handle_call_token(fh, &ies, &sin, fd)) {
09621 ast_variables_destroy(ies.vars);
09622 return 1;
09623 }
09624
09625 if (ies.calltoken && ies.calltokendata) {
09626
09627
09628
09629
09630 new = NEW_ALLOW_CALLTOKEN_VALIDATED;
09631 } else {
09632 new = NEW_ALLOW;
09633 }
09634 }
09635 } else {
09636
09637 f.frametype = AST_FRAME_NULL;
09638 f.subclass = 0;
09639 memset(&ies, 0, sizeof(ies));
09640 }
09641
09642 if (!fr->callno) {
09643 int check_dcallno = 0;
09644
09645
09646
09647
09648
09649
09650
09651
09652
09653 if ((ntohs(mh->callno) & IAX_FLAG_FULL) && ((f.frametype == AST_FRAME_IAX) && (f.subclass == IAX_COMMAND_ACK))) {
09654 check_dcallno = 1;
09655 }
09656
09657 if (!(fr->callno = find_callno(ntohs(mh->callno) & ~IAX_FLAG_FULL, dcallno, &sin, new, fd, check_dcallno))) {
09658 if (f.frametype == AST_FRAME_IAX && f.subclass == IAX_COMMAND_NEW) {
09659 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REJECT, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09660 } else if (f.frametype == AST_FRAME_IAX && (f.subclass == IAX_COMMAND_REGREQ || f.subclass == IAX_COMMAND_REGREL)) {
09661 send_apathetic_reply(1, ntohs(fh->scallno), &sin, IAX_COMMAND_REGREJ, ntohl(fh->ts), fh->iseqno + 1, fd, NULL);
09662 }
09663 ast_variables_destroy(ies.vars);
09664 return 1;
09665 }
09666 }
09667
09668 if (fr->callno > 0)
09669 ast_mutex_lock(&iaxsl[fr->callno]);
09670
09671 if (!fr->callno || !iaxs[fr->callno]) {
09672
09673
09674 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09675
09676 if (((f.subclass != IAX_COMMAND_INVAL) &&
09677 (f.subclass != IAX_COMMAND_TXCNT) &&
09678 (f.subclass != IAX_COMMAND_TXACC) &&
09679 (f.subclass != IAX_COMMAND_FWDOWNL))||
09680 (f.frametype != AST_FRAME_IAX))
09681 raw_hangup(&sin, ntohs(fh->dcallno) & ~IAX_FLAG_RETRANS, ntohs(mh->callno) & ~IAX_FLAG_FULL,
09682 fd);
09683 }
09684 if (fr->callno > 0)
09685 ast_mutex_unlock(&iaxsl[fr->callno]);
09686 ast_variables_destroy(ies.vars);
09687 return 1;
09688 }
09689 if (ast_test_flag(iaxs[fr->callno], IAX_ENCRYPTED) && !decrypted) {
09690 if (decrypt_frame(fr->callno, fh, &f, &res)) {
09691 ast_log(LOG_NOTICE, "Packet Decrypt Failed!\n");
09692 ast_variables_destroy(ies.vars);
09693 ast_mutex_unlock(&iaxsl[fr->callno]);
09694 return 1;
09695 }
09696 decrypted = 1;
09697 }
09698 #ifdef DEBUG_SUPPORT
09699 if (decrypted) {
09700 iax_outputframe(NULL, fh, 3, &sin, res - sizeof(*fh));
09701 }
09702 #endif
09703
09704
09705 iaxs[fr->callno]->frames_received++;
09706
09707 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) && !minivid &&
09708 f.subclass != IAX_COMMAND_TXCNT &&
09709 f.subclass != IAX_COMMAND_TXACC) {
09710 unsigned short new_peercallno;
09711
09712 new_peercallno = (unsigned short) (ntohs(mh->callno) & ~IAX_FLAG_FULL);
09713 if (new_peercallno && new_peercallno != iaxs[fr->callno]->peercallno) {
09714 if (iaxs[fr->callno]->peercallno) {
09715 remove_by_peercallno(iaxs[fr->callno]);
09716 }
09717 iaxs[fr->callno]->peercallno = new_peercallno;
09718 store_by_peercallno(iaxs[fr->callno]);
09719 }
09720 }
09721 if (ntohs(mh->callno) & IAX_FLAG_FULL) {
09722 if (iaxdebug)
09723 ast_debug(1, "Received packet %d, (%d, %d)\n", fh->oseqno, f.frametype, f.subclass);
09724
09725 fr->oseqno = fh->oseqno;
09726 fr->iseqno = fh->iseqno;
09727 fr->ts = ntohl(fh->ts);
09728 #ifdef IAXTESTS
09729 if (test_resync) {
09730 ast_debug(1, "Simulating frame ts resync, was %u now %u\n", fr->ts, fr->ts + test_resync);
09731 fr->ts += test_resync;
09732 }
09733 #endif
09734 #if 0
09735 if ( (ntohs(fh->dcallno) & IAX_FLAG_RETRANS) ||
09736 ( (f.frametype != AST_FRAME_VOICE) && ! (f.frametype == AST_FRAME_IAX &&
09737 (f.subclass == IAX_COMMAND_NEW ||
09738 f.subclass == IAX_COMMAND_AUTHREQ ||
09739 f.subclass == IAX_COMMAND_ACCEPT ||
09740 f.subclass == IAX_COMMAND_REJECT)) ) )
09741 #endif
09742 if ((ntohs(fh->dcallno) & IAX_FLAG_RETRANS) || (f.frametype != AST_FRAME_VOICE))
09743 updatehistory = 0;
09744 if ((iaxs[fr->callno]->iseqno != fr->oseqno) &&
09745 (iaxs[fr->callno]->iseqno ||
09746 ((f.subclass != IAX_COMMAND_TXCNT) &&
09747 (f.subclass != IAX_COMMAND_TXREADY) &&
09748 (f.subclass != IAX_COMMAND_TXREL) &&
09749 (f.subclass != IAX_COMMAND_UNQUELCH ) &&
09750 (f.subclass != IAX_COMMAND_TXACC)) ||
09751 (f.frametype != AST_FRAME_IAX))) {
09752 if (
09753 ((f.subclass != IAX_COMMAND_ACK) &&
09754 (f.subclass != IAX_COMMAND_INVAL) &&
09755 (f.subclass != IAX_COMMAND_TXCNT) &&
09756 (f.subclass != IAX_COMMAND_TXREADY) &&
09757 (f.subclass != IAX_COMMAND_TXREL) &&
09758 (f.subclass != IAX_COMMAND_UNQUELCH ) &&
09759 (f.subclass != IAX_COMMAND_TXACC) &&
09760 (f.subclass != IAX_COMMAND_VNAK)) ||
09761 (f.frametype != AST_FRAME_IAX)) {
09762
09763 ast_debug(1, "Packet arrived out of order (expecting %d, got %d) (frametype = %d, subclass = %d)\n",
09764 iaxs[fr->callno]->iseqno, fr->oseqno, f.frametype, f.subclass);
09765
09766
09767 if ((unsigned char) (iaxs[fr->callno]->iseqno - fr->oseqno) < 128) {
09768
09769 if ((f.frametype != AST_FRAME_IAX) ||
09770 ((f.subclass != IAX_COMMAND_ACK) && (f.subclass != IAX_COMMAND_INVAL))) {
09771 ast_debug(1, "Acking anyway\n");
09772
09773
09774 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
09775 }
09776 } else {
09777
09778 iax2_vnak(fr->callno);
09779 }
09780 ast_variables_destroy(ies.vars);
09781 ast_mutex_unlock(&iaxsl[fr->callno]);
09782 return 1;
09783 }
09784 } else {
09785
09786 if (((f.subclass != IAX_COMMAND_ACK) &&
09787 (f.subclass != IAX_COMMAND_INVAL) &&
09788 (f.subclass != IAX_COMMAND_TXCNT) &&
09789 (f.subclass != IAX_COMMAND_TXACC) &&
09790 (f.subclass != IAX_COMMAND_VNAK)) ||
09791 (f.frametype != AST_FRAME_IAX))
09792 iaxs[fr->callno]->iseqno++;
09793 }
09794
09795 if (f.frametype == AST_FRAME_TEXT && thread->buf[res - 1] != '\0') {
09796 if (res < thread->buf_size)
09797 thread->buf[res++] = '\0';
09798 else
09799 thread->buf[res - 1] = '\0';
09800 }
09801
09802
09803
09804 if (!inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
09805 ((f.subclass != IAX_COMMAND_INVAL) ||
09806 (f.frametype != AST_FRAME_IAX))) {
09807 unsigned char x;
09808 int call_to_destroy;
09809
09810 if (iaxs[fr->callno]->rseqno >= iaxs[fr->callno]->oseqno || (fr->iseqno >= iaxs[fr->callno]->rseqno && fr->iseqno < iaxs[fr->callno]->oseqno))
09811 x = fr->iseqno;
09812 else
09813 x = iaxs[fr->callno]->oseqno;
09814 if ((x != iaxs[fr->callno]->oseqno) || (iaxs[fr->callno]->oseqno == fr->iseqno)) {
09815
09816
09817 for (x=iaxs[fr->callno]->rseqno; x != fr->iseqno; x++) {
09818
09819 if (iaxdebug)
09820 ast_debug(1, "Cancelling transmission of packet %d\n", x);
09821 call_to_destroy = 0;
09822 AST_LIST_LOCK(&frame_queue);
09823 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
09824
09825 if ((fr->callno == cur->callno) && (x == cur->oseqno)) {
09826 cur->retries = -1;
09827
09828 if (cur->final)
09829 call_to_destroy = fr->callno;
09830 }
09831 }
09832 AST_LIST_UNLOCK(&frame_queue);
09833 if (call_to_destroy) {
09834 if (iaxdebug)
09835 ast_debug(1, "Really destroying %d, having been acked on final message\n", call_to_destroy);
09836 ast_mutex_lock(&iaxsl[call_to_destroy]);
09837 iax2_destroy(call_to_destroy);
09838 ast_mutex_unlock(&iaxsl[call_to_destroy]);
09839 }
09840 }
09841
09842 if (iaxs[fr->callno])
09843 iaxs[fr->callno]->rseqno = fr->iseqno;
09844 else {
09845
09846 ast_variables_destroy(ies.vars);
09847 ast_mutex_unlock(&iaxsl[fr->callno]);
09848 return 1;
09849 }
09850 } else {
09851 ast_debug(1, "Received iseqno %d not within window %d->%d\n", fr->iseqno, iaxs[fr->callno]->rseqno, iaxs[fr->callno]->oseqno);
09852 }
09853 }
09854 if (inaddrcmp(&sin, &iaxs[fr->callno]->addr) &&
09855 ((f.frametype != AST_FRAME_IAX) ||
09856 ((f.subclass != IAX_COMMAND_TXACC) &&
09857 (f.subclass != IAX_COMMAND_TXCNT)))) {
09858
09859 ast_variables_destroy(ies.vars);
09860 ast_mutex_unlock(&iaxsl[fr->callno]);
09861 return 1;
09862 }
09863
09864
09865
09866
09867 if ((f.frametype == AST_FRAME_VOICE) ||
09868 (f.frametype == AST_FRAME_VIDEO) ||
09869 (f.frametype == AST_FRAME_IAX)) {
09870 if (ast_test_flag(iaxs[fr->callno], IAX_DELAYPBXSTART)) {
09871 ast_clear_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
09872 if (!ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->chosenformat)) {
09873 ast_variables_destroy(ies.vars);
09874 ast_mutex_unlock(&iaxsl[fr->callno]);
09875 return 1;
09876 }
09877 }
09878
09879 if (ies.vars) {
09880 struct ast_datastore *variablestore = NULL;
09881 struct ast_variable *var, *prev = NULL;
09882 AST_LIST_HEAD(, ast_var_t) *varlist;
09883
09884 iax2_lock_owner(fr->callno);
09885 if (!iaxs[fr->callno]) {
09886 ast_variables_destroy(ies.vars);
09887 ast_mutex_unlock(&iaxsl[fr->callno]);
09888 return 1;
09889 }
09890 if ((c = iaxs[fr->callno]->owner)) {
09891 varlist = ast_calloc(1, sizeof(*varlist));
09892 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
09893
09894 if (variablestore && varlist) {
09895 variablestore->data = varlist;
09896 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
09897 AST_LIST_HEAD_INIT(varlist);
09898 ast_debug(1, "I can haz IAX vars?\n");
09899 for (var = ies.vars; var; var = var->next) {
09900 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
09901 if (prev) {
09902 ast_free(prev);
09903 }
09904 prev = var;
09905 if (!newvar) {
09906
09907 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
09908 } else {
09909 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
09910 }
09911 }
09912 if (prev) {
09913 ast_free(prev);
09914 }
09915 ies.vars = NULL;
09916 ast_channel_datastore_add(c, variablestore);
09917 } else {
09918 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
09919 if (variablestore) {
09920 ast_datastore_free(variablestore);
09921 }
09922 if (varlist) {
09923 ast_free(varlist);
09924 }
09925 }
09926 ast_channel_unlock(c);
09927 } else {
09928
09929
09930 ast_debug(1, "No channel, so populating IAXVARs to the pvt, as an intermediate step.\n");
09931 for (var = ies.vars; var && var->next; var = var->next);
09932 if (var) {
09933 var->next = iaxs[fr->callno]->iaxvars;
09934 iaxs[fr->callno]->iaxvars = ies.vars;
09935 ies.vars = NULL;
09936 }
09937 }
09938 }
09939
09940 if (ies.vars) {
09941 ast_debug(1, "I have IAX variables, but they were not processed\n");
09942 }
09943 }
09944
09945
09946
09947 if ((f.frametype == AST_FRAME_IAX) && (f.subclass != IAX_COMMAND_CALLTOKEN) && iaxs[fr->callno]->hold_signaling) {
09948 send_signaling(iaxs[fr->callno]);
09949 }
09950
09951 if (f.frametype == AST_FRAME_VOICE) {
09952 if (f.subclass != iaxs[fr->callno]->voiceformat) {
09953 iaxs[fr->callno]->voiceformat = f.subclass;
09954 ast_debug(1, "Ooh, voice format changed to %d\n", f.subclass);
09955 if (iaxs[fr->callno]->owner) {
09956 iax2_lock_owner(fr->callno);
09957 if (iaxs[fr->callno]) {
09958 if (iaxs[fr->callno]->owner) {
09959 int orignative;
09960
09961 orignative = iaxs[fr->callno]->owner->nativeformats;
09962 iaxs[fr->callno]->owner->nativeformats = f.subclass;
09963 if (iaxs[fr->callno]->owner->readformat)
09964 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
09965 iaxs[fr->callno]->owner->nativeformats = orignative;
09966 ast_channel_unlock(iaxs[fr->callno]->owner);
09967 }
09968 } else {
09969 ast_debug(1, "Neat, somebody took away the channel at a magical time but i found it!\n");
09970
09971 if (ies.vars) {
09972 ast_variables_destroy(ies.vars);
09973 ast_debug(1, "I can haz iaxvars, but they is no good. :-(\n");
09974 ies.vars = NULL;
09975 }
09976 ast_mutex_unlock(&iaxsl[fr->callno]);
09977 return 1;
09978 }
09979 }
09980 }
09981 }
09982 if (f.frametype == AST_FRAME_VIDEO) {
09983 if (f.subclass != iaxs[fr->callno]->videoformat) {
09984 ast_debug(1, "Ooh, video format changed to %d\n", f.subclass & ~0x1);
09985 iaxs[fr->callno]->videoformat = f.subclass & ~0x1;
09986 }
09987 }
09988 if (f.frametype == AST_FRAME_CONTROL && iaxs[fr->callno]->owner) {
09989 if (f.subclass == AST_CONTROL_BUSY) {
09990 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_BUSY;
09991 } else if (f.subclass == AST_CONTROL_CONGESTION) {
09992 iaxs[fr->callno]->owner->hangupcause = AST_CAUSE_CONGESTION;
09993 }
09994 }
09995 if (f.frametype == AST_FRAME_IAX) {
09996 ast_sched_thread_del(sched, iaxs[fr->callno]->initid);
09997
09998 if (iaxdebug)
09999 ast_debug(1, "IAX subclass %d received\n", f.subclass);
10000
10001
10002 if (iaxs[fr->callno]->last < fr->ts &&
10003 f.subclass != IAX_COMMAND_ACK &&
10004 f.subclass != IAX_COMMAND_PONG &&
10005 f.subclass != IAX_COMMAND_LAGRP) {
10006 iaxs[fr->callno]->last = fr->ts;
10007 if (iaxdebug)
10008 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
10009 }
10010 iaxs[fr->callno]->last_iax_message = f.subclass;
10011 if (!iaxs[fr->callno]->first_iax_message) {
10012 iaxs[fr->callno]->first_iax_message = f.subclass;
10013 }
10014 switch(f.subclass) {
10015 case IAX_COMMAND_ACK:
10016
10017 break;
10018 case IAX_COMMAND_QUELCH:
10019 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10020
10021 if (iaxs[fr->callno]->owner) {
10022 manager_event(EVENT_FLAG_CALL, "Hold",
10023 "Status: On\r\n"
10024 "Channel: %s\r\n"
10025 "Uniqueid: %s\r\n",
10026 iaxs[fr->callno]->owner->name,
10027 iaxs[fr->callno]->owner->uniqueid);
10028 }
10029
10030 ast_set_flag(iaxs[fr->callno], IAX_QUELCH);
10031 if (ies.musiconhold) {
10032 iax2_lock_owner(fr->callno);
10033 if (!iaxs[fr->callno] || !iaxs[fr->callno]->owner) {
10034 break;
10035 }
10036 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10037 const char *moh_suggest = iaxs[fr->callno]->mohsuggest;
10038
10039
10040
10041
10042
10043 iax2_queue_control_data(fr->callno, AST_CONTROL_HOLD,
10044 S_OR(moh_suggest, NULL),
10045 !ast_strlen_zero(moh_suggest) ? strlen(moh_suggest) + 1 : 0);
10046 }
10047 ast_channel_unlock(iaxs[fr->callno]->owner);
10048 }
10049 }
10050 break;
10051 case IAX_COMMAND_UNQUELCH:
10052 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
10053 iax2_lock_owner(fr->callno);
10054 if (!iaxs[fr->callno]) {
10055 break;
10056 }
10057
10058 if (iaxs[fr->callno]->owner && ast_test_flag(iaxs[fr->callno], IAX_QUELCH)) {
10059 manager_event(EVENT_FLAG_CALL, "Hold",
10060 "Status: Off\r\n"
10061 "Channel: %s\r\n"
10062 "Uniqueid: %s\r\n",
10063 iaxs[fr->callno]->owner->name,
10064 iaxs[fr->callno]->owner->uniqueid);
10065 }
10066
10067 ast_clear_flag(iaxs[fr->callno], IAX_QUELCH);
10068 if (!iaxs[fr->callno]->owner) {
10069 break;
10070 }
10071 if (ast_bridged_channel(iaxs[fr->callno]->owner)) {
10072
10073
10074
10075
10076 iax2_queue_control_data(fr->callno, AST_CONTROL_UNHOLD, NULL, 0);
10077 }
10078 ast_channel_unlock(iaxs[fr->callno]->owner);
10079 }
10080 break;
10081 case IAX_COMMAND_TXACC:
10082 if (iaxs[fr->callno]->transferring == TRANSFER_BEGIN) {
10083
10084 AST_LIST_LOCK(&frame_queue);
10085 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
10086
10087 if ((fr->callno == cur->callno) && (cur->transfer))
10088 cur->retries = -1;
10089 }
10090 AST_LIST_UNLOCK(&frame_queue);
10091 memset(&ied1, 0, sizeof(ied1));
10092 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->callno);
10093 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREADY, 0, ied1.buf, ied1.pos, -1);
10094 iaxs[fr->callno]->transferring = TRANSFER_READY;
10095 }
10096 break;
10097 case IAX_COMMAND_NEW:
10098
10099 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD))
10100 break;
10101 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10102 ast_mutex_unlock(&iaxsl[fr->callno]);
10103 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10104 ast_mutex_lock(&iaxsl[fr->callno]);
10105 if (!iaxs[fr->callno]) {
10106 break;
10107 }
10108 }
10109
10110 if (ast_test_flag(iaxs[fr->callno], IAX_TRUNK)) {
10111 int new_callno;
10112 if ((new_callno = make_trunk(fr->callno, 1)) != -1)
10113 fr->callno = new_callno;
10114 }
10115
10116 if (delayreject)
10117 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10118 if (check_access(fr->callno, &sin, &ies)) {
10119
10120 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10121 if (authdebug)
10122 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);
10123 break;
10124 }
10125 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_test_flag(iaxs[fr->callno], IAX_FORCE_ENCRYPT)) {
10126 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10127 ast_log(LOG_WARNING, "Rejected connect attempt. No secret present while force encrypt enabled.\n");
10128 break;
10129 }
10130 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10131 const char *context, *exten, *cid_num;
10132
10133 context = ast_strdupa(iaxs[fr->callno]->context);
10134 exten = ast_strdupa(iaxs[fr->callno]->exten);
10135 cid_num = ast_strdupa(iaxs[fr->callno]->cid_num);
10136
10137
10138 ast_mutex_unlock(&iaxsl[fr->callno]);
10139 exists = ast_exists_extension(NULL, context, exten, 1, cid_num);
10140 ast_mutex_lock(&iaxsl[fr->callno]);
10141
10142 if (!iaxs[fr->callno]) {
10143 break;
10144 }
10145 } else
10146 exists = 0;
10147
10148 save_osptoken(fr, &ies);
10149 if (ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) {
10150 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10151 memset(&ied0, 0, sizeof(ied0));
10152 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10153 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10154 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10155 if (!iaxs[fr->callno]) {
10156 break;
10157 }
10158 if (authdebug)
10159 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);
10160 } else {
10161
10162
10163 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10164 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10165 using_prefs = "reqonly";
10166 } else {
10167 using_prefs = "disabled";
10168 }
10169 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10170 memset(&pref, 0, sizeof(pref));
10171 strcpy(caller_pref_buf, "disabled");
10172 strcpy(host_pref_buf, "disabled");
10173 } else {
10174 using_prefs = "mine";
10175
10176 if (ies.codec_prefs)
10177 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10178 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10179
10180 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10181 pref = iaxs[fr->callno]->rprefs;
10182 using_prefs = "caller";
10183 } else {
10184 pref = iaxs[fr->callno]->prefs;
10185 }
10186 } else
10187 pref = iaxs[fr->callno]->prefs;
10188
10189 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10190 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10191 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10192 }
10193 if (!format) {
10194 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
10195 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10196 if (!format) {
10197 memset(&ied0, 0, sizeof(ied0));
10198 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10199 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10200 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10201 if (!iaxs[fr->callno]) {
10202 break;
10203 }
10204 if (authdebug) {
10205 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
10206 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
10207 else
10208 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
10209 }
10210 } else {
10211
10212 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10213 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10214 format = 0;
10215 } else {
10216 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10217 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10218 memset(&pref, 0, sizeof(pref));
10219 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10220 strcpy(caller_pref_buf,"disabled");
10221 strcpy(host_pref_buf,"disabled");
10222 } else {
10223 using_prefs = "mine";
10224 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10225
10226 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10227 pref = iaxs[fr->callno]->prefs;
10228 } else {
10229 pref = iaxs[fr->callno]->rprefs;
10230 using_prefs = "caller";
10231 }
10232 format = ast_codec_choose(&pref, iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability, 1);
10233
10234 } else
10235 format = ast_best_codec(iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10236 }
10237 }
10238
10239 if (!format) {
10240 memset(&ied0, 0, sizeof(ied0));
10241 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10242 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10243 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10244 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10245 if (!iaxs[fr->callno]) {
10246 break;
10247 }
10248 if (authdebug)
10249 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
10250 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
10251 break;
10252 }
10253 }
10254 }
10255 if (format) {
10256
10257 memset(&ied1, 0, sizeof(ied1));
10258 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10259 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10260 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10261 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10262 ast_verb(3, "Accepting UNAUTHENTICATED call from %s:\n"
10263 "%srequested format = %s,\n"
10264 "%srequested prefs = %s,\n"
10265 "%sactual format = %s,\n"
10266 "%shost prefs = %s,\n"
10267 "%spriority = %s\n",
10268 ast_inet_ntoa(sin.sin_addr),
10269 VERBOSE_PREFIX_4,
10270 ast_getformatname(iaxs[fr->callno]->peerformat),
10271 VERBOSE_PREFIX_4,
10272 caller_pref_buf,
10273 VERBOSE_PREFIX_4,
10274 ast_getformatname(format),
10275 VERBOSE_PREFIX_4,
10276 host_pref_buf,
10277 VERBOSE_PREFIX_4,
10278 using_prefs);
10279
10280 iaxs[fr->callno]->chosenformat = format;
10281 ast_set_flag(iaxs[fr->callno], IAX_DELAYPBXSTART);
10282 } else {
10283 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10284
10285 ast_verb(3, "Accepted unauthenticated TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10286 }
10287 }
10288 }
10289 break;
10290 }
10291 if (iaxs[fr->callno]->authmethods & IAX_AUTH_MD5)
10292 merge_encryption(iaxs[fr->callno],ies.encmethods);
10293 else
10294 iaxs[fr->callno]->encmethods = 0;
10295 if (!authenticate_request(fr->callno) && iaxs[fr->callno])
10296 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED);
10297 break;
10298 case IAX_COMMAND_DPREQ:
10299
10300 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD) &&
10301 !ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED) && ies.called_number) {
10302 if (iaxcompat) {
10303
10304 spawn_dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num);
10305 } else {
10306
10307 dp_lookup(fr->callno, iaxs[fr->callno]->context, ies.called_number, iaxs[fr->callno]->cid_num, 1);
10308 }
10309 }
10310 break;
10311 case IAX_COMMAND_HANGUP:
10312 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
10313 ast_debug(1, "Immediately destroying %d, having received hangup\n", fr->callno);
10314
10315 if (ies.causecode && iaxs[fr->callno]->owner)
10316 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
10317
10318 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10319 iax2_destroy(fr->callno);
10320 break;
10321 case IAX_COMMAND_REJECT:
10322
10323 if (ies.causecode && iaxs[fr->callno]->owner)
10324 iaxs[fr->callno]->owner->hangupcause = ies.causecode;
10325
10326 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
10327 if (iaxs[fr->callno]->owner && authdebug)
10328 ast_log(LOG_WARNING, "Call rejected by %s: %s\n",
10329 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr),
10330 ies.cause ? ies.cause : "<Unknown>");
10331 ast_debug(1, "Immediately destroying %d, having received reject\n",
10332 fr->callno);
10333 }
10334
10335 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK,
10336 fr->ts, NULL, 0, fr->iseqno);
10337 if (!ast_test_flag(iaxs[fr->callno], IAX_PROVISION))
10338 iaxs[fr->callno]->error = EPERM;
10339 iax2_destroy(fr->callno);
10340 break;
10341 case IAX_COMMAND_TRANSFER:
10342 {
10343 struct ast_channel *bridged_chan;
10344 struct ast_channel *owner;
10345
10346 iax2_lock_owner(fr->callno);
10347 if (!iaxs[fr->callno]) {
10348
10349 break;
10350 }
10351 owner = iaxs[fr->callno]->owner;
10352 bridged_chan = owner ? ast_bridged_channel(owner) : NULL;
10353 if (bridged_chan && ies.called_number) {
10354 ast_mutex_unlock(&iaxsl[fr->callno]);
10355
10356
10357 pbx_builtin_setvar_helper(owner, "BLINDTRANSFER", bridged_chan->name);
10358 pbx_builtin_setvar_helper(bridged_chan, "BLINDTRANSFER", owner->name);
10359
10360 if (!strcmp(ies.called_number, ast_parking_ext())) {
10361 ast_debug(1, "Parking call '%s'\n", bridged_chan->name);
10362 if (iax_park(bridged_chan, owner)) {
10363 ast_log(LOG_WARNING, "Failed to park call '%s'\n",
10364 bridged_chan->name);
10365 }
10366 ast_mutex_lock(&iaxsl[fr->callno]);
10367 } else {
10368 ast_mutex_lock(&iaxsl[fr->callno]);
10369
10370 if (iaxs[fr->callno]) {
10371 if (ast_async_goto(bridged_chan, iaxs[fr->callno]->context,
10372 ies.called_number, 1)) {
10373 ast_log(LOG_WARNING,
10374 "Async goto of '%s' to '%s@%s' failed\n",
10375 bridged_chan->name, ies.called_number,
10376 iaxs[fr->callno]->context);
10377 } else {
10378 ast_debug(1, "Async goto of '%s' to '%s@%s' started\n",
10379 bridged_chan->name, ies.called_number,
10380 iaxs[fr->callno]->context);
10381 }
10382 } else {
10383
10384 }
10385 }
10386 } else {
10387 ast_debug(1, "Async goto not applicable on call %d\n", fr->callno);
10388 }
10389 if (owner) {
10390 ast_channel_unlock(owner);
10391 }
10392
10393 break;
10394 }
10395 case IAX_COMMAND_ACCEPT:
10396
10397 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD | IAX_STATE_AUTHENTICATED))
10398 break;
10399 if (ast_test_flag(iaxs[fr->callno], IAX_PROVISION)) {
10400
10401 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10402 iax2_destroy(fr->callno);
10403 break;
10404 }
10405 if (ies.format) {
10406 iaxs[fr->callno]->peerformat = ies.format;
10407 } else {
10408 if (iaxs[fr->callno]->owner)
10409 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->owner->nativeformats;
10410 else
10411 iaxs[fr->callno]->peerformat = iaxs[fr->callno]->capability;
10412 }
10413 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));
10414 if (!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability)) {
10415 memset(&ied0, 0, sizeof(ied0));
10416 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10417 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10418 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10419 if (!iaxs[fr->callno]) {
10420 break;
10421 }
10422 if (authdebug)
10423 ast_log(LOG_NOTICE, "Rejected call to %s, format 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
10424 } else {
10425 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10426 iax2_lock_owner(fr->callno);
10427 if (iaxs[fr->callno] && iaxs[fr->callno]->owner) {
10428
10429 iaxs[fr->callno]->owner->nativeformats = iaxs[fr->callno]->peerformat;
10430 ast_verb(3, "Format for call is %s\n", ast_getformatname(iaxs[fr->callno]->owner->nativeformats));
10431
10432
10433 if (iaxs[fr->callno]->owner->writeformat)
10434 ast_set_write_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->writeformat);
10435 if (iaxs[fr->callno]->owner->readformat)
10436 ast_set_read_format(iaxs[fr->callno]->owner, iaxs[fr->callno]->owner->readformat);
10437 ast_channel_unlock(iaxs[fr->callno]->owner);
10438 }
10439 }
10440 if (iaxs[fr->callno]) {
10441 AST_LIST_LOCK(&dpcache);
10442 AST_LIST_TRAVERSE(&iaxs[fr->callno]->dpentries, dp, peer_list)
10443 if (!(dp->flags & CACHE_FLAG_TRANSMITTED))
10444 iax2_dprequest(dp, fr->callno);
10445 AST_LIST_UNLOCK(&dpcache);
10446 }
10447 break;
10448 case IAX_COMMAND_POKE:
10449
10450 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, NULL, 0, -1);
10451 break;
10452 case IAX_COMMAND_PING:
10453 {
10454 struct iax_ie_data pingied;
10455 construct_rr(iaxs[fr->callno], &pingied);
10456
10457 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_PONG, fr->ts, pingied.buf, pingied.pos, -1);
10458 }
10459 break;
10460 case IAX_COMMAND_PONG:
10461
10462 iaxs[fr->callno]->pingtime = calc_timestamp(iaxs[fr->callno], 0, &f) - fr->ts;
10463
10464 save_rr(fr, &ies);
10465
10466
10467 log_jitterstats(fr->callno);
10468
10469 if (iaxs[fr->callno]->peerpoke) {
10470 peer = iaxs[fr->callno]->peerpoke;
10471 if ((peer->lastms < 0) || (peer->historicms > peer->maxms)) {
10472 if (iaxs[fr->callno]->pingtime <= peer->maxms) {
10473 ast_log(LOG_NOTICE, "Peer '%s' is now REACHABLE! Time: %d\n", peer->name, iaxs[fr->callno]->pingtime);
10474 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);
10475 ast_devstate_changed(AST_DEVICE_NOT_INUSE, "IAX2/%s", peer->name);
10476 }
10477 } else if ((peer->historicms > 0) && (peer->historicms <= peer->maxms)) {
10478 if (iaxs[fr->callno]->pingtime > peer->maxms) {
10479 ast_log(LOG_NOTICE, "Peer '%s' is now TOO LAGGED (%d ms)!\n", peer->name, iaxs[fr->callno]->pingtime);
10480 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);
10481 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
10482 }
10483 }
10484 peer->lastms = iaxs[fr->callno]->pingtime;
10485 if (peer->smoothing && (peer->lastms > -1))
10486 peer->historicms = (iaxs[fr->callno]->pingtime + peer->historicms) / 2;
10487 else if (peer->smoothing && peer->lastms < 0)
10488 peer->historicms = (0 + peer->historicms) / 2;
10489 else
10490 peer->historicms = iaxs[fr->callno]->pingtime;
10491
10492
10493 if (peer->pokeexpire > -1) {
10494 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
10495 peer_unref(peer);
10496 peer->pokeexpire = -1;
10497 }
10498 }
10499
10500 if ((peer->lastms < 0) || (peer->historicms > peer->maxms))
10501 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
10502 else
10503 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqok, iax2_poke_peer_s, peer_ref(peer));
10504 if (peer->pokeexpire == -1)
10505 peer_unref(peer);
10506
10507 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10508
10509 iax2_destroy(fr->callno);
10510 peer->callno = 0;
10511 ast_debug(1, "Peer %s: got pong, lastms %d, historicms %d, maxms %d\n", peer->name, peer->lastms, peer->historicms, peer->maxms);
10512 }
10513 break;
10514 case IAX_COMMAND_LAGRQ:
10515 case IAX_COMMAND_LAGRP:
10516 f.src = "LAGRQ";
10517 f.mallocd = 0;
10518 f.offset = 0;
10519 f.samples = 0;
10520 iax_frame_wrap(fr, &f);
10521 if(f.subclass == IAX_COMMAND_LAGRQ) {
10522
10523 fr->af.subclass = IAX_COMMAND_LAGRP;
10524 iax2_send(iaxs[fr->callno], &fr->af, fr->ts, -1, 0, 0, 0);
10525 } else {
10526
10527 unsigned int ts;
10528
10529 ts = calc_timestamp(iaxs[fr->callno], 0, &fr->af);
10530 iaxs[fr->callno]->lag = ts - fr->ts;
10531 if (iaxdebug)
10532 ast_debug(1, "Peer %s lag measured as %dms\n",
10533 ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr), iaxs[fr->callno]->lag);
10534 }
10535 break;
10536 case IAX_COMMAND_AUTHREQ:
10537 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10538 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>");
10539 break;
10540 }
10541 if (authenticate_reply(iaxs[fr->callno], &iaxs[fr->callno]->addr, &ies, iaxs[fr->callno]->secret, iaxs[fr->callno]->outkey)) {
10542 struct ast_frame hangup_fr = { .frametype = AST_FRAME_CONTROL,
10543 .subclass = AST_CONTROL_HANGUP,
10544 };
10545 ast_log(LOG_WARNING,
10546 "I don't know how to authenticate %s to %s\n",
10547 ies.username ? ies.username : "<unknown>", ast_inet_ntoa(iaxs[fr->callno]->addr.sin_addr));
10548 iax2_queue_frame(fr->callno, &hangup_fr);
10549 }
10550 break;
10551 case IAX_COMMAND_AUTHREP:
10552
10553 if (delayreject)
10554 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10555
10556 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED | IAX_STATE_TBD)) {
10557 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>");
10558 break;
10559 }
10560 if (authenticate_verify(iaxs[fr->callno], &ies)) {
10561 if (authdebug)
10562 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);
10563 memset(&ied0, 0, sizeof(ied0));
10564 auth_fail(fr->callno, IAX_COMMAND_REJECT);
10565 break;
10566 }
10567 if (strcasecmp(iaxs[fr->callno]->exten, "TBD")) {
10568
10569 exists = ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num);
10570 } else
10571 exists = 0;
10572 if (strcmp(iaxs[fr->callno]->exten, "TBD") && !exists) {
10573 if (authdebug)
10574 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);
10575 memset(&ied0, 0, sizeof(ied0));
10576 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10577 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10578 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10579 if (!iaxs[fr->callno]) {
10580 break;
10581 }
10582 } else {
10583
10584 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10585 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10586 using_prefs = "reqonly";
10587 } else {
10588 using_prefs = "disabled";
10589 }
10590 format = iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability;
10591 memset(&pref, 0, sizeof(pref));
10592 strcpy(caller_pref_buf, "disabled");
10593 strcpy(host_pref_buf, "disabled");
10594 } else {
10595 using_prefs = "mine";
10596 if (ies.codec_prefs)
10597 ast_codec_pref_convert(&iaxs[fr->callno]->rprefs, ies.codec_prefs, 32, 0);
10598 if (ast_codec_pref_index(&iaxs[fr->callno]->rprefs, 0)) {
10599 if (ast_test_flag(iaxs[fr->callno], IAX_CODEC_USER_FIRST)) {
10600 pref = iaxs[fr->callno]->rprefs;
10601 using_prefs = "caller";
10602 } else {
10603 pref = iaxs[fr->callno]->prefs;
10604 }
10605 } else
10606 pref = iaxs[fr->callno]->prefs;
10607
10608 format = ast_codec_choose(&pref, iaxs[fr->callno]->capability & iaxs[fr->callno]->peercapability, 0);
10609 ast_codec_pref_string(&iaxs[fr->callno]->rprefs, caller_pref_buf, sizeof(caller_pref_buf) - 1);
10610 ast_codec_pref_string(&iaxs[fr->callno]->prefs, host_pref_buf, sizeof(host_pref_buf) - 1);
10611 }
10612 if (!format) {
10613 if(!ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10614 ast_debug(1, "We don't do requested format %s, falling back to peer capability %d\n", ast_getformatname(iaxs[fr->callno]->peerformat), iaxs[fr->callno]->peercapability);
10615 format = iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability;
10616 }
10617 if (!format) {
10618 if (authdebug) {
10619 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
10620 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
10621 else
10622 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
10623 }
10624 memset(&ied0, 0, sizeof(ied0));
10625 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10626 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10627 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10628 if (!iaxs[fr->callno]) {
10629 break;
10630 }
10631 } else {
10632
10633 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP)) {
10634 if(!(iaxs[fr->callno]->peerformat & iaxs[fr->callno]->capability))
10635 format = 0;
10636 } else {
10637 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOPREFS)) {
10638 using_prefs = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ? "reqonly" : "disabled";
10639 memset(&pref, 0, sizeof(pref));
10640 format = ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP) ?
10641 iaxs[fr->callno]->peerformat : 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_flag(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 if (!format) {
10660 ast_log(LOG_ERROR, "No best format in 0x%x???\n", iaxs[fr->callno]->peercapability & iaxs[fr->callno]->capability);
10661 if (authdebug) {
10662 if(ast_test_flag(iaxs[fr->callno], IAX_CODEC_NOCAP))
10663 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested 0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->capability);
10664 else
10665 ast_log(LOG_NOTICE, "Rejected connect attempt from %s, requested/capability 0x%x/0x%x incompatible with our capability 0x%x.\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat, iaxs[fr->callno]->peercapability, iaxs[fr->callno]->capability);
10666 }
10667 memset(&ied0, 0, sizeof(ied0));
10668 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "Unable to negotiate codec");
10669 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_BEARERCAPABILITY_NOTAVAIL);
10670 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10671 if (!iaxs[fr->callno]) {
10672 break;
10673 }
10674 }
10675 }
10676 }
10677 if (format) {
10678
10679 memset(&ied1, 0, sizeof(ied1));
10680 iax_ie_append_int(&ied1, IAX_IE_FORMAT, format);
10681 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACCEPT, 0, ied1.buf, ied1.pos, -1);
10682 if (strcmp(iaxs[fr->callno]->exten, "TBD")) {
10683 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10684 ast_verb(3, "Accepting AUTHENTICATED call from %s:\n"
10685 "%srequested format = %s,\n"
10686 "%srequested prefs = %s,\n"
10687 "%sactual format = %s,\n"
10688 "%shost prefs = %s,\n"
10689 "%spriority = %s\n",
10690 ast_inet_ntoa(sin.sin_addr),
10691 VERBOSE_PREFIX_4,
10692 ast_getformatname(iaxs[fr->callno]->peerformat),
10693 VERBOSE_PREFIX_4,
10694 caller_pref_buf,
10695 VERBOSE_PREFIX_4,
10696 ast_getformatname(format),
10697 VERBOSE_PREFIX_4,
10698 host_pref_buf,
10699 VERBOSE_PREFIX_4,
10700 using_prefs);
10701
10702 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10703 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, format)))
10704 iax2_destroy(fr->callno);
10705 else if (ies.vars) {
10706 struct ast_datastore *variablestore;
10707 struct ast_variable *var, *prev = NULL;
10708 AST_LIST_HEAD(, ast_var_t) *varlist;
10709 varlist = ast_calloc(1, sizeof(*varlist));
10710 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10711 if (variablestore && varlist) {
10712 variablestore->data = varlist;
10713 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10714 AST_LIST_HEAD_INIT(varlist);
10715 ast_debug(1, "I can haz IAX vars? w00t\n");
10716 for (var = ies.vars; var; var = var->next) {
10717 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10718 if (prev)
10719 ast_free(prev);
10720 prev = var;
10721 if (!newvar) {
10722
10723 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10724 } else {
10725 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10726 }
10727 }
10728 if (prev)
10729 ast_free(prev);
10730 ies.vars = NULL;
10731 ast_channel_datastore_add(c, variablestore);
10732 } else {
10733 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10734 if (variablestore)
10735 ast_datastore_free(variablestore);
10736 if (varlist)
10737 ast_free(varlist);
10738 }
10739 }
10740 } else {
10741 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10742
10743 ast_verb(3, "Accepted AUTHENTICATED TBD call from %s\n", ast_inet_ntoa(sin.sin_addr));
10744 if (ast_test_flag(iaxs[fr->callno], IAX_IMMEDIATE)) {
10745 goto immediatedial;
10746 }
10747 }
10748 }
10749 }
10750 break;
10751 case IAX_COMMAND_DIAL:
10752 immediatedial:
10753 if (ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD)) {
10754 ast_clear_flag(&iaxs[fr->callno]->state, IAX_STATE_TBD);
10755 ast_string_field_set(iaxs[fr->callno], exten, ies.called_number ? ies.called_number : "s");
10756 if (!ast_exists_extension(NULL, iaxs[fr->callno]->context, iaxs[fr->callno]->exten, 1, iaxs[fr->callno]->cid_num)) {
10757 if (authdebug)
10758 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);
10759 memset(&ied0, 0, sizeof(ied0));
10760 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No such context/extension");
10761 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_NO_ROUTE_DESTINATION);
10762 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10763 if (!iaxs[fr->callno]) {
10764 break;
10765 }
10766 } else {
10767 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10768 ast_verb(3, "Accepting DIAL from %s, formats = 0x%x\n", ast_inet_ntoa(sin.sin_addr), iaxs[fr->callno]->peerformat);
10769 ast_set_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED);
10770 send_command(iaxs[fr->callno], AST_FRAME_CONTROL, AST_CONTROL_PROGRESS, 0, NULL, 0, -1);
10771 if (!(c = ast_iax2_new(fr->callno, AST_STATE_RING, iaxs[fr->callno]->peerformat)))
10772 iax2_destroy(fr->callno);
10773 else if (ies.vars) {
10774 struct ast_datastore *variablestore;
10775 struct ast_variable *var, *prev = NULL;
10776 AST_LIST_HEAD(, ast_var_t) *varlist;
10777 varlist = ast_calloc(1, sizeof(*varlist));
10778 variablestore = ast_datastore_alloc(&iax2_variable_datastore_info, NULL);
10779 ast_debug(1, "I can haz IAX vars? w00t\n");
10780 if (variablestore && varlist) {
10781 variablestore->data = varlist;
10782 variablestore->inheritance = DATASTORE_INHERIT_FOREVER;
10783 AST_LIST_HEAD_INIT(varlist);
10784 for (var = ies.vars; var; var = var->next) {
10785 struct ast_var_t *newvar = ast_var_assign(var->name, var->value);
10786 if (prev)
10787 ast_free(prev);
10788 prev = var;
10789 if (!newvar) {
10790
10791 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10792 } else {
10793 AST_LIST_INSERT_TAIL(varlist, newvar, entries);
10794 }
10795 }
10796 if (prev)
10797 ast_free(prev);
10798 ies.vars = NULL;
10799 ast_channel_datastore_add(c, variablestore);
10800 } else {
10801 ast_log(LOG_ERROR, "Memory allocation error while processing IAX2 variables\n");
10802 if (variablestore)
10803 ast_datastore_free(variablestore);
10804 if (varlist)
10805 ast_free(varlist);
10806 }
10807 }
10808 }
10809 }
10810 break;
10811 case IAX_COMMAND_INVAL:
10812 iaxs[fr->callno]->error = ENOTCONN;
10813 ast_debug(1, "Immediately destroying %d, having received INVAL\n", fr->callno);
10814 iax2_destroy(fr->callno);
10815 ast_debug(1, "Destroying call %d\n", fr->callno);
10816 break;
10817 case IAX_COMMAND_VNAK:
10818 ast_debug(1, "Received VNAK: resending outstanding frames\n");
10819
10820 vnak_retransmit(fr->callno, fr->iseqno);
10821 break;
10822 case IAX_COMMAND_REGREQ:
10823 case IAX_COMMAND_REGREL:
10824
10825 if (delayreject)
10826 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10827 if (register_verify(fr->callno, &sin, &ies)) {
10828 if (!iaxs[fr->callno]) {
10829 break;
10830 }
10831
10832 auth_fail(fr->callno, IAX_COMMAND_REGREJ);
10833 break;
10834 }
10835 if (!iaxs[fr->callno]) {
10836 break;
10837 }
10838 if ((ast_strlen_zero(iaxs[fr->callno]->secret) && ast_strlen_zero(iaxs[fr->callno]->inkeys)) ||
10839 ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_AUTHENTICATED)) {
10840
10841 if (f.subclass == IAX_COMMAND_REGREL)
10842 memset(&sin, 0, sizeof(sin));
10843 if (update_registry(&sin, fr->callno, ies.devicetype, fd, ies.refresh))
10844 ast_log(LOG_WARNING, "Registry error\n");
10845 if (!iaxs[fr->callno]) {
10846 break;
10847 }
10848 if (ies.provverpres && ies.serviceident && sin.sin_addr.s_addr) {
10849 ast_mutex_unlock(&iaxsl[fr->callno]);
10850 check_provisioning(&sin, fd, ies.serviceident, ies.provver);
10851 ast_mutex_lock(&iaxsl[fr->callno]);
10852 }
10853 break;
10854 }
10855 registry_authrequest(fr->callno);
10856 break;
10857 case IAX_COMMAND_REGACK:
10858 if (iax2_ack_registry(&ies, &sin, fr->callno))
10859 ast_log(LOG_WARNING, "Registration failure\n");
10860
10861 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10862 iax2_destroy(fr->callno);
10863 break;
10864 case IAX_COMMAND_REGREJ:
10865 if (iaxs[fr->callno]->reg) {
10866 if (authdebug) {
10867 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));
10868 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>");
10869 }
10870 iaxs[fr->callno]->reg->regstate = REG_STATE_REJECTED;
10871 }
10872
10873 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10874 iax2_destroy(fr->callno);
10875 break;
10876 case IAX_COMMAND_REGAUTH:
10877
10878 if (registry_rerequest(&ies, fr->callno, &sin)) {
10879 memset(&ied0, 0, sizeof(ied0));
10880 iax_ie_append_str(&ied0, IAX_IE_CAUSE, "No authority found");
10881 iax_ie_append_byte(&ied0, IAX_IE_CAUSECODE, AST_CAUSE_FACILITY_NOT_SUBSCRIBED);
10882 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
10883 }
10884 break;
10885 case IAX_COMMAND_TXREJ:
10886 iaxs[fr->callno]->transferring = 0;
10887 ast_verb(3, "Channel '%s' unable to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10888 memset(&iaxs[fr->callno]->transfer, 0, sizeof(iaxs[fr->callno]->transfer));
10889 if (iaxs[fr->callno]->bridgecallno) {
10890 if (iaxs[iaxs[fr->callno]->bridgecallno]->transferring) {
10891 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = 0;
10892 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREJ, 0, NULL, 0, -1);
10893 }
10894 }
10895 break;
10896 case IAX_COMMAND_TXREADY:
10897 if ((iaxs[fr->callno]->transferring == TRANSFER_BEGIN) ||
10898 (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)) {
10899 if (iaxs[fr->callno]->transferring == TRANSFER_MBEGIN)
10900 iaxs[fr->callno]->transferring = TRANSFER_MREADY;
10901 else
10902 iaxs[fr->callno]->transferring = TRANSFER_READY;
10903 ast_verb(3, "Channel '%s' ready to transfer\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>");
10904 if (iaxs[fr->callno]->bridgecallno) {
10905 if ((iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_READY) ||
10906 (iaxs[iaxs[fr->callno]->bridgecallno]->transferring == TRANSFER_MREADY)) {
10907
10908 if (iaxs[fr->callno]->transferring == TRANSFER_MREADY) {
10909 ast_verb(3, "Attempting media bridge of %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
10910 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
10911
10912 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_MEDIA;
10913 iaxs[fr->callno]->transferring = TRANSFER_MEDIA;
10914
10915 memset(&ied0, 0, sizeof(ied0));
10916 memset(&ied1, 0, sizeof(ied1));
10917 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
10918 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
10919 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied0.buf, ied0.pos, -1);
10920 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXMEDIA, 0, ied1.buf, ied1.pos, -1);
10921 } else {
10922 ast_verb(3, "Releasing %s and %s\n", iaxs[fr->callno]->owner ? iaxs[fr->callno]->owner->name : "<Unknown>",
10923 iaxs[iaxs[fr->callno]->bridgecallno]->owner ? iaxs[iaxs[fr->callno]->bridgecallno]->owner->name : "<Unknown>");
10924
10925 iaxs[iaxs[fr->callno]->bridgecallno]->transferring = TRANSFER_RELEASED;
10926 iaxs[fr->callno]->transferring = TRANSFER_RELEASED;
10927 ast_set_flag(iaxs[iaxs[fr->callno]->bridgecallno], IAX_ALREADYGONE);
10928 ast_set_flag(iaxs[fr->callno], IAX_ALREADYGONE);
10929
10930
10931 stop_stuff(fr->callno);
10932 stop_stuff(iaxs[fr->callno]->bridgecallno);
10933
10934 memset(&ied0, 0, sizeof(ied0));
10935 memset(&ied1, 0, sizeof(ied1));
10936 iax_ie_append_short(&ied0, IAX_IE_CALLNO, iaxs[iaxs[fr->callno]->bridgecallno]->peercallno);
10937 iax_ie_append_short(&ied1, IAX_IE_CALLNO, iaxs[fr->callno]->peercallno);
10938 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied0.buf, ied0.pos, -1);
10939 send_command(iaxs[iaxs[fr->callno]->bridgecallno], AST_FRAME_IAX, IAX_COMMAND_TXREL, 0, ied1.buf, ied1.pos, -1);
10940 }
10941
10942 }
10943 }
10944 }
10945 break;
10946 case IAX_COMMAND_TXREQ:
10947 try_transfer(iaxs[fr->callno], &ies);
10948 break;
10949 case IAX_COMMAND_TXCNT:
10950 if (iaxs[fr->callno]->transferring)
10951 send_command_transfer(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_TXACC, 0, NULL, 0);
10952 break;
10953 case IAX_COMMAND_TXREL:
10954
10955 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
10956 complete_transfer(fr->callno, &ies);
10957 stop_stuff(fr->callno);
10958 break;
10959 case IAX_COMMAND_TXMEDIA:
10960 if (iaxs[fr->callno]->transferring == TRANSFER_READY) {
10961 AST_LIST_LOCK(&frame_queue);
10962 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
10963
10964 if ((fr->callno == cur->callno) && (cur->transfer))
10965 cur->retries = -1;
10966 }
10967 AST_LIST_UNLOCK(&frame_queue);
10968
10969 iaxs[fr->callno]->transferring = TRANSFER_MEDIAPASS;
10970 }
10971 break;
10972 case IAX_COMMAND_RTKEY:
10973 if (!IAX_CALLENCRYPTED(iaxs[fr->callno])) {
10974 ast_log(LOG_WARNING,
10975 "we've been told to rotate our encryption key, "
10976 "but this isn't an encrypted call. bad things will happen.\n"
10977 );
10978 break;
10979 }
10980
10981 IAX_DEBUGDIGEST("Receiving", ies.challenge);
10982
10983 ast_aes_decrypt_key((unsigned char *) ies.challenge, &iaxs[fr->callno]->dcx);
10984 break;
10985 case IAX_COMMAND_DPREP:
10986 complete_dpreply(iaxs[fr->callno], &ies);
10987 break;
10988 case IAX_COMMAND_UNSUPPORT:
10989 ast_log(LOG_NOTICE, "Peer did not understand our iax command '%d'\n", ies.iax_unknown);
10990 break;
10991 case IAX_COMMAND_FWDOWNL:
10992
10993 if (!ast_test_flag(&globalflags, IAX_ALLOWFWDOWNLOAD)) {
10994 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, NULL, 0, -1);
10995 break;
10996 }
10997 memset(&ied0, 0, sizeof(ied0));
10998 res = iax_firmware_append(&ied0, (unsigned char *)ies.devicetype, ies.fwdesc);
10999 if (res < 0)
11000 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_REJECT, 0, ied0.buf, ied0.pos, -1);
11001 else if (res > 0)
11002 send_command_final(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11003 else
11004 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_FWDATA, 0, ied0.buf, ied0.pos, -1);
11005 break;
11006 case IAX_COMMAND_CALLTOKEN:
11007 {
11008 struct iax_frame *cur;
11009 int found = 0;
11010 AST_LIST_LOCK(&frame_queue);
11011 AST_LIST_TRAVERSE(&frame_queue, cur, list) {
11012
11013
11014
11015 if (cur->callno == fr->callno) {
11016 found = 1;
11017 break;
11018 }
11019 }
11020 AST_LIST_UNLOCK(&frame_queue);
11021
11022
11023 if (cur && found && ies.calltoken && ies.calltokendata) {
11024 resend_with_token(fr->callno, cur, (char *) ies.calltokendata);
11025 }
11026 break;
11027 }
11028 default:
11029 ast_debug(1, "Unknown IAX command %d on %d/%d\n", f.subclass, fr->callno, iaxs[fr->callno]->peercallno);
11030 memset(&ied0, 0, sizeof(ied0));
11031 iax_ie_append_byte(&ied0, IAX_IE_IAX_UNKNOWN, f.subclass);
11032 send_command(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_UNSUPPORT, 0, ied0.buf, ied0.pos, -1);
11033 }
11034
11035 if (ies.vars) {
11036 ast_variables_destroy(ies.vars);
11037 ast_debug(1, "I can haz IAX vars, but they is no good :-(\n");
11038 ies.vars = NULL;
11039 }
11040
11041
11042 if ((f.subclass != IAX_COMMAND_ACK) &&
11043 (f.subclass != IAX_COMMAND_TXCNT) &&
11044 (f.subclass != IAX_COMMAND_TXACC) &&
11045 (f.subclass != IAX_COMMAND_INVAL) &&
11046 (f.subclass != IAX_COMMAND_VNAK)) {
11047 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11048 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11049 }
11050 ast_mutex_unlock(&iaxsl[fr->callno]);
11051 return 1;
11052 }
11053
11054 if (iaxs[fr->callno] && iaxs[fr->callno]->aseqno != iaxs[fr->callno]->iseqno)
11055 send_command_immediate(iaxs[fr->callno], AST_FRAME_IAX, IAX_COMMAND_ACK, fr->ts, NULL, 0,fr->iseqno);
11056 } else if (minivid) {
11057 f.frametype = AST_FRAME_VIDEO;
11058 if (iaxs[fr->callno]->videoformat > 0)
11059 f.subclass = iaxs[fr->callno]->videoformat | (ntohs(vh->ts) & 0x8000 ? 1 : 0);
11060 else {
11061 ast_log(LOG_WARNING, "Received mini frame before first full video frame\n");
11062 iax2_vnak(fr->callno);
11063 ast_variables_destroy(ies.vars);
11064 ast_mutex_unlock(&iaxsl[fr->callno]);
11065 return 1;
11066 }
11067 f.datalen = res - sizeof(*vh);
11068 if (f.datalen)
11069 f.data.ptr = thread->buf + sizeof(*vh);
11070 else
11071 f.data.ptr = NULL;
11072 #ifdef IAXTESTS
11073 if (test_resync) {
11074 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | ((ntohs(vh->ts) + test_resync) & 0x7fff);
11075 } else
11076 #endif
11077 fr->ts = (iaxs[fr->callno]->last & 0xFFFF8000L) | (ntohs(vh->ts) & 0x7fff);
11078 } else {
11079
11080 f.frametype = AST_FRAME_VOICE;
11081 if (iaxs[fr->callno]->voiceformat > 0)
11082 f.subclass = iaxs[fr->callno]->voiceformat;
11083 else {
11084 ast_debug(1, "Received mini frame before first full voice frame\n");
11085 iax2_vnak(fr->callno);
11086 ast_variables_destroy(ies.vars);
11087 ast_mutex_unlock(&iaxsl[fr->callno]);
11088 return 1;
11089 }
11090 f.datalen = res - sizeof(struct ast_iax2_mini_hdr);
11091 if (f.datalen < 0) {
11092 ast_log(LOG_WARNING, "Datalen < 0?\n");
11093 ast_variables_destroy(ies.vars);
11094 ast_mutex_unlock(&iaxsl[fr->callno]);
11095 return 1;
11096 }
11097 if (f.datalen)
11098 f.data.ptr = thread->buf + sizeof(*mh);
11099 else
11100 f.data.ptr = NULL;
11101 #ifdef IAXTESTS
11102 if (test_resync) {
11103 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ((ntohs(mh->ts) + test_resync) & 0xffff);
11104 } else
11105 #endif
11106 fr->ts = (iaxs[fr->callno]->last & 0xFFFF0000L) | ntohs(mh->ts);
11107
11108 }
11109
11110 if (!ast_test_flag(&iaxs[fr->callno]->state, IAX_STATE_STARTED)) {
11111 ast_variables_destroy(ies.vars);
11112 ast_mutex_unlock(&iaxsl[fr->callno]);
11113 return 1;
11114 }
11115
11116 f.src = "IAX2";
11117 f.mallocd = 0;
11118 f.offset = 0;
11119 f.len = 0;
11120 if (f.datalen && (f.frametype == AST_FRAME_VOICE)) {
11121 f.samples = ast_codec_get_samples(&f);
11122
11123 if (f.subclass == AST_FORMAT_SLINEAR)
11124 ast_frame_byteswap_be(&f);
11125 } else
11126 f.samples = 0;
11127 iax_frame_wrap(fr, &f);
11128
11129
11130 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11131
11132 fr->outoforder = 0;
11133 } else {
11134 if (iaxdebug && iaxs[fr->callno])
11135 ast_debug(1, "Received out of order packet... (type=%d, subclass %d, ts = %d, last = %d)\n", f.frametype, f.subclass, fr->ts, iaxs[fr->callno]->last);
11136 fr->outoforder = -1;
11137 }
11138 fr->cacheable = ((f.frametype == AST_FRAME_VOICE) || (f.frametype == AST_FRAME_VIDEO));
11139 duped_fr = iaxfrdup2(fr);
11140 if (duped_fr) {
11141 schedule_delivery(duped_fr, updatehistory, 0, &fr->ts);
11142 }
11143 if (iaxs[fr->callno] && iaxs[fr->callno]->last < fr->ts) {
11144 iaxs[fr->callno]->last = fr->ts;
11145 #if 1
11146 if (iaxdebug)
11147 ast_debug(1, "For call=%d, set last=%d\n", fr->callno, fr->ts);
11148 #endif
11149 }
11150
11151
11152 ast_variables_destroy(ies.vars);
11153 ast_mutex_unlock(&iaxsl[fr->callno]);
11154 return 1;
11155 }
11156
11157
11158 static void iax2_process_thread_cleanup(void *data)
11159 {
11160 struct iax2_thread *thread = data;
11161 ast_mutex_destroy(&thread->lock);
11162 ast_cond_destroy(&thread->cond);
11163 ast_mutex_destroy(&thread->init_lock);
11164 ast_cond_destroy(&thread->init_cond);
11165 ast_free(thread);
11166 ast_atomic_dec_and_test(&iaxactivethreadcount);
11167 }
11168
11169 static void *iax2_process_thread(void *data)
11170 {
11171 struct iax2_thread *thread = data;
11172 struct timeval wait;
11173 struct timespec ts;
11174 int put_into_idle = 0;
11175 int first_time = 1;
11176 int old_state;
11177
11178 ast_atomic_fetchadd_int(&iaxactivethreadcount, 1);
11179
11180 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_state);
11181 pthread_cleanup_push(iax2_process_thread_cleanup, data);
11182
11183 for (;;) {
11184
11185 ast_mutex_lock(&thread->lock);
11186
11187 if (thread->stop) {
11188 ast_mutex_unlock(&thread->lock);
11189 break;
11190 }
11191
11192
11193 if (first_time) {
11194 signal_condition(&thread->init_lock, &thread->init_cond);
11195 first_time = 0;
11196 }
11197
11198
11199 if (put_into_idle) {
11200 insert_idle_thread(thread);
11201 }
11202
11203 if (thread->type == IAX_THREAD_TYPE_DYNAMIC) {
11204 struct iax2_thread *t = NULL;
11205
11206 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11207 ts.tv_sec = wait.tv_sec;
11208 ts.tv_nsec = wait.tv_usec * 1000;
11209 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11210
11211
11212 if (!put_into_idle || thread->stop) {
11213 ast_mutex_unlock(&thread->lock);
11214 break;
11215 }
11216 AST_LIST_LOCK(&dynamic_list);
11217
11218 if ((t = AST_LIST_REMOVE(&dynamic_list, thread, list)))
11219 ast_atomic_fetchadd_int(&iaxdynamicthreadcount, -1);
11220 AST_LIST_UNLOCK(&dynamic_list);
11221 if (t) {
11222
11223
11224
11225 ast_mutex_unlock(&thread->lock);
11226 break;
11227 }
11228
11229
11230
11231 wait = ast_tvadd(ast_tvnow(), ast_samp2tv(30000, 1000));
11232 ts.tv_sec = wait.tv_sec;
11233 ts.tv_nsec = wait.tv_usec * 1000;
11234 if (ast_cond_timedwait(&thread->cond, &thread->lock, &ts) == ETIMEDOUT) {
11235 ast_mutex_unlock(&thread->lock);
11236 break;
11237 }
11238 }
11239 } else {
11240 ast_cond_wait(&thread->cond, &thread->lock);
11241 }
11242
11243
11244 put_into_idle = 1;
11245
11246 ast_mutex_unlock(&thread->lock);
11247
11248 if (thread->stop) {
11249 break;
11250 }
11251
11252 if (thread->iostate == IAX_IOSTATE_IDLE)
11253 continue;
11254
11255
11256 switch (thread->iostate) {
11257 case IAX_IOSTATE_READY:
11258 thread->actions++;
11259 thread->iostate = IAX_IOSTATE_PROCESSING;
11260 socket_process(thread);
11261 handle_deferred_full_frames(thread);
11262 break;
11263 case IAX_IOSTATE_SCHEDREADY:
11264 thread->actions++;
11265 thread->iostate = IAX_IOSTATE_PROCESSING;
11266 #ifdef SCHED_MULTITHREADED
11267 thread->schedfunc(thread->scheddata);
11268 #endif
11269 default:
11270 break;
11271 }
11272 time(&thread->checktime);
11273 thread->iostate = IAX_IOSTATE_IDLE;
11274 #ifdef DEBUG_SCHED_MULTITHREAD
11275 thread->curfunc[0]='\0';
11276 #endif
11277
11278
11279
11280
11281 AST_LIST_LOCK(&active_list);
11282 AST_LIST_REMOVE(&active_list, thread, list);
11283 AST_LIST_UNLOCK(&active_list);
11284
11285
11286 handle_deferred_full_frames(thread);
11287 }
11288
11289
11290
11291
11292
11293 AST_LIST_LOCK(&idle_list);
11294 AST_LIST_REMOVE(&idle_list, thread, list);
11295 AST_LIST_UNLOCK(&idle_list);
11296
11297 AST_LIST_LOCK(&dynamic_list);
11298 AST_LIST_REMOVE(&dynamic_list, thread, list);
11299 AST_LIST_UNLOCK(&dynamic_list);
11300
11301
11302
11303
11304 pthread_cleanup_pop(1);
11305 return NULL;
11306 }
11307
11308 static int iax2_do_register(struct iax2_registry *reg)
11309 {
11310 struct iax_ie_data ied;
11311 if (iaxdebug)
11312 ast_debug(1, "Sending registration request for '%s'\n", reg->username);
11313
11314 if (reg->dnsmgr &&
11315 ((reg->regstate == REG_STATE_TIMEOUT) || !reg->addr.sin_addr.s_addr)) {
11316
11317 ast_dnsmgr_refresh(reg->dnsmgr);
11318 }
11319
11320
11321
11322
11323
11324 if (reg->dnsmgr && ast_dnsmgr_changed(reg->dnsmgr) && (reg->callno > 0)) {
11325 int callno = reg->callno;
11326 ast_mutex_lock(&iaxsl[callno]);
11327 iax2_destroy(callno);
11328 ast_mutex_unlock(&iaxsl[callno]);
11329 reg->callno = 0;
11330 }
11331 if (!reg->addr.sin_addr.s_addr) {
11332 if (iaxdebug)
11333 ast_debug(1, "Unable to send registration request for '%s' without IP address\n", reg->username);
11334
11335 reg->expire = iax2_sched_replace(reg->expire, sched,
11336 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11337 return -1;
11338 }
11339
11340 if (!reg->callno) {
11341 ast_debug(3, "Allocate call number\n");
11342 reg->callno = find_callno_locked(0, 0, ®->addr, NEW_FORCE, defaultsockfd, 0);
11343 if (reg->callno < 1) {
11344 ast_log(LOG_WARNING, "Unable to create call for registration\n");
11345 return -1;
11346 } else
11347 ast_debug(3, "Registration created on call %d\n", reg->callno);
11348 iaxs[reg->callno]->reg = reg;
11349 ast_mutex_unlock(&iaxsl[reg->callno]);
11350 }
11351
11352 reg->expire = iax2_sched_replace(reg->expire, sched,
11353 (5 * reg->refresh / 6) * 1000, iax2_do_register_s, reg);
11354
11355 memset(&ied, 0, sizeof(ied));
11356 iax_ie_append_str(&ied, IAX_IE_USERNAME, reg->username);
11357 iax_ie_append_short(&ied, IAX_IE_REFRESH, reg->refresh);
11358 add_empty_calltoken_ie(iaxs[reg->callno], &ied);
11359 send_command(iaxs[reg->callno],AST_FRAME_IAX, IAX_COMMAND_REGREQ, 0, ied.buf, ied.pos, -1);
11360 reg->regstate = REG_STATE_REGSENT;
11361 return 0;
11362 }
11363
11364 static int iax2_provision(struct sockaddr_in *end, int sockfd, char *dest, const char *template, int force)
11365 {
11366
11367
11368 struct iax_ie_data provdata;
11369 struct iax_ie_data ied;
11370 unsigned int sig;
11371 struct sockaddr_in sin;
11372 int callno;
11373 struct create_addr_info cai;
11374
11375 memset(&cai, 0, sizeof(cai));
11376
11377 ast_debug(1, "Provisioning '%s' from template '%s'\n", dest, template);
11378
11379 if (iax_provision_build(&provdata, &sig, template, force)) {
11380 ast_debug(1, "No provisioning found for template '%s'\n", template);
11381 return 0;
11382 }
11383
11384 if (end) {
11385 memcpy(&sin, end, sizeof(sin));
11386 cai.sockfd = sockfd;
11387 } else if (create_addr(dest, NULL, &sin, &cai))
11388 return -1;
11389
11390
11391 memset(&ied, 0, sizeof(ied));
11392 iax_ie_append_raw(&ied, IAX_IE_PROVISIONING, provdata.buf, provdata.pos);
11393
11394 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11395 if (!callno)
11396 return -1;
11397
11398 if (iaxs[callno]) {
11399
11400 iaxs[callno]->autoid = iax2_sched_replace(iaxs[callno]->autoid,
11401 sched, 15000, auto_hangup, (void *)(long)callno);
11402 ast_set_flag(iaxs[callno], IAX_PROVISION);
11403
11404 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_PROVISION, 0, ied.buf, ied.pos, -1);
11405 }
11406 ast_mutex_unlock(&iaxsl[callno]);
11407
11408 return 1;
11409 }
11410
11411 static char *papp = "IAX2Provision";
11412
11413
11414
11415
11416 static int iax2_prov_app(struct ast_channel *chan, void *data)
11417 {
11418 int res;
11419 char *sdata;
11420 char *opts;
11421 int force =0;
11422 unsigned short callno = PTR_TO_CALLNO(chan->tech_pvt);
11423 if (ast_strlen_zero(data))
11424 data = "default";
11425 sdata = ast_strdupa(data);
11426 opts = strchr(sdata, '|');
11427 if (opts)
11428 *opts='\0';
11429
11430 if (chan->tech != &iax2_tech) {
11431 ast_log(LOG_NOTICE, "Can't provision a non-IAX device!\n");
11432 return -1;
11433 }
11434 if (!callno || !iaxs[callno] || !iaxs[callno]->addr.sin_addr.s_addr) {
11435 ast_log(LOG_NOTICE, "Can't provision something with no IP?\n");
11436 return -1;
11437 }
11438 res = iax2_provision(&iaxs[callno]->addr, iaxs[callno]->sockfd, NULL, sdata, force);
11439 ast_verb(3, "Provisioned IAXY at '%s' with '%s'= %d\n",
11440 ast_inet_ntoa(iaxs[callno]->addr.sin_addr),
11441 sdata, res);
11442 return res;
11443 }
11444
11445 static char *handle_cli_iax2_provision(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
11446 {
11447 int force = 0;
11448 int res;
11449
11450 switch (cmd) {
11451 case CLI_INIT:
11452 e->command = "iax2 provision";
11453 e->usage =
11454 "Usage: iax2 provision <host> <template> [forced]\n"
11455 " Provisions the given peer or IP address using a template\n"
11456 " matching either 'template' or '*' if the template is not\n"
11457 " found. If 'forced' is specified, even empty provisioning\n"
11458 " fields will be provisioned as empty fields.\n";
11459 return NULL;
11460 case CLI_GENERATE:
11461 if (a->pos == 3)
11462 return iax_prov_complete_template(a->line, a->word, a->pos, a->n);
11463 return NULL;
11464 }
11465
11466 if (a->argc < 4)
11467 return CLI_SHOWUSAGE;
11468 if (a->argc > 4) {
11469 if (!strcasecmp(a->argv[4], "forced"))
11470 force = 1;
11471 else
11472 return CLI_SHOWUSAGE;
11473 }
11474 res = iax2_provision(NULL, -1, a->argv[2], a->argv[3], force);
11475 if (res < 0)
11476 ast_cli(a->fd, "Unable to find peer/address '%s'\n", a->argv[2]);
11477 else if (res < 1)
11478 ast_cli(a->fd, "No template (including wildcard) matching '%s'\n", a->argv[3]);
11479 else
11480 ast_cli(a->fd, "Provisioning '%s' with template '%s'%s\n", a->argv[2], a->argv[3], force ? ", forced" : "");
11481 return CLI_SUCCESS;
11482 }
11483
11484 static void __iax2_poke_noanswer(const void *data)
11485 {
11486 struct iax2_peer *peer = (struct iax2_peer *)data;
11487 int callno;
11488
11489 if (peer->lastms > -1) {
11490 ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE! Time: %d\n", peer->name, peer->lastms);
11491 manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: IAX2\r\nPeer: IAX2/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, peer->lastms);
11492 ast_devstate_changed(AST_DEVICE_UNAVAILABLE, "IAX2/%s", peer->name);
11493 }
11494 if ((callno = peer->callno) > 0) {
11495 ast_mutex_lock(&iaxsl[callno]);
11496 iax2_destroy(callno);
11497 ast_mutex_unlock(&iaxsl[callno]);
11498 }
11499 peer->callno = 0;
11500 peer->lastms = -1;
11501
11502 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_peer_s, peer_ref(peer));
11503 if (peer->pokeexpire == -1)
11504 peer_unref(peer);
11505 }
11506
11507 static int iax2_poke_noanswer(const void *data)
11508 {
11509 struct iax2_peer *peer = (struct iax2_peer *)data;
11510 peer->pokeexpire = -1;
11511 #ifdef SCHED_MULTITHREADED
11512 if (schedule_action(__iax2_poke_noanswer, data))
11513 #endif
11514 __iax2_poke_noanswer(data);
11515 peer_unref(peer);
11516 return 0;
11517 }
11518
11519 static int iax2_poke_peer_cb(void *obj, void *arg, int flags)
11520 {
11521 struct iax2_peer *peer = obj;
11522
11523 iax2_poke_peer(peer, 0);
11524
11525 return 0;
11526 }
11527
11528 static int iax2_poke_peer(struct iax2_peer *peer, int heldcall)
11529 {
11530 int callno;
11531 if (!peer->maxms || (!peer->addr.sin_addr.s_addr && !peer->dnsmgr)) {
11532
11533
11534 peer->lastms = 0;
11535 peer->historicms = 0;
11536 peer->pokeexpire = -1;
11537 peer->callno = 0;
11538 return 0;
11539 }
11540
11541
11542 if ((callno = peer->callno) > 0) {
11543 ast_log(LOG_NOTICE, "Still have a callno...\n");
11544 ast_mutex_lock(&iaxsl[callno]);
11545 iax2_destroy(callno);
11546 ast_mutex_unlock(&iaxsl[callno]);
11547 }
11548 if (heldcall)
11549 ast_mutex_unlock(&iaxsl[heldcall]);
11550 callno = peer->callno = find_callno(0, 0, &peer->addr, NEW_FORCE, peer->sockfd, 0);
11551 if (heldcall)
11552 ast_mutex_lock(&iaxsl[heldcall]);
11553 if (peer->callno < 1) {
11554 ast_log(LOG_WARNING, "Unable to allocate call for poking peer '%s'\n", peer->name);
11555 return -1;
11556 }
11557
11558
11559 iaxs[peer->callno]->pingtime = peer->maxms / 4 + 1;
11560 iaxs[peer->callno]->peerpoke = peer;
11561
11562 if (peer->pokeexpire > -1) {
11563 if (!ast_sched_thread_del(sched, peer->pokeexpire)) {
11564 peer->pokeexpire = -1;
11565 peer_unref(peer);
11566 }
11567 }
11568
11569
11570
11571 if (peer->lastms < 0)
11572 peer->pokeexpire = iax2_sched_add(sched, peer->pokefreqnotok, iax2_poke_noanswer, peer_ref(peer));
11573 else
11574 peer->pokeexpire = iax2_sched_add(sched, DEFAULT_MAXMS * 2, iax2_poke_noanswer, peer_ref(peer));
11575
11576 if (peer->pokeexpire == -1)
11577 peer_unref(peer);
11578
11579
11580 ast_mutex_lock(&iaxsl[callno]);
11581 if (iaxs[callno]) {
11582 struct iax_ie_data ied = {
11583 .buf = { 0 },
11584 .pos = 0,
11585 };
11586 add_empty_calltoken_ie(iaxs[callno], &ied);
11587 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_POKE, 0, ied.buf, ied.pos, -1);
11588 }
11589 ast_mutex_unlock(&iaxsl[callno]);
11590
11591 return 0;
11592 }
11593
11594 static void free_context(struct iax2_context *con)
11595 {
11596 struct iax2_context *conl;
11597 while(con) {
11598 conl = con;
11599 con = con->next;
11600 ast_free(conl);
11601 }
11602 }
11603
11604 static struct ast_channel *iax2_request(const char *type, int format, void *data, int *cause)
11605 {
11606 int callno;
11607 int res;
11608 int fmt, native;
11609 struct sockaddr_in sin;
11610 struct ast_channel *c;
11611 struct parsed_dial_string pds;
11612 struct create_addr_info cai;
11613 char *tmpstr;
11614
11615 memset(&pds, 0, sizeof(pds));
11616 tmpstr = ast_strdupa(data);
11617 parse_dial_string(tmpstr, &pds);
11618
11619 if (ast_strlen_zero(pds.peer)) {
11620 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
11621 return NULL;
11622 }
11623
11624 memset(&cai, 0, sizeof(cai));
11625 cai.capability = iax2_capability;
11626
11627 ast_copy_flags(&cai, &globalflags, IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
11628
11629
11630 if (create_addr(pds.peer, NULL, &sin, &cai)) {
11631 *cause = AST_CAUSE_UNREGISTERED;
11632 return NULL;
11633 }
11634
11635 if (pds.port)
11636 sin.sin_port = htons(atoi(pds.port));
11637
11638 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
11639 if (callno < 1) {
11640 ast_log(LOG_WARNING, "Unable to create call\n");
11641 *cause = AST_CAUSE_CONGESTION;
11642 return NULL;
11643 }
11644
11645
11646 ast_copy_flags(iaxs[callno], &cai, IAX_TRUNK | IAX_SENDANI | IAX_NOTRANSFER | IAX_TRANSFERMEDIA | IAX_USEJITTERBUF | IAX_FORCEJITTERBUF);
11647 if (ast_test_flag(&cai, IAX_TRUNK)) {
11648 int new_callno;
11649 if ((new_callno = make_trunk(callno, 1)) != -1)
11650 callno = new_callno;
11651 }
11652 iaxs[callno]->maxtime = cai.maxtime;
11653 if (cai.found)
11654 ast_string_field_set(iaxs[callno], host, pds.peer);
11655
11656 c = ast_iax2_new(callno, AST_STATE_DOWN, cai.capability);
11657
11658 ast_mutex_unlock(&iaxsl[callno]);
11659
11660 if (c) {
11661
11662 if (c->nativeformats & format)
11663 c->nativeformats &= format;
11664 else {
11665 native = c->nativeformats;
11666 fmt = format;
11667 res = ast_translator_best_choice(&fmt, &native);
11668 if (res < 0) {
11669 ast_log(LOG_WARNING, "Unable to create translator path for %s to %s on %s\n",
11670 ast_getformatname(c->nativeformats), ast_getformatname(fmt), c->name);
11671 ast_hangup(c);
11672 return NULL;
11673 }
11674 c->nativeformats = native;
11675 }
11676 c->readformat = ast_best_codec(c->nativeformats);
11677 c->writeformat = c->readformat;
11678 }
11679
11680 return c;
11681 }
11682
11683 static void *network_thread(void *ignore)
11684 {
11685
11686
11687 int res, count, wakeup;
11688 struct iax_frame *f;
11689
11690 if (timer)
11691 ast_io_add(io, ast_timer_fd(timer), timing_read, AST_IO_IN | AST_IO_PRI, NULL);
11692
11693 for(;;) {
11694 pthread_testcancel();
11695
11696
11697
11698 AST_LIST_LOCK(&frame_queue);
11699 count = 0;
11700 wakeup = -1;
11701 AST_LIST_TRAVERSE_SAFE_BEGIN(&frame_queue, f, list) {
11702 if (f->sentyet)
11703 continue;
11704
11705
11706 if (ast_mutex_trylock(&iaxsl[f->callno])) {
11707 wakeup = 1;
11708 continue;
11709 }
11710
11711 f->sentyet = 1;
11712
11713 if (iaxs[f->callno]) {
11714 send_packet(f);
11715 count++;
11716 }
11717
11718 ast_mutex_unlock(&iaxsl[f->callno]);
11719
11720 if (f->retries < 0) {
11721
11722 AST_LIST_REMOVE_CURRENT(list);
11723
11724 iax_frame_free(f);
11725 } else {
11726
11727 f->retries++;
11728 f->retrans = iax2_sched_add(sched, f->retrytime, attempt_transmit, f);
11729 }
11730 }
11731 AST_LIST_TRAVERSE_SAFE_END;
11732 AST_LIST_UNLOCK(&frame_queue);
11733
11734 pthread_testcancel();
11735 if (count >= 20)
11736 ast_debug(1, "chan_iax2: Sent %d queued outbound frames all at once\n", count);
11737
11738
11739 res = ast_io_wait(io, wakeup);
11740 if (res >= 0) {
11741 if (res >= 20)
11742 ast_debug(1, "chan_iax2: ast_io_wait ran %d I/Os all at once\n", res);
11743 }
11744 }
11745 return NULL;
11746 }
11747
11748 static int start_network_thread(void)
11749 {
11750 struct iax2_thread *thread;
11751 int threadcount = 0;
11752 int x;
11753 for (x = 0; x < iaxthreadcount; x++) {
11754 thread = ast_calloc(1, sizeof(*thread));
11755 if (thread) {
11756 thread->type = IAX_THREAD_TYPE_POOL;
11757 thread->threadnum = ++threadcount;
11758 ast_mutex_init(&thread->lock);
11759 ast_cond_init(&thread->cond, NULL);
11760 if (ast_pthread_create_background(&thread->threadid, NULL, iax2_process_thread, thread)) {
11761 ast_log(LOG_WARNING, "Failed to create new thread!\n");
11762 ast_free(thread);
11763 thread = NULL;
11764 }
11765 AST_LIST_LOCK(&idle_list);
11766 AST_LIST_INSERT_TAIL(&idle_list, thread, list);
11767 AST_LIST_UNLOCK(&idle_list);
11768 }
11769 }
11770 ast_pthread_create_background(&netthreadid, NULL, network_thread, NULL);
11771 ast_verb(2, "%d helper threads started\n", threadcount);
11772 return 0;
11773 }
11774
11775 static struct iax2_context *build_context(const char *context)
11776 {
11777 struct iax2_context *con;
11778
11779 if ((con = ast_calloc(1, sizeof(*con))))
11780 ast_copy_string(con->context, context, sizeof(con->context));
11781
11782 return con;
11783 }
11784
11785 static int get_auth_methods(const char *value)
11786 {
11787 int methods = 0;
11788 if (strstr(value, "rsa"))
11789 methods |= IAX_AUTH_RSA;
11790 if (strstr(value, "md5"))
11791 methods |= IAX_AUTH_MD5;
11792 if (strstr(value, "plaintext"))
11793 methods |= IAX_AUTH_PLAINTEXT;
11794 return methods;
11795 }
11796
11797
11798
11799
11800
11801 static int check_srcaddr(struct sockaddr *sa, socklen_t salen)
11802 {
11803 int sd;
11804 int res;
11805
11806 sd = socket(AF_INET, SOCK_DGRAM, 0);
11807 if (sd < 0) {
11808 ast_log(LOG_ERROR, "Socket: %s\n", strerror(errno));
11809 return -1;
11810 }
11811
11812 res = bind(sd, sa, salen);
11813 if (res < 0) {
11814 ast_debug(1, "Can't bind: %s\n", strerror(errno));
11815 close(sd);
11816 return 1;
11817 }
11818
11819 close(sd);
11820 return 0;
11821 }
11822
11823
11824
11825
11826 static int peer_set_srcaddr(struct iax2_peer *peer, const char *srcaddr)
11827 {
11828 struct sockaddr_in sin;
11829 int nonlocal = 1;
11830 int port = IAX_DEFAULT_PORTNO;
11831 int sockfd = defaultsockfd;
11832 char *tmp;
11833 char *addr;
11834 char *portstr;
11835
11836 if (!(tmp = ast_strdupa(srcaddr)))
11837 return -1;
11838
11839 addr = strsep(&tmp, ":");
11840 portstr = tmp;
11841
11842 if (portstr) {
11843 port = atoi(portstr);
11844 if (port < 1)
11845 port = IAX_DEFAULT_PORTNO;
11846 }
11847
11848 if (!ast_get_ip(&sin, addr)) {
11849 struct ast_netsock *sock;
11850 int res;
11851
11852 sin.sin_port = 0;
11853 sin.sin_family = AF_INET;
11854 res = check_srcaddr((struct sockaddr *) &sin, sizeof(sin));
11855 if (res == 0) {
11856
11857 sin.sin_port = htons(port);
11858 if (!(sock = ast_netsock_find(netsock, &sin)))
11859 sock = ast_netsock_find(outsock, &sin);
11860 if (sock) {
11861 sockfd = ast_netsock_sockfd(sock);
11862 nonlocal = 0;
11863 } else {
11864 unsigned int orig_saddr = sin.sin_addr.s_addr;
11865
11866 sin.sin_addr.s_addr = INADDR_ANY;
11867 if (ast_netsock_find(netsock, &sin)) {
11868 sin.sin_addr.s_addr = orig_saddr;
11869 sock = ast_netsock_bind(outsock, io, srcaddr, port, qos.tos, qos.cos, socket_read, NULL);
11870 if (sock) {
11871 sockfd = ast_netsock_sockfd(sock);
11872 ast_netsock_unref(sock);
11873 nonlocal = 0;
11874 } else {
11875 nonlocal = 2;
11876 }
11877 }
11878 }
11879 }
11880 }
11881
11882 peer->sockfd = sockfd;
11883
11884 if (nonlocal == 1) {
11885 ast_log(LOG_WARNING, "Non-local or unbound address specified (%s) in sourceaddress for '%s', reverting to default\n",
11886 srcaddr, peer->name);
11887 return -1;
11888 } else if (nonlocal == 2) {
11889 ast_log(LOG_WARNING, "Unable to bind to sourceaddress '%s' for '%s', reverting to default\n",
11890 srcaddr, peer->name);
11891 return -1;
11892 } else {
11893 ast_debug(1, "Using sourceaddress %s for '%s'\n", srcaddr, peer->name);
11894 return 0;
11895 }
11896 }
11897
11898 static void peer_destructor(void *obj)
11899 {
11900 struct iax2_peer *peer = obj;
11901 int callno = peer->callno;
11902
11903 ast_free_ha(peer->ha);
11904
11905 if (callno > 0) {
11906 ast_mutex_lock(&iaxsl[callno]);
11907 iax2_destroy(callno);
11908 ast_mutex_unlock(&iaxsl[callno]);
11909 }
11910
11911 register_peer_exten(peer, 0);
11912
11913 if (peer->dnsmgr)
11914 ast_dnsmgr_release(peer->dnsmgr);
11915
11916 if (peer->mwi_event_sub)
11917 ast_event_unsubscribe(peer->mwi_event_sub);
11918
11919 ast_string_field_free_memory(peer);
11920 }
11921
11922
11923 static struct iax2_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
11924 {
11925 struct iax2_peer *peer = NULL;
11926 struct ast_ha *oldha = NULL;
11927 int maskfound = 0;
11928 int found = 0;
11929 int firstpass = 1;
11930 struct iax2_peer tmp_peer = {
11931 .name = name,
11932 };
11933
11934 if (!temponly) {
11935 peer = ao2_find(peers, &tmp_peer, OBJ_POINTER);
11936 if (peer && !ast_test_flag(peer, IAX_DELME))
11937 firstpass = 0;
11938 }
11939
11940 if (peer) {
11941 found++;
11942 if (firstpass) {
11943 oldha = peer->ha;
11944 peer->ha = NULL;
11945 }
11946 unlink_peer(peer);
11947 } else if ((peer = ao2_alloc(sizeof(*peer), peer_destructor))) {
11948 peer->expire = -1;
11949 peer->pokeexpire = -1;
11950 peer->sockfd = defaultsockfd;
11951 if (ast_string_field_init(peer, 32))
11952 peer = peer_unref(peer);
11953 }
11954
11955 if (peer) {
11956 if (firstpass) {
11957 ast_copy_flags(peer, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_FORCE_ENCRYPT);
11958 peer->encmethods = iax2_encryption;
11959 peer->adsi = adsi;
11960 ast_string_field_set(peer,secret,"");
11961 if (!found) {
11962 ast_string_field_set(peer, name, name);
11963 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
11964 peer->expiry = min_reg_expire;
11965 }
11966 peer->prefs = prefs;
11967 peer->capability = iax2_capability;
11968 peer->smoothing = 0;
11969 peer->pokefreqok = DEFAULT_FREQ_OK;
11970 peer->pokefreqnotok = DEFAULT_FREQ_NOTOK;
11971 peer->maxcallno = 0;
11972 peercnt_modify(0, 0, &peer->addr);
11973 peer->calltoken_required = CALLTOKEN_DEFAULT;
11974 ast_string_field_set(peer,context,"");
11975 ast_string_field_set(peer,peercontext,"");
11976 ast_clear_flag(peer, IAX_HASCALLERID);
11977 ast_string_field_set(peer, cid_name, "");
11978 ast_string_field_set(peer, cid_num, "");
11979 ast_string_field_set(peer, mohinterpret, mohinterpret);
11980 ast_string_field_set(peer, mohsuggest, mohsuggest);
11981 }
11982
11983 if (!v) {
11984 v = alt;
11985 alt = NULL;
11986 }
11987 while(v) {
11988 if (!strcasecmp(v->name, "secret")) {
11989 ast_string_field_set(peer, secret, v->value);
11990 } else if (!strcasecmp(v->name, "mailbox")) {
11991 ast_string_field_set(peer, mailbox, v->value);
11992 } else if (!strcasecmp(v->name, "hasvoicemail")) {
11993 if (ast_true(v->value) && ast_strlen_zero(peer->mailbox)) {
11994 ast_string_field_set(peer, mailbox, name);
11995 }
11996 } else if (!strcasecmp(v->name, "mohinterpret")) {
11997 ast_string_field_set(peer, mohinterpret, v->value);
11998 } else if (!strcasecmp(v->name, "mohsuggest")) {
11999 ast_string_field_set(peer, mohsuggest, v->value);
12000 } else if (!strcasecmp(v->name, "dbsecret")) {
12001 ast_string_field_set(peer, dbsecret, v->value);
12002 } else if (!strcasecmp(v->name, "trunk")) {
12003 ast_set2_flag(peer, ast_true(v->value), IAX_TRUNK);
12004 if (ast_test_flag(peer, IAX_TRUNK) && !timer) {
12005 ast_log(LOG_WARNING, "Unable to support trunking on peer '%s' without a timing interface\n", peer->name);
12006 ast_clear_flag(peer, IAX_TRUNK);
12007 }
12008 } else if (!strcasecmp(v->name, "auth")) {
12009 peer->authmethods = get_auth_methods(v->value);
12010 } else if (!strcasecmp(v->name, "encryption")) {
12011 peer->encmethods |= get_encrypt_methods(v->value);
12012 if (!peer->encmethods) {
12013 ast_clear_flag(peer, IAX_FORCE_ENCRYPT);
12014 }
12015 } else if (!strcasecmp(v->name, "forceencryption")) {
12016 if (ast_false(v->value)) {
12017 ast_clear_flag(peer, IAX_FORCE_ENCRYPT);
12018 } else {
12019 peer->encmethods |= get_encrypt_methods(v->value);
12020 if (peer->encmethods) {
12021 ast_set_flag(peer, IAX_FORCE_ENCRYPT);
12022 }
12023 }
12024 } else if (!strcasecmp(v->name, "transfer")) {
12025 if (!strcasecmp(v->value, "mediaonly")) {
12026 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12027 } else if (ast_true(v->value)) {
12028 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12029 } else
12030 ast_set_flags_to(peer, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12031 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12032 ast_set2_flag(peer, ast_true(v->value), IAX_USEJITTERBUF);
12033 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12034 ast_set2_flag(peer, ast_true(v->value), IAX_FORCEJITTERBUF);
12035 } else if (!strcasecmp(v->name, "host")) {
12036 if (!strcasecmp(v->value, "dynamic")) {
12037
12038 ast_set_flag(peer, IAX_DYNAMIC);
12039 if (!found) {
12040
12041
12042 memset(&peer->addr.sin_addr, 0, 4);
12043 if (peer->addr.sin_port) {
12044
12045 peer->defaddr.sin_port = peer->addr.sin_port;
12046 peer->addr.sin_port = 0;
12047 }
12048 }
12049 } else {
12050
12051 ast_sched_thread_del(sched, peer->expire);
12052 ast_clear_flag(peer, IAX_DYNAMIC);
12053 if (ast_dnsmgr_lookup(v->value, &peer->addr, &peer->dnsmgr, srvlookup ? "_iax._udp" : NULL))
12054 return peer_unref(peer);
12055 if (!peer->addr.sin_port)
12056 peer->addr.sin_port = htons(IAX_DEFAULT_PORTNO);
12057 }
12058 if (!maskfound)
12059 inet_aton("255.255.255.255", &peer->mask);
12060 } else if (!strcasecmp(v->name, "defaultip")) {
12061 if (ast_get_ip(&peer->defaddr, v->value))
12062 return peer_unref(peer);
12063 } else if (!strcasecmp(v->name, "sourceaddress")) {
12064 peer_set_srcaddr(peer, v->value);
12065 } else if (!strcasecmp(v->name, "permit") ||
12066 !strcasecmp(v->name, "deny")) {
12067 peer->ha = ast_append_ha(v->name, v->value, peer->ha, NULL);
12068 } else if (!strcasecmp(v->name, "mask")) {
12069 maskfound++;
12070 inet_aton(v->value, &peer->mask);
12071 } else if (!strcasecmp(v->name, "context")) {
12072 ast_string_field_set(peer, context, v->value);
12073 } else if (!strcasecmp(v->name, "regexten")) {
12074 ast_string_field_set(peer, regexten, v->value);
12075 } else if (!strcasecmp(v->name, "peercontext")) {
12076 ast_string_field_set(peer, peercontext, v->value);
12077 } else if (!strcasecmp(v->name, "port")) {
12078 if (ast_test_flag(peer, IAX_DYNAMIC))
12079 peer->defaddr.sin_port = htons(atoi(v->value));
12080 else
12081 peer->addr.sin_port = htons(atoi(v->value));
12082 } else if (!strcasecmp(v->name, "username")) {
12083 ast_string_field_set(peer, username, v->value);
12084 } else if (!strcasecmp(v->name, "allow")) {
12085 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 1);
12086 } else if (!strcasecmp(v->name, "disallow")) {
12087 ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, 0);
12088 } else if (!strcasecmp(v->name, "callerid")) {
12089 if (!ast_strlen_zero(v->value)) {
12090 char name2[80];
12091 char num2[80];
12092 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12093 ast_string_field_set(peer, cid_name, name2);
12094 ast_string_field_set(peer, cid_num, num2);
12095 } else {
12096 ast_string_field_set(peer, cid_name, "");
12097 ast_string_field_set(peer, cid_num, "");
12098 }
12099 ast_set_flag(peer, IAX_HASCALLERID);
12100 } else if (!strcasecmp(v->name, "fullname")) {
12101 ast_string_field_set(peer, cid_name, S_OR(v->value, ""));
12102 ast_set_flag(peer, IAX_HASCALLERID);
12103 } else if (!strcasecmp(v->name, "cid_number")) {
12104 ast_string_field_set(peer, cid_num, S_OR(v->value, ""));
12105 ast_set_flag(peer, IAX_HASCALLERID);
12106 } else if (!strcasecmp(v->name, "sendani")) {
12107 ast_set2_flag(peer, ast_true(v->value), IAX_SENDANI);
12108 } else if (!strcasecmp(v->name, "inkeys")) {
12109 ast_string_field_set(peer, inkeys, v->value);
12110 } else if (!strcasecmp(v->name, "outkey")) {
12111 ast_string_field_set(peer, outkey, v->value);
12112 } else if (!strcasecmp(v->name, "qualify")) {
12113 if (!strcasecmp(v->value, "no")) {
12114 peer->maxms = 0;
12115 } else if (!strcasecmp(v->value, "yes")) {
12116 peer->maxms = DEFAULT_MAXMS;
12117 } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
12118 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);
12119 peer->maxms = 0;
12120 }
12121 } else if (!strcasecmp(v->name, "qualifysmoothing")) {
12122 peer->smoothing = ast_true(v->value);
12123 } else if (!strcasecmp(v->name, "qualifyfreqok")) {
12124 if (sscanf(v->value, "%30d", &peer->pokefreqok) != 1) {
12125 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);
12126 }
12127 } else if (!strcasecmp(v->name, "qualifyfreqnotok")) {
12128 if (sscanf(v->value, "%30d", &peer->pokefreqnotok) != 1) {
12129 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);
12130 } else ast_log(LOG_WARNING, "Set peer->pokefreqnotok to %d\n", peer->pokefreqnotok);
12131 } else if (!strcasecmp(v->name, "timezone")) {
12132 ast_string_field_set(peer, zonetag, v->value);
12133 } else if (!strcasecmp(v->name, "adsi")) {
12134 peer->adsi = ast_true(v->value);
12135 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12136 if (sscanf(v->value, "%10hu", &peer->maxcallno) != 1) {
12137 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d.\n", v->value, v->lineno);
12138 } else {
12139 peercnt_modify(1, peer->maxcallno, &peer->addr);
12140 }
12141 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12142
12143 if (ast_false(v->value)) {
12144 peer->calltoken_required = CALLTOKEN_NO;
12145 } else if (!strcasecmp(v->value, "auto")) {
12146 peer->calltoken_required = CALLTOKEN_AUTO;
12147 } else if (ast_true(v->value)) {
12148 peer->calltoken_required = CALLTOKEN_YES;
12149 } else {
12150 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12151 }
12152 }
12153
12154 v = v->next;
12155 if (!v) {
12156 v = alt;
12157 alt = NULL;
12158 }
12159 }
12160 if (!peer->authmethods)
12161 peer->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12162 ast_clear_flag(peer, IAX_DELME);
12163
12164 peer->addr.sin_family = AF_INET;
12165 }
12166
12167 if (oldha)
12168 ast_free_ha(oldha);
12169
12170 if (!ast_strlen_zero(peer->mailbox)) {
12171 char *mailbox, *context;
12172 context = mailbox = ast_strdupa(peer->mailbox);
12173 strsep(&context, "@");
12174 if (ast_strlen_zero(context))
12175 context = "default";
12176 peer->mwi_event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, NULL,
12177 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
12178 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
12179 AST_EVENT_IE_END);
12180 }
12181
12182 return peer;
12183 }
12184
12185 static void user_destructor(void *obj)
12186 {
12187 struct iax2_user *user = obj;
12188
12189 ast_free_ha(user->ha);
12190 free_context(user->contexts);
12191 if(user->vars) {
12192 ast_variables_destroy(user->vars);
12193 user->vars = NULL;
12194 }
12195 ast_string_field_free_memory(user);
12196 }
12197
12198
12199 static struct iax2_user *build_user(const char *name, struct ast_variable *v, struct ast_variable *alt, int temponly)
12200 {
12201 struct iax2_user *user = NULL;
12202 struct iax2_context *con, *conl = NULL;
12203 struct ast_ha *oldha = NULL;
12204 struct iax2_context *oldcon = NULL;
12205 int format;
12206 int firstpass=1;
12207 int oldcurauthreq = 0;
12208 char *varname = NULL, *varval = NULL;
12209 struct ast_variable *tmpvar = NULL;
12210 struct iax2_user tmp_user = {
12211 .name = name,
12212 };
12213
12214 if (!temponly) {
12215 user = ao2_find(users, &tmp_user, OBJ_POINTER);
12216 if (user && !ast_test_flag(user, IAX_DELME))
12217 firstpass = 0;
12218 }
12219
12220 if (user) {
12221 if (firstpass) {
12222 oldcurauthreq = user->curauthreq;
12223 oldha = user->ha;
12224 oldcon = user->contexts;
12225 user->ha = NULL;
12226 user->contexts = NULL;
12227 }
12228
12229 ao2_unlink(users, user);
12230 } else {
12231 user = ao2_alloc(sizeof(*user), user_destructor);
12232 }
12233
12234 if (user) {
12235 if (firstpass) {
12236 ast_string_field_free_memory(user);
12237 memset(user, 0, sizeof(struct iax2_user));
12238 if (ast_string_field_init(user, 32)) {
12239 user = user_unref(user);
12240 goto cleanup;
12241 }
12242 user->maxauthreq = maxauthreq;
12243 user->curauthreq = oldcurauthreq;
12244 user->prefs = prefs;
12245 user->capability = iax2_capability;
12246 user->encmethods = iax2_encryption;
12247 user->adsi = adsi;
12248 user->calltoken_required = CALLTOKEN_DEFAULT;
12249 ast_string_field_set(user, name, name);
12250 ast_string_field_set(user, language, language);
12251 ast_copy_flags(user, &globalflags, IAX_USEJITTERBUF | IAX_FORCEJITTERBUF | IAX_CODEC_USER_FIRST | IAX_CODEC_NOPREFS | IAX_CODEC_NOCAP | IAX_FORCE_ENCRYPT);
12252 ast_clear_flag(user, IAX_HASCALLERID);
12253 ast_string_field_set(user, cid_name, "");
12254 ast_string_field_set(user, cid_num, "");
12255 ast_string_field_set(user, accountcode, accountcode);
12256 ast_string_field_set(user, mohinterpret, mohinterpret);
12257 ast_string_field_set(user, mohsuggest, mohsuggest);
12258 }
12259 if (!v) {
12260 v = alt;
12261 alt = NULL;
12262 }
12263 while(v) {
12264 if (!strcasecmp(v->name, "context")) {
12265 con = build_context(v->value);
12266 if (con) {
12267 if (conl)
12268 conl->next = con;
12269 else
12270 user->contexts = con;
12271 conl = con;
12272 }
12273 } else if (!strcasecmp(v->name, "permit") ||
12274 !strcasecmp(v->name, "deny")) {
12275 user->ha = ast_append_ha(v->name, v->value, user->ha, NULL);
12276 } else if (!strcasecmp(v->name, "setvar")) {
12277 varname = ast_strdupa(v->value);
12278 if (varname && (varval = strchr(varname,'='))) {
12279 *varval = '\0';
12280 varval++;
12281 if((tmpvar = ast_variable_new(varname, varval, ""))) {
12282 tmpvar->next = user->vars;
12283 user->vars = tmpvar;
12284 }
12285 }
12286 } else if (!strcasecmp(v->name, "allow")) {
12287 ast_parse_allow_disallow(&user->prefs, &user->capability, v->value, 1);
12288 } else if (!strcasecmp(v->name, "disallow")) {
12289 ast_parse_allow_disallow(&user->prefs, &user->capability,v->value, 0);
12290 } else if (!strcasecmp(v->name, "trunk")) {
12291 ast_set2_flag(user, ast_true(v->value), IAX_TRUNK);
12292 if (ast_test_flag(user, IAX_TRUNK) && !timer) {
12293 ast_log(LOG_WARNING, "Unable to support trunking on user '%s' without a timing interface\n", user->name);
12294 ast_clear_flag(user, IAX_TRUNK);
12295 }
12296 } else if (!strcasecmp(v->name, "auth")) {
12297 user->authmethods = get_auth_methods(v->value);
12298 } else if (!strcasecmp(v->name, "encryption")) {
12299 user->encmethods |= get_encrypt_methods(v->value);
12300 if (!user->encmethods) {
12301 ast_clear_flag(user, IAX_FORCE_ENCRYPT);
12302 }
12303 } else if (!strcasecmp(v->name, "forceencryption")) {
12304 if (ast_false(v->value)) {
12305 ast_clear_flag(user, IAX_FORCE_ENCRYPT);
12306 } else {
12307 user->encmethods |= get_encrypt_methods(v->value);
12308 if (user->encmethods) {
12309 ast_set_flag(user, IAX_FORCE_ENCRYPT);
12310 }
12311 }
12312 } else if (!strcasecmp(v->name, "transfer")) {
12313 if (!strcasecmp(v->value, "mediaonly")) {
12314 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12315 } else if (ast_true(v->value)) {
12316 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12317 } else
12318 ast_set_flags_to(user, IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12319 } else if (!strcasecmp(v->name, "codecpriority")) {
12320 if(!strcasecmp(v->value, "caller"))
12321 ast_set_flag(user, IAX_CODEC_USER_FIRST);
12322 else if(!strcasecmp(v->value, "disabled"))
12323 ast_set_flag(user, IAX_CODEC_NOPREFS);
12324 else if(!strcasecmp(v->value, "reqonly")) {
12325 ast_set_flag(user, IAX_CODEC_NOCAP);
12326 ast_set_flag(user, IAX_CODEC_NOPREFS);
12327 }
12328 } else if (!strcasecmp(v->name, "immediate")) {
12329 ast_set2_flag(user, ast_true(v->value), IAX_IMMEDIATE);
12330 } else if (!strcasecmp(v->name, "jitterbuffer")) {
12331 ast_set2_flag(user, ast_true(v->value), IAX_USEJITTERBUF);
12332 } else if (!strcasecmp(v->name, "forcejitterbuffer")) {
12333 ast_set2_flag(user, ast_true(v->value), IAX_FORCEJITTERBUF);
12334 } else if (!strcasecmp(v->name, "dbsecret")) {
12335 ast_string_field_set(user, dbsecret, v->value);
12336 } else if (!strcasecmp(v->name, "secret")) {
12337 if (!ast_strlen_zero(user->secret)) {
12338 char *old = ast_strdupa(user->secret);
12339
12340 ast_string_field_build(user, secret, "%s;%s", old, v->value);
12341 } else
12342 ast_string_field_set(user, secret, v->value);
12343 } else if (!strcasecmp(v->name, "callerid")) {
12344 if (!ast_strlen_zero(v->value) && strcasecmp(v->value, "asreceived")) {
12345 char name2[80];
12346 char num2[80];
12347 ast_callerid_split(v->value, name2, sizeof(name2), num2, sizeof(num2));
12348 ast_string_field_set(user, cid_name, name2);
12349 ast_string_field_set(user, cid_num, num2);
12350 ast_set_flag(user, IAX_HASCALLERID);
12351 } else {
12352 ast_clear_flag(user, IAX_HASCALLERID);
12353 ast_string_field_set(user, cid_name, "");
12354 ast_string_field_set(user, cid_num, "");
12355 }
12356 } else if (!strcasecmp(v->name, "fullname")) {
12357 if (!ast_strlen_zero(v->value)) {
12358 ast_string_field_set(user, cid_name, v->value);
12359 ast_set_flag(user, IAX_HASCALLERID);
12360 } else {
12361 ast_string_field_set(user, cid_name, "");
12362 if (ast_strlen_zero(user->cid_num))
12363 ast_clear_flag(user, IAX_HASCALLERID);
12364 }
12365 } else if (!strcasecmp(v->name, "cid_number")) {
12366 if (!ast_strlen_zero(v->value)) {
12367 ast_string_field_set(user, cid_num, v->value);
12368 ast_set_flag(user, IAX_HASCALLERID);
12369 } else {
12370 ast_string_field_set(user, cid_num, "");
12371 if (ast_strlen_zero(user->cid_name))
12372 ast_clear_flag(user, IAX_HASCALLERID);
12373 }
12374 } else if (!strcasecmp(v->name, "accountcode")) {
12375 ast_string_field_set(user, accountcode, v->value);
12376 } else if (!strcasecmp(v->name, "mohinterpret")) {
12377 ast_string_field_set(user, mohinterpret, v->value);
12378 } else if (!strcasecmp(v->name, "mohsuggest")) {
12379 ast_string_field_set(user, mohsuggest, v->value);
12380 } else if (!strcasecmp(v->name, "parkinglot")) {
12381 ast_string_field_set(user, parkinglot, v->value);
12382 } else if (!strcasecmp(v->name, "language")) {
12383 ast_string_field_set(user, language, v->value);
12384 } else if (!strcasecmp(v->name, "amaflags")) {
12385 format = ast_cdr_amaflags2int(v->value);
12386 if (format < 0) {
12387 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12388 } else {
12389 user->amaflags = format;
12390 }
12391 } else if (!strcasecmp(v->name, "inkeys")) {
12392 ast_string_field_set(user, inkeys, v->value);
12393 } else if (!strcasecmp(v->name, "maxauthreq")) {
12394 user->maxauthreq = atoi(v->value);
12395 if (user->maxauthreq < 0)
12396 user->maxauthreq = 0;
12397 } else if (!strcasecmp(v->name, "adsi")) {
12398 user->adsi = ast_true(v->value);
12399 } else if (!strcasecmp(v->name, "requirecalltoken")) {
12400
12401 if (ast_false(v->value)) {
12402 user->calltoken_required = CALLTOKEN_NO;
12403 } else if (!strcasecmp(v->value, "auto")) {
12404 user->calltoken_required = CALLTOKEN_AUTO;
12405 } else if (ast_true(v->value)) {
12406 user->calltoken_required = CALLTOKEN_YES;
12407 } else {
12408 ast_log(LOG_WARNING, "requirecalltoken must be set to a valid value. at line %d\n", v->lineno);
12409 }
12410 }
12411
12412 v = v->next;
12413 if (!v) {
12414 v = alt;
12415 alt = NULL;
12416 }
12417 }
12418 if (!user->authmethods) {
12419 if (!ast_strlen_zero(user->secret)) {
12420 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12421 if (!ast_strlen_zero(user->inkeys))
12422 user->authmethods |= IAX_AUTH_RSA;
12423 } else if (!ast_strlen_zero(user->inkeys)) {
12424 user->authmethods = IAX_AUTH_RSA;
12425 } else {
12426 user->authmethods = IAX_AUTH_MD5 | IAX_AUTH_PLAINTEXT;
12427 }
12428 }
12429 ast_clear_flag(user, IAX_DELME);
12430 }
12431 cleanup:
12432 if (oldha)
12433 ast_free_ha(oldha);
12434 if (oldcon)
12435 free_context(oldcon);
12436 return user;
12437 }
12438
12439 static int peer_delme_cb(void *obj, void *arg, int flags)
12440 {
12441 struct iax2_peer *peer = obj;
12442
12443 ast_set_flag(peer, IAX_DELME);
12444
12445 return 0;
12446 }
12447
12448 static int user_delme_cb(void *obj, void *arg, int flags)
12449 {
12450 struct iax2_user *user = obj;
12451
12452 ast_set_flag(user, IAX_DELME);
12453
12454 return 0;
12455 }
12456
12457 static void delete_users(void)
12458 {
12459 struct iax2_registry *reg;
12460
12461 ao2_callback(users, 0, user_delme_cb, NULL);
12462
12463 AST_LIST_LOCK(®istrations);
12464 while ((reg = AST_LIST_REMOVE_HEAD(®istrations, entry))) {
12465 if (sched) {
12466 ast_sched_thread_del(sched, reg->expire);
12467 }
12468 if (reg->callno) {
12469 int callno = reg->callno;
12470 ast_mutex_lock(&iaxsl[callno]);
12471 if (iaxs[callno]) {
12472 iaxs[callno]->reg = NULL;
12473 iax2_destroy(callno);
12474 }
12475 ast_mutex_unlock(&iaxsl[callno]);
12476 }
12477 if (reg->dnsmgr)
12478 ast_dnsmgr_release(reg->dnsmgr);
12479 ast_free(reg);
12480 }
12481 AST_LIST_UNLOCK(®istrations);
12482
12483 ao2_callback(peers, 0, peer_delme_cb, NULL);
12484 }
12485
12486 static void prune_users(void)
12487 {
12488 struct iax2_user *user;
12489 struct ao2_iterator i;
12490
12491 i = ao2_iterator_init(users, 0);
12492 while ((user = ao2_iterator_next(&i))) {
12493 if (ast_test_flag(user, IAX_DELME) || ast_test_flag(user, IAX_RTCACHEFRIENDS)) {
12494 ao2_unlink(users, user);
12495 }
12496 user_unref(user);
12497 }
12498 ao2_iterator_destroy(&i);
12499 }
12500
12501
12502 static void prune_peers(void)
12503 {
12504 struct iax2_peer *peer;
12505 struct ao2_iterator i;
12506
12507 i = ao2_iterator_init(peers, 0);
12508 while ((peer = ao2_iterator_next(&i))) {
12509 if (ast_test_flag(peer, IAX_DELME) || ast_test_flag(peer, IAX_RTCACHEFRIENDS)) {
12510 unlink_peer(peer);
12511 }
12512 peer_unref(peer);
12513 }
12514 ao2_iterator_destroy(&i);
12515 }
12516
12517 static void set_config_destroy(void)
12518 {
12519 strcpy(accountcode, "");
12520 strcpy(language, "");
12521 strcpy(mohinterpret, "default");
12522 strcpy(mohsuggest, "");
12523 trunkmaxsize = MAX_TRUNKDATA;
12524 amaflags = 0;
12525 delayreject = 0;
12526 ast_clear_flag((&globalflags), IAX_NOTRANSFER);
12527 ast_clear_flag((&globalflags), IAX_TRANSFERMEDIA);
12528 ast_clear_flag((&globalflags), IAX_USEJITTERBUF);
12529 ast_clear_flag((&globalflags), IAX_FORCEJITTERBUF);
12530 delete_users();
12531 ao2_callback(callno_limits, OBJ_NODATA, addr_range_delme_cb, NULL);
12532 ao2_callback(calltoken_ignores, OBJ_NODATA, addr_range_delme_cb, NULL);
12533 }
12534
12535
12536 static int set_config(const char *config_file, int reload)
12537 {
12538 struct ast_config *cfg, *ucfg;
12539 int capability=iax2_capability;
12540 struct ast_variable *v;
12541 char *cat;
12542 const char *utype;
12543 const char *tosval;
12544 int format;
12545 int portno = IAX_DEFAULT_PORTNO;
12546 int x;
12547 int mtuv;
12548 struct iax2_user *user;
12549 struct iax2_peer *peer;
12550 struct ast_netsock *ns;
12551 struct ast_flags config_flags = { reload ? CONFIG_FLAG_FILEUNCHANGED : 0 };
12552 #if 0
12553 static unsigned short int last_port=0;
12554 #endif
12555
12556 cfg = ast_config_load(config_file, config_flags);
12557
12558 if (!cfg) {
12559 ast_log(LOG_ERROR, "Unable to load config %s\n", config_file);
12560 return -1;
12561 } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
12562 ucfg = ast_config_load("users.conf", config_flags);
12563 if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
12564 return 0;
12565
12566 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
12567 if ((cfg = ast_config_load(config_file, config_flags)) == CONFIG_STATUS_FILEINVALID) {
12568 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
12569 ast_config_destroy(ucfg);
12570 return 0;
12571 }
12572 } else if (cfg == CONFIG_STATUS_FILEINVALID) {
12573 ast_log(LOG_ERROR, "Config file %s is in an invalid format. Aborting.\n", config_file);
12574 return 0;
12575 } else {
12576 ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
12577 if ((ucfg = ast_config_load("users.conf", config_flags)) == CONFIG_STATUS_FILEINVALID) {
12578 ast_log(LOG_ERROR, "Config file users.conf is in an invalid format. Aborting.\n");
12579 ast_config_destroy(cfg);
12580 return 0;
12581 }
12582 }
12583
12584 if (reload) {
12585 set_config_destroy();
12586 }
12587
12588
12589 memset(&prefs, 0 , sizeof(struct ast_codec_pref));
12590
12591
12592 memset(&globalflags, 0, sizeof(globalflags));
12593 ast_set_flag(&globalflags, IAX_RTUPDATE);
12594 ast_set_flag(&globalflags, IAX_SHRINKCALLERID);
12595
12596 #ifdef SO_NO_CHECK
12597 nochecksums = 0;
12598 #endif
12599
12600 default_parkinglot[0] = '\0';
12601
12602 min_reg_expire = IAX_DEFAULT_REG_EXPIRE;
12603 max_reg_expire = IAX_DEFAULT_REG_EXPIRE;
12604 global_max_trunk_mtu = MAX_TRUNK_MTU;
12605 global_maxcallno = DEFAULT_MAXCALLNO_LIMIT;
12606 global_maxcallno_nonval = DEFAULT_MAXCALLNO_LIMIT_NONVAL;
12607
12608 maxauthreq = 3;
12609
12610 srvlookup = 0;
12611
12612 v = ast_variable_browse(cfg, "general");
12613
12614
12615 tosval = ast_variable_retrieve(cfg, "general", "tos");
12616 if (tosval) {
12617 if (ast_str2tos(tosval, &qos.tos))
12618 ast_log(LOG_WARNING, "Invalid tos value, refer to QoS documentation\n");
12619 }
12620
12621 tosval = ast_variable_retrieve(cfg, "general", "cos");
12622 if (tosval) {
12623 if (ast_str2cos(tosval, &qos.cos))
12624 ast_log(LOG_WARNING, "Invalid cos value, refer to QoS documentation\n");
12625 }
12626 while(v) {
12627 if (!strcasecmp(v->name, "bindport")){
12628 if (reload)
12629 ast_log(LOG_NOTICE, "Ignoring bindport on reload\n");
12630 else
12631 portno = atoi(v->value);
12632 } else if (!strcasecmp(v->name, "pingtime"))
12633 ping_time = atoi(v->value);
12634 else if (!strcasecmp(v->name, "iaxthreadcount")) {
12635 if (reload) {
12636 if (atoi(v->value) != iaxthreadcount)
12637 ast_log(LOG_NOTICE, "Ignoring any changes to iaxthreadcount during reload\n");
12638 } else {
12639 iaxthreadcount = atoi(v->value);
12640 if (iaxthreadcount < 1) {
12641 ast_log(LOG_NOTICE, "iaxthreadcount must be at least 1.\n");
12642 iaxthreadcount = 1;
12643 } else if (iaxthreadcount > 256) {
12644 ast_log(LOG_NOTICE, "limiting iaxthreadcount to 256\n");
12645 iaxthreadcount = 256;
12646 }
12647 }
12648 } else if (!strcasecmp(v->name, "iaxmaxthreadcount")) {
12649 if (reload) {
12650 AST_LIST_LOCK(&dynamic_list);
12651 iaxmaxthreadcount = atoi(v->value);
12652 AST_LIST_UNLOCK(&dynamic_list);
12653 } else {
12654 iaxmaxthreadcount = atoi(v->value);
12655 if (iaxmaxthreadcount < 0) {
12656 ast_log(LOG_NOTICE, "iaxmaxthreadcount must be at least 0.\n");
12657 iaxmaxthreadcount = 0;
12658 } else if (iaxmaxthreadcount > 256) {
12659 ast_log(LOG_NOTICE, "Limiting iaxmaxthreadcount to 256\n");
12660 iaxmaxthreadcount = 256;
12661 }
12662 }
12663 } else if (!strcasecmp(v->name, "nochecksums")) {
12664 #ifdef SO_NO_CHECK
12665 if (ast_true(v->value))
12666 nochecksums = 1;
12667 else
12668 nochecksums = 0;
12669 #else
12670 if (ast_true(v->value))
12671 ast_log(LOG_WARNING, "Disabling RTP checksums is not supported on this operating system!\n");
12672 #endif
12673 }
12674 else if (!strcasecmp(v->name, "maxjitterbuffer"))
12675 maxjitterbuffer = atoi(v->value);
12676 else if (!strcasecmp(v->name, "resyncthreshold"))
12677 resyncthreshold = atoi(v->value);
12678 else if (!strcasecmp(v->name, "maxjitterinterps"))
12679 maxjitterinterps = atoi(v->value);
12680 else if (!strcasecmp(v->name, "jittertargetextra"))
12681 jittertargetextra = atoi(v->value);
12682 else if (!strcasecmp(v->name, "lagrqtime"))
12683 lagrq_time = atoi(v->value);
12684 else if (!strcasecmp(v->name, "maxregexpire"))
12685 max_reg_expire = atoi(v->value);
12686 else if (!strcasecmp(v->name, "minregexpire"))
12687 min_reg_expire = atoi(v->value);
12688 else if (!strcasecmp(v->name, "bindaddr")) {
12689 if (reload) {
12690 ast_log(LOG_NOTICE, "Ignoring bindaddr on reload\n");
12691 } else {
12692 if (!(ns = ast_netsock_bind(netsock, io, v->value, portno, qos.tos, qos.cos, socket_read, NULL))) {
12693 ast_log(LOG_WARNING, "Unable apply binding to '%s' at line %d\n", v->value, v->lineno);
12694 } else {
12695 if (strchr(v->value, ':'))
12696 ast_verb(2, "Binding IAX2 to '%s'\n", v->value);
12697 else
12698 ast_verb(2, "Binding IAX2 to '%s:%d'\n", v->value, portno);
12699 if (defaultsockfd < 0)
12700 defaultsockfd = ast_netsock_sockfd(ns);
12701 ast_netsock_unref(ns);
12702 }
12703 }
12704 } else if (!strcasecmp(v->name, "authdebug")) {
12705 authdebug = ast_true(v->value);
12706 } else if (!strcasecmp(v->name, "encryption")) {
12707 iax2_encryption |= get_encrypt_methods(v->value);
12708 if (!iax2_encryption) {
12709 ast_clear_flag((&globalflags), IAX_FORCE_ENCRYPT);
12710 }
12711 } else if (!strcasecmp(v->name, "forceencryption")) {
12712 if (ast_false(v->value)) {
12713 ast_clear_flag((&globalflags), IAX_FORCE_ENCRYPT);
12714 } else {
12715 iax2_encryption |= get_encrypt_methods(v->value);
12716 if (iax2_encryption) {
12717 ast_set_flag((&globalflags), IAX_FORCE_ENCRYPT);
12718 }
12719 }
12720 } else if (!strcasecmp(v->name, "transfer")) {
12721 if (!strcasecmp(v->value, "mediaonly")) {
12722 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_TRANSFERMEDIA);
12723 } else if (ast_true(v->value)) {
12724 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, 0);
12725 } else
12726 ast_set_flags_to((&globalflags), IAX_NOTRANSFER|IAX_TRANSFERMEDIA, IAX_NOTRANSFER);
12727 } else if (!strcasecmp(v->name, "codecpriority")) {
12728 if(!strcasecmp(v->value, "caller"))
12729 ast_set_flag((&globalflags), IAX_CODEC_USER_FIRST);
12730 else if(!strcasecmp(v->value, "disabled"))
12731 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
12732 else if(!strcasecmp(v->value, "reqonly")) {
12733 ast_set_flag((&globalflags), IAX_CODEC_NOCAP);
12734 ast_set_flag((&globalflags), IAX_CODEC_NOPREFS);
12735 }
12736 } else if (!strcasecmp(v->name, "jitterbuffer"))
12737 ast_set2_flag((&globalflags), ast_true(v->value), IAX_USEJITTERBUF);
12738 else if (!strcasecmp(v->name, "forcejitterbuffer"))
12739 ast_set2_flag((&globalflags), ast_true(v->value), IAX_FORCEJITTERBUF);
12740 else if (!strcasecmp(v->name, "delayreject"))
12741 delayreject = ast_true(v->value);
12742 else if (!strcasecmp(v->name, "allowfwdownload"))
12743 ast_set2_flag((&globalflags), ast_true(v->value), IAX_ALLOWFWDOWNLOAD);
12744 else if (!strcasecmp(v->name, "rtcachefriends"))
12745 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTCACHEFRIENDS);
12746 else if (!strcasecmp(v->name, "rtignoreregexpire"))
12747 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTIGNOREREGEXPIRE);
12748 else if (!strcasecmp(v->name, "rtupdate"))
12749 ast_set2_flag((&globalflags), ast_true(v->value), IAX_RTUPDATE);
12750 else if (!strcasecmp(v->name, "trunktimestamps"))
12751 ast_set2_flag(&globalflags, ast_true(v->value), IAX_TRUNKTIMESTAMPS);
12752 else if (!strcasecmp(v->name, "rtautoclear")) {
12753 int i = atoi(v->value);
12754 if(i > 0)
12755 global_rtautoclear = i;
12756 else
12757 i = 0;
12758 ast_set2_flag((&globalflags), i || ast_true(v->value), IAX_RTAUTOCLEAR);
12759 } else if (!strcasecmp(v->name, "trunkfreq")) {
12760 trunkfreq = atoi(v->value);
12761 if (trunkfreq < 10)
12762 trunkfreq = 10;
12763 } else if (!strcasecmp(v->name, "trunkmtu")) {
12764 mtuv = atoi(v->value);
12765 if (mtuv == 0 )
12766 global_max_trunk_mtu = 0;
12767 else if (mtuv >= 172 && mtuv < 4000)
12768 global_max_trunk_mtu = mtuv;
12769 else
12770 ast_log(LOG_NOTICE, "trunkmtu value out of bounds (%d) at line %d\n",
12771 mtuv, v->lineno);
12772 } else if (!strcasecmp(v->name, "trunkmaxsize")) {
12773 trunkmaxsize = atoi(v->value);
12774 if (trunkmaxsize == 0)
12775 trunkmaxsize = MAX_TRUNKDATA;
12776 } else if (!strcasecmp(v->name, "autokill")) {
12777 if (sscanf(v->value, "%30d", &x) == 1) {
12778 if (x >= 0)
12779 autokill = x;
12780 else
12781 ast_log(LOG_NOTICE, "Nice try, but autokill has to be >0 or 'yes' or 'no' at line %d\n", v->lineno);
12782 } else if (ast_true(v->value)) {
12783 autokill = DEFAULT_MAXMS;
12784 } else {
12785 autokill = 0;
12786 }
12787 } else if (!strcasecmp(v->name, "bandwidth")) {
12788 if (!strcasecmp(v->value, "low")) {
12789 capability = IAX_CAPABILITY_LOWBANDWIDTH;
12790 } else if (!strcasecmp(v->value, "medium")) {
12791 capability = IAX_CAPABILITY_MEDBANDWIDTH;
12792 } else if (!strcasecmp(v->value, "high")) {
12793 capability = IAX_CAPABILITY_FULLBANDWIDTH;
12794 } else
12795 ast_log(LOG_WARNING, "bandwidth must be either low, medium, or high\n");
12796 } else if (!strcasecmp(v->name, "allow")) {
12797 ast_parse_allow_disallow(&prefs, &capability, v->value, 1);
12798 } else if (!strcasecmp(v->name, "disallow")) {
12799 ast_parse_allow_disallow(&prefs, &capability, v->value, 0);
12800 } else if (!strcasecmp(v->name, "register")) {
12801 iax2_register(v->value, v->lineno);
12802 } else if (!strcasecmp(v->name, "iaxcompat")) {
12803 iaxcompat = ast_true(v->value);
12804 } else if (!strcasecmp(v->name, "regcontext")) {
12805 ast_copy_string(regcontext, v->value, sizeof(regcontext));
12806
12807 ast_context_find_or_create(NULL, NULL, regcontext, "IAX2");
12808 } else if (!strcasecmp(v->name, "tos")) {
12809 if (ast_str2tos(v->value, &qos.tos))
12810 ast_log(LOG_WARNING, "Invalid tos value at line %d, refer to QoS documentation\n", v->lineno);
12811 } else if (!strcasecmp(v->name, "cos")) {
12812 if (ast_str2cos(v->value, &qos.cos))
12813 ast_log(LOG_WARNING, "Invalid cos value at line %d, refer to QoS documentation\n", v->lineno);
12814 } else if (!strcasecmp(v->name, "parkinglot")) {
12815 ast_copy_string(default_parkinglot, v->value, sizeof(default_parkinglot));
12816 } else if (!strcasecmp(v->name, "accountcode")) {
12817 ast_copy_string(accountcode, v->value, sizeof(accountcode));
12818 } else if (!strcasecmp(v->name, "mohinterpret")) {
12819 ast_copy_string(mohinterpret, v->value, sizeof(mohinterpret));
12820 } else if (!strcasecmp(v->name, "mohsuggest")) {
12821 ast_copy_string(mohsuggest, v->value, sizeof(mohsuggest));
12822 } else if (!strcasecmp(v->name, "amaflags")) {
12823 format = ast_cdr_amaflags2int(v->value);
12824 if (format < 0) {
12825 ast_log(LOG_WARNING, "Invalid AMA Flags: %s at line %d\n", v->value, v->lineno);
12826 } else {
12827 amaflags = format;
12828 }
12829 } else if (!strcasecmp(v->name, "language")) {
12830 ast_copy_string(language, v->value, sizeof(language));
12831 } else if (!strcasecmp(v->name, "maxauthreq")) {
12832 maxauthreq = atoi(v->value);
12833 if (maxauthreq < 0)
12834 maxauthreq = 0;
12835 } else if (!strcasecmp(v->name, "adsi")) {
12836 adsi = ast_true(v->value);
12837 } else if (!strcasecmp(v->name, "srvlookup")) {
12838 srvlookup = ast_true(v->value);
12839 } else if (!strcasecmp(v->name, "maxcallnumbers")) {
12840 if (sscanf(v->value, "%10hu", &global_maxcallno) != 1) {
12841 ast_log(LOG_WARNING, "maxcallnumbers must be set to a valid number. %s is not valid at line %d\n", v->value, v->lineno);
12842 }
12843 } else if (!strcasecmp(v->name, "maxcallnumbers_nonvalidated")) {
12844 if (sscanf(v->value, "%10hu", &global_maxcallno_nonval) != 1) {
12845 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);
12846 }
12847 } else if (!strcasecmp(v->name, "calltokenoptional")) {
12848 if (add_calltoken_ignore(v->value)) {
12849 ast_log(LOG_WARNING, "Invalid calltokenoptional address range - '%s' line %d\n", v->value, v->lineno);
12850 }
12851 } else if (!strcasecmp(v->name, "shrinkcallerid")) {
12852 if (ast_true(v->value)) {
12853 ast_set_flag((&globalflags), IAX_SHRINKCALLERID);
12854 } else if (ast_false(v->value)) {
12855 ast_clear_flag((&globalflags), IAX_SHRINKCALLERID);
12856 } else {
12857 ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
12858 }
12859 }
12860
12861 v = v->next;
12862 }
12863
12864 if (defaultsockfd < 0) {
12865 if (!(ns = ast_netsock_bind(netsock, io, "0.0.0.0", portno, qos.tos, qos.cos, socket_read, NULL))) {
12866 ast_log(LOG_ERROR, "Unable to create network socket: %s\n", strerror(errno));
12867 } else {
12868 ast_verb(2, "Binding IAX2 to default address 0.0.0.0:%d\n", portno);
12869 defaultsockfd = ast_netsock_sockfd(ns);
12870 ast_netsock_unref(ns);
12871 }
12872 }
12873 if (reload) {
12874 ast_netsock_release(outsock);
12875 outsock = ast_netsock_list_alloc();
12876 if (!outsock) {
12877 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
12878 return -1;
12879 }
12880 ast_netsock_init(outsock);
12881 }
12882
12883 if (min_reg_expire > max_reg_expire) {
12884 ast_log(LOG_WARNING, "Minimum registration interval of %d is more than maximum of %d, resetting minimum to %d\n",
12885 min_reg_expire, max_reg_expire, max_reg_expire);
12886 min_reg_expire = max_reg_expire;
12887 }
12888 iax2_capability = capability;
12889
12890 if (ucfg) {
12891 struct ast_variable *gen;
12892 int genhasiax;
12893 int genregisteriax;
12894 const char *hasiax, *registeriax;
12895
12896 genhasiax = ast_true(ast_variable_retrieve(ucfg, "general", "hasiax"));
12897 genregisteriax = ast_true(ast_variable_retrieve(ucfg, "general", "registeriax"));
12898 gen = ast_variable_browse(ucfg, "general");
12899 cat = ast_category_browse(ucfg, NULL);
12900 while (cat) {
12901 if (strcasecmp(cat, "general")) {
12902 hasiax = ast_variable_retrieve(ucfg, cat, "hasiax");
12903 registeriax = ast_variable_retrieve(ucfg, cat, "registeriax");
12904 if (ast_true(hasiax) || (!hasiax && genhasiax)) {
12905
12906 user = build_user(cat, gen, ast_variable_browse(ucfg, cat), 0);
12907 if (user) {
12908 ao2_link(users, user);
12909 user = user_unref(user);
12910 }
12911 peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0);
12912 if (peer) {
12913 if (ast_test_flag(peer, IAX_DYNAMIC))
12914 reg_source_db(peer);
12915 ao2_link(peers, peer);
12916 peer = peer_unref(peer);
12917 }
12918 }
12919 if (ast_true(registeriax) || (!registeriax && genregisteriax)) {
12920 char tmp[256];
12921 const char *host = ast_variable_retrieve(ucfg, cat, "host");
12922 const char *username = ast_variable_retrieve(ucfg, cat, "username");
12923 const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
12924 if (!host)
12925 host = ast_variable_retrieve(ucfg, "general", "host");
12926 if (!username)
12927 username = ast_variable_retrieve(ucfg, "general", "username");
12928 if (!secret)
12929 secret = ast_variable_retrieve(ucfg, "general", "secret");
12930 if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
12931 if (!ast_strlen_zero(secret))
12932 snprintf(tmp, sizeof(tmp), "%s:%s@%s", username, secret, host);
12933 else
12934 snprintf(tmp, sizeof(tmp), "%s@%s", username, host);
12935 iax2_register(tmp, 0);
12936 }
12937 }
12938 }
12939 cat = ast_category_browse(ucfg, cat);
12940 }
12941 ast_config_destroy(ucfg);
12942 }
12943
12944 cat = ast_category_browse(cfg, NULL);
12945 while(cat) {
12946 if (strcasecmp(cat, "general")) {
12947 utype = ast_variable_retrieve(cfg, cat, "type");
12948 if (!strcasecmp(cat, "callnumberlimits")) {
12949 build_callno_limits(ast_variable_browse(cfg, cat));
12950 } else if (utype) {
12951 if (!strcasecmp(utype, "user") || !strcasecmp(utype, "friend")) {
12952 user = build_user(cat, ast_variable_browse(cfg, cat), NULL, 0);
12953 if (user) {
12954 ao2_link(users, user);
12955 user = user_unref(user);
12956 }
12957 }
12958 if (!strcasecmp(utype, "peer") || !strcasecmp(utype, "friend")) {
12959 peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0);
12960 if (peer) {
12961 if (ast_test_flag(peer, IAX_DYNAMIC))
12962 reg_source_db(peer);
12963 ao2_link(peers, peer);
12964 peer = peer_unref(peer);
12965 }
12966 } else if (strcasecmp(utype, "user")) {
12967 ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, config_file);
12968 }
12969 } else
12970 ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
12971 }
12972 cat = ast_category_browse(cfg, cat);
12973 }
12974 ast_config_destroy(cfg);
12975 return 1;
12976 }
12977
12978 static void poke_all_peers(void)
12979 {
12980 struct ao2_iterator i;
12981 struct iax2_peer *peer;
12982
12983 i = ao2_iterator_init(peers, 0);
12984 while ((peer = ao2_iterator_next(&i))) {
12985 iax2_poke_peer(peer, 0);
12986 peer_unref(peer);
12987 }
12988 ao2_iterator_destroy(&i);
12989 }
12990 static int reload_config(void)
12991 {
12992 static const char config[] = "iax.conf";
12993 struct iax2_registry *reg;
12994
12995 if (set_config(config, 1) > 0) {
12996 prune_peers();
12997 prune_users();
12998 ao2_callback(callno_limits, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
12999 ao2_callback(calltoken_ignores, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, prune_addr_range_cb, NULL);
13000 ao2_callback(peercnts, OBJ_NODATA, set_peercnt_limit_all_cb, NULL);
13001 trunk_timed = trunk_untimed = 0;
13002 trunk_nmaxmtu = trunk_maxmtu = 0;
13003 memset(&debugaddr, '\0', sizeof(debugaddr));
13004
13005 AST_LIST_LOCK(®istrations);
13006 AST_LIST_TRAVERSE(®istrations, reg, entry)
13007 iax2_do_register(reg);
13008 AST_LIST_UNLOCK(®istrations);
13009
13010
13011 poke_all_peers();
13012 }
13013
13014 reload_firmware(0);
13015 iax_provision_reload(1);
13016 ast_unload_realtime("iaxpeers");
13017
13018 return 0;
13019 }
13020
13021 static char *handle_cli_iax2_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13022 {
13023 switch (cmd) {
13024 case CLI_INIT:
13025 e->command = "iax2 reload";
13026 e->usage =
13027 "Usage: iax2 reload\n"
13028 " Reloads IAX configuration from iax.conf\n";
13029 return NULL;
13030 case CLI_GENERATE:
13031 return NULL;
13032 }
13033
13034 reload_config();
13035
13036 return CLI_SUCCESS;
13037 }
13038
13039 static int reload(void)
13040 {
13041 return reload_config();
13042 }
13043
13044 static int cache_get_callno_locked(const char *data)
13045 {
13046 struct sockaddr_in sin;
13047 int x;
13048 int callno;
13049 struct iax_ie_data ied;
13050 struct create_addr_info cai;
13051 struct parsed_dial_string pds;
13052 char *tmpstr;
13053
13054 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13055
13056
13057 if (!ast_mutex_trylock(&iaxsl[x])) {
13058 if (iaxs[x] && !strcasecmp(data, iaxs[x]->dproot))
13059 return x;
13060 ast_mutex_unlock(&iaxsl[x]);
13061 }
13062 }
13063
13064
13065
13066 memset(&cai, 0, sizeof(cai));
13067 memset(&ied, 0, sizeof(ied));
13068 memset(&pds, 0, sizeof(pds));
13069
13070 tmpstr = ast_strdupa(data);
13071 parse_dial_string(tmpstr, &pds);
13072
13073 if (ast_strlen_zero(pds.peer)) {
13074 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", data);
13075 return -1;
13076 }
13077
13078
13079 if (create_addr(pds.peer, NULL, &sin, &cai))
13080 return -1;
13081
13082 ast_debug(1, "peer: %s, username: %s, password: %s, context: %s\n",
13083 pds.peer, pds.username, pds.password, pds.context);
13084
13085 callno = find_callno_locked(0, 0, &sin, NEW_FORCE, cai.sockfd, 0);
13086 if (callno < 1) {
13087 ast_log(LOG_WARNING, "Unable to create call\n");
13088 return -1;
13089 }
13090
13091 ast_string_field_set(iaxs[callno], dproot, data);
13092 iaxs[callno]->capability = IAX_CAPABILITY_FULLBANDWIDTH;
13093
13094 iax_ie_append_short(&ied, IAX_IE_VERSION, IAX_PROTO_VERSION);
13095 iax_ie_append_str(&ied, IAX_IE_CALLED_NUMBER, "TBD");
13096
13097
13098
13099 if (pds.exten)
13100 iax_ie_append_str(&ied, IAX_IE_CALLED_CONTEXT, pds.exten);
13101 if (pds.username)
13102 iax_ie_append_str(&ied, IAX_IE_USERNAME, pds.username);
13103 iax_ie_append_int(&ied, IAX_IE_FORMAT, IAX_CAPABILITY_FULLBANDWIDTH);
13104 iax_ie_append_int(&ied, IAX_IE_CAPABILITY, IAX_CAPABILITY_FULLBANDWIDTH);
13105
13106 if (pds.password)
13107 ast_string_field_set(iaxs[callno], secret, pds.password);
13108 if (pds.key)
13109 ast_string_field_set(iaxs[callno], outkey, pds.key);
13110
13111 add_empty_calltoken_ie(iaxs[callno], &ied);
13112 send_command(iaxs[callno], AST_FRAME_IAX, IAX_COMMAND_NEW, 0, ied.buf, ied.pos, -1);
13113
13114 return callno;
13115 }
13116
13117 static struct iax2_dpcache *find_cache(struct ast_channel *chan, const char *data, const char *context, const char *exten, int priority)
13118 {
13119 struct iax2_dpcache *dp = NULL;
13120 struct timeval now = ast_tvnow();
13121 int x, com[2], timeout, old = 0, outfd, doabort, callno;
13122 struct ast_channel *c = NULL;
13123 struct ast_frame *f = NULL;
13124
13125 AST_LIST_TRAVERSE_SAFE_BEGIN(&dpcache, dp, cache_list) {
13126 if (ast_tvcmp(now, dp->expiry) > 0) {
13127 AST_LIST_REMOVE_CURRENT(cache_list);
13128 if ((dp->flags & CACHE_FLAG_PENDING) || dp->callno)
13129 ast_log(LOG_WARNING, "DP still has peer field or pending or callno (flags = %d, peer = blah, callno = %d)\n", dp->flags, dp->callno);
13130 else
13131 ast_free(dp);
13132 continue;
13133 }
13134 if (!strcmp(dp->peercontext, data) && !strcmp(dp->exten, exten))
13135 break;
13136 }
13137 AST_LIST_TRAVERSE_SAFE_END;
13138
13139 if (!dp) {
13140
13141
13142 if ((callno = cache_get_callno_locked(data)) < 0) {
13143 ast_log(LOG_WARNING, "Unable to generate call for '%s'\n", data);
13144 return NULL;
13145 }
13146 if (!(dp = ast_calloc(1, sizeof(*dp)))) {
13147 ast_mutex_unlock(&iaxsl[callno]);
13148 return NULL;
13149 }
13150 ast_copy_string(dp->peercontext, data, sizeof(dp->peercontext));
13151 ast_copy_string(dp->exten, exten, sizeof(dp->exten));
13152 dp->expiry = ast_tvnow();
13153 dp->orig = dp->expiry;
13154
13155 dp->expiry.tv_sec += iaxdefaultdpcache;
13156 dp->flags = CACHE_FLAG_PENDING;
13157 for (x = 0; x < ARRAY_LEN(dp->waiters); x++)
13158 dp->waiters[x] = -1;
13159
13160 AST_LIST_INSERT_TAIL(&dpcache, dp, cache_list);
13161 AST_LIST_INSERT_TAIL(&iaxs[callno]->dpentries, dp, peer_list);
13162
13163 if (ast_test_flag(&iaxs[callno]->state, IAX_STATE_STARTED))
13164 iax2_dprequest(dp, callno);
13165 ast_mutex_unlock(&iaxsl[callno]);
13166 }
13167
13168
13169 if (dp->flags & CACHE_FLAG_PENDING) {
13170
13171
13172 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13173
13174 if (dp->waiters[x] < 0)
13175 break;
13176 }
13177 if (x >= ARRAY_LEN(dp->waiters)) {
13178 ast_log(LOG_WARNING, "No more waiter positions available\n");
13179 return NULL;
13180 }
13181 if (pipe(com)) {
13182 ast_log(LOG_WARNING, "Unable to create pipe for comm\n");
13183 return NULL;
13184 }
13185 dp->waiters[x] = com[1];
13186
13187 timeout = iaxdefaulttimeout * 1000;
13188
13189 AST_LIST_UNLOCK(&dpcache);
13190
13191 if (chan)
13192 old = ast_channel_defer_dtmf(chan);
13193 doabort = 0;
13194 while(timeout) {
13195 c = ast_waitfor_nandfds(&chan, chan ? 1 : 0, &com[0], 1, NULL, &outfd, &timeout);
13196 if (outfd > -1)
13197 break;
13198 if (!c)
13199 continue;
13200 if (!(f = ast_read(c))) {
13201 doabort = 1;
13202 break;
13203 }
13204 ast_frfree(f);
13205 }
13206 if (!timeout) {
13207 ast_log(LOG_WARNING, "Timeout waiting for %s exten %s\n", data, exten);
13208 }
13209 AST_LIST_LOCK(&dpcache);
13210 dp->waiters[x] = -1;
13211 close(com[1]);
13212 close(com[0]);
13213 if (doabort) {
13214
13215
13216 if (!old && chan)
13217 ast_channel_undefer_dtmf(chan);
13218 return NULL;
13219 }
13220 if (!(dp->flags & CACHE_FLAG_TIMEOUT)) {
13221
13222 if (dp->flags & CACHE_FLAG_PENDING) {
13223
13224
13225 dp->flags &= ~CACHE_FLAG_PENDING;
13226 dp->flags |= CACHE_FLAG_TIMEOUT;
13227
13228
13229 dp->expiry.tv_sec = dp->orig.tv_sec + 60;
13230 for (x = 0; x < ARRAY_LEN(dp->waiters); x++) {
13231 if (dp->waiters[x] > -1) {
13232 if (write(dp->waiters[x], "asdf", 4) < 0) {
13233 ast_log(LOG_WARNING, "write() failed: %s\n", strerror(errno));
13234 }
13235 }
13236 }
13237 }
13238 }
13239
13240 if (!old && chan)
13241 ast_channel_undefer_dtmf(chan);
13242 }
13243 return dp;
13244 }
13245
13246
13247 static int iax2_exists(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13248 {
13249 int res = 0;
13250 struct iax2_dpcache *dp = NULL;
13251 #if 0
13252 ast_log(LOG_NOTICE, "iax2_exists: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13253 #endif
13254 if ((priority != 1) && (priority != 2))
13255 return 0;
13256
13257 AST_LIST_LOCK(&dpcache);
13258 if ((dp = find_cache(chan, data, context, exten, priority))) {
13259 if (dp->flags & CACHE_FLAG_EXISTS)
13260 res = 1;
13261 } else {
13262 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13263 }
13264 AST_LIST_UNLOCK(&dpcache);
13265
13266 return res;
13267 }
13268
13269
13270 static int iax2_canmatch(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13271 {
13272 int res = 0;
13273 struct iax2_dpcache *dp = NULL;
13274 #if 0
13275 ast_log(LOG_NOTICE, "iax2_canmatch: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13276 #endif
13277 if ((priority != 1) && (priority != 2))
13278 return 0;
13279
13280 AST_LIST_LOCK(&dpcache);
13281 if ((dp = find_cache(chan, data, context, exten, priority))) {
13282 if (dp->flags & CACHE_FLAG_CANEXIST)
13283 res = 1;
13284 } else {
13285 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13286 }
13287 AST_LIST_UNLOCK(&dpcache);
13288
13289 return res;
13290 }
13291
13292
13293 static int iax2_matchmore(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13294 {
13295 int res = 0;
13296 struct iax2_dpcache *dp = NULL;
13297 #if 0
13298 ast_log(LOG_NOTICE, "iax2_matchmore: con: %s, exten: %s, pri: %d, cid: %s, data: %s\n", context, exten, priority, callerid ? callerid : "<unknown>", data);
13299 #endif
13300 if ((priority != 1) && (priority != 2))
13301 return 0;
13302
13303 AST_LIST_LOCK(&dpcache);
13304 if ((dp = find_cache(chan, data, context, exten, priority))) {
13305 if (dp->flags & CACHE_FLAG_MATCHMORE)
13306 res = 1;
13307 } else {
13308 ast_log(LOG_WARNING, "Unable to make DP cache\n");
13309 }
13310 AST_LIST_UNLOCK(&dpcache);
13311
13312 return res;
13313 }
13314
13315
13316 static int iax2_exec(struct ast_channel *chan, const char *context, const char *exten, int priority, const char *callerid, const char *data)
13317 {
13318 char odata[256];
13319 char req[256];
13320 char *ncontext;
13321 struct iax2_dpcache *dp = NULL;
13322 struct ast_app *dial = NULL;
13323 #if 0
13324 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);
13325 #endif
13326 if (priority == 2) {
13327
13328 const char *dialstatus = pbx_builtin_getvar_helper(chan, "DIALSTATUS");
13329 if (dialstatus) {
13330 dial = pbx_findapp(dialstatus);
13331 if (dial)
13332 pbx_exec(chan, dial, "");
13333 }
13334 return -1;
13335 } else if (priority != 1)
13336 return -1;
13337
13338 AST_LIST_LOCK(&dpcache);
13339 if ((dp = find_cache(chan, data, context, exten, priority))) {
13340 if (dp->flags & CACHE_FLAG_EXISTS) {
13341 ast_copy_string(odata, data, sizeof(odata));
13342 ncontext = strchr(odata, '/');
13343 if (ncontext) {
13344 *ncontext = '\0';
13345 ncontext++;
13346 snprintf(req, sizeof(req), "IAX2/%s/%s@%s", odata, exten, ncontext);
13347 } else {
13348 snprintf(req, sizeof(req), "IAX2/%s/%s", odata, exten);
13349 }
13350 ast_verb(3, "Executing Dial('%s')\n", req);
13351 } else {
13352 AST_LIST_UNLOCK(&dpcache);
13353 ast_log(LOG_WARNING, "Can't execute nonexistent extension '%s[@%s]' in data '%s'\n", exten, context, data);
13354 return -1;
13355 }
13356 }
13357 AST_LIST_UNLOCK(&dpcache);
13358
13359 if ((dial = pbx_findapp("Dial")))
13360 return pbx_exec(chan, dial, req);
13361 else
13362 ast_log(LOG_WARNING, "No dial application registered\n");
13363
13364 return -1;
13365 }
13366
13367 static int function_iaxpeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
13368 {
13369 struct iax2_peer *peer;
13370 char *peername, *colname;
13371
13372 peername = ast_strdupa(data);
13373
13374
13375 if (!strcmp(peername,"CURRENTCHANNEL")) {
13376 unsigned short callno;
13377 if (chan->tech != &iax2_tech)
13378 return -1;
13379 callno = PTR_TO_CALLNO(chan->tech_pvt);
13380 ast_copy_string(buf, iaxs[callno]->addr.sin_addr.s_addr ? ast_inet_ntoa(iaxs[callno]->addr.sin_addr) : "", len);
13381 return 0;
13382 }
13383
13384 if ((colname = strchr(peername, ',')))
13385 *colname++ = '\0';
13386 else
13387 colname = "ip";
13388
13389 if (!(peer = find_peer(peername, 1)))
13390 return -1;
13391
13392 if (!strcasecmp(colname, "ip")) {
13393 ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
13394 } else if (!strcasecmp(colname, "status")) {
13395 peer_status(peer, buf, len);
13396 } else if (!strcasecmp(colname, "mailbox")) {
13397 ast_copy_string(buf, peer->mailbox, len);
13398 } else if (!strcasecmp(colname, "context")) {
13399 ast_copy_string(buf, peer->context, len);
13400 } else if (!strcasecmp(colname, "expire")) {
13401 snprintf(buf, len, "%d", peer->expire);
13402 } else if (!strcasecmp(colname, "dynamic")) {
13403 ast_copy_string(buf, (ast_test_flag(peer, IAX_DYNAMIC) ? "yes" : "no"), len);
13404 } else if (!strcasecmp(colname, "callerid_name")) {
13405 ast_copy_string(buf, peer->cid_name, len);
13406 } else if (!strcasecmp(colname, "callerid_num")) {
13407 ast_copy_string(buf, peer->cid_num, len);
13408 } else if (!strcasecmp(colname, "codecs")) {
13409 ast_getformatname_multiple(buf, len -1, peer->capability);
13410 } else if (!strncasecmp(colname, "codec[", 6)) {
13411 char *codecnum, *ptr;
13412 int codec = 0;
13413
13414 codecnum = strchr(colname, '[');
13415 *codecnum = '\0';
13416 codecnum++;
13417 if ((ptr = strchr(codecnum, ']'))) {
13418 *ptr = '\0';
13419 }
13420 if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
13421 ast_copy_string(buf, ast_getformatname(codec), len);
13422 } else {
13423 buf[0] = '\0';
13424 }
13425 } else {
13426 buf[0] = '\0';
13427 }
13428
13429 peer_unref(peer);
13430
13431 return 0;
13432 }
13433
13434 struct ast_custom_function iaxpeer_function = {
13435 .name = "IAXPEER",
13436 .read = function_iaxpeer,
13437 };
13438
13439 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *args, char *buf, size_t buflen)
13440 {
13441 struct chan_iax2_pvt *pvt;
13442 unsigned int callno;
13443 int res = 0;
13444
13445 if (!chan || chan->tech != &iax2_tech) {
13446 ast_log(LOG_ERROR, "This function requires a valid IAX2 channel\n");
13447 return -1;
13448 }
13449
13450 callno = PTR_TO_CALLNO(chan->tech_pvt);
13451 ast_mutex_lock(&iaxsl[callno]);
13452 if (!(pvt = iaxs[callno])) {
13453 ast_mutex_unlock(&iaxsl[callno]);
13454 return -1;
13455 }
13456
13457 if (!strcasecmp(args, "osptoken")) {
13458 ast_copy_string(buf, pvt->osptoken, buflen);
13459 } else if (!strcasecmp(args, "peerip")) {
13460 ast_copy_string(buf, pvt->addr.sin_addr.s_addr ? ast_inet_ntoa(pvt->addr.sin_addr) : "", buflen);
13461 } else if (!strcasecmp(args, "peername")) {
13462 ast_copy_string(buf, pvt->username, buflen);
13463 } else {
13464 res = -1;
13465 }
13466
13467 ast_mutex_unlock(&iaxsl[callno]);
13468
13469 return res;
13470 }
13471
13472
13473 static int iax2_devicestate(void *data)
13474 {
13475 struct parsed_dial_string pds;
13476 char *tmp = ast_strdupa(data);
13477 struct iax2_peer *p;
13478 int res = AST_DEVICE_INVALID;
13479
13480 memset(&pds, 0, sizeof(pds));
13481 parse_dial_string(tmp, &pds);
13482
13483 if (ast_strlen_zero(pds.peer)) {
13484 ast_log(LOG_WARNING, "No peer provided in the IAX2 dial string '%s'\n", (char *) data);
13485 return res;
13486 }
13487
13488 ast_debug(3, "Checking device state for device %s\n", pds.peer);
13489
13490
13491 if (!(p = find_peer(pds.peer, 1)))
13492 return res;
13493
13494 res = AST_DEVICE_UNAVAILABLE;
13495 ast_debug(3, "iax2_devicestate: Found peer. What's device state of %s? addr=%d, defaddr=%d maxms=%d, lastms=%d\n",
13496 pds.peer, p->addr.sin_addr.s_addr, p->defaddr.sin_addr.s_addr, p->maxms, p->lastms);
13497
13498 if ((p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) &&
13499 (!p->maxms || ((p->lastms > -1) && (p->historicms <= p->maxms)))) {
13500
13501
13502 if (p->historicms == 0 || p->historicms <= p->maxms)
13503
13504 res = AST_DEVICE_UNKNOWN;
13505 }
13506
13507 peer_unref(p);
13508
13509 return res;
13510 }
13511
13512 static struct ast_switch iax2_switch =
13513 {
13514 name: "IAX2",
13515 description: "IAX Remote Dialplan Switch",
13516 exists: iax2_exists,
13517 canmatch: iax2_canmatch,
13518 exec: iax2_exec,
13519 matchmore: iax2_matchmore,
13520 };
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626 static struct ast_cli_entry cli_iax2[] = {
13627 AST_CLI_DEFINE(handle_cli_iax2_provision, "Provision an IAX device"),
13628 AST_CLI_DEFINE(handle_cli_iax2_prune_realtime, "Prune a cached realtime lookup"),
13629 AST_CLI_DEFINE(handle_cli_iax2_reload, "Reload IAX configuration"),
13630 AST_CLI_DEFINE(handle_cli_iax2_set_mtu, "Set the IAX systemwide trunking MTU"),
13631 AST_CLI_DEFINE(handle_cli_iax2_set_debug, "Enable/Disable IAX debugging"),
13632 AST_CLI_DEFINE(handle_cli_iax2_set_debug_trunk, "Enable/Disable IAX trunk debugging"),
13633 AST_CLI_DEFINE(handle_cli_iax2_set_debug_jb, "Enable/Disable IAX jitterbuffer debugging"),
13634 AST_CLI_DEFINE(handle_cli_iax2_show_cache, "Display IAX cached dialplan"),
13635 AST_CLI_DEFINE(handle_cli_iax2_show_channels, "List active IAX channels"),
13636 AST_CLI_DEFINE(handle_cli_iax2_show_firmware, "List available IAX firmware"),
13637 AST_CLI_DEFINE(handle_cli_iax2_show_netstats, "List active IAX channel netstats"),
13638 AST_CLI_DEFINE(handle_cli_iax2_show_peer, "Show details on specific IAX peer"),
13639 AST_CLI_DEFINE(handle_cli_iax2_show_peers, "List defined IAX peers"),
13640 AST_CLI_DEFINE(handle_cli_iax2_show_registry, "Display IAX registration status"),
13641 AST_CLI_DEFINE(handle_cli_iax2_show_stats, "Display IAX statistics"),
13642 AST_CLI_DEFINE(handle_cli_iax2_show_threads, "Display IAX helper thread info"),
13643 AST_CLI_DEFINE(handle_cli_iax2_show_users, "List defined IAX users"),
13644 AST_CLI_DEFINE(handle_cli_iax2_test_losspct, "Set IAX2 incoming frame loss percentage"),
13645 AST_CLI_DEFINE(handle_cli_iax2_unregister, "Unregister (force expiration) an IAX2 peer from the registry"),
13646 AST_CLI_DEFINE(handle_cli_iax2_show_callno_limits, "Show current entries in IP call number limit table"),
13647 #ifdef IAXTESTS
13648 AST_CLI_DEFINE(handle_cli_iax2_test_jitter, "Simulates jitter for testing"),
13649 AST_CLI_DEFINE(handle_cli_iax2_test_late, "Test the receipt of a late frame"),
13650 AST_CLI_DEFINE(handle_cli_iax2_test_resync, "Test a resync in received timestamps"),
13651 #endif
13652 };
13653
13654 static void cleanup_thread_list(void *head)
13655 {
13656 AST_LIST_HEAD(iax2_thread_list, iax2_thread);
13657 struct iax2_thread_list *list_head = head;
13658 struct iax2_thread *thread;
13659
13660 AST_LIST_LOCK(list_head);
13661 while ((thread = AST_LIST_REMOVE_HEAD(&idle_list, list))) {
13662 pthread_t thread_id = thread->threadid;
13663
13664 thread->stop = 1;
13665 signal_condition(&thread->lock, &thread->cond);
13666
13667 AST_LIST_UNLOCK(list_head);
13668 pthread_join(thread_id, NULL);
13669 AST_LIST_LOCK(list_head);
13670 }
13671 AST_LIST_UNLOCK(list_head);
13672 }
13673
13674 static int __unload_module(void)
13675 {
13676 struct ast_context *con;
13677 int x;
13678
13679 ast_manager_unregister("IAXpeers");
13680 ast_manager_unregister("IAXpeerlist");
13681 ast_manager_unregister("IAXnetstats");
13682 ast_manager_unregister("IAXregistry");
13683 ast_unregister_application(papp);
13684 ast_cli_unregister_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
13685 ast_unregister_switch(&iax2_switch);
13686 ast_channel_unregister(&iax2_tech);
13687
13688 if (netthreadid != AST_PTHREADT_NULL) {
13689 AST_LIST_LOCK(&frame_queue);
13690 pthread_cancel(netthreadid);
13691 AST_LIST_UNLOCK(&frame_queue);
13692 pthread_join(netthreadid, NULL);
13693 }
13694
13695 for (x = 0; x < ARRAY_LEN(iaxs); x++) {
13696 if (iaxs[x]) {
13697 iax2_destroy(x);
13698 }
13699 }
13700
13701
13702 cleanup_thread_list(&idle_list);
13703 cleanup_thread_list(&active_list);
13704 cleanup_thread_list(&dynamic_list);
13705
13706 sched = ast_sched_thread_destroy(sched);
13707
13708 ast_netsock_release(netsock);
13709 ast_netsock_release(outsock);
13710
13711 delete_users();
13712 iax_provision_unload();
13713 reload_firmware(1);
13714
13715 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
13716 ast_mutex_destroy(&iaxsl[x]);
13717 }
13718
13719 ao2_ref(peers, -1);
13720 ao2_ref(users, -1);
13721 ao2_ref(iax_peercallno_pvts, -1);
13722 ao2_ref(iax_transfercallno_pvts, -1);
13723 ao2_ref(peercnts, -1);
13724 ao2_ref(callno_limits, -1);
13725 ao2_ref(calltoken_ignores, -1);
13726 ao2_ref(callno_pool, -1);
13727 ao2_ref(callno_pool_trunk, -1);
13728 if (timer) {
13729 ast_timer_close(timer);
13730 }
13731
13732 con = ast_context_find(regcontext);
13733 if (con)
13734 ast_context_destroy(con, "IAX2");
13735 ast_unload_realtime("iaxpeers");
13736 return 0;
13737 }
13738
13739 static int unload_module(void)
13740 {
13741 ast_custom_function_unregister(&iaxpeer_function);
13742 ast_custom_function_unregister(&iaxvar_function);
13743 return __unload_module();
13744 }
13745
13746 static int peer_set_sock_cb(void *obj, void *arg, int flags)
13747 {
13748 struct iax2_peer *peer = obj;
13749
13750 if (peer->sockfd < 0)
13751 peer->sockfd = defaultsockfd;
13752
13753 return 0;
13754 }
13755
13756 static int pvt_hash_cb(const void *obj, const int flags)
13757 {
13758 const struct chan_iax2_pvt *pvt = obj;
13759
13760 return pvt->peercallno;
13761 }
13762
13763 static int pvt_cmp_cb(void *obj, void *arg, int flags)
13764 {
13765 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
13766
13767
13768
13769
13770 return match(&pvt2->addr, pvt2->peercallno, pvt2->callno, pvt,
13771 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
13772 }
13773
13774 static int transfercallno_pvt_hash_cb(const void *obj, const int flags)
13775 {
13776 const struct chan_iax2_pvt *pvt = obj;
13777
13778 return pvt->transfercallno;
13779 }
13780
13781 static int transfercallno_pvt_cmp_cb(void *obj, void *arg, int flags)
13782 {
13783 struct chan_iax2_pvt *pvt = obj, *pvt2 = arg;
13784
13785
13786
13787
13788 return match(&pvt2->transfer, pvt2->transfercallno, pvt2->callno, pvt,
13789 pvt2->frames_received) ? CMP_MATCH | CMP_STOP : 0;
13790 }
13791
13792 static int load_objects(void)
13793 {
13794 peers = users = iax_peercallno_pvts = iax_transfercallno_pvts = NULL;
13795 peercnts = callno_limits = calltoken_ignores = callno_pool = callno_pool_trunk = NULL;
13796
13797 if (!(peers = ao2_container_alloc(MAX_PEER_BUCKETS, peer_hash_cb, peer_cmp_cb))) {
13798 goto container_fail;
13799 } else if (!(users = ao2_container_alloc(MAX_USER_BUCKETS, user_hash_cb, user_cmp_cb))) {
13800 goto container_fail;
13801 } else if (!(iax_peercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, pvt_hash_cb, pvt_cmp_cb))) {
13802 goto container_fail;
13803 } else if (!(iax_transfercallno_pvts = ao2_container_alloc(IAX_MAX_CALLS, transfercallno_pvt_hash_cb, transfercallno_pvt_cmp_cb))) {
13804 goto container_fail;
13805 } else if (!(peercnts = ao2_container_alloc(MAX_PEER_BUCKETS, peercnt_hash_cb, peercnt_cmp_cb))) {
13806 goto container_fail;
13807 } else if (!(callno_limits = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
13808 goto container_fail;
13809 } else if (!(calltoken_ignores = ao2_container_alloc(MAX_PEER_BUCKETS, addr_range_hash_cb, addr_range_cmp_cb))) {
13810 goto container_fail;
13811 } else if (create_callno_pools()) {
13812 goto container_fail;
13813 }
13814
13815 return 0;
13816
13817 container_fail:
13818 if (peers) {
13819 ao2_ref(peers, -1);
13820 }
13821 if (users) {
13822 ao2_ref(users, -1);
13823 }
13824 if (iax_peercallno_pvts) {
13825 ao2_ref(iax_peercallno_pvts, -1);
13826 }
13827 if (iax_transfercallno_pvts) {
13828 ao2_ref(iax_transfercallno_pvts, -1);
13829 }
13830 if (peercnts) {
13831 ao2_ref(peercnts, -1);
13832 }
13833 if (callno_limits) {
13834 ao2_ref(callno_limits, -1);
13835 }
13836 if (calltoken_ignores) {
13837 ao2_ref(calltoken_ignores, -1);
13838 }
13839 if (callno_pool) {
13840 ao2_ref(callno_pool, -1);
13841 }
13842 if (callno_pool_trunk) {
13843 ao2_ref(callno_pool_trunk, -1);
13844 }
13845 return AST_MODULE_LOAD_FAILURE;
13846 }
13847
13848
13849
13850
13851 static int load_module(void)
13852 {
13853 static const char config[] = "iax.conf";
13854 int x = 0;
13855 struct iax2_registry *reg = NULL;
13856
13857 if (load_objects()) {
13858 return AST_MODULE_LOAD_FAILURE;
13859 }
13860
13861 memset(iaxs, 0, sizeof(iaxs));
13862
13863 for (x = 0; x < ARRAY_LEN(iaxsl); x++) {
13864 ast_mutex_init(&iaxsl[x]);
13865 }
13866
13867 if (!(sched = ast_sched_thread_create())) {
13868 ast_log(LOG_ERROR, "Failed to create scheduler thread\n");
13869 return AST_MODULE_LOAD_FAILURE;
13870 }
13871
13872 if (!(io = io_context_create())) {
13873 ast_log(LOG_ERROR, "Failed to create I/O context\n");
13874 sched = ast_sched_thread_destroy(sched);
13875 return AST_MODULE_LOAD_FAILURE;
13876 }
13877
13878 if (!(netsock = ast_netsock_list_alloc())) {
13879 ast_log(LOG_ERROR, "Failed to create netsock list\n");
13880 io_context_destroy(io);
13881 sched = ast_sched_thread_destroy(sched);
13882 return AST_MODULE_LOAD_FAILURE;
13883 }
13884 ast_netsock_init(netsock);
13885
13886 outsock = ast_netsock_list_alloc();
13887 if (!outsock) {
13888 ast_log(LOG_ERROR, "Could not allocate outsock list.\n");
13889 io_context_destroy(io);
13890 sched = ast_sched_thread_destroy(sched);
13891 return AST_MODULE_LOAD_FAILURE;
13892 }
13893 ast_netsock_init(outsock);
13894
13895 randomcalltokendata = ast_random();
13896
13897 iax_set_output(iax_debug_output);
13898 iax_set_error(iax_error_output);
13899 jb_setoutput(jb_error_output, jb_warning_output, NULL);
13900
13901 if ((timer = ast_timer_open())) {
13902 ast_timer_set_rate(timer, trunkfreq);
13903 }
13904
13905 if (set_config(config, 0) == -1) {
13906 if (timer) {
13907 ast_timer_close(timer);
13908 }
13909 return AST_MODULE_LOAD_DECLINE;
13910 }
13911
13912 ast_cli_register_multiple(cli_iax2, ARRAY_LEN(cli_iax2));
13913
13914 ast_register_application_xml(papp, iax2_prov_app);
13915
13916 ast_custom_function_register(&iaxpeer_function);
13917 ast_custom_function_register(&iaxvar_function);
13918
13919 ast_manager_register( "IAXpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peers, "List IAX Peers" );
13920 ast_manager_register( "IAXpeerlist", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_peer_list, "List IAX Peers" );
13921 ast_manager_register( "IAXnetstats", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_netstats, "Show IAX Netstats" );
13922 ast_manager_register( "IAXregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_iax2_show_registry, "Show IAX registrations");
13923
13924 if (ast_channel_register(&iax2_tech)) {
13925 ast_log(LOG_ERROR, "Unable to register channel class %s\n", "IAX2");
13926 __unload_module();
13927 return AST_MODULE_LOAD_FAILURE;
13928 }
13929
13930 if (ast_register_switch(&iax2_switch)) {
13931 ast_log(LOG_ERROR, "Unable to register IAX switch\n");
13932 }
13933
13934 if (start_network_thread()) {
13935 ast_log(LOG_ERROR, "Unable to start network thread\n");
13936 __unload_module();
13937 return AST_MODULE_LOAD_FAILURE;
13938 } else {
13939 ast_verb(2, "IAX Ready and Listening\n");
13940 }
13941
13942 AST_LIST_LOCK(®istrations);
13943 AST_LIST_TRAVERSE(®istrations, reg, entry)
13944 iax2_do_register(reg);
13945 AST_LIST_UNLOCK(®istrations);
13946
13947 ao2_callback(peers, 0, peer_set_sock_cb, NULL);
13948 ao2_callback(peers, 0, iax2_poke_peer_cb, NULL);
13949
13950
13951 reload_firmware(0);
13952 iax_provision_reload(0);
13953
13954 ast_realtime_require_field("iaxpeers", "name", RQ_CHAR, 10, "ipaddr", RQ_CHAR, 15, "port", RQ_UINTEGER2, 5, "regseconds", RQ_UINTEGER2, 6, SENTINEL);
13955
13956 return AST_MODULE_LOAD_SUCCESS;
13957 }
13958
13959 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Inter Asterisk eXchange (Ver 2)",
13960 .load = load_module,
13961 .unload = unload_module,
13962 .reload = reload,
13963 );