Util.cc 24 KB

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