Util.cc 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "Util.h"
  36. #include "File.h"
  37. #include "message.h"
  38. #include "Randomizer.h"
  39. #include "a2netcompat.h"
  40. #include "DlAbortEx.h"
  41. #include "BitfieldMan.h"
  42. #include "DefaultDiskWriter.h"
  43. #include "FatalException.h"
  44. #include "FileEntry.h"
  45. #include "StringFormat.h"
  46. #include "A2STR.h"
  47. #include <signal.h>
  48. #include <limits.h>
  49. #include <stdint.h>
  50. #include <cerrno>
  51. #include <cassert>
  52. #include <cstring>
  53. #include <cstdio>
  54. #include <cstdlib>
  55. #include <iomanip>
  56. #include <sstream>
  57. #include <ostream>
  58. #include <algorithm>
  59. #ifndef HAVE_SLEEP
  60. # ifdef HAVE_WINSOCK_H
  61. # define WIN32_LEAN_AND_MEAN
  62. # include <windows.h>
  63. # endif // HAVE_WINSOCK_H
  64. #endif // HAVE_SLEEP
  65. // For libc6 which doesn't define ULLONG_MAX properly because of broken limits.h
  66. #ifndef ULLONG_MAX
  67. # define ULLONG_MAX 18446744073709551615ULL
  68. #endif // ULLONG_MAX
  69. namespace aria2 {
  70. const std::string Util::DEFAULT_TRIM_CHARSET("\r\n\t ");
  71. std::string Util::trim(const std::string& src, const std::string& trimCharset)
  72. {
  73. std::string temp(src);
  74. trimSelf(temp, trimCharset);
  75. return temp;
  76. }
  77. void Util::trimSelf(std::string& str, const std::string& trimCharset)
  78. {
  79. std::string::size_type first = str.find_first_not_of(trimCharset);
  80. if(first == std::string::npos) {
  81. str.clear();
  82. } else {
  83. std::string::size_type last = str.find_last_not_of(trimCharset)+1;
  84. str.erase(last);
  85. str.erase(0, first);
  86. }
  87. }
  88. void Util::split(std::pair<std::string, std::string>& hp, const std::string& src, char delim)
  89. {
  90. hp.first = A2STR::NIL;
  91. hp.second = A2STR::NIL;
  92. std::string::size_type p = src.find(delim);
  93. if(p == std::string::npos) {
  94. hp.first = src;
  95. hp.second = A2STR::NIL;
  96. } else {
  97. hp.first = trim(src.substr(0, p));
  98. hp.second = trim(src.substr(p+1));
  99. }
  100. }
  101. std::pair<std::string, std::string> Util::split(const std::string& src, const std::string& delims)
  102. {
  103. std::pair<std::string, std::string> hp;
  104. hp.first = A2STR::NIL;
  105. hp.second = A2STR::NIL;
  106. std::string::size_type p = src.find_first_of(delims);
  107. if(p == std::string::npos) {
  108. hp.first = src;
  109. hp.second = A2STR::NIL;
  110. } else {
  111. hp.first = trim(src.substr(0, p));
  112. hp.second = trim(src.substr(p+1));
  113. }
  114. return hp;
  115. }
  116. int64_t Util::difftv(struct timeval tv1, struct timeval tv2) {
  117. if((tv1.tv_sec < tv2.tv_sec) ||
  118. ((tv1.tv_sec == tv2.tv_sec) && (tv1.tv_usec < tv2.tv_usec))) {
  119. return 0;
  120. }
  121. return ((int64_t)(tv1.tv_sec-tv2.tv_sec)*1000000+
  122. tv1.tv_usec-tv2.tv_usec);
  123. }
  124. int32_t Util::difftvsec(struct timeval tv1, struct timeval tv2) {
  125. if(tv1.tv_sec < tv2.tv_sec) {
  126. return 0;
  127. }
  128. return tv1.tv_sec-tv2.tv_sec;
  129. }
  130. void Util::slice(std::deque<std::string>& result, const std::string& src, char delim, bool doTrim) {
  131. std::string::size_type p = 0;
  132. while(1) {
  133. std::string::size_type np = src.find(delim, p);
  134. if(np == std::string::npos) {
  135. std::string term = src.substr(p);
  136. if(doTrim) {
  137. term = trim(term);
  138. }
  139. if(term.size()) {
  140. result.push_back(term);
  141. }
  142. break;
  143. }
  144. std::string term = src.substr(p, np-p);
  145. if(doTrim) {
  146. term = trim(term);
  147. }
  148. p = np+1;
  149. if(term.size()) {
  150. result.push_back(term);
  151. }
  152. }
  153. }
  154. bool Util::startsWith(const std::string& target, const std::string& part) {
  155. if(target.size() < part.size()) {
  156. return false;
  157. }
  158. if(part.empty()) {
  159. return true;
  160. }
  161. if(target.find(part) == 0) {
  162. return true;
  163. } else {
  164. return false;
  165. }
  166. }
  167. bool Util::endsWith(const std::string& target, const std::string& part) {
  168. if(target.size() < part.size()) {
  169. return false;
  170. }
  171. if(part.empty()) {
  172. return true;
  173. }
  174. if(target.rfind(part) == target.size()-part.size()) {
  175. return true;
  176. } else {
  177. return false;
  178. }
  179. }
  180. std::string Util::replace(const std::string& target, const std::string& oldstr, const std::string& newstr) {
  181. if(target.empty() || oldstr.empty()) {
  182. return target;
  183. }
  184. std::string result;
  185. std::string::size_type p = 0;
  186. std::string::size_type np = target.find(oldstr);
  187. while(np != std::string::npos) {
  188. result += target.substr(p, np-p)+newstr;
  189. p = np+oldstr.size();
  190. np = target.find(oldstr, p);
  191. }
  192. result += target.substr(p);
  193. return result;
  194. }
  195. bool Util::shouldUrlencode(const char c)
  196. {
  197. return !(// ALPHA
  198. ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') ||
  199. // DIGIT
  200. ('0' <= c && c <= '9') ||
  201. // safe
  202. '$' == c || '-' == c || '_' == c || '.' == c ||
  203. // extra
  204. '!' == c || '*' == c || '\'' == c ||'(' == c ||
  205. ')' == c || ',' == c ||
  206. // reserved
  207. ';' == c || '/' == c || '?' == c || ':' == c ||
  208. '@' == c || '&' == c || '=' == c || '+' == c);
  209. }
  210. std::string Util::urlencode(const unsigned char* target, size_t len) {
  211. std::string dest;
  212. for(size_t i = 0; i < len; i++) {
  213. if(shouldUrlencode(target[i])) {
  214. dest.append(StringFormat("%%%02x", target[i]).str());
  215. } else {
  216. dest += target[i];
  217. }
  218. }
  219. return dest;
  220. }
  221. std::string Util::torrentUrlencode(const unsigned char* target, size_t len) {
  222. std::string dest;
  223. for(size_t i = 0; i < len; i++) {
  224. if(('0' <= target[i] && target[i] <= '9') ||
  225. ('A' <= target[i] && target[i] <= 'Z') ||
  226. ('a' <= target[i] && target[i] <= 'z')) {
  227. dest += target[i];
  228. } else {
  229. dest.append(StringFormat("%%%02x", target[i]).str());
  230. }
  231. }
  232. return dest;
  233. }
  234. std::string Util::urldecode(const std::string& target) {
  235. std::string result;
  236. for(std::string::const_iterator itr = target.begin();
  237. itr != target.end(); itr++) {
  238. if(*itr == '%') {
  239. if(itr+1 != target.end() && itr+2 != target.end() &&
  240. isxdigit(*(itr+1)) && isxdigit(*(itr+2))) {
  241. result += Util::parseInt(std::string(itr+1, itr+3), 16);
  242. itr += 2;
  243. } else {
  244. result += *itr;
  245. }
  246. } else {
  247. result += *itr;
  248. }
  249. }
  250. return result;
  251. }
  252. std::string Util::toHex(const unsigned char* src, size_t len) {
  253. char* temp = new char[len*2+1];
  254. for(size_t i = 0; i < len; i++) {
  255. sprintf(temp+i*2, "%02x", src[i]);
  256. }
  257. temp[len*2] = '\0';
  258. std::string hex = temp;
  259. delete [] temp;
  260. return hex;
  261. }
  262. FILE* Util::openFile(const std::string& filename, const std::string& mode) {
  263. FILE* file = fopen(filename.c_str(), mode.c_str());
  264. return file;
  265. }
  266. void Util::fileCopy(const std::string& dest, const std::string& src) {
  267. File file(src);
  268. rangedFileCopy(dest, src, 0, file.size());
  269. }
  270. void Util::rangedFileCopy(const std::string& dest, const std::string& src, off_t srcOffset, uint64_t length)
  271. {
  272. size_t bufSize = 4096;
  273. unsigned char buf[bufSize];
  274. DefaultDiskWriter srcdw;
  275. DefaultDiskWriter destdw;
  276. srcdw.openExistingFile(src);
  277. destdw.initAndOpenFile(dest);
  278. lldiv_t res = lldiv(length, bufSize);
  279. unsigned int x = res.quot;
  280. unsigned int r = res.rem;
  281. off_t initialOffset = srcOffset;
  282. for(unsigned int i = 0; i < x; ++i) {
  283. size_t readLength = 0;
  284. while(readLength < bufSize) {
  285. ssize_t ret = srcdw.readData(buf, bufSize-readLength, srcOffset);
  286. destdw.writeData(buf, ret, srcOffset-initialOffset);
  287. srcOffset += ret;
  288. readLength += ret;
  289. }
  290. }
  291. if(r > 0) {
  292. size_t readLength = 0;
  293. while(readLength < r) {
  294. ssize_t ret = srcdw.readData(buf, r-readLength, srcOffset);
  295. destdw.writeData(buf, ret, srcOffset-initialOffset);
  296. srcOffset += ret;
  297. readLength += ret;
  298. }
  299. }
  300. }
  301. bool Util::isPowerOf(int num, int base) {
  302. if(base <= 0) { return false; }
  303. if(base == 1) { return true; }
  304. while(num%base == 0) {
  305. num /= base;
  306. if(num == 1) {
  307. return true;
  308. }
  309. }
  310. return false;
  311. }
  312. std::string Util::secfmt(time_t sec) {
  313. std::string str;
  314. if(sec >= 3600) {
  315. str = itos(sec/3600)+"h";
  316. sec %= 3600;
  317. }
  318. if(sec >= 60) {
  319. int min = sec/60;
  320. if(min < 10) {
  321. str += "0";
  322. }
  323. str += itos(min)+"m";
  324. sec %= 60;
  325. }
  326. if(sec < 10) {
  327. str += "0";
  328. }
  329. str += itos(sec)+"s";
  330. return str;
  331. }
  332. size_t Util::expandBuffer(char** pbuf, size_t curLength, size_t newLength) {
  333. char* newbuf = new char[newLength];
  334. memcpy(newbuf, *pbuf, curLength);
  335. delete [] *pbuf;
  336. *pbuf = newbuf;
  337. return newLength;
  338. }
  339. int getNum(const char* buf, int offset, size_t length) {
  340. char* temp = new char[length+1];
  341. memcpy(temp, buf+offset, length);
  342. temp[length] = '\0';
  343. int x = strtol(temp, 0, 10);
  344. delete [] temp;
  345. return x;
  346. }
  347. void unfoldSubRange(const std::string& src, std::deque<int>& range) {
  348. if(src.empty()) {
  349. return;
  350. }
  351. std::string::size_type p = src.find_first_of(",-");
  352. if(p == 0) {
  353. return;
  354. } else if(p == std::string::npos) {
  355. range.push_back(atoi(src.c_str()));
  356. } else {
  357. if(src.at(p) == ',') {
  358. int num = getNum(src.c_str(), 0, p);
  359. range.push_back(num);
  360. unfoldSubRange(src.substr(p+1), range);
  361. } else if(src.at(p) == '-') {
  362. std::string::size_type rightNumBegin = p+1;
  363. std::string::size_type nextDelim = src.find_first_of(",", rightNumBegin);
  364. if(nextDelim == std::string::npos) {
  365. nextDelim = src.size();
  366. }
  367. int left = getNum(src.c_str(), 0, p);
  368. int right = getNum(src.c_str(), rightNumBegin, nextDelim-rightNumBegin);
  369. for(int i = left; i <= right; i++) {
  370. range.push_back(i);
  371. }
  372. if(src.size() > nextDelim) {
  373. unfoldSubRange(src.substr(nextDelim+1), range);
  374. }
  375. }
  376. }
  377. }
  378. void Util::unfoldRange(const std::string& src, std::deque<int>& range) {
  379. unfoldSubRange(src, range);
  380. std::sort(range.begin(), range.end());
  381. range.erase(std::unique(range.begin(), range.end()), range.end());
  382. }
  383. int32_t Util::parseInt(const std::string& s, int32_t base)
  384. {
  385. std::string trimed = Util::trim(s);
  386. if(trimed.empty()) {
  387. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  388. "empty string").str());
  389. }
  390. char* stop;
  391. errno = 0;
  392. long int v = strtol(trimed.c_str(), &stop, base);
  393. if(*stop != '\0') {
  394. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  395. trimed.c_str()).str());
  396. } else if((((v == LONG_MIN) || (v == LONG_MAX)) && (errno == ERANGE)) ||
  397. (v > INT32_MAX) ||
  398. (v < INT32_MIN)) {
  399. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  400. trimed.c_str()).str());
  401. }
  402. return v;
  403. }
  404. uint32_t Util::parseUInt(const std::string& s, int base)
  405. {
  406. std::string trimed = Util::trim(s);
  407. if(trimed.empty()) {
  408. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  409. "empty string").str());
  410. }
  411. // We don't allow negative number.
  412. if(trimed[0] == '-') {
  413. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  414. trimed.c_str()).str());
  415. }
  416. char* stop;
  417. errno = 0;
  418. unsigned long int v = strtoul(trimed.c_str(), &stop, base);
  419. if(*stop != '\0') {
  420. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  421. trimed.c_str()).str());
  422. } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
  423. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  424. trimed.c_str()).str());
  425. }
  426. return v;
  427. }
  428. int64_t Util::parseLLInt(const std::string& s, int32_t base)
  429. {
  430. std::string trimed = Util::trim(s);
  431. if(trimed.empty()) {
  432. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  433. "empty string").str());
  434. }
  435. char* stop;
  436. errno = 0;
  437. int64_t v = strtoll(trimed.c_str(), &stop, base);
  438. if(*stop != '\0') {
  439. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  440. trimed.c_str()).str());
  441. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  442. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  443. trimed.c_str()).str());
  444. }
  445. return v;
  446. }
  447. uint64_t Util::parseULLInt(const std::string& s, int base)
  448. {
  449. std::string trimed = Util::trim(s);
  450. if(trimed.empty()) {
  451. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  452. "empty string").str());
  453. }
  454. // We don't allow negative number.
  455. if(trimed[0] == '-') {
  456. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  457. trimed.c_str()).str());
  458. }
  459. char* stop;
  460. errno = 0;
  461. uint64_t v = strtoull(trimed.c_str(), &stop, base);
  462. if(*stop != '\0') {
  463. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  464. trimed.c_str()).str());
  465. } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
  466. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  467. trimed.c_str()).str());
  468. }
  469. return v;
  470. }
  471. IntSequence Util::parseIntRange(const std::string& src)
  472. {
  473. IntSequence::Values values;
  474. std::string temp = src;
  475. while(temp.size()) {
  476. std::pair<std::string, std::string> p = Util::split(temp, ",");
  477. temp = p.second;
  478. if(p.first.empty()) {
  479. continue;
  480. }
  481. if(p.first.find("-") == std::string::npos) {
  482. int32_t v = Util::parseInt(p.first.c_str());
  483. values.push_back(IntSequence::Value(v, v+1));
  484. } else {
  485. std::pair<std::string, std::string> vp = Util::split(p.first.c_str(), "-");
  486. if(vp.first.empty() || vp.second.empty()) {
  487. throw DlAbortEx
  488. (StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str());
  489. }
  490. int32_t v1 = Util::parseInt(vp.first.c_str());
  491. int32_t v2 = Util::parseInt(vp.second.c_str());
  492. values.push_back(IntSequence::Value(v1, v2+1));
  493. }
  494. }
  495. return values;
  496. }
  497. std::string Util::getContentDispositionFilename(const std::string& header) {
  498. static const std::string keyName = "filename=";
  499. std::string::size_type attributesp = header.find(keyName);
  500. if(attributesp == std::string::npos) {
  501. return A2STR::NIL;
  502. }
  503. std::string::size_type filenamesp = attributesp+keyName.size();
  504. std::string::size_type filenameep;
  505. if(filenamesp == header.size()) {
  506. return A2STR::NIL;
  507. }
  508. if(header[filenamesp] == '\'' || header[filenamesp] == '"') {
  509. char quoteChar = header[filenamesp];
  510. filenameep = header.find(quoteChar, filenamesp+1);
  511. } else {
  512. filenameep = header.find(';', filenamesp);
  513. }
  514. if(filenameep == std::string::npos) {
  515. filenameep = header.size();
  516. }
  517. static const std::string TRIMMED("\r\n '\"");
  518. return trim(header.substr(filenamesp, filenameep-filenamesp), TRIMMED);
  519. }
  520. static int nbits[] = {
  521. 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  522. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  523. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  524. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  525. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  526. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  527. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  528. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  529. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  530. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  531. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  532. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  533. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  534. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  535. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  536. 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8,
  537. };
  538. unsigned int Util::countBit(uint32_t n) {
  539. return
  540. nbits[n&0xffu]+
  541. nbits[(n >> 8)&0xffu]+
  542. nbits[(n >> 16)&0xffu]+
  543. nbits[(n >> 24)&0xffu];
  544. }
  545. std::string Util::randomAlpha(size_t length, const RandomizerHandle& randomizer) {
  546. static const char *random_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  547. std::string str;
  548. for(size_t i = 0; i < length; i++) {
  549. size_t index = randomizer->getRandomNumber(strlen(random_chars));
  550. str += random_chars[index];
  551. }
  552. return str;
  553. }
  554. std::string Util::toUpper(const std::string& src) {
  555. std::string temp = src;
  556. std::transform(temp.begin(), temp.end(), temp.begin(), ::toupper);
  557. return temp;
  558. }
  559. std::string Util::toLower(const std::string& src) {
  560. std::string temp = src;
  561. std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
  562. return temp;
  563. }
  564. bool Util::isNumbersAndDotsNotation(const std::string& name) {
  565. struct sockaddr_in sockaddr;
  566. if(inet_aton(name.c_str(), &sockaddr.sin_addr)) {
  567. return true;
  568. } else {
  569. return false;
  570. }
  571. }
  572. void Util::setGlobalSignalHandler(int sig, void (*handler)(int), int flags) {
  573. #ifdef HAVE_SIGACTION
  574. struct sigaction sigact;
  575. sigact.sa_handler = handler;
  576. sigact.sa_flags = flags;
  577. sigemptyset(&sigact.sa_mask);
  578. sigaction(sig, &sigact, NULL);
  579. #else
  580. signal(sig, handler);
  581. #endif // HAVE_SIGACTION
  582. }
  583. void Util::indexRange(size_t& startIndex, size_t& endIndex,
  584. off_t offset, size_t srcLength, size_t destLength)
  585. {
  586. int64_t _startIndex = offset/destLength;
  587. int64_t _endIndex = (offset+srcLength-1)/destLength;
  588. assert(_startIndex <= INT32_MAX);
  589. assert(_endIndex <= INT32_MAX);
  590. startIndex = _startIndex;
  591. endIndex = _endIndex;
  592. }
  593. std::string Util::getHomeDir()
  594. {
  595. const char* p = getenv("HOME");
  596. if(p) {
  597. return p;
  598. } else {
  599. return A2STR::NIL;
  600. }
  601. }
  602. int64_t Util::getRealSize(const std::string& sizeWithUnit)
  603. {
  604. std::string::size_type p = sizeWithUnit.find_first_of("KM");
  605. std::string size;
  606. int32_t mult = 1;
  607. if(p == std::string::npos) {
  608. size = sizeWithUnit;
  609. } else {
  610. if(sizeWithUnit[p] == 'K') {
  611. mult = 1024;
  612. } else if(sizeWithUnit[p] == 'M') {
  613. mult = 1024*1024;
  614. }
  615. size = sizeWithUnit.substr(0, p);
  616. }
  617. int64_t v = Util::parseLLInt(size);
  618. if(v < 0) {
  619. throw DlAbortEx
  620. (StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str());
  621. } else if(INT64_MAX/mult < v) {
  622. throw DlAbortEx(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  623. "overflow/underflow").str());
  624. }
  625. return v*mult;
  626. }
  627. std::string Util::abbrevSize(int64_t size)
  628. {
  629. if(size < 1024) {
  630. return Util::itos(size, true);
  631. }
  632. char units[] = { 'K', 'M' };
  633. size_t numUnit = sizeof(units)/sizeof(char);
  634. size_t i = 0;
  635. int r = size&0x3ff;
  636. size >>= 10;
  637. for(; i < numUnit-1 && size >= 1024; ++i) {
  638. r = size&0x3ff;
  639. size >>= 10;
  640. }
  641. return Util::itos(size, true)+"."+Util::itos(r*10/1024)+units[i]+"i";
  642. }
  643. time_t Util::httpGMT(const std::string& httpStdTime)
  644. {
  645. struct tm tm;
  646. memset(&tm, 0, sizeof(tm));
  647. char* r = strptime(httpStdTime.c_str(), "%a, %Y-%m-%d %H:%M:%S GMT", &tm);
  648. if(r != httpStdTime.c_str()+httpStdTime.size()) {
  649. return -1;
  650. }
  651. time_t thetime = timegm(&tm);
  652. if(thetime == -1) {
  653. if(tm.tm_year >= 2038-1900) {
  654. thetime = INT32_MAX;
  655. }
  656. }
  657. return thetime;
  658. }
  659. void Util::toStream(std::ostream& os, const FileEntries& fileEntries)
  660. {
  661. os << _("Files:") << "\n";
  662. os << "idx|path/length" << "\n";
  663. os << "===+===========================================================================" << "\n";
  664. int32_t count = 1;
  665. for(FileEntries::const_iterator itr = fileEntries.begin();
  666. itr != fileEntries.end(); count++, itr++) {
  667. os << std::setw(3) << count << "|" << (*itr)->getPath() << "\n";
  668. os << " |" << Util::abbrevSize((*itr)->getLength()) << "B" << "\n";
  669. os << "---+---------------------------------------------------------------------------" << "\n";
  670. }
  671. }
  672. void Util::sleep(long seconds) {
  673. #ifdef HAVE_SLEEP
  674. ::sleep(seconds);
  675. #elif defined(HAVE_USLEEP)
  676. ::usleep(seconds * 1000000);
  677. #elif defined(HAVE_WINSOCK2_H)
  678. ::Sleep(seconds * 1000);
  679. #else
  680. #error no sleep function is available (nanosleep?)
  681. #endif
  682. }
  683. void Util::usleep(long microseconds) {
  684. #ifdef HAVE_USLEEP
  685. ::usleep(microseconds);
  686. #elif defined(HAVE_WINSOCK2_H)
  687. LARGE_INTEGER current, freq, end;
  688. static enum {GET_FREQUENCY, GET_MICROSECONDS, SKIP_MICROSECONDS} state = GET_FREQUENCY;
  689. if (state == GET_FREQUENCY) {
  690. if (QueryPerformanceFrequency(&freq))
  691. state = GET_MICROSECONDS;
  692. else
  693. state = SKIP_MICROSECONDS;
  694. }
  695. long msec = microseconds / 1000;
  696. microseconds %= 1000;
  697. if (state == GET_MICROSECONDS && microseconds) {
  698. QueryPerformanceCounter(&end);
  699. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  700. while (QueryPerformanceCounter(&current) && (current.QuadPart <= end.QuadPart))
  701. /* noop */ ;
  702. }
  703. if (msec)
  704. Sleep(msec);
  705. #else
  706. #error no usleep function is available (nanosleep?)
  707. #endif
  708. }
  709. bool Util::isNumber(const std::string& what)
  710. {
  711. if(what.empty()) {
  712. return false;
  713. }
  714. for(uint32_t i = 0; i < what.size(); ++i) {
  715. if(!isdigit(what[i])) {
  716. return false;
  717. }
  718. }
  719. return true;
  720. }
  721. bool Util::isLowercase(const std::string& what)
  722. {
  723. if(what.empty()) {
  724. return false;
  725. }
  726. for(uint32_t i = 0; i < what.size(); ++i) {
  727. if(!('a' <= what[i] && what[i] <= 'z')) {
  728. return false;
  729. }
  730. }
  731. return true;
  732. }
  733. bool Util::isUppercase(const std::string& what)
  734. {
  735. if(what.empty()) {
  736. return false;
  737. }
  738. for(uint32_t i = 0; i < what.size(); ++i) {
  739. if(!('A' <= what[i] && what[i] <= 'Z')) {
  740. return false;
  741. }
  742. }
  743. return true;
  744. }
  745. unsigned int Util::alphaToNum(const std::string& alphabets)
  746. {
  747. if(alphabets.empty()) {
  748. return 0;
  749. }
  750. char base;
  751. if(islower(alphabets[0])) {
  752. base = 'a';
  753. } else {
  754. base = 'A';
  755. }
  756. uint64_t num = 0;
  757. for(size_t i = 0; i < alphabets.size(); ++i) {
  758. unsigned int v = alphabets[i]-base;
  759. num = num*26+v;
  760. if(num > UINT32_MAX) {
  761. return 0;
  762. }
  763. }
  764. return num;
  765. }
  766. void Util::mkdirs(const std::string& dirpath)
  767. {
  768. File dir(dirpath);
  769. if(dir.isDir()) {
  770. // do nothing
  771. } else if(dir.exists()) {
  772. throw DlAbortEx
  773. (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
  774. "File already exists.").str());
  775. } else if(!dir.mkdirs()) {
  776. throw DlAbortEx
  777. (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
  778. strerror(errno)).str());
  779. }
  780. }
  781. void Util::convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  782. {
  783. size_t numBlock = dest->countBlock();
  784. for(size_t index = 0; index < numBlock; ++index) {
  785. if(src->isBitSetOffsetRange((uint64_t)index*dest->getBlockLength(),
  786. dest->getBlockLength())) {
  787. dest->setBit(index);
  788. }
  789. }
  790. }
  791. std::string Util::toString(const BinaryStreamHandle& binaryStream)
  792. {
  793. std::stringstream strm;
  794. char data[2048];
  795. while(1) {
  796. int32_t dataLength = binaryStream->readData((unsigned char*)data, sizeof(data), strm.tellp());
  797. strm.write(data, dataLength);
  798. if(dataLength == 0) {
  799. break;
  800. }
  801. }
  802. return strm.str();
  803. }
  804. #ifdef HAVE_POSIX_MEMALIGN
  805. /**
  806. * In linux 2.6, alignment and size should be a multiple of 512.
  807. */
  808. void* Util::allocateAlignedMemory(size_t alignment, size_t size)
  809. {
  810. void* buffer;
  811. int res;
  812. if((res = posix_memalign(&buffer, alignment, size)) != 0) {
  813. throw FatalException
  814. (StringFormat("Error in posix_memalign: %s", strerror(res)).str());
  815. }
  816. return buffer;
  817. }
  818. #endif // HAVE_POSIX_MEMALIGN
  819. std::pair<std::string, uint16_t>
  820. Util::getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  821. {
  822. char host[NI_MAXHOST];
  823. char service[NI_MAXSERV];
  824. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  825. NI_NUMERICHOST|NI_NUMERICSERV);
  826. if(s != 0) {
  827. throw DlAbortEx(StringFormat("Failed to get hostname and port. cause: %s",
  828. gai_strerror(s)).str());
  829. }
  830. return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO
  831. }
  832. } // namespace aria2