util.cc 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503
  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 <sstream>
  45. #include <ostream>
  46. #include <algorithm>
  47. #include <fstream>
  48. #include <iomanip>
  49. #ifndef HAVE_SLEEP
  50. # ifdef HAVE_WINSOCK_H
  51. # define WIN32_LEAN_AND_MEAN
  52. # include <windows.h>
  53. # endif // HAVE_WINSOCK_H
  54. #endif // HAVE_SLEEP
  55. #ifdef HAVE_LIBGCRYPT
  56. # include <gcrypt.h>
  57. #elif HAVE_LIBSSL
  58. # include <openssl/rand.h>
  59. # include "SimpleRandomizer.h"
  60. #endif // HAVE_LIBSSL
  61. #include "File.h"
  62. #include "message.h"
  63. #include "Randomizer.h"
  64. #include "a2netcompat.h"
  65. #include "DlAbortEx.h"
  66. #include "BitfieldMan.h"
  67. #include "DefaultDiskWriter.h"
  68. #include "FatalException.h"
  69. #include "FileEntry.h"
  70. #include "StringFormat.h"
  71. #include "A2STR.h"
  72. #include "array_fun.h"
  73. #include "bitfield.h"
  74. #include "DownloadHandlerConstants.h"
  75. #include "RequestGroup.h"
  76. #include "LogFactory.h"
  77. #include "Option.h"
  78. #ifdef ENABLE_MESSAGE_DIGEST
  79. # include "MessageDigestHelper.h"
  80. #endif // ENABLE_MESSAGE_DIGEST
  81. // For libc6 which doesn't define ULLONG_MAX properly because of broken limits.h
  82. #ifndef ULLONG_MAX
  83. # define ULLONG_MAX 18446744073709551615ULL
  84. #endif // ULLONG_MAX
  85. namespace aria2 {
  86. namespace util {
  87. const std::string DEFAULT_STRIP_CHARSET("\r\n\t ");
  88. std::string strip(const std::string& str, const std::string& chars)
  89. {
  90. return stripIter(str.begin(), str.end(), chars);
  91. }
  92. void divide
  93. (std::pair<std::string, std::string>& hp, const std::string& src, char delim)
  94. {
  95. std::string::const_iterator first = src.begin();
  96. std::string::const_iterator last = src.end();
  97. std::string::const_iterator dpos = std::find(first, last, delim);
  98. if(dpos == last) {
  99. hp.first = strip(src);
  100. hp.second = A2STR::NIL;
  101. } else {
  102. hp.first = stripIter(first, dpos);
  103. hp.second = stripIter(dpos+1, last);
  104. }
  105. }
  106. std::string itos(int64_t value, bool comma)
  107. {
  108. bool flag = false;
  109. std::string str;
  110. if(value < 0) {
  111. if(value == INT64_MIN) {
  112. if(comma) {
  113. str = "-9,223,372,036,854,775,808";
  114. } else {
  115. str = "-9223372036854775808";
  116. }
  117. return str;
  118. }
  119. flag = true;
  120. value = -value;
  121. }
  122. str = uitos(value, comma);
  123. if(flag) {
  124. str.insert(str.begin(), '-');
  125. }
  126. return str;
  127. }
  128. int64_t difftv(struct timeval tv1, struct timeval tv2) {
  129. if((tv1.tv_sec < tv2.tv_sec) ||
  130. ((tv1.tv_sec == tv2.tv_sec) && (tv1.tv_usec < tv2.tv_usec))) {
  131. return 0;
  132. }
  133. return ((int64_t)(tv1.tv_sec-tv2.tv_sec)*1000000+
  134. tv1.tv_usec-tv2.tv_usec);
  135. }
  136. int32_t difftvsec(struct timeval tv1, struct timeval tv2) {
  137. if(tv1.tv_sec < tv2.tv_sec) {
  138. return 0;
  139. }
  140. return tv1.tv_sec-tv2.tv_sec;
  141. }
  142. bool startsWith(const std::string& target, const std::string& part) {
  143. if(target.size() < part.size()) {
  144. return false;
  145. }
  146. if(part.empty()) {
  147. return true;
  148. }
  149. if(target.find(part) == 0) {
  150. return true;
  151. } else {
  152. return false;
  153. }
  154. }
  155. bool endsWith(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.rfind(part) == target.size()-part.size()) {
  163. return true;
  164. } else {
  165. return false;
  166. }
  167. }
  168. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr) {
  169. if(target.empty() || oldstr.empty()) {
  170. return target;
  171. }
  172. std::string result;
  173. std::string::size_type p = 0;
  174. std::string::size_type np = target.find(oldstr);
  175. while(np != std::string::npos) {
  176. result += target.substr(p, np-p);
  177. result += newstr;
  178. p = np+oldstr.size();
  179. np = target.find(oldstr, p);
  180. }
  181. result += target.substr(p);
  182. return result;
  183. }
  184. bool isAlpha(const char c)
  185. {
  186. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  187. }
  188. bool isDigit(const char c)
  189. {
  190. return '0' <= c && c <= '9';
  191. }
  192. bool isHexDigit(const char c)
  193. {
  194. return isDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
  195. }
  196. bool isHexDigit(const std::string& s)
  197. {
  198. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  199. if(!isHexDigit(*i)) {
  200. return false;
  201. }
  202. }
  203. return true;
  204. }
  205. bool inRFC3986ReservedChars(const char c)
  206. {
  207. static const char reserved[] = {
  208. ':' , '/' , '?' , '#' , '[' , ']' , '@',
  209. '!' , '$' , '&' , '\'' , '(' , ')',
  210. '*' , '+' , ',' , ';' , '=' };
  211. return std::find(vbegin(reserved), vend(reserved), c) != vend(reserved);
  212. }
  213. bool inRFC3986UnreservedChars(const char c)
  214. {
  215. static const char unreserved[] = { '-', '.', '_', '~' };
  216. return isAlpha(c) || isDigit(c) ||
  217. std::find(vbegin(unreserved), vend(unreserved), c) != vend(unreserved);
  218. }
  219. bool inRFC2978MIMECharset(const char c)
  220. {
  221. static const char chars[] = {
  222. '!', '#', '$', '%', '&',
  223. '\'', '+', '-', '^', '_',
  224. '`', '{', '}', '~'
  225. };
  226. return isAlpha(c) || isDigit(c) ||
  227. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  228. }
  229. bool inRFC2616HttpToken(const char c)
  230. {
  231. static const char chars[] = {
  232. '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.',
  233. '^', '_', '`', '|', '~'
  234. };
  235. return isAlpha(c) || isDigit(c) ||
  236. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  237. }
  238. namespace {
  239. bool isUtf8Tail(unsigned char ch)
  240. {
  241. return in(ch, 0x80u, 0xbfu);
  242. }
  243. } // namespace
  244. bool isUtf8(const std::string& str)
  245. {
  246. for(std::string::const_iterator s = str.begin(), eos = str.end(); s != eos;
  247. ++s) {
  248. unsigned char firstChar = *s;
  249. // See ABNF in http://tools.ietf.org/search/rfc3629#section-4
  250. if(in(firstChar, 0x20u, 0x7eu) ||
  251. firstChar == 0x09u || firstChar == 0x0au ||firstChar == 0x0du) {
  252. // UTF8-1 (without ctrl chars)
  253. } else if(in(firstChar, 0xc2u, 0xdfu)) {
  254. // UTF8-2
  255. if(++s == eos || !isUtf8Tail(*s)) {
  256. return false;
  257. }
  258. } else if(0xe0u == firstChar) {
  259. // UTF8-3
  260. if(++s == eos || !in(static_cast<unsigned char>(*s), 0xa0u, 0xbfu) ||
  261. ++s == eos || !isUtf8Tail(*s)) {
  262. return false;
  263. }
  264. } else if(in(firstChar, 0xe1u, 0xecu) || in(firstChar, 0xeeu, 0xefu)) {
  265. // UTF8-3
  266. if(++s == eos || !isUtf8Tail(*s) ||
  267. ++s == eos || !isUtf8Tail(*s)) {
  268. return false;
  269. }
  270. } else if(0xedu == firstChar) {
  271. // UTF8-3
  272. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x9fu) ||
  273. ++s == eos || !isUtf8Tail(*s)) {
  274. return false;
  275. }
  276. } else if(0xf0u == firstChar) {
  277. // UTF8-4
  278. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x90u, 0xbfu) ||
  279. ++s == eos || !isUtf8Tail(*s) ||
  280. ++s == eos || !isUtf8Tail(*s)) {
  281. return false;
  282. }
  283. } else if(in(firstChar, 0xf1u, 0xf3u)) {
  284. // UTF8-4
  285. if(++s == eos || !isUtf8Tail(*s) ||
  286. ++s == eos || !isUtf8Tail(*s) ||
  287. ++s == eos || !isUtf8Tail(*s)) {
  288. return false;
  289. }
  290. } else if(0xf4u == firstChar) {
  291. // UTF8-4
  292. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x8fu) ||
  293. ++s == eos || !isUtf8Tail(*s) ||
  294. ++s == eos || !isUtf8Tail(*s)) {
  295. return false;
  296. }
  297. } else {
  298. return false;
  299. }
  300. }
  301. return true;
  302. }
  303. std::string percentEncode(const unsigned char* target, size_t len)
  304. {
  305. std::string dest;
  306. for(size_t i = 0; i < len; ++i) {
  307. if(inRFC3986UnreservedChars(target[i])) {
  308. dest += target[i];
  309. } else {
  310. dest.append(StringFormat("%%%02X", target[i]).str());
  311. }
  312. }
  313. return dest;
  314. }
  315. std::string percentEncode(const std::string& target)
  316. {
  317. return percentEncode(reinterpret_cast<const unsigned char*>(target.c_str()),
  318. target.size());
  319. }
  320. std::string torrentPercentEncode(const unsigned char* target, size_t len) {
  321. std::string dest;
  322. for(size_t i = 0; i < len; ++i) {
  323. if(isAlpha(target[i]) || isDigit(target[i])) {
  324. dest += target[i];
  325. } else {
  326. dest.append(StringFormat("%%%02X", target[i]).str());
  327. }
  328. }
  329. return dest;
  330. }
  331. std::string torrentPercentEncode(const std::string& target)
  332. {
  333. return torrentPercentEncode
  334. (reinterpret_cast<const unsigned char*>(target.c_str()), target.size());
  335. }
  336. std::string percentDecode(const std::string& target) {
  337. std::string result;
  338. for(std::string::const_iterator itr = target.begin(), eoi = target.end();
  339. itr != eoi; ++itr) {
  340. if(*itr == '%') {
  341. if(itr+1 != target.end() && itr+2 != target.end() &&
  342. isHexDigit(*(itr+1)) && isHexDigit(*(itr+2))) {
  343. result += parseInt(std::string(itr+1, itr+3), 16);
  344. itr += 2;
  345. } else {
  346. result += *itr;
  347. }
  348. } else {
  349. result += *itr;
  350. }
  351. }
  352. return result;
  353. }
  354. std::string toHex(const unsigned char* src, size_t len) {
  355. std::string out(len*2, '\0');
  356. std::string::iterator o = out.begin();
  357. const unsigned char* last = src+len;
  358. for(const unsigned char* i = src; i != last; ++i) {
  359. *o = (*i >> 4);
  360. *(o+1) = (*i)&0x0fu;
  361. for(int j = 0; j < 2; ++j) {
  362. if(*o < 10) {
  363. *o += '0';
  364. } else {
  365. *o += 'a'-10;
  366. }
  367. ++o;
  368. }
  369. }
  370. return out;
  371. }
  372. std::string toHex(const char* src, size_t len)
  373. {
  374. return toHex(reinterpret_cast<const unsigned char*>(src), len);
  375. }
  376. std::string toHex(const std::string& src)
  377. {
  378. return toHex(reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
  379. }
  380. namespace {
  381. unsigned int hexCharToUInt(unsigned char ch)
  382. {
  383. if('a' <= ch && ch <= 'f') {
  384. ch -= 'a';
  385. ch += 10;
  386. } else if('A' <= ch && ch <= 'F') {
  387. ch -= 'A';
  388. ch += 10;
  389. } else if('0' <= ch && ch <= '9') {
  390. ch -= '0';
  391. } else {
  392. ch = 255;
  393. }
  394. return ch;
  395. }
  396. } // namespace
  397. std::string fromHex(const std::string& src)
  398. {
  399. std::string dest;
  400. if(src.size()%2) {
  401. return dest;
  402. }
  403. for(size_t i = 0, eoi = src.size(); i < eoi; i += 2) {
  404. unsigned char high = hexCharToUInt(src[i]);
  405. unsigned char low = hexCharToUInt(src[i+1]);
  406. if(high == 255 || low == 255) {
  407. dest.clear();
  408. return dest;
  409. }
  410. dest += (high*16+low);
  411. }
  412. return dest;
  413. }
  414. FILE* openFile(const std::string& filename, const std::string& mode) {
  415. FILE* file = fopen(filename.c_str(), mode.c_str());
  416. return file;
  417. }
  418. bool isPowerOf(int num, int base) {
  419. if(base <= 0) { return false; }
  420. if(base == 1) { return true; }
  421. while(num%base == 0) {
  422. num /= base;
  423. if(num == 1) {
  424. return true;
  425. }
  426. }
  427. return false;
  428. }
  429. std::string secfmt(time_t sec) {
  430. std::string str;
  431. if(sec >= 3600) {
  432. str = itos(sec/3600);
  433. str += "h";
  434. sec %= 3600;
  435. }
  436. if(sec >= 60) {
  437. int min = sec/60;
  438. if(min < 10) {
  439. str += "0";
  440. }
  441. str += itos(min);
  442. str += "m";
  443. sec %= 60;
  444. }
  445. if(sec < 10) {
  446. str += "0";
  447. }
  448. str += itos(sec);
  449. str += "s";
  450. return str;
  451. }
  452. int getNum(const char* buf, int offset, size_t length) {
  453. char* temp = new char[length+1];
  454. memcpy(temp, buf+offset, length);
  455. temp[length] = '\0';
  456. int x = strtol(temp, 0, 10);
  457. delete [] temp;
  458. return x;
  459. }
  460. int32_t parseInt(const std::string& s, int32_t base)
  461. {
  462. int64_t v = parseLLInt(s, base);
  463. if(v < INT32_MIN || INT32_MAX < v) {
  464. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  465. s.c_str()).str());
  466. }
  467. return v;
  468. }
  469. uint32_t parseUInt(const std::string& s, int base)
  470. {
  471. uint64_t v = parseULLInt(s, base);
  472. if(UINT32_MAX < v) {
  473. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  474. s.c_str()).str());
  475. }
  476. return v;
  477. }
  478. bool parseUIntNoThrow(uint32_t& result, const std::string& s, int base)
  479. {
  480. // TODO what happens when we don't trim s?
  481. std::string trimed = strip(s);
  482. if(trimed.empty()) {
  483. return false;
  484. }
  485. // We don't allow negative number.
  486. if(trimed[0] == '-') {
  487. return false;
  488. }
  489. char* stop;
  490. errno = 0;
  491. unsigned long int v = strtoul(trimed.c_str(), &stop, base);
  492. if(*stop != '\0') {
  493. return false;
  494. } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
  495. return false;
  496. }
  497. result = v;
  498. return true;
  499. }
  500. int64_t parseLLInt(const std::string& s, int32_t base)
  501. {
  502. std::string trimed = strip(s);
  503. if(trimed.empty()) {
  504. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  505. "empty string").str());
  506. }
  507. char* stop;
  508. errno = 0;
  509. int64_t v = strtoll(trimed.c_str(), &stop, base);
  510. if(*stop != '\0') {
  511. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  512. trimed.c_str()).str());
  513. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  514. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  515. trimed.c_str()).str());
  516. }
  517. return v;
  518. }
  519. bool parseLLIntNoThrow(int64_t& result, const std::string& s, int base)
  520. {
  521. std::string trimed = strip(s);
  522. if(trimed.empty()) {
  523. return false;
  524. }
  525. char* stop;
  526. errno = 0;
  527. int64_t v = strtoll(trimed.c_str(), &stop, base);
  528. if(*stop != '\0') {
  529. return false;
  530. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  531. return false;
  532. }
  533. result = v;
  534. return true;
  535. }
  536. uint64_t parseULLInt(const std::string& s, int base)
  537. {
  538. std::string trimed = strip(s);
  539. if(trimed.empty()) {
  540. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  541. "empty string").str());
  542. }
  543. // We don't allow negative number.
  544. if(trimed[0] == '-') {
  545. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  546. trimed.c_str()).str());
  547. }
  548. char* stop;
  549. errno = 0;
  550. uint64_t v = strtoull(trimed.c_str(), &stop, base);
  551. if(*stop != '\0') {
  552. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  553. trimed.c_str()).str());
  554. } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
  555. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  556. trimed.c_str()).str());
  557. }
  558. return v;
  559. }
  560. IntSequence parseIntRange(const std::string& src)
  561. {
  562. IntSequence::Values values;
  563. std::string temp = src;
  564. while(temp.size()) {
  565. std::pair<std::string, std::string> p;
  566. divide(p, temp, ',');
  567. temp = p.second;
  568. if(p.first.empty()) {
  569. continue;
  570. }
  571. if(p.first.find("-") == std::string::npos) {
  572. int32_t v = parseInt(p.first.c_str());
  573. values.push_back(IntSequence::Value(v, v+1));
  574. } else {
  575. std::pair<std::string, std::string> vp;
  576. divide(vp, p.first.c_str(), '-');
  577. if(vp.first.empty() || vp.second.empty()) {
  578. throw DL_ABORT_EX
  579. (StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str());
  580. }
  581. int32_t v1 = parseInt(vp.first.c_str());
  582. int32_t v2 = parseInt(vp.second.c_str());
  583. values.push_back(IntSequence::Value(v1, v2+1));
  584. }
  585. }
  586. return values;
  587. }
  588. namespace {
  589. void computeHeadPieces
  590. (std::vector<size_t>& indexes,
  591. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  592. size_t pieceLength,
  593. uint64_t head)
  594. {
  595. if(head == 0) {
  596. return;
  597. }
  598. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  599. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  600. if((*fi)->getLength() == 0) {
  601. continue;
  602. }
  603. size_t lastIndex =
  604. ((*fi)->getOffset()+std::min(head, (*fi)->getLength())-1)/pieceLength;
  605. for(size_t index = (*fi)->getOffset()/pieceLength;
  606. index <= lastIndex; ++index) {
  607. indexes.push_back(index);
  608. }
  609. }
  610. }
  611. } // namespace
  612. namespace {
  613. void computeTailPieces
  614. (std::vector<size_t>& indexes,
  615. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  616. size_t pieceLength,
  617. uint64_t tail)
  618. {
  619. if(tail == 0) {
  620. return;
  621. }
  622. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  623. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  624. if((*fi)->getLength() == 0) {
  625. continue;
  626. }
  627. uint64_t endOffset = (*fi)->getLastOffset();
  628. size_t fromIndex =
  629. (endOffset-1-(std::min(tail, (*fi)->getLength())-1))/pieceLength;
  630. for(size_t index = fromIndex; index <= (endOffset-1)/pieceLength;
  631. ++index) {
  632. indexes.push_back(index);
  633. }
  634. }
  635. }
  636. } // namespace
  637. void parsePrioritizePieceRange
  638. (std::vector<size_t>& result, const std::string& src,
  639. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  640. size_t pieceLength,
  641. uint64_t defaultSize)
  642. {
  643. std::vector<size_t> indexes;
  644. std::vector<std::string> parts;
  645. split(src, std::back_inserter(parts), ",", true);
  646. for(std::vector<std::string>::const_iterator i = parts.begin(),
  647. eoi = parts.end(); i != eoi; ++i) {
  648. if((*i) == "head") {
  649. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  650. } else if(util::startsWith(*i, "head=")) {
  651. std::string sizestr = std::string((*i).begin()+(*i).find("=")+1,
  652. (*i).end());
  653. computeHeadPieces(indexes, fileEntries, pieceLength,
  654. std::max((int64_t)0, getRealSize(sizestr)));
  655. } else if((*i) == "tail") {
  656. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  657. } else if(util::startsWith(*i, "tail=")) {
  658. std::string sizestr = std::string((*i).begin()+(*i).find("=")+1,
  659. (*i).end());
  660. computeTailPieces(indexes, fileEntries, pieceLength,
  661. std::max((int64_t)0, getRealSize(sizestr)));
  662. } else {
  663. throw DL_ABORT_EX
  664. (StringFormat("Unrecognized token %s", (*i).c_str()).str());
  665. }
  666. }
  667. std::sort(indexes.begin(), indexes.end());
  668. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  669. result.insert(result.end(), indexes.begin(), indexes.end());
  670. }
  671. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  672. // character not in ISO/IEC 8859-1, returns empty string.
  673. std::string iso8859ToUtf8(const std::string& src)
  674. {
  675. std::string dest;
  676. for(std::string::const_iterator itr = src.begin(), eoi = src.end();
  677. itr != eoi; ++itr) {
  678. unsigned char c = *itr;
  679. if(0xa0u <= c) {
  680. if(c <= 0xbfu) {
  681. dest += 0xc2u;
  682. } else {
  683. dest += 0xc3u;
  684. }
  685. dest += c&(~0x40u);
  686. } else if(0x80u <= c && c <= 0x9fu) {
  687. return A2STR::NIL;
  688. } else {
  689. dest += c;
  690. }
  691. }
  692. return dest;
  693. }
  694. namespace {
  695. template<typename OutputIterator>
  696. void parseParam(OutputIterator out, const std::string& header)
  697. {
  698. for(std::string::const_iterator i = header.begin(), eoi = header.end();
  699. i != eoi;) {
  700. std::string::const_iterator paramFirst = i;
  701. std::string::const_iterator paramLast = paramFirst;
  702. for(; paramLast != eoi && *paramLast != '=' && *paramLast != ';';
  703. ++paramLast);
  704. std::string param;
  705. if(paramLast == eoi || *paramLast == ';') {
  706. // No value, parmname only
  707. param = std::string(paramFirst, paramLast);
  708. } else {
  709. for(; paramLast != eoi && *paramLast != '"' && *paramLast != ';';
  710. ++paramLast);
  711. if(paramLast != eoi && *paramLast == '"') {
  712. // quoted-string
  713. ++paramLast;
  714. for(; paramLast != eoi && *paramLast != '"'; ++paramLast);
  715. if(paramLast != eoi) {
  716. ++paramLast;
  717. }
  718. param = std::string(paramFirst, paramLast);
  719. for(; paramLast != eoi && *paramLast != ';'; ++paramLast);
  720. } else {
  721. param = std::string(paramFirst, paramLast);
  722. }
  723. }
  724. param = strip(param);
  725. *out++ = param;
  726. if(paramLast == eoi) {
  727. break;
  728. }
  729. i = paramLast;
  730. ++i;
  731. }
  732. }
  733. } // namespace
  734. std::string getContentDispositionFilename(const std::string& header)
  735. {
  736. std::string filename;
  737. std::vector<std::string> params;
  738. parseParam(std::back_inserter(params), header);
  739. for(std::vector<std::string>::const_iterator i = params.begin(),
  740. eoi = params.end(); i != eoi; ++i) {
  741. const std::string& param = *i;
  742. static const std::string keyName = "filename";
  743. if(!startsWith(toLower(param), keyName) || param.size() == keyName.size()) {
  744. continue;
  745. }
  746. std::string::const_iterator markeritr = param.begin()+keyName.size();
  747. if(*markeritr == '*') {
  748. // See RFC2231 Section4 and draft-reschke-rfc2231-in-http.
  749. // Please note that this function doesn't do charset conversion
  750. // except that if iso-8859-1 is specified, it is converted to
  751. // utf-8.
  752. ++markeritr;
  753. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  754. if(markeritr == param.end() || *markeritr != '=') {
  755. continue;
  756. }
  757. std::pair<std::string, std::string> paramPair;
  758. divide(paramPair, param, '=');
  759. std::string value = paramPair.second;
  760. std::vector<std::string> extValues;
  761. split(value, std::back_inserter(extValues), "'", false, true);
  762. if(extValues.size() != 3) {
  763. continue;
  764. }
  765. bool bad = false;
  766. const std::string& charset = extValues[0];
  767. for(std::string::const_iterator j = charset.begin(), eoi = charset.end();
  768. j != eoi; ++j) {
  769. // Since we first split parameter by ', we can safely assume
  770. // that ' is not included in charset.
  771. if(!inRFC2978MIMECharset(*j)) {
  772. bad = true;
  773. break;
  774. }
  775. }
  776. if(bad) {
  777. continue;
  778. }
  779. bad = false;
  780. value = extValues[2];
  781. for(std::string::const_iterator j = value.begin(), eoi = value.end();
  782. j != eoi; ++j){
  783. if(*j == '%') {
  784. if(j+1 != value.end() && isHexDigit(*(j+1)) &&
  785. j+2 != value.end() && isHexDigit(*(j+2))) {
  786. j += 2;
  787. } else {
  788. bad = true;
  789. break;
  790. }
  791. } else {
  792. if(*j == '*' || *j == '\'' || !inRFC2616HttpToken(*j)) {
  793. bad = true;
  794. break;
  795. }
  796. }
  797. }
  798. if(bad) {
  799. continue;
  800. }
  801. value = percentDecode(value);
  802. if(toLower(extValues[0]) == "iso-8859-1") {
  803. value = iso8859ToUtf8(value);
  804. }
  805. if(!detectDirTraversal(value) &&
  806. value.find(A2STR::SLASH_C) == std::string::npos) {
  807. filename = value;
  808. }
  809. if(!filename.empty()) {
  810. break;
  811. }
  812. } else {
  813. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  814. if(markeritr == param.end() || *markeritr != '=') {
  815. continue;
  816. }
  817. std::pair<std::string, std::string> paramPair;
  818. divide(paramPair, param, '=');
  819. std::string value = paramPair.second;
  820. if(value.empty()) {
  821. continue;
  822. }
  823. std::string::iterator filenameLast;
  824. if(*value.begin() == '\'' || *value.begin() == '"') {
  825. char qc = *value.begin();
  826. for(filenameLast = value.begin()+1;
  827. filenameLast != value.end() && *filenameLast != qc;
  828. ++filenameLast);
  829. } else {
  830. filenameLast = value.end();
  831. }
  832. static const std::string TRIMMED("\r\n\t '\"");
  833. value = percentDecode(std::string(value.begin(), filenameLast));
  834. value = strip(value, TRIMMED);
  835. value.erase(std::remove(value.begin(), value.end(), '\\'), value.end());
  836. if(!detectDirTraversal(value) &&
  837. value.find(A2STR::SLASH_C) == std::string::npos) {
  838. filename = value;
  839. }
  840. // continue because there is a chance we can find filename*=...
  841. }
  842. }
  843. return filename;
  844. }
  845. std::string randomAlpha(size_t length, const RandomizerHandle& randomizer) {
  846. static const char *random_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  847. std::string str;
  848. for(size_t i = 0; i < length; ++i) {
  849. size_t index = randomizer->getRandomNumber(strlen(random_chars));
  850. str += random_chars[index];
  851. }
  852. return str;
  853. }
  854. std::string toUpper(const std::string& src) {
  855. std::string temp = src;
  856. std::transform(temp.begin(), temp.end(), temp.begin(), ::toupper);
  857. return temp;
  858. }
  859. std::string toLower(const std::string& src) {
  860. std::string temp = src;
  861. std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
  862. return temp;
  863. }
  864. void uppercase(std::string& s)
  865. {
  866. std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  867. }
  868. void lowercase(std::string& s)
  869. {
  870. std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  871. }
  872. bool isNumericHost(const std::string& name)
  873. {
  874. struct addrinfo hints;
  875. struct addrinfo* res;
  876. memset(&hints, 0, sizeof(hints));
  877. hints.ai_family = AF_UNSPEC;
  878. hints.ai_flags = AI_NUMERICHOST;
  879. if(getaddrinfo(name.c_str(), 0, &hints, &res)) {
  880. return false;
  881. }
  882. freeaddrinfo(res);
  883. return true;
  884. }
  885. void setGlobalSignalHandler(int sig, void (*handler)(int), int flags) {
  886. #ifdef HAVE_SIGACTION
  887. struct sigaction sigact;
  888. sigact.sa_handler = handler;
  889. sigact.sa_flags = flags;
  890. sigemptyset(&sigact.sa_mask);
  891. sigaction(sig, &sigact, NULL);
  892. #else
  893. signal(sig, handler);
  894. #endif // HAVE_SIGACTION
  895. }
  896. std::string getHomeDir()
  897. {
  898. const char* p = getenv("HOME");
  899. if(p) {
  900. return p;
  901. } else {
  902. return A2STR::NIL;
  903. }
  904. }
  905. int64_t getRealSize(const std::string& sizeWithUnit)
  906. {
  907. std::string::size_type p = sizeWithUnit.find_first_of("KM");
  908. std::string size;
  909. int32_t mult = 1;
  910. if(p == std::string::npos) {
  911. size = sizeWithUnit;
  912. } else {
  913. if(sizeWithUnit[p] == 'K') {
  914. mult = 1024;
  915. } else if(sizeWithUnit[p] == 'M') {
  916. mult = 1024*1024;
  917. }
  918. size = sizeWithUnit.substr(0, p);
  919. }
  920. int64_t v = parseLLInt(size);
  921. if(v < 0) {
  922. throw DL_ABORT_EX
  923. (StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str());
  924. } else if(INT64_MAX/mult < v) {
  925. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  926. "overflow/underflow").str());
  927. }
  928. return v*mult;
  929. }
  930. std::string abbrevSize(int64_t size)
  931. {
  932. if(size < 1024) {
  933. return itos(size, true);
  934. }
  935. char units[] = { 'K', 'M' };
  936. size_t numUnit = sizeof(units)/sizeof(char);
  937. size_t i = 0;
  938. int r = size&0x3ffu;
  939. size >>= 10;
  940. for(; i < numUnit-1 && size >= 1024; ++i) {
  941. r = size&0x3ffu;
  942. size >>= 10;
  943. }
  944. std::string result = itos(size, true);
  945. result += A2STR::DOT_C;
  946. result += itos(r*10/1024);
  947. result += units[i];
  948. result += "i";
  949. return result;
  950. }
  951. void sleep(long seconds) {
  952. #ifdef HAVE_SLEEP
  953. ::sleep(seconds);
  954. #elif defined(HAVE_USLEEP)
  955. ::usleep(seconds * 1000000);
  956. #elif defined(HAVE_WINSOCK2_H)
  957. ::Sleep(seconds * 1000);
  958. #else
  959. #error no sleep function is available (nanosleep?)
  960. #endif
  961. }
  962. void usleep(long microseconds) {
  963. #ifdef HAVE_USLEEP
  964. ::usleep(microseconds);
  965. #elif defined(HAVE_WINSOCK2_H)
  966. LARGE_INTEGER current, freq, end;
  967. static enum {GET_FREQUENCY, GET_MICROSECONDS, SKIP_MICROSECONDS} state = GET_FREQUENCY;
  968. if (state == GET_FREQUENCY) {
  969. if (QueryPerformanceFrequency(&freq))
  970. state = GET_MICROSECONDS;
  971. else
  972. state = SKIP_MICROSECONDS;
  973. }
  974. long msec = microseconds / 1000;
  975. microseconds %= 1000;
  976. if (state == GET_MICROSECONDS && microseconds) {
  977. QueryPerformanceCounter(&end);
  978. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  979. while (QueryPerformanceCounter(&current) && (current.QuadPart <= end.QuadPart))
  980. /* noop */ ;
  981. }
  982. if (msec)
  983. Sleep(msec);
  984. #else
  985. #error no usleep function is available (nanosleep?)
  986. #endif
  987. }
  988. bool isNumber(const std::string& what)
  989. {
  990. if(what.empty()) {
  991. return false;
  992. }
  993. for(std::string::const_iterator i = what.begin(), eoi = what.end();
  994. i != eoi; ++i) {
  995. if(!isDigit(*i)) {
  996. return false;
  997. }
  998. }
  999. return true;
  1000. }
  1001. bool isLowercase(const std::string& what)
  1002. {
  1003. if(what.empty()) {
  1004. return false;
  1005. }
  1006. for(uint32_t i = 0, eoi = what.size(); i < eoi; ++i) {
  1007. if(!('a' <= what[i] && what[i] <= 'z')) {
  1008. return false;
  1009. }
  1010. }
  1011. return true;
  1012. }
  1013. bool isUppercase(const std::string& what)
  1014. {
  1015. if(what.empty()) {
  1016. return false;
  1017. }
  1018. for(uint32_t i = 0, eoi = what.size(); i < eoi; ++i) {
  1019. if(!('A' <= what[i] && what[i] <= 'Z')) {
  1020. return false;
  1021. }
  1022. }
  1023. return true;
  1024. }
  1025. unsigned int alphaToNum(const std::string& alphabets)
  1026. {
  1027. if(alphabets.empty()) {
  1028. return 0;
  1029. }
  1030. char base;
  1031. if(islower(alphabets[0])) {
  1032. base = 'a';
  1033. } else {
  1034. base = 'A';
  1035. }
  1036. uint64_t num = 0;
  1037. for(size_t i = 0, eoi = alphabets.size(); i < eoi; ++i) {
  1038. unsigned int v = alphabets[i]-base;
  1039. num = num*26+v;
  1040. if(num > UINT32_MAX) {
  1041. return 0;
  1042. }
  1043. }
  1044. return num;
  1045. }
  1046. void mkdirs(const std::string& dirpath)
  1047. {
  1048. File dir(dirpath);
  1049. if(!dir.mkdirs() &&!dir.isDir()) {
  1050. throw DL_ABORT_EX
  1051. (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
  1052. strerror(errno)).str());
  1053. }
  1054. }
  1055. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1056. {
  1057. size_t numBlock = dest->countBlock();
  1058. for(size_t index = 0; index < numBlock; ++index) {
  1059. if(src->isBitSetOffsetRange((uint64_t)index*dest->getBlockLength(),
  1060. dest->getBlockLength())) {
  1061. dest->setBit(index);
  1062. }
  1063. }
  1064. }
  1065. std::string toString(const BinaryStreamHandle& binaryStream)
  1066. {
  1067. std::stringstream strm;
  1068. char data[2048];
  1069. while(1) {
  1070. int32_t dataLength = binaryStream->readData
  1071. (reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1072. strm.write(data, dataLength);
  1073. if(dataLength == 0) {
  1074. break;
  1075. }
  1076. }
  1077. return strm.str();
  1078. }
  1079. #ifdef HAVE_POSIX_MEMALIGN
  1080. /**
  1081. * In linux 2.6, alignment and size should be a multiple of 512.
  1082. */
  1083. void* allocateAlignedMemory(size_t alignment, size_t size)
  1084. {
  1085. void* buffer;
  1086. int res;
  1087. if((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1088. throw FATAL_EXCEPTION
  1089. (StringFormat("Error in posix_memalign: %s", strerror(res)).str());
  1090. }
  1091. return buffer;
  1092. }
  1093. #endif // HAVE_POSIX_MEMALIGN
  1094. std::pair<std::string, uint16_t>
  1095. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1096. {
  1097. char host[NI_MAXHOST];
  1098. char service[NI_MAXSERV];
  1099. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1100. NI_NUMERICHOST|NI_NUMERICSERV);
  1101. if(s != 0) {
  1102. throw DL_ABORT_EX(StringFormat("Failed to get hostname and port. cause: %s",
  1103. gai_strerror(s)).str());
  1104. }
  1105. return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO
  1106. }
  1107. std::string htmlEscape(const std::string& src)
  1108. {
  1109. std::string dest;
  1110. for(std::string::const_iterator i = src.begin(), eoi = src.end();
  1111. i != eoi; ++i) {
  1112. char ch = *i;
  1113. if(ch == '<') {
  1114. dest += "&lt;";
  1115. } else if(ch == '>') {
  1116. dest += "&gt;";
  1117. } else if(ch == '&') {
  1118. dest += "&amp;";
  1119. } else if(ch == '\'') {
  1120. dest += "&#39;";
  1121. } else if(ch == '"') {
  1122. dest += "&quot;";
  1123. } else {
  1124. dest += ch;
  1125. }
  1126. }
  1127. return dest;
  1128. }
  1129. std::map<size_t, std::string>::value_type
  1130. parseIndexPath(const std::string& line)
  1131. {
  1132. std::pair<std::string, std::string> p;
  1133. divide(p, line, '=');
  1134. size_t index = parseUInt(p.first);
  1135. if(p.second.empty()) {
  1136. throw DL_ABORT_EX(StringFormat("Path with index=%u is empty.",
  1137. static_cast<unsigned int>(index)).str());
  1138. }
  1139. return std::map<size_t, std::string>::value_type(index, p.second);
  1140. }
  1141. std::map<size_t, std::string> createIndexPathMap(std::istream& i)
  1142. {
  1143. std::map<size_t, std::string> indexPathMap;
  1144. std::string line;
  1145. while(getline(i, line)) {
  1146. indexPathMap.insert(indexPathMap.begin(), parseIndexPath(line));
  1147. }
  1148. return indexPathMap;
  1149. }
  1150. void generateRandomData(unsigned char* data, size_t length)
  1151. {
  1152. #ifdef HAVE_LIBGCRYPT
  1153. gcry_randomize(data, length, GCRY_STRONG_RANDOM);
  1154. #elif HAVE_LIBSSL
  1155. if(RAND_bytes(data, length) != 1) {
  1156. for(size_t i = 0; i < length; ++i) {
  1157. data[i] = SimpleRandomizer::getInstance()->getRandomNumber(UINT8_MAX+1);
  1158. }
  1159. }
  1160. #else
  1161. std::ifstream i("/dev/urandom", std::ios::binary);
  1162. i.read(reinterpret_cast<char*>(data), length);
  1163. #endif // HAVE_LIBSSL
  1164. }
  1165. bool saveAs
  1166. (const std::string& filename, const std::string& data, bool overwrite)
  1167. {
  1168. if(!overwrite && File(filename).exists()) {
  1169. return false;
  1170. }
  1171. std::string tempFilename = strconcat(filename, "__temp");
  1172. {
  1173. std::ofstream out(tempFilename.c_str(), std::ios::binary);
  1174. if(!out) {
  1175. return false;
  1176. }
  1177. out << data;
  1178. out.flush();
  1179. if(!out) {
  1180. return false;
  1181. }
  1182. }
  1183. return File(tempFilename).renameTo(filename);
  1184. }
  1185. std::string applyDir(const std::string& dir, const std::string& relPath)
  1186. {
  1187. if(dir.empty()) {
  1188. return strconcat(A2STR::DOT_C, A2STR::SLASH_C, relPath);
  1189. } else if(dir == A2STR::SLASH_C) {
  1190. return strconcat(A2STR::SLASH_C, relPath);
  1191. } else {
  1192. return strconcat(dir, A2STR::SLASH_C, relPath);
  1193. }
  1194. }
  1195. std::string fixTaintedBasename(const std::string& src)
  1196. {
  1197. static std::string SLASH_REP = "%2F";
  1198. return escapePath(replace(src, A2STR::SLASH_C, SLASH_REP));
  1199. }
  1200. void generateRandomKey(unsigned char* key)
  1201. {
  1202. #ifdef ENABLE_MESSAGE_DIGEST
  1203. unsigned char bytes[40];
  1204. generateRandomData(bytes, sizeof(bytes));
  1205. MessageDigestHelper::digest
  1206. (key, 20, MessageDigestContext::SHA1, bytes, sizeof(bytes));
  1207. #else // !ENABLE_MESSAGE_DIGEST
  1208. generateRandomData(key, 20);
  1209. #endif // !ENABLE_MESSAGE_DIGEST
  1210. }
  1211. // Returns true is given numeric ipv4addr is in Private Address Space.
  1212. //
  1213. // From Section.3 RFC1918
  1214. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1215. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1216. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1217. bool inPrivateAddress(const std::string& ipv4addr)
  1218. {
  1219. if(util::startsWith(ipv4addr, "10.") ||
  1220. util::startsWith(ipv4addr, "192.168.")) {
  1221. return true;
  1222. }
  1223. if(util::startsWith(ipv4addr, "172.")) {
  1224. for(int i = 16; i <= 31; ++i) {
  1225. if(util::startsWith(ipv4addr, "172."+util::itos(i)+".")) {
  1226. return true;
  1227. }
  1228. }
  1229. }
  1230. return false;
  1231. }
  1232. bool detectDirTraversal(const std::string& s)
  1233. {
  1234. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1235. unsigned char c = *i;
  1236. if(in(c, 0x00u, 0x1fu) || c == 0x7fu) {
  1237. return true;
  1238. }
  1239. }
  1240. static std::string DS = "./";
  1241. static std::string DDS = "../";
  1242. static std::string SD = "/.";
  1243. static std::string SDD = "/..";
  1244. static std::string SDDS = "/../";
  1245. static std::string SDS = "/./";
  1246. static std::string DD = "..";
  1247. return s == A2STR::DOT_C ||
  1248. s == DD ||
  1249. util::startsWith(s, A2STR::SLASH_C) ||
  1250. util::startsWith(s, DS) ||
  1251. util::startsWith(s, DDS) ||
  1252. s.find(SDDS) != std::string::npos ||
  1253. s.find(SDS) != std::string::npos ||
  1254. util::endsWith(s, A2STR::SLASH_C) ||
  1255. util::endsWith(s, SD) ||
  1256. util::endsWith(s, SDD);
  1257. }
  1258. std::string escapePath(const std::string& s)
  1259. {
  1260. // We don't escape '/' because we use it as a path separator.
  1261. #ifdef __MINGW32__
  1262. static const char WIN_INVALID_PATH_CHARS[] =
  1263. { '"', '*', ':', '<', '>', '?', '\\', '|' };
  1264. #endif // __MINGW32__
  1265. std::string d;
  1266. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1267. unsigned char c = *i;
  1268. if(in(c, 0x00u, 0x1fu) || c == 0x7fu
  1269. #ifdef __MINGW32__
  1270. || std::find(vbegin(WIN_INVALID_PATH_CHARS),
  1271. vend(WIN_INVALID_PATH_CHARS),
  1272. c) != vend(WIN_INVALID_PATH_CHARS)
  1273. #endif // __MINGW32__
  1274. ){
  1275. d += StringFormat("%%%02X", c).str();
  1276. } else {
  1277. d += *i;
  1278. }
  1279. }
  1280. return d;
  1281. }
  1282. bool getCidrPrefix(struct in_addr& in, const std::string& ip, int bits)
  1283. {
  1284. struct in_addr t;
  1285. if(inet_aton(ip.c_str(), &t) == 0) {
  1286. return false;
  1287. }
  1288. int lastindex = bits/8;
  1289. if(lastindex < 4) {
  1290. char* p = reinterpret_cast<char*>(&t.s_addr);
  1291. const char* last = p+4;
  1292. p += lastindex;
  1293. if(bits%8 != 0) {
  1294. *p &= bitfield::lastByteMask(bits);
  1295. ++p;
  1296. }
  1297. for(; p != last; ++p) {
  1298. *p &= 0;
  1299. }
  1300. }
  1301. in = t;
  1302. return true;
  1303. }
  1304. bool inSameCidrBlock(const std::string& ip1, const std::string& ip2, int bits)
  1305. {
  1306. struct in_addr in1;
  1307. struct in_addr in2;
  1308. if(!getCidrPrefix(in1, ip1, bits) || !getCidrPrefix(in2, ip2, bits)) {
  1309. return false;
  1310. }
  1311. return in1.s_addr == in2.s_addr;
  1312. }
  1313. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group)
  1314. {
  1315. for(std::vector<std::string>::const_iterator i =
  1316. DownloadHandlerConstants::getMetalinkContentTypes().begin(),
  1317. eoi = DownloadHandlerConstants::getMetalinkContentTypes().end();
  1318. i != eoi; ++i) {
  1319. group->removeAcceptType(*i);
  1320. }
  1321. }
  1322. void executeHook(const std::string& command, const std::string& arg)
  1323. {
  1324. LogFactory::getInstance()->info("Executing user command: %s %s",
  1325. command.c_str(), arg.c_str());
  1326. #ifndef __MINGW32__
  1327. pid_t cpid = fork();
  1328. if(cpid == -1) {
  1329. LogFactory::getInstance()->error("fork() failed."
  1330. " Cannot execute user command.");
  1331. } else if(cpid == 0) {
  1332. execl(command.c_str(), command.c_str(), arg.c_str(),
  1333. reinterpret_cast<char*>(0));
  1334. perror(("Could not execute user command: "+command).c_str());
  1335. exit(EXIT_FAILURE);
  1336. }
  1337. #else
  1338. PROCESS_INFORMATION pi;
  1339. STARTUPINFO si;
  1340. memset(&si, 0, sizeof (si));
  1341. si.cb = sizeof(STARTUPINFO);
  1342. memset(&pi, 0, sizeof (pi));
  1343. std::string cmdline = command;
  1344. strappend(cmdline, " ", arg);
  1345. DWORD rc = CreateProcess(
  1346. NULL,
  1347. (LPSTR)cmdline.c_str(),
  1348. NULL,
  1349. NULL,
  1350. true,
  1351. NULL,
  1352. NULL,
  1353. 0,
  1354. &si,
  1355. &pi);
  1356. if(!rc)
  1357. LogFactory::getInstance()->error("CreateProcess() failed."
  1358. " Cannot execute user command.");
  1359. #endif
  1360. }
  1361. void executeHookByOptName
  1362. (const SharedHandle<RequestGroup>& group, const Option* option,
  1363. const std::string& opt)
  1364. {
  1365. executeHookByOptName(group.get(), option, opt);
  1366. }
  1367. void executeHookByOptName
  1368. (const RequestGroup* group, const Option* option, const std::string& opt)
  1369. {
  1370. if(!option->blank(opt)) {
  1371. executeHook(option->get(opt), util::itos(group->getGID()));
  1372. }
  1373. }
  1374. std::string createSafePath
  1375. (const std::string& dir, const std::string& filename)
  1376. {
  1377. return util::applyDir
  1378. (dir,
  1379. util::isUtf8(filename)?
  1380. util::fixTaintedBasename(filename):
  1381. util::escapePath(util::percentEncode(filename)));
  1382. }
  1383. std::string encodeNonUtf8(const std::string& s)
  1384. {
  1385. return util::isUtf8(s)?s:util::percentEncode(s);
  1386. }
  1387. } // namespace util
  1388. } // namespace aria2