Util.cc 22 KB

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