Util.cc 22 KB

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