util.cc 39 KB

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