Menu

[c3f7b3]: / dcpp / AdcHub.cpp  Maximize  Restore  History

Download this file

1163 lines (978 with data), 32.8 kB

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
/*
* Copyright (C) 2001-2025 Jacek Sieka, arnetheduck on gmail point com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "stdinc.h"
#include "AdcHub.h"
#include <boost/format.hpp>
#include <boost/scoped_array.hpp>
#include "AdcCommand.h"
#include "ChatMessage.h"
#include "ClientManager.h"
#include "ConnectionManager.h"
#include "ConnectivityManager.h"
#include "CryptoManager.h"
#include "format.h"
#include "LogManager.h"
#include "ShareManager.h"
#include "StringTokenizer.h"
#include "ThrottleManager.h"
#include "UploadManager.h"
#include "PluginManager.h"
#include "UserCommand.h"
#include "Util.h"
#include "version.h"
#include <cmath>
namespace dcpp {
using std::make_pair;
const string AdcHub::CLIENT_PROTOCOL("ADC/1.0");
const string AdcHub::SECURE_CLIENT_PROTOCOL("ADCS/0.10");
const string AdcHub::ADCS_FEATURE("ADC0");
const string AdcHub::TCP4_FEATURE("TCP4");
const string AdcHub::TCP6_FEATURE("TCP6");
const string AdcHub::UDP4_FEATURE("UDP4");
const string AdcHub::UDP6_FEATURE("UDP6");
const string AdcHub::NAT0_FEATURE("NAT0");
const string AdcHub::SEGA_FEATURE("SEGA");
const string AdcHub::CCPM_FEATURE("CCPM");
const string AdcHub::SUDP_FEATURE("SUDP");
const string AdcHub::BASE_SUPPORT("ADBASE");
const string AdcHub::BAS0_SUPPORT("ADBAS0");
const string AdcHub::TIGR_SUPPORT("ADTIGR");
const string AdcHub::UCM0_SUPPORT("ADUCM0");
const string AdcHub::BLO0_SUPPORT("ADBLO0");
const string AdcHub::ZLIF_SUPPORT("ADZLIF");
const vector<StringList> AdcHub::searchExts;
AdcHub::AdcHub(const string& aHubURL, bool secure) :
Client(aHubURL, '\n', secure), oldPassword(false), udp(Socket::TYPE_UDP), sid(0) {
TimerManager::getInstance()->addListener(this);
}
AdcHub::~AdcHub() {
TimerManager::getInstance()->removeListener(this);
clearUsers();
}
OnlineUser& AdcHub::getUser(const uint32_t aSID, const CID& aCID) {
OnlineUser* ou = findUser(aSID);
if(ou) {
return *ou;
}
UserPtr p = ClientManager::getInstance()->getUser(aCID);
{
Lock l(cs);
ou = users.emplace(aSID, new OnlineUser(p, *this, aSID)).first->second;
}
if(aSID != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOnline(ou);
return *ou;
}
OnlineUser* AdcHub::findUser(const uint32_t aSID) const {
Lock l(cs);
auto i = users.find(aSID);
return i == users.end() ? NULL : i->second;
}
OnlineUser* AdcHub::findUser(const CID& aCID) const {
Lock l(cs);
for(auto& i: users) {
if(i.second->getUser()->getCID() == aCID) {
return i.second;
}
}
return 0;
}
void AdcHub::putUser(const uint32_t aSID, bool disconnect) {
OnlineUser* ou = nullptr;
{
Lock l(cs);
auto i = users.find(aSID);
if(i == users.end())
return;
ou = i->second;
users.erase(i);
}
if(aSID != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOffline(ou, disconnect);
fire(ClientListener::UserRemoved(), this, *ou);
delete ou;
}
void AdcHub::clearUsers() {
decltype(users) tmp;
{
Lock l(cs);
users.swap(tmp);
}
for(auto& i: tmp) {
if(i.first != AdcCommand::HUB_SID)
ClientManager::getInstance()->putOffline(i.second);
delete i.second;
}
}
void AdcHub::handle(AdcCommand::INF, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
string cid;
OnlineUser* u = 0;
if(c.getParam("ID", 0, cid)) {
u = findUser(CID(cid));
if(u) {
if(u->getIdentity().getSID() != c.getFrom()) {
// Same CID but different SID not allowed - buggy hub?
string nick;
if(!c.getParam("NI", 0, nick)) {
nick = "[nick unknown]";
}
fire(ClientListener::StatusMessage(), this, str(F_("%1% (%2%) has same CID {%3%} as %4% (%5%), ignoring")
% u->getIdentity().getNick() % u->getIdentity().getSIDString() % cid % nick % AdcCommand::fromSID(c.getFrom())),
ClientListener::FLAG_IS_SPAM);
return;
}
} else {
u = &getUser(c.getFrom(), CID(cid));
}
} else if(c.getFrom() == AdcCommand::HUB_SID) {
u = &getUser(c.getFrom(), CID());
} else {
u = findUser(c.getFrom());
}
if(!u) {
dcdebug("AdcHub::INF Unknown user / no ID\n");
return;
}
for(auto& i: c.getParameters()) {
if(i.length() < 2)
continue;
u->getIdentity().set(i.c_str(), i.substr(2));
}
if(u->getIdentity().supports(ADCS_FEATURE)) {
u->getUser()->setFlag(User::TLS);
}
if(u->getUser() == getMyIdentity().getUser()) {
state = STATE_NORMAL;
setAutoReconnect(true);
setMyIdentity(u->getIdentity());
updateCounts(false);
}
if(u->getIdentity().isHub()) {
setHubIdentity(u->getIdentity());
fire(ClientListener::HubUpdated(), this);
} else {
updated(*u);
}
}
void AdcHub::handle(AdcCommand::SUP, AdcCommand& c) noexcept {
if(state != STATE_PROTOCOL) /** @todo SUP changes */
return;
bool baseOk = false;
bool tigrOk = false;
for(auto& i: c.getParameters()) {
if(i == BAS0_SUPPORT) {
baseOk = true;
tigrOk = true;
} else if(i == BASE_SUPPORT) {
baseOk = true;
} else if(i == TIGR_SUPPORT) {
tigrOk = true;
}
}
if(!baseOk) {
fire(ClientListener::StatusMessage(), this, _("Failed to negotiate base protocol"));
disconnect(false);
return;
} else if(!tigrOk) {
oldPassword = true;
// Some hubs fake BASE support without TIGR support =/
fire(ClientListener::StatusMessage(), this, _("Hub probably uses an old version of ADC, please encourage the owner to upgrade"));
}
}
void AdcHub::handle(AdcCommand::SID, AdcCommand& c) noexcept {
if(state != STATE_PROTOCOL) {
dcdebug("Invalid state for SID\n");
return;
}
if(c.getParameters().empty())
return;
sid = AdcCommand::toSID(c.getParam(0));
state = STATE_IDENTIFY;
infoImpl();
}
void AdcHub::handle(AdcCommand::MSG, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
auto from = findUser(c.getFrom());
if(!from || from->getIdentity().noChat())
return;
decltype(from) to = nullptr, replyTo = nullptr;
string temp;
string chatMessage = c.getParam(0);
if(c.getParam("PM", 1, temp)) { // add PM<group-cid> as well
to = findUser(c.getTo());
if(!to)
return;
replyTo = findUser(AdcCommand::toSID(temp));
if(!replyTo || PluginManager::getInstance()->runHook(HOOK_CHAT_PM_IN, replyTo, chatMessage))
return;
} else if(PluginManager::getInstance()->runHook(HOOK_CHAT_IN, this, chatMessage))
return;
fire(ClientListener::Message(), this, ChatMessage(chatMessage, from, to, replyTo, c.hasFlag("ME", 1),
c.getParam("TS", 1, temp) ? Util::toInt64(temp) : 0));
}
void AdcHub::handle(AdcCommand::GPA, AdcCommand& c) noexcept {
if(c.getParameters().empty())
return;
salt = c.getParam(0);
state = STATE_VERIFY;
fire(ClientListener::GetPassword(), this);
}
void AdcHub::handle(AdcCommand::QUI, AdcCommand& c) noexcept {
uint32_t s = AdcCommand::toSID(c.getParam(0));
OnlineUser* victim = findUser(s);
if(victim) {
string tmp;
if(c.getParam("MS", 1, tmp)) {
OnlineUser* source = 0;
string tmp2;
if(c.getParam("ID", 1, tmp2)) {
source = findUser(AdcCommand::toSID(tmp2));
}
if(source) {
tmp = str(F_("%1% was kicked by %2%: %3%") % victim->getIdentity().getNick() %
source->getIdentity().getNick() % tmp);
} else {
tmp = str(F_("%1% was kicked: %2%") % victim->getIdentity().getNick() % tmp);
}
fire(ClientListener::StatusMessage(), this, tmp, ClientListener::FLAG_IS_SPAM);
}
putUser(s, c.getParam("DI", 1, tmp));
}
if(s == sid) {
// this QUI is directed to us
string tmp;
if(c.getParam("TL", 1, tmp)) {
if(tmp == "-1") {
setAutoReconnect(false);
} else {
setAutoReconnect(true);
setReconnDelay(Util::toUInt32(tmp));
}
}
if(!victim && c.getParam("MS", 1, tmp)) {
fire(ClientListener::StatusMessage(), this, tmp, ClientListener::FLAG_NORMAL);
}
if(c.getParam("RD", 1, tmp)) {
fire(ClientListener::Redirect(), this, tmp);
}
}
}
void AdcHub::handle(AdcCommand::CTM, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
bool secure = false;
if(protocol == CLIENT_PROTOCOL && !SETTING(REQUIRE_TLS)) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
if(!u->getIdentity().isTcpActive()) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC, "IP unknown", AdcCommand::TYPE_DIRECT).setTo(c.getFrom()));
return;
}
ConnectionManager::getInstance()->adcConnect(*u, port, token, secure);
}
void AdcHub::handle(AdcCommand::RCM, AdcCommand& c) noexcept {
if(c.getParameters().size() < 2) {
return;
}
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& token = c.getParam(1);
bool secure;
if(protocol == CLIENT_PROTOCOL && !SETTING(REQUIRE_TLS)) {
secure = false;
} else if(protocol == SECURE_CLIENT_PROTOCOL && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
if(ClientManager::getInstance()->isActive()) {
connect(*u, token, CONNECTION_TYPE_LAST, secure);
return;
}
if (!u->getIdentity().supports(NAT0_FEATURE))
return;
// Attempt to traverse NATs and/or firewalls with TCP.
// If they respond with their own, symmetric, RNT command, both
// clients call ConnectionManager::adcConnect.
send(AdcCommand(AdcCommand::CMD_NAT, u->getIdentity().getSID(), AdcCommand::TYPE_DIRECT).
addParam(protocol).addParam(std::to_string(sock->getLocalPort())).addParam(token));
}
void AdcHub::handle(AdcCommand::CMD, AdcCommand& c) noexcept {
if(c.getParameters().size() < 1)
return;
const string& name = c.getParam(0);
bool rem = c.hasFlag("RM", 1);
if(rem) {
fire(ClientListener::HubUserCommand(), this, (int)UserCommand::TYPE_REMOVE, 0, name, Util::emptyString);
return;
}
bool sep = c.hasFlag("SP", 1);
string sctx;
if(!c.getParam("CT", 1, sctx))
return;
int ctx = Util::toInt(sctx);
if(ctx <= 0)
return;
if(sep) {
fire(ClientListener::HubUserCommand(), this, (int)UserCommand::TYPE_SEPARATOR, ctx, name, Util::emptyString);
return;
}
bool once = c.hasFlag("CO", 1);
string txt;
if(!c.getParam("TT", 1, txt))
return;
fire(ClientListener::HubUserCommand(), this, (int)(once ? UserCommand::TYPE_RAW_ONCE : UserCommand::TYPE_RAW), ctx, name, txt);
}
void AdcHub::sendUDP(const AdcCommand& cmd) noexcept {
string command;
string ip;
string port;
{
Lock l(cs);
auto i = users.find(cmd.getTo());
if(i == users.end()) {
dcdebug("AdcHub::sendUDP: invalid user\n");
return;
}
OnlineUser& ou = *i->second;
if(!ou.getIdentity().isUdpActive()) {
return;
}
ip = CONNSTATE(INCOMING_CONNECTIONS6) ? ou.getIdentity().getIp() : ou.getIdentity().getIp4();
port = ou.getIdentity().getUdpPort();
command = cmd.toString(ou.getUser()->getCID());
}
try {
udp.writeTo(ip, port, command);
} catch(const SocketException& e) {
dcdebug("AdcHub::sendUDP: write failed: %s\n", e.getError().c_str());
udp.close();
}
}
void AdcHub::handle(AdcCommand::STA, AdcCommand& c) noexcept {
if(c.getParameters().size() < 2)
return;
OnlineUser* u = c.getFrom() == AdcCommand::HUB_SID ? &getUser(c.getFrom(), CID()) : findUser(c.getFrom());
if(!u)
return;
//int severity = Util::toInt(c.getParam(0).substr(0, 1));
if(c.getParam(0).size() != 3) {
return;
}
switch(Util::toInt(c.getParam(0).substr(1))) {
case AdcCommand::ERROR_BAD_PASSWORD:
{
if(c.getType() == AdcCommand::TYPE_INFO) {
setPassword(Util::emptyString);
}
break;
}
case AdcCommand::ERROR_COMMAND_ACCESS:
{
if(c.getType() == AdcCommand::TYPE_INFO) {
string tmp;
if(c.getParam("FC", 1, tmp) && tmp.size() == 4)
forbiddenCommands.insert(AdcCommand::toFourCC(tmp.c_str()));
}
break;
}
case AdcCommand::ERROR_PROTOCOL_UNSUPPORTED:
{
string tmp;
if(c.getParam("PR", 1, tmp)) {
if(tmp == CLIENT_PROTOCOL) {
u->getUser()->setFlag(User::NO_ADC_1_0_PROTOCOL);
} else if(tmp == SECURE_CLIENT_PROTOCOL) {
u->getUser()->setFlag(User::NO_ADCS_0_10_PROTOCOL);
u->getUser()->unsetFlag(User::TLS);
}
// Try again...
ConnectionManager::getInstance()->force(u->getUser());
}
return;
}
}
fire(ClientListener::Message(), this, ChatMessage(c.getParam(1), u));
}
void AdcHub::handle(AdcCommand::SCH, AdcCommand& c) noexcept {
OnlineUser* ou = findUser(c.getFrom());
if(!ou) {
dcdebug("Invalid user in AdcHub::onSCH\n");
return;
}
fire(ClientListener::AdcSearch(), this, c, *ou);
}
void AdcHub::handle(AdcCommand::RES, AdcCommand& c) noexcept {
OnlineUser* ou = findUser(c.getFrom());
if(!ou) {
dcdebug("Invalid user in AdcHub::onRES\n");
return;
}
SearchManager::getInstance()->onRES(c, ou->getUser());
}
void AdcHub::handle(AdcCommand::GET, AdcCommand& c) noexcept {
if(c.getParameters().size() < 5) {
if(!c.getParameters().empty()) {
if(c.getParam(0) == "blom") {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC,
"Too few parameters for blom", AdcCommand::TYPE_HUB));
} else {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unknown transfer type", AdcCommand::TYPE_HUB));
}
} else {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_GENERIC,
"Too few parameters for GET", AdcCommand::TYPE_HUB));
}
return;
}
const string& type = c.getParam(0);
string sk, sh;
if(type == "blom" && c.getParam("BK", 4, sk) && c.getParam("BH", 4, sh)) {
ByteVector v;
size_t m = Util::toUInt32(c.getParam(3)) * 8;
size_t k = Util::toUInt32(sk);
size_t h = Util::toUInt32(sh);
if(k > 8 || k < 1) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported k", AdcCommand::TYPE_HUB));
return;
}
if(h > 64 || h < 1) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported h", AdcCommand::TYPE_HUB));
return;
}
size_t n = ShareManager::getInstance()->getSharedFiles();
// Ideal size for m is n * k / ln(2), but we allow some slack
// When h >= 32, m can't go above 2^h anyway since it's stored in a size_t.
if(m > (5 * Util::roundUp((int64_t)(n * k / log(2.)), (int64_t)64)) || (h < 32 && m > static_cast<size_t>(1U << h))) {
send(AdcCommand(AdcCommand::SEV_FATAL, AdcCommand::ERROR_TRANSFER_GENERIC,
"Unsupported m", AdcCommand::TYPE_HUB));
return;
}
if (m > 0) {
ShareManager::getInstance()->getBloom(v, k, m, h);
}
AdcCommand cmd(AdcCommand::CMD_SND, AdcCommand::TYPE_HUB);
cmd.addParam(c.getParam(0));
cmd.addParam(c.getParam(1));
cmd.addParam(c.getParam(2));
cmd.addParam(c.getParam(3));
cmd.addParam(c.getParam(4));
send(cmd);
if (m > 0) {
send((char*)&v[0], v.size());
}
}
}
void AdcHub::handle(AdcCommand::NAT, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
// bool secure = secureAvail(c.getFrom(), protocol, token);
bool secure = false;
if(protocol == CLIENT_PROTOCOL) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
// Trigger connection attempt sequence locally ...
auto localPort = std::to_string(sock->getLocalPort());
dcdebug("triggering connecting attempt in NAT: remote port = %s, local port = %d\n", port.c_str(), sock->getLocalPort());
ConnectionManager::getInstance()->adcConnect(*u, port, localPort, BufferedSocket::NAT_CLIENT, token, secure);
// ... and signal other client to do likewise.
send(AdcCommand(AdcCommand::CMD_RNT, u->getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(protocol).
addParam(localPort).addParam(token));
}
void AdcHub::handle(AdcCommand::RNT, AdcCommand& c) noexcept {
if(c.getParameters().size() < 3)
return;
// Sent request for NAT traversal cooperation, which
// was acknowledged (with requisite local port information).
OnlineUser* u = findUser(c.getFrom());
if(!u || u->getUser() == ClientManager::getInstance()->getMe())
return;
const string& protocol = c.getParam(0);
const string& port = c.getParam(1);
const string& token = c.getParam(2);
bool secure = false;
if(protocol == CLIENT_PROTOCOL) {
// Nothing special
} else if(protocol == SECURE_CLIENT_PROTOCOL && CryptoManager::getInstance()->TLSOk()) {
secure = true;
} else {
unknownProtocol(c.getFrom(), protocol, token);
return;
}
// Trigger connection attempt sequence locally
dcdebug("triggering connecting attempt in RNT: remote port = %s, local port = %d\n", port.c_str(), sock->getLocalPort());
ConnectionManager::getInstance()->adcConnect(*u, port, std::to_string(sock->getLocalPort()), BufferedSocket::NAT_SERVER, token, secure);
}
void AdcHub::handle(AdcCommand::ZON, AdcCommand& c) noexcept {
if(c.getType() == AdcCommand::TYPE_INFO) {
try {
sock->setMode(BufferedSocket::MODE_ZPIPE);
} catch (const Exception& e) {
dcdebug("AdcHub::handleZON failed with error: %s\n", e.getError().c_str());
}
}
}
void AdcHub::handle(AdcCommand::ZOF, AdcCommand& c) noexcept {
if(c.getType() == AdcCommand::TYPE_INFO) {
try {
sock->setMode(BufferedSocket::MODE_LINE);
} catch (const Exception& e) {
dcdebug("AdcHub::handleZOF failed with error: %s\n", e.getError().c_str());
}
}
}
void AdcHub::connect(const OnlineUser& user, const string& token, ConnectionType type) {
connect(user, token, type, CryptoManager::getInstance()->TLSOk() && user.getUser()->isSet(User::TLS));
}
void AdcHub::connect(const OnlineUser& user, const string& token, ConnectionType type, bool secure) {
if(state != STATE_NORMAL)
return;
const string* proto;
if(secure) {
if(user.getUser()->isSet(User::NO_ADCS_0_10_PROTOCOL)) {
/// @todo log
return;
}
proto = &SECURE_CLIENT_PROTOCOL;
} else {
if(user.getUser()->isSet(User::NO_ADC_1_0_PROTOCOL) || SETTING(REQUIRE_TLS)) {
/// @todo log, consider removing from queue
return;
}
proto = &CLIENT_PROTOCOL;
}
ConnectionManager::getInstance()->addToken(token, user, type);
if(ClientManager::getInstance()->isActive()) {
const string& port = secure ? ConnectionManager::getInstance()->getSecurePort() : ConnectionManager::getInstance()->getPort();
if(port.empty()) {
// Oops?
LogManager::getInstance()->message(str(F_("Not listening for connections - please restart %1%") % APPNAME));
return;
}
send(AdcCommand(AdcCommand::CMD_CTM, user.getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(*proto).addParam(port).addParam(token));
} else {
send(AdcCommand(AdcCommand::CMD_RCM, user.getIdentity().getSID(), AdcCommand::TYPE_DIRECT).addParam(*proto).addParam(token));
}
}
void AdcHub::hubMessage(const string& aMessage, bool thirdPerson) {
if(state != STATE_NORMAL)
return;
if(PluginManager::getInstance()->runHook(HOOK_CHAT_OUT, this, aMessage))
return;
AdcCommand c(AdcCommand::CMD_MSG, AdcCommand::TYPE_BROADCAST);
c.addParam(aMessage);
if(thirdPerson)
c.addParam("ME", "1");
send(c);
}
void AdcHub::privateMessage(const OnlineUser& user, const string& aMessage, bool thirdPerson) {
if(state != STATE_NORMAL)
return;
AdcCommand c(AdcCommand::CMD_MSG, user.getIdentity().getSID(), AdcCommand::TYPE_ECHO);
c.addParam(aMessage);
if(thirdPerson)
c.addParam("ME", "1");
c.addParam("PM", getMySID());
send(c);
}
void AdcHub::sendUserCmd(const UserCommand& command, const ParamMap& params) {
if(state != STATE_NORMAL)
return;
string cmd = Util::formatParams(command.getCommand(), params, escape);
if(command.isChat()) {
if(command.getTo().empty()) {
hubMessage(cmd);
} else {
const string& to = command.getTo();
Lock l(cs);
for(auto& i: users) {
if(i.second->getIdentity().getNick() == to) {
privateMessage(*i.second, cmd);
return;
}
}
}
} else {
send(cmd);
}
}
const vector<StringList>& AdcHub::getSearchExts() {
if(!searchExts.empty())
return searchExts;
// the list is always immutable except for this function where it is initially being filled.
const_cast<vector<StringList>&>(searchExts) = {
// these extensions *must* be sorted alphabetically!
{ "ape", "flac", "m4a", "mid", "mp3", "mpc", "ogg", "ra", "wav", "wma" },
{ "7z", "ace", "arj", "bz2", "gz", "lha", "lzh", "rar", "tar", "z", "zip" },
{ "doc", "docx", "htm", "html", "nfo", "odf", "odp", "ods", "odt", "pdf", "ppt", "pptx", "rtf", "txt", "xls", "xlsx", "xml", "xps" },
{ "app", "bat", "cmd", "com", "dll", "exe", "jar", "msi", "ps1", "vbs", "wsf" },
{ "bmp", "cdr", "eps", "gif", "ico", "img", "jpeg", "jpg", "png", "ps", "psd", "sfw", "tga", "tif", "webp" },
{ "3gp", "asf", "asx", "avi", "divx", "flv", "mkv", "mov", "mp4", "mpeg", "mpg", "ogm", "pxp", "qt", "rm", "rmvb", "swf", "vob", "webm", "wmv" }
};
return searchExts;
}
StringList AdcHub::parseSearchExts(int flag) {
StringList ret;
const auto& searchExts = getSearchExts();
for(auto i = searchExts.cbegin(), ibegin = i, iend = searchExts.cend(); i != iend; ++i) {
if(flag & (1 << (i - ibegin))) {
ret.insert(ret.begin(), i->begin(), i->end());
}
}
return ret;
}
void AdcHub::search(int aSizeMode, int64_t aSize, int aFileType, const string& aString, const string& aToken, const StringList& aExtList, const string& aKey) {
if(state != STATE_NORMAL)
return;
AdcCommand c(AdcCommand::CMD_SCH, AdcCommand::TYPE_BROADCAST);
/* token format: [per-hub unique id] "/" [per-search actual token]
this allows easily knowing which hub a search was sent on when parsing a search result,
whithout having to bother maintaining a list of sent tokens. */
c.addParam("TO", std::to_string(getUniqueId()) + "/" + aToken);
if(aFileType == SearchManager::TYPE_TTH) {
c.addParam("TR", aString);
} else {
if(aSizeMode == SearchManager::SIZE_ATLEAST) {
c.addParam("GE", Util::toString(aSize));
} else if(aSizeMode == SearchManager::SIZE_ATMOST) {
c.addParam("LE", Util::toString(aSize));
}
StringTokenizer<string> st(aString, ' ');
for(auto& i: st.getTokens()) {
c.addParam("AN", i);
}
if(aFileType == SearchManager::TYPE_DIRECTORY) {
c.addParam("TY", "2");
}
if(aExtList.size() > 2) {
StringList exts = aExtList;
sort(exts.begin(), exts.end());
uint8_t gr = 0;
StringList rx;
const auto& searchExts = getSearchExts();
for(auto i = searchExts.cbegin(), ibegin = i, iend = searchExts.cend(); i != iend; ++i) {
const StringList& def = *i;
// gather the exts not present in any of the lists
StringList temp(def.size() + exts.size());
temp = StringList(temp.begin(), set_symmetric_difference(def.begin(), def.end(),
exts.begin(), exts.end(), temp.begin()));
// figure out whether the remaining exts have to be added or removed from the set
StringList rx_;
bool ok = true;
for(auto diff = temp.begin(); diff != temp.end();) {
if(find(def.cbegin(), def.cend(), *diff) == def.cend()) {
++diff; // will be added further below as an "EX"
} else {
if(rx_.size() == 2) {
ok = false;
break;
}
rx_.push_back(*diff);
diff = temp.erase(diff);
}
}
if(!ok) // too many "RX"s necessary - disregard this group
continue;
// let's include this group!
gr += 1 << (i - ibegin);
exts = temp; // the exts to still add (that were not defined in the group)
rx.insert(rx.begin(), rx_.begin(), rx_.end());
if(exts.size() <= 2)
break;
// keep looping to see if there are more exts that can be grouped
}
if(gr) {
// some extensions can be grouped; let's send a command with grouped exts.
AdcCommand c_gr(AdcCommand::CMD_SCH, AdcCommand::TYPE_FEATURE);
c_gr.setFeatures('+' + SEGA_FEATURE);
const auto& params = c.getParameters();
for(auto& i: params)
c_gr.addParam(i);
for(auto& i: exts)
c_gr.addParam("EX", i);
c_gr.addParam("GR", Util::toString(gr));
for(auto& i: rx)
c_gr.addParam("RX", i);
sendSearch(c_gr);
// make sure users with the feature don't receive the search twice.
c.setType(AdcCommand::TYPE_FEATURE);
c.setFeatures('-' + SEGA_FEATURE);
}
}
for(auto& i: aExtList)
c.addParam("EX", i);
}
// Verify that it is an active ADCS hub
if(SETTING(ENABLE_SUDP) && !aKey.empty() && ClientManager::getInstance()->isActive() && isSecure()) {
c.addParam("KY", aKey);
}
sendSearch(c);
}
void AdcHub::sendSearch(AdcCommand& c) {
if(ClientManager::getInstance()->isActive()) {
send(c);
} else {
c.setType(AdcCommand::TYPE_FEATURE);
string features = c.getFeatures();
c.setFeatures(features + '+' + TCP4_FEATURE + '-' + NAT0_FEATURE);
send(c);
c.setFeatures(features + '+' + NAT0_FEATURE);
send(c);
}
}
void AdcHub::password(const string& pwd) {
if(state != STATE_VERIFY)
return;
if(!salt.empty()) {
size_t saltBytes = salt.size() * 5 / 8;
boost::scoped_array<uint8_t> buf(new uint8_t[saltBytes]);
Encoder::fromBase32(salt.c_str(), &buf[0], saltBytes);
TigerHash th;
if(oldPassword) {
CID cid = getMyIdentity().getUser()->getCID();
th.update(cid.data(), CID::SIZE);
}
th.update(pwd.data(), pwd.length());
th.update(&buf[0], saltBytes);
send(AdcCommand(AdcCommand::CMD_PAS, AdcCommand::TYPE_HUB).addParam(Encoder::toBase32(th.finalize(), TigerHash::BYTES)));
salt.clear();
}
}
static void addParam(StringMap& lastInfoMap, AdcCommand& c, const string& var, const string& value) {
auto i = lastInfoMap.find(var);
if(i != lastInfoMap.end()) {
if(i->second != value) {
if(value.empty()) {
lastInfoMap.erase(i);
} else {
i->second = value;
}
c.addParam(var, value);
}
} else if(!value.empty()) {
lastInfoMap.emplace(var, value);
c.addParam(var, value);
}
}
void AdcHub::appendConnectivity(StringMap& lastInfoMap, AdcCommand& c, bool v4, bool v6) {
if (v4) {
if(CONNSETTING(NO_IP_OVERRIDE) && !getUserIp4().empty()) {
addParam(lastInfoMap, c, "I4", Socket::resolve(getUserIp4(), AF_INET));
} else {
addParam(lastInfoMap, c, "I4", "0.0.0.0");
}
if(isActiveV4()) {
addParam(lastInfoMap, c, "U4", SearchManager::getInstance()->getPort());
} else {
addParam(lastInfoMap, c, "U4", "");
}
} else {
addParam(lastInfoMap, c, "I4", "");
addParam(lastInfoMap, c, "U4", "");
}
if (v6) {
if (CONNSETTING(NO_IP_OVERRIDE6) && !getUserIp6().empty()) {
addParam(lastInfoMap, c, "I6", Socket::resolve(getUserIp6(), AF_INET6));
} else {
addParam(lastInfoMap, c, "I6", "::");
}
if(isActiveV6()) {
addParam(lastInfoMap, c, "U6", SearchManager::getInstance()->getPort());
} else {
addParam(lastInfoMap, c, "U6", "");
}
} else {
addParam(lastInfoMap, c, "I6", "");
addParam(lastInfoMap, c, "U6", "");
}
}
void AdcHub::infoImpl() {
if(state != STATE_IDENTIFY && state != STATE_NORMAL)
return;
reloadSettings(false);
AdcCommand c(AdcCommand::CMD_INF, AdcCommand::TYPE_BROADCAST);
if (state == STATE_NORMAL) {
updateCounts(false);
}
addParam(lastInfoMap, c, "ID", ClientManager::getInstance()->getMyCID().toBase32());
addParam(lastInfoMap, c, "PD", ClientManager::getInstance()->getMyPID().toBase32());
addParam(lastInfoMap, c, "NI", get(Nick));
addParam(lastInfoMap, c, "DE", get(Description));
addParam(lastInfoMap, c, "SL", Util::toString(SETTING(SLOTS)));
addParam(lastInfoMap, c, "FS", Util::toString(UploadManager::getInstance()->getFreeSlots()));
addParam(lastInfoMap, c, "SS", ShareManager::getInstance()->getShareSizeString());
addParam(lastInfoMap, c, "SF", std::to_string(ShareManager::getInstance()->getSharedFiles()));
addParam(lastInfoMap, c, "EM", get(Email));
addParam(lastInfoMap, c, "HN", std::to_string(counts[COUNT_NORMAL]));
addParam(lastInfoMap, c, "HR", std::to_string(counts[COUNT_REGISTERED]));
addParam(lastInfoMap, c, "HO", std::to_string(counts[COUNT_OP]));
addParam(lastInfoMap, c, "AP", "++");
addParam(lastInfoMap, c, "VE", VERSIONSTRING);
addParam(lastInfoMap, c, "AW", Util::getAway() ? "1" : Util::emptyString);
int limit = ThrottleManager::getInstance()->getDownLimit();
if (limit > 0) {
addParam(lastInfoMap, c, "DS", Util::toString(limit * 1024));
} else {
addParam(lastInfoMap, c, "DS", Util::emptyString);
}
limit = ThrottleManager::getInstance()->getUpLimit();
if (limit > 0) {
addParam(lastInfoMap, c, "US", Util::toString(limit * 1024));
} else {
addParam(lastInfoMap, c, "US", std::to_string((long)(Util::toDouble(SETTING(UPLOAD_SPEED))*1024*1024/8)));
}
addParam(lastInfoMap, c, "LC", Util::getIETFLang());
string su(SEGA_FEATURE);
if(CryptoManager::getInstance()->TLSOk()) {
su += "," + ADCS_FEATURE;
if(SETTING(ENABLE_CCPM)) {
su += "," + CCPM_FEATURE;
}
auto &kp = CryptoManager::getInstance()->getKeyprint();
addParam(lastInfoMap, c, "KP", CryptoManager::getInstance()->keyprintToString(kp));
}
if(SETTING(ENABLE_SUDP) && isSecure()) {
su += "," + SUDP_FEATURE;
}
bool addV4 = !sock->isV6Valid() || (get(HubSettings::Connection) != SettingsManager::INCOMING_DISABLED);
bool addV6 = sock->isV6Valid() || (get(HubSettings::Connection6) != SettingsManager::INCOMING_DISABLED);
if(addV4 && isActiveV4()) {
su += "," + TCP4_FEATURE;
su += "," + UDP4_FEATURE;
}
if(addV6 && isActiveV6()) {
su += "," + TCP6_FEATURE;
su += "," + UDP6_FEATURE;
}
if ((addV6 && !isActiveV6() && get(HubSettings::Connection6) != SettingsManager::INCOMING_DISABLED) ||
(addV4 && !isActiveV4() && get(HubSettings::Connection) != SettingsManager::INCOMING_DISABLED)) {
su += "," + NAT0_FEATURE;
}
addParam(lastInfoMap, c, "SU", su);
appendConnectivity(lastInfoMap, c, addV4, addV6);
if(!c.getParameters().empty()) {
send(c);
}
}
int64_t AdcHub::getAvailable() const {
Lock l(cs);
int64_t x = 0;
for(auto& i: users) {
x += i.second->getIdentity().getBytesShared();
}
return x;
}
void AdcHub::checkNick(string& nick) {
for(size_t i = 0, n = nick.size(); i < n; ++i) {
if(static_cast<uint8_t>(nick[i]) <= 32) {
nick[i] = '_';
}
}
}
void AdcHub::send(const AdcCommand& cmd) {
if(forbiddenCommands.find(AdcCommand::toFourCC(cmd.getFourCC().c_str())) == forbiddenCommands.end()) {
if(cmd.getType() == AdcCommand::TYPE_UDP)
sendUDP(cmd);
send(cmd.toString(sid));
}
}
void AdcHub::unknownProtocol(uint32_t target, const string& protocol, const string& token) {
AdcCommand cmd(AdcCommand::SEV_FATAL, AdcCommand::ERROR_PROTOCOL_UNSUPPORTED, "Protocol unknown", AdcCommand::TYPE_DIRECT);
cmd.setTo(target);
cmd.addParam("PR", protocol);
cmd.addParam("TO", token);
send(cmd);
}
void AdcHub::on(Connected c) noexcept {
Client::on(c);
if(state != STATE_PROTOCOL) {
return;
}
lastInfoMap.clear();
sid = 0;
forbiddenCommands.clear();
AdcCommand cmd(AdcCommand::CMD_SUP, AdcCommand::TYPE_HUB);
cmd.addParam(BAS0_SUPPORT).addParam(BASE_SUPPORT).addParam(TIGR_SUPPORT);
if(SETTING(HUB_USER_COMMANDS)) {
cmd.addParam(UCM0_SUPPORT);
}
if(SETTING(SEND_BLOOM)) {
cmd.addParam(BLO0_SUPPORT);
}
cmd.addParam(ZLIF_SUPPORT);
send(cmd);
}
void AdcHub::on(Line l, const string& aLine) noexcept {
Client::on(l, aLine);
if(!Text::validateUtf8(aLine)) {
// @todo report to user?
return;
}
if(PluginManager::getInstance()->runHook(HOOK_NETWORK_HUB_IN, this, aLine))
return;
dispatch(aLine);
}
void AdcHub::on(Failed f, const string& aLine) noexcept {
clearUsers();
Client::on(f, aLine);
}
void AdcHub::on(Second s, uint64_t aTick) noexcept {
Client::on(s, aTick);
if(state == STATE_NORMAL && (aTick > (getLastActivity() + 120*1000))) {
send("\n", 1);
}
}
OnlineUserList AdcHub::getUsers() const {
Lock l(cs);
OnlineUserList ret;
ret.reserve(users.size());
for(auto& i: users)
ret.push_back(i.second);
return ret;
}
} // namespace dcpp
MongoDB Logo MongoDB