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
|
/*
* Copyright (C) 2001-2012 Jacek Sieka, arnetheduck on gmail point com
* Copyright (C) 2009-2019 EiskaltDC++ developers
* Copyright (C) 2019 Boris Pek <tehnick-8@yandex.ru>
*
* 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 2 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 "SearchManager.h"
#include "UploadManager.h"
#include "format.h"
#include "ClientManager.h"
#include "ShareManager.h"
#include "SearchResult.h"
#include "LogManager.h"
#include "QueueManager.h"
#include "QueueItem.h"
#include "StringTokenizer.h"
#include "FinishedManager.h"
namespace dcpp {
const char* SearchManager::types[TYPE_LAST] = {
N_("Any"),
N_("Audio"),
N_("Compressed"),
N_("Document"),
N_("Executable"),
N_("Picture"),
N_("Video"),
N_("Directory"),
N_("TTH"),
N_("CD Image")
};
const char* SearchManager::getTypeStr(int type) {
return _(types[type]);
}
SearchManager::SearchManager() :
stop(false)
{
queue.start();
}
SearchManager::~SearchManager() {
if(socket.get()) {
stop = true;
socket->disconnect();
#ifdef _WIN32
join();
#endif
}
}
string SearchManager::normalizeWhitespace(const string& aString){
string::size_type found = 0;
string normalized = aString;
while((found = normalized.find_first_of("\t\n\r", found)) != string::npos) {
normalized[found] = ' ';
found++;
}
return normalized;
}
void SearchManager::search(const string& aName, int64_t aSize, TypeModes aTypeMode /* = TYPE_ANY */, SizeModes aSizeMode /* = SIZE_ATLEAST */, const string& aToken /* = Util::emptyString */, void* aOwner /* = NULL */) {
ClientManager::getInstance()->search(aSizeMode, aSize, aTypeMode, normalizeWhitespace(aName), aToken, aOwner);
}
uint64_t SearchManager::search(StringList& who, const string& aName, int64_t aSize /* = 0 */, TypeModes aTypeMode /* = TYPE_ANY */, SizeModes aSizeMode /* = SIZE_ATLEAST */, const string& aToken /* = Util::emptyString */, const StringList& aExtList, void* aOwner /* = NULL */) {
return ClientManager::getInstance()->search(who, aSizeMode, aSize, aTypeMode, normalizeWhitespace(aName), aToken, aExtList, aOwner);
}
void SearchManager::listen() {
disconnect();
try {
socket.reset(new Socket);
socket->create(Socket::TYPE_UDP);
socket->setBlocking(true);
socket->setSocketOpt(SO_REUSEADDR, 1);
port = socket->bind(Util::toString(SETTING(UDP_PORT)), SETTING(BIND_IFACE)? socket->getIfaceI4(SETTING(BIND_IFACE_NAME)).c_str() : SETTING(BIND_ADDRESS));
start();
} catch(...) {
socket.reset();
throw;
}
}
void SearchManager::disconnect() noexcept {
if(socket.get()) {
stop = true;
queue.shutdown();
socket->disconnect();
port.clear();
join();
socket.reset();
stop = false;
}
}
#define BUFSIZE 8192
int SearchManager::run() {
std::unique_ptr<uint8_t[]> buf(new uint8_t[BUFSIZE]);
int len;
sockaddr_in remoteAddr = { 0 };
while(!stop) {
try {
if (!socket.get()) {
continue;
}
if(socket->wait(400, Socket::WAIT_READ) != Socket::WAIT_READ) {
continue;
}
if ((len = socket->read(&buf[0], BUFSIZE, remoteAddr)) > 0) {
onData(&buf[0], len, inet_ntoa(remoteAddr.sin_addr));
continue;
}
} catch(const SocketException& e) {
dcdebug("SearchManager::run Error: %s\n", e.getError().c_str());
}
bool failed = false;
while(!stop) {
try {
socket->disconnect();
socket->create(Socket::TYPE_UDP);
socket->setBlocking(true);
socket->bind(port, SETTING(BIND_ADDRESS));
if(failed) {
LogManager::getInstance()->message(_("Search enabled again"));
failed = false;
}
break;
} catch(const SocketException& e) {
dcdebug("SearchManager::run Stopped listening: %s\n", e.getError().c_str());
if(!failed) {
LogManager::getInstance()->message(str(F_("Search disabled: %1%") % e.getError()));
failed = true;
}
// Spin for 60 seconds
for(auto i = 0; i < 60 && !stop; ++i) {
Thread::sleep(1000);
}
}
}
}
return 0;
}
int SearchManager::UdpQueue::run() {
string x = Util::emptyString;
string remoteIp = Util::emptyString;
stop = false;
;
while(true) {
if (resultList.empty())
s.wait();
if(stop)
break;
{
Lock l(csudp);
if(resultList.empty()) continue;
x = resultList.front().first;
remoteIp = resultList.front().second;
resultList.pop_front();
}
if(x.compare(0, 4, "$SR ") == 0) {
string::size_type i, j;
// Directories: $SR <nick><0x20><directory><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
// Files: $SR <nick><0x20><filename><0x05><filesize><0x20><free slots>/<total slots><0x05><Hubname><0x20>(<Hubip:port>)
i = 4;
if( (j = x.find(' ', i)) == string::npos) {
continue;
}
string nick = x.substr(i, j-i);
i = j + 1;
// A file has 2 0x05, a directory only one
size_t cnt = count(x.begin() + j, x.end(), 0x05);
SearchResult::Types type = SearchResult::TYPE_FILE;
string file;
int64_t size = 0;
if(cnt == 1) {
// We have a directory...find the first space beyond the first 0x05 from the back
// (dirs might contain spaces as well...clever protocol, eh?)
type = SearchResult::TYPE_DIRECTORY;
// Get past the hubname that might contain spaces
if((j = x.rfind(0x05)) == string::npos) {
continue;
}
// Find the end of the directory info
if((j = x.rfind(' ', j-1)) == string::npos) {
continue;
}
if(j < i + 1) {
continue;
}
file = x.substr(i, j-i) + '\\';
} else if(cnt == 2) {
if( (j = x.find((char)5, i)) == string::npos) {
continue;
}
file = x.substr(i, j-i);
i = j + 1;
if( (j = x.find(' ', i)) == string::npos) {
continue;
}
size = Util::toInt64(x.substr(i, j-i));
}
i = j + 1;
if( (j = x.find('/', i)) == string::npos) {
continue;
}
uint8_t freeSlots = (uint8_t)Util::toInt(x.substr(i, j-i));
i = j + 1;
if( (j = x.find((char)5, i)) == string::npos) {
continue;
}
uint8_t slots = (uint8_t)Util::toInt(x.substr(i, j-i));
i = j + 1;
if( (j = x.rfind(" (")) == string::npos) {
continue;
}
string hubName = x.substr(i, j-i);
i = j + 2;
if( (j = x.rfind(')')) == string::npos) {
continue;
}
string hubIpPort = x.substr(i, j-i);
string url = ClientManager::getInstance()->findHub(hubIpPort);
string encoding = ClientManager::getInstance()->findHubEncoding(url);
nick = Text::toUtf8(nick, encoding);
file = Text::toUtf8(file, encoding);
hubName = Text::toUtf8(hubName, encoding);
UserPtr user = ClientManager::getInstance()->findUser(nick, url);
if(!user) {
// Could happen if hub has multiple URLs / IPs
user = ClientManager::getInstance()->findLegacyUser(nick);
if(!user)
continue;
}
ClientManager::getInstance()->setIPUser(user, remoteIp);
string tth;
if(hubName.compare(0, 4, "TTH:") == 0) {
tth = hubName.substr(4);
StringList names = ClientManager::getInstance()->getHubNames(user->getCID(), Util::emptyString);
hubName = names.empty() ? _("Offline") : Util::toString(names);
}
if(tth.empty() && type == SearchResult::TYPE_FILE) {
continue;
}
SearchResultPtr sr(new SearchResult(user, type, slots, freeSlots, size,
file, hubName, url, remoteIp, TTHValue(tth), Util::emptyString));
SearchManager::getInstance()->fire(SearchManagerListener::SR(), sr);
} else if(x.compare(1, 4, "RES ") == 0 && x[x.length() - 1] == 0x0a) {
AdcCommand c(x.substr(0, x.length()-1));
if(c.getParameters().empty())
continue;
string cid = c.getParam(0);
if(cid.size() != 39)
continue;
UserPtr user = ClientManager::getInstance()->findUser(CID(cid));
if(!user)
continue;
// This should be handled by AdcCommand really...
c.getParameters().erase(c.getParameters().begin());
SearchManager::getInstance()->onRES(c, user, remoteIp);
} if(x.compare(1, 4, "PSR ") == 0 && x[x.length() - 1] == 0x0a) {
AdcCommand c(x.substr(0, x.length()-1));
if(c.getParameters().empty())
continue;
string cid = c.getParam(0);
if(cid.size() != 39)
continue;
UserPtr user = ClientManager::getInstance()->findUser(CID(cid));
// when user == NULL then it is probably NMDC user, check it later
c.getParameters().erase(c.getParameters().begin());
SearchManager::getInstance()->onPSR(c, user, remoteIp);
} /*else if(x.compare(1, 4, "SCH ") == 0 && x[x.length() - 1] == 0x0a) {
try {
respond(AdcCommand(x.substr(0, x.length()-1)));
} catch(ParseException& ) {
}
}*/ // Needs further DoS investigation
Thread::sleep(10);
}
return 0;
}
void SearchManager::onData(const uint8_t* buf, size_t aLen, const string& remoteIp) {
string x((char*)buf, aLen);
queue.addResult(x, remoteIp);
}
void SearchManager::onRES(const AdcCommand& cmd, const UserPtr& from, const string& remoteIp) {
int freeSlots = -1;
int64_t size = -1;
string file;
string tth;
string token;
for(StringIterC i = cmd.getParameters().begin(); i != cmd.getParameters().end(); ++i) {
const string& str = *i;
if(str.compare(0, 2, "FN") == 0) {
file = Util::toNmdcFile(str.substr(2));
} else if(str.compare(0, 2, "SL") == 0) {
freeSlots = Util::toInt(str.substr(2));
} else if(str.compare(0, 2, "SI") == 0) {
size = Util::toInt64(str.substr(2));
} else if(str.compare(0, 2, "TR") == 0) {
tth = str.substr(2);
} else if(str.compare(0, 2, "TO") == 0) {
token = str.substr(2);
}
}
if(!file.empty() && freeSlots != -1 && size != -1) {
/// @todo get the hub this was sent from, to be passed as a hint? (eg by using the token?)
StringList names = ClientManager::getInstance()->getHubNames(from->getCID(), Util::emptyString);
string hubName = names.empty() ? _("Offline") : Util::toString(names);
StringList hubs = ClientManager::getInstance()->getHubs(from->getCID(), Util::emptyString);
string hub = hubs.empty() ? _("Offline") : Util::toString(hubs);
SearchResult::Types type = (file[file.length() - 1] == '\\' ? SearchResult::TYPE_DIRECTORY : SearchResult::TYPE_FILE);
if(type == SearchResult::TYPE_FILE && tth.empty())
return;
uint8_t slots = ClientManager::getInstance()->getSlots(from->getCID());
SearchResultPtr sr(new SearchResult(from, type, slots, (uint8_t)freeSlots, size,
file, hubName, hub, remoteIp, TTHValue(tth), token));
fire(SearchManagerListener::SR(), sr);
}
}
void SearchManager::onPSR(const AdcCommand& cmd, UserPtr from, const string& remoteIp) {
string udpPort;
uint32_t partialCount = 0;
string tth;
string hubIpPort;
string nick;
PartsInfo partialInfo;
for(StringIterC i = cmd.getParameters().begin(); i != cmd.getParameters().end(); ++i) {
const string& str = *i;
if(str.compare(0, 2, "U4") == 0) {
udpPort = str.substr(2);
} else if(str.compare(0, 2, "NI") == 0) {
nick = str.substr(2);
} else if(str.compare(0, 2, "HI") == 0) {
hubIpPort = str.substr(2);
} else if(str.compare(0, 2, "TR") == 0) {
tth = str.substr(2);
} else if(str.compare(0, 2, "PC") == 0) {
partialCount = Util::toUInt32(str.substr(2))*2;
} else if(str.compare(0, 2, "PI") == 0) {
StringTokenizer<string> tok(str.substr(2), ',');
for(auto& i : tok.getTokens()) {
partialInfo.push_back((uint16_t)Util::toInt(i));
}
}
}
string url = ClientManager::getInstance()->findHub(hubIpPort);
if(!from || from == ClientManager::getInstance()->getMe()) {
// for NMDC support
if(nick.empty() || hubIpPort.empty()) {
return;
}
from = ClientManager::getInstance()->findUser(nick, url);
if(!from) {
// Could happen if hub has multiple URLs / IPs
from = ClientManager::getInstance()->findLegacyUser(nick);
if(!from) {
dcdebug("Search result from unknown user");
return;
}
}
}
ClientManager::getInstance()->setIPUser(from, remoteIp, udpPort);
if(partialInfo.size() != partialCount) {
// what to do now ? just ignore partial search result :-/
return;
}
PartsInfo outPartialInfo;
QueueItem::PartialSource ps(from->isNMDC() ? ClientManager::getInstance()->getClient(url)->getMyIdentity().getNick() : Util::emptyString, hubIpPort, remoteIp, udpPort);
ps.setPartialInfo(partialInfo);
QueueManager::getInstance()->handlePartialResult(from, url, TTHValue(tth), ps, outPartialInfo);
if((Util::toInt(udpPort) > 0) && !outPartialInfo.empty()) {
try {
AdcCommand cmd = SearchManager::getInstance()->toPSR(false, ps.getMyNick(), hubIpPort, tth, outPartialInfo);
ClientManager::getInstance()->send(cmd, from->getCID());
} catch(...) {
dcdebug("Partial search caught error\n");
}
}
}
void SearchManager::respond(const AdcCommand& adc, const CID& from, bool isUdpActive, const string& hubIpPort) {
// Filter own searches
if(from == ClientManager::getInstance()->getMe()->getCID())
return;
UserPtr p = ClientManager::getInstance()->findUser(from);
if(!p)
return;
SearchResultList results;
ShareManager::getInstance()->search(results, adc.getParameters(), isUdpActive ? 10 : 5);
string token;
adc.getParam("TO", 0, token);
// TODO: don't send replies to passive users
if(results.empty()) {
string tth;
if(!adc.getParam("TR", 0, tth))
return;
PartsInfo partialInfo;
if(!QueueManager::getInstance()->handlePartialSearch(TTHValue(tth), partialInfo)) {
// if not found, try to find in finished list
if(!FinishedManager::getInstance()->handlePartialRequest(TTHValue(tth), partialInfo)) {
return;
}
}
AdcCommand cmd = toPSR(true, Util::emptyString, hubIpPort, tth, partialInfo);
ClientManager::getInstance()->send(cmd, from);
return;
}
for(SearchResultList::const_iterator i = results.begin(); i != results.end(); ++i) {
AdcCommand cmd = (*i)->toRES(AdcCommand::TYPE_UDP);
if(!token.empty())
cmd.addParam("TO", token);
ClientManager::getInstance()->send(cmd, from);
}
}
string SearchManager::getPartsString(const PartsInfo& partsInfo) const {
string ret;
for(PartsInfo::const_iterator i = partsInfo.begin(); i < partsInfo.end(); i+=2){
ret += Util::toString(*i) + "," + Util::toString(*(i+1)) + ",";
}
return ret.substr(0, ret.size()-1);
}
AdcCommand SearchManager::toPSR(bool wantResponse, const string& myNick, const string& hubIpPort, const string& tth, const vector<uint16_t>& partialInfo) const {
AdcCommand cmd(AdcCommand::CMD_PSR, AdcCommand::TYPE_UDP);
if(!myNick.empty())
cmd.addParam("NI", Text::utf8ToAcp(myNick));
cmd.addParam("HI", hubIpPort);
cmd.addParam("U4", (wantResponse && ClientManager::getInstance()->isActive(hubIpPort)) ? SearchManager::getInstance()->getPort() : Util::emptyString);
cmd.addParam("TR", tth);
cmd.addParam("PC", Util::toString(partialInfo.size() / 2));
cmd.addParam("PI", getPartsString(partialInfo));
return cmd;
}
} // namespace dcpp
|