Util.cc 25 KB

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