util.cc 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  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 <cerrno>
  38. #include <cassert>
  39. #include <cstring>
  40. #include <cstdio>
  41. #include <cstdlib>
  42. #include <sstream>
  43. #include <ostream>
  44. #include <algorithm>
  45. #include <fstream>
  46. #include <iomanip>
  47. #include "SimpleRandomizer.h"
  48. #include "File.h"
  49. #include "Randomizer.h"
  50. #include "a2netcompat.h"
  51. #include "BitfieldMan.h"
  52. #include "DefaultDiskWriter.h"
  53. #include "FatalException.h"
  54. #include "FileEntry.h"
  55. #include "A2STR.h"
  56. #include "array_fun.h"
  57. #include "bitfield.h"
  58. #include "DownloadHandlerConstants.h"
  59. #include "RequestGroup.h"
  60. #include "LogFactory.h"
  61. #include "Logger.h"
  62. #include "Option.h"
  63. #include "DownloadContext.h"
  64. #include "BufferedFile.h"
  65. #include "SocketCore.h"
  66. #include "prefs.h"
  67. #ifdef ENABLE_MESSAGE_DIGEST
  68. # include "MessageDigest.h"
  69. # include "message_digest_helper.h"
  70. #endif // ENABLE_MESSAGE_DIGEST
  71. // For libc6 which doesn't define ULLONG_MAX properly because of broken limits.h
  72. #ifndef ULLONG_MAX
  73. # define ULLONG_MAX 18446744073709551615ULL
  74. #endif // ULLONG_MAX
  75. namespace aria2 {
  76. #ifdef __MINGW32__
  77. namespace {
  78. int utf8ToWChar(wchar_t* out, size_t outLength, const char* src)
  79. {
  80. return MultiByteToWideChar(CP_UTF8, 0, src, -1, out, outLength);
  81. }
  82. } // namespace
  83. namespace {
  84. int ansiToWChar(wchar_t* out, size_t outLength, const char* src)
  85. {
  86. return MultiByteToWideChar(CP_ACP, 0, src, -1, out, outLength);
  87. }
  88. } // namespace
  89. namespace {
  90. int wCharToUtf8(char* out, size_t outLength, const wchar_t* src)
  91. {
  92. return WideCharToMultiByte(CP_UTF8, 0, src, -1, out, outLength, 0, 0);
  93. }
  94. } // namespace
  95. namespace {
  96. int wCharToAnsi(char* out, size_t outLength, const wchar_t* src)
  97. {
  98. return WideCharToMultiByte(CP_ACP, 0, src, -1, out, outLength, 0, 0);
  99. }
  100. } // namespace
  101. std::wstring utf8ToWChar(const char* src)
  102. {
  103. int len = utf8ToWChar(0, 0, src);
  104. if(len == 0) {
  105. abort();
  106. }
  107. array_ptr<wchar_t> buf(new wchar_t[len]);
  108. len = utf8ToWChar(buf, len, src);
  109. if(len == 0) {
  110. abort();
  111. } else {
  112. std::wstring dest(buf);
  113. return dest;
  114. }
  115. }
  116. std::wstring utf8ToWChar(const std::string& src)
  117. {
  118. return utf8ToWChar(src.c_str());
  119. }
  120. std::string utf8ToNative(const std::string& src)
  121. {
  122. std::wstring wsrc = utf8ToWChar(src);
  123. int len = wCharToAnsi(0, 0, wsrc.c_str());
  124. if(len == 0) {
  125. abort();
  126. }
  127. array_ptr<char> buf(new char[len]);
  128. len = wCharToAnsi(buf, len, wsrc.c_str());
  129. if(len == 0) {
  130. abort();
  131. } else {
  132. std::string dest(buf);
  133. return dest;
  134. }
  135. }
  136. std::string wCharToUtf8(const std::wstring& wsrc)
  137. {
  138. int len = wCharToUtf8(0, 0, wsrc.c_str());
  139. if(len == 0) {
  140. abort();
  141. }
  142. array_ptr<char> buf(new char[len]);
  143. len = wCharToUtf8(buf, len, wsrc.c_str());
  144. if(len == 0) {
  145. abort();
  146. } else {
  147. std::string dest(buf);
  148. return dest;
  149. }
  150. }
  151. std::string nativeToUtf8(const std::string& src)
  152. {
  153. int len = ansiToWChar(0, 0, src.c_str());
  154. if(len == 0) {
  155. abort();
  156. }
  157. array_ptr<wchar_t> buf(new wchar_t[len]);
  158. len = ansiToWChar(buf, len, src.c_str());
  159. if(len == 0) {
  160. abort();
  161. } else {
  162. return wCharToUtf8(std::wstring(buf));
  163. }
  164. }
  165. #endif // __MINGW32__
  166. namespace util {
  167. const std::string DEFAULT_STRIP_CHARSET("\r\n\t ");
  168. std::string strip(const std::string& str, const std::string& chars)
  169. {
  170. std::pair<std::string::const_iterator,
  171. std::string::const_iterator> p =
  172. stripIter(str.begin(), str.end(), chars);
  173. return std::string(p.first, p.second);
  174. }
  175. std::string itos(int64_t value, bool comma)
  176. {
  177. bool flag = false;
  178. std::string str;
  179. if(value < 0) {
  180. if(value == INT64_MIN) {
  181. if(comma) {
  182. str = "-9,223,372,036,854,775,808";
  183. } else {
  184. str = "-9223372036854775808";
  185. }
  186. return str;
  187. }
  188. flag = true;
  189. value = -value;
  190. }
  191. str = uitos(value, comma);
  192. if(flag) {
  193. str.insert(str.begin(), '-');
  194. }
  195. return str;
  196. }
  197. int64_t difftv(struct timeval tv1, struct timeval tv2) {
  198. if((tv1.tv_sec < tv2.tv_sec) ||
  199. ((tv1.tv_sec == tv2.tv_sec) && (tv1.tv_usec < tv2.tv_usec))) {
  200. return 0;
  201. }
  202. return ((int64_t)(tv1.tv_sec-tv2.tv_sec)*1000000+
  203. tv1.tv_usec-tv2.tv_usec);
  204. }
  205. int32_t difftvsec(struct timeval tv1, struct timeval tv2) {
  206. if(tv1.tv_sec < tv2.tv_sec) {
  207. return 0;
  208. }
  209. return tv1.tv_sec-tv2.tv_sec;
  210. }
  211. bool endsWith(const std::string& target, const std::string& part) {
  212. if(target.size() < part.size()) {
  213. return false;
  214. }
  215. if(part.empty()) {
  216. return true;
  217. }
  218. if(target.rfind(part) == target.size()-part.size()) {
  219. return true;
  220. } else {
  221. return false;
  222. }
  223. }
  224. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr) {
  225. if(target.empty() || oldstr.empty()) {
  226. return target;
  227. }
  228. std::string result;
  229. std::string::size_type p = 0;
  230. std::string::size_type np = target.find(oldstr);
  231. while(np != std::string::npos) {
  232. result += target.substr(p, np-p);
  233. result += newstr;
  234. p = np+oldstr.size();
  235. np = target.find(oldstr, p);
  236. }
  237. result += target.substr(p);
  238. return result;
  239. }
  240. bool isAlpha(const char c)
  241. {
  242. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  243. }
  244. bool isDigit(const char c)
  245. {
  246. return '0' <= c && c <= '9';
  247. }
  248. bool isHexDigit(const char c)
  249. {
  250. return isDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
  251. }
  252. bool isHexDigit(const std::string& s)
  253. {
  254. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  255. if(!isHexDigit(*i)) {
  256. return false;
  257. }
  258. }
  259. return true;
  260. }
  261. bool inRFC3986ReservedChars(const char c)
  262. {
  263. static const char reserved[] = {
  264. ':' , '/' , '?' , '#' , '[' , ']' , '@',
  265. '!' , '$' , '&' , '\'' , '(' , ')',
  266. '*' , '+' , ',' , ';' , '=' };
  267. return std::find(vbegin(reserved), vend(reserved), c) != vend(reserved);
  268. }
  269. bool inRFC3986UnreservedChars(const char c)
  270. {
  271. static const char unreserved[] = { '-', '.', '_', '~' };
  272. return isAlpha(c) || isDigit(c) ||
  273. std::find(vbegin(unreserved), vend(unreserved), c) != vend(unreserved);
  274. }
  275. bool inRFC2978MIMECharset(const char c)
  276. {
  277. static const char chars[] = {
  278. '!', '#', '$', '%', '&',
  279. '\'', '+', '-', '^', '_',
  280. '`', '{', '}', '~'
  281. };
  282. return isAlpha(c) || isDigit(c) ||
  283. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  284. }
  285. bool inRFC2616HttpToken(const char c)
  286. {
  287. static const char chars[] = {
  288. '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.',
  289. '^', '_', '`', '|', '~'
  290. };
  291. return isAlpha(c) || isDigit(c) ||
  292. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  293. }
  294. namespace {
  295. bool isUtf8Tail(unsigned char ch)
  296. {
  297. return in(ch, 0x80u, 0xbfu);
  298. }
  299. } // namespace
  300. bool isUtf8(const std::string& str)
  301. {
  302. for(std::string::const_iterator s = str.begin(), eos = str.end(); s != eos;
  303. ++s) {
  304. unsigned char firstChar = *s;
  305. // See ABNF in http://tools.ietf.org/search/rfc3629#section-4
  306. if(in(firstChar, 0x20u, 0x7eu) ||
  307. firstChar == 0x08u || // \b
  308. firstChar == 0x09u || // \t
  309. firstChar == 0x0au || // \n
  310. firstChar == 0x0cu || // \f
  311. firstChar == 0x0du // \r
  312. ) {
  313. // UTF8-1 (without ctrl chars)
  314. } else if(in(firstChar, 0xc2u, 0xdfu)) {
  315. // UTF8-2
  316. if(++s == eos || !isUtf8Tail(*s)) {
  317. return false;
  318. }
  319. } else if(0xe0u == firstChar) {
  320. // UTF8-3
  321. if(++s == eos || !in(static_cast<unsigned char>(*s), 0xa0u, 0xbfu) ||
  322. ++s == eos || !isUtf8Tail(*s)) {
  323. return false;
  324. }
  325. } else if(in(firstChar, 0xe1u, 0xecu) || in(firstChar, 0xeeu, 0xefu)) {
  326. // UTF8-3
  327. if(++s == eos || !isUtf8Tail(*s) ||
  328. ++s == eos || !isUtf8Tail(*s)) {
  329. return false;
  330. }
  331. } else if(0xedu == firstChar) {
  332. // UTF8-3
  333. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x9fu) ||
  334. ++s == eos || !isUtf8Tail(*s)) {
  335. return false;
  336. }
  337. } else if(0xf0u == firstChar) {
  338. // UTF8-4
  339. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x90u, 0xbfu) ||
  340. ++s == eos || !isUtf8Tail(*s) ||
  341. ++s == eos || !isUtf8Tail(*s)) {
  342. return false;
  343. }
  344. } else if(in(firstChar, 0xf1u, 0xf3u)) {
  345. // UTF8-4
  346. if(++s == eos || !isUtf8Tail(*s) ||
  347. ++s == eos || !isUtf8Tail(*s) ||
  348. ++s == eos || !isUtf8Tail(*s)) {
  349. return false;
  350. }
  351. } else if(0xf4u == firstChar) {
  352. // UTF8-4
  353. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x8fu) ||
  354. ++s == eos || !isUtf8Tail(*s) ||
  355. ++s == eos || !isUtf8Tail(*s)) {
  356. return false;
  357. }
  358. } else {
  359. return false;
  360. }
  361. }
  362. return true;
  363. }
  364. std::string percentEncode(const unsigned char* target, size_t len)
  365. {
  366. std::string dest;
  367. for(size_t i = 0; i < len; ++i) {
  368. if(inRFC3986UnreservedChars(target[i])) {
  369. dest += target[i];
  370. } else {
  371. dest.append(fmt("%%%02X", target[i]));
  372. }
  373. }
  374. return dest;
  375. }
  376. std::string percentEncode(const std::string& target)
  377. {
  378. return percentEncode(reinterpret_cast<const unsigned char*>(target.c_str()),
  379. target.size());
  380. }
  381. std::string percentEncodeMini(const std::string& src)
  382. {
  383. std::string result;
  384. for(std::string::const_iterator i = src.begin(), eoi = src.end(); i != eoi;
  385. ++i) {
  386. // Non-Printable ASCII and non-ASCII chars + some ASCII chars.
  387. unsigned char c = *i;
  388. if(in(c, 0x00u, 0x20u) || c >= 0x7fu ||
  389. // Chromium escapes following characters. Firefox4 escapes
  390. // more.
  391. c == '"' || c == '<' || c == '>') {
  392. result += fmt("%%%02X", c);
  393. } else {
  394. result += c;
  395. }
  396. }
  397. return result;
  398. }
  399. std::string torrentPercentEncode(const unsigned char* target, size_t len) {
  400. std::string dest;
  401. for(size_t i = 0; i < len; ++i) {
  402. if(isAlpha(target[i]) || isDigit(target[i])) {
  403. dest += target[i];
  404. } else {
  405. dest.append(fmt("%%%02X", target[i]));
  406. }
  407. }
  408. return dest;
  409. }
  410. std::string torrentPercentEncode(const std::string& target)
  411. {
  412. return torrentPercentEncode
  413. (reinterpret_cast<const unsigned char*>(target.c_str()), target.size());
  414. }
  415. std::string percentDecode
  416. (std::string::const_iterator first, std::string::const_iterator last)
  417. {
  418. std::string result;
  419. for(; first != last; ++first) {
  420. if(*first == '%') {
  421. if(first+1 != last && first+2 != last &&
  422. isHexDigit(*(first+1)) && isHexDigit(*(first+2))) {
  423. result += parseInt(first+1, first+3, 16);
  424. first += 2;
  425. } else {
  426. result += *first;
  427. }
  428. } else {
  429. result += *first;
  430. }
  431. }
  432. return result;
  433. }
  434. std::string toHex(const unsigned char* src, size_t len) {
  435. std::string out(len*2, '\0');
  436. std::string::iterator o = out.begin();
  437. const unsigned char* last = src+len;
  438. for(const unsigned char* i = src; i != last; ++i) {
  439. *o = (*i >> 4);
  440. *(o+1) = (*i)&0x0fu;
  441. for(int j = 0; j < 2; ++j) {
  442. if(*o < 10) {
  443. *o += '0';
  444. } else {
  445. *o += 'a'-10;
  446. }
  447. ++o;
  448. }
  449. }
  450. return out;
  451. }
  452. std::string toHex(const char* src, size_t len)
  453. {
  454. return toHex(reinterpret_cast<const unsigned char*>(src), len);
  455. }
  456. std::string toHex(const std::string& src)
  457. {
  458. return toHex(reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
  459. }
  460. namespace {
  461. unsigned int hexCharToUInt(unsigned char ch)
  462. {
  463. if('a' <= ch && ch <= 'f') {
  464. ch -= 'a';
  465. ch += 10;
  466. } else if('A' <= ch && ch <= 'F') {
  467. ch -= 'A';
  468. ch += 10;
  469. } else if('0' <= ch && ch <= '9') {
  470. ch -= '0';
  471. } else {
  472. ch = 255;
  473. }
  474. return ch;
  475. }
  476. } // namespace
  477. std::string fromHex(const std::string& src)
  478. {
  479. std::string dest;
  480. if(src.size()%2) {
  481. return dest;
  482. }
  483. for(size_t i = 0, eoi = src.size(); i < eoi; i += 2) {
  484. unsigned char high = hexCharToUInt(src[i]);
  485. unsigned char low = hexCharToUInt(src[i+1]);
  486. if(high == 255 || low == 255) {
  487. dest.clear();
  488. return dest;
  489. }
  490. dest += (high*16+low);
  491. }
  492. return dest;
  493. }
  494. FILE* openFile(const std::string& filename, const std::string& mode) {
  495. FILE* file = fopen(filename.c_str(), mode.c_str());
  496. return file;
  497. }
  498. bool isPowerOf(int num, int base) {
  499. if(base <= 0) { return false; }
  500. if(base == 1) { return true; }
  501. while(num%base == 0) {
  502. num /= base;
  503. if(num == 1) {
  504. return true;
  505. }
  506. }
  507. return false;
  508. }
  509. std::string secfmt(time_t sec) {
  510. std::string str;
  511. if(sec >= 3600) {
  512. str = itos(sec/3600);
  513. str += "h";
  514. sec %= 3600;
  515. }
  516. if(sec >= 60) {
  517. int min = sec/60;
  518. if(min < 10) {
  519. str += "0";
  520. }
  521. str += itos(min);
  522. str += "m";
  523. sec %= 60;
  524. }
  525. if(sec < 10) {
  526. str += "0";
  527. }
  528. str += itos(sec);
  529. str += "s";
  530. return str;
  531. }
  532. int getNum(const char* buf, int offset, size_t length) {
  533. char* temp = new char[length+1];
  534. memcpy(temp, buf+offset, length);
  535. temp[length] = '\0';
  536. int x = strtol(temp, 0, 10);
  537. delete [] temp;
  538. return x;
  539. }
  540. void parseIntSegments(SegList<int>& sgl, const std::string& src)
  541. {
  542. for(std::string::const_iterator i = src.begin(), eoi = src.end(); i != eoi;) {
  543. std::string::const_iterator j = std::find(i, eoi, ',');
  544. if(j == i) {
  545. ++i;
  546. continue;
  547. }
  548. std::string::const_iterator p = std::find(i, j, '-');
  549. if(p == j) {
  550. int a = parseInt(i, j);
  551. sgl.add(a, a+1);
  552. } else if(p == i || p+1 == j) {
  553. throw DL_ABORT_EX(fmt(MSG_INCOMPLETE_RANGE, std::string(i, j).c_str()));
  554. } else {
  555. int a = parseInt(i, p);
  556. int b = parseInt(p+1, j);
  557. sgl.add(a, b+1);
  558. }
  559. if(j == eoi) {
  560. break;
  561. }
  562. i = j+1;
  563. }
  564. }
  565. namespace {
  566. void computeHeadPieces
  567. (std::vector<size_t>& indexes,
  568. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  569. size_t pieceLength,
  570. uint64_t head)
  571. {
  572. if(head == 0) {
  573. return;
  574. }
  575. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  576. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  577. if((*fi)->getLength() == 0) {
  578. continue;
  579. }
  580. size_t lastIndex =
  581. ((*fi)->getOffset()+std::min(head, (*fi)->getLength())-1)/pieceLength;
  582. for(size_t index = (*fi)->getOffset()/pieceLength;
  583. index <= lastIndex; ++index) {
  584. indexes.push_back(index);
  585. }
  586. }
  587. }
  588. } // namespace
  589. namespace {
  590. void computeTailPieces
  591. (std::vector<size_t>& indexes,
  592. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  593. size_t pieceLength,
  594. uint64_t tail)
  595. {
  596. if(tail == 0) {
  597. return;
  598. }
  599. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  600. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  601. if((*fi)->getLength() == 0) {
  602. continue;
  603. }
  604. uint64_t endOffset = (*fi)->getLastOffset();
  605. size_t fromIndex =
  606. (endOffset-1-(std::min(tail, (*fi)->getLength())-1))/pieceLength;
  607. for(size_t index = fromIndex; index <= (endOffset-1)/pieceLength;
  608. ++index) {
  609. indexes.push_back(index);
  610. }
  611. }
  612. }
  613. } // namespace
  614. void parsePrioritizePieceRange
  615. (std::vector<size_t>& result, const std::string& src,
  616. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  617. size_t pieceLength,
  618. uint64_t defaultSize)
  619. {
  620. std::vector<size_t> indexes;
  621. std::vector<Scip> parts;
  622. const char A2_HEAD[] = "head";
  623. const char A2_HEADEQ[] = "head=";
  624. const char A2_TAIL[] = "tail";
  625. const char A2_TAILEQ[] = "tail=";
  626. splitIter(src.begin(), src.end(), std::back_inserter(parts), ',', true);
  627. for(std::vector<Scip>::const_iterator i = parts.begin(),
  628. eoi = parts.end(); i != eoi; ++i) {
  629. if(util::streq((*i).first, (*i).second, A2_HEAD, vend(A2_HEAD)-1)) {
  630. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  631. } else if(util::startsWith((*i).first, (*i).second,
  632. A2_HEADEQ, vend(A2_HEADEQ)-1)) {
  633. std::string sizestr((*i).first+5, (*i).second);
  634. computeHeadPieces(indexes, fileEntries, pieceLength,
  635. std::max((int64_t)0, getRealSize(sizestr)));
  636. } else if(util::streq((*i).first, (*i).second, A2_TAIL, vend(A2_TAIL)-1)) {
  637. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  638. } else if(util::startsWith((*i).first, (*i).second,
  639. A2_TAILEQ, vend(A2_TAILEQ)-1)) {
  640. std::string sizestr((*i).first+5, (*i).second);
  641. computeTailPieces(indexes, fileEntries, pieceLength,
  642. std::max((int64_t)0, getRealSize(sizestr)));
  643. } else {
  644. throw DL_ABORT_EX(fmt("Unrecognized token %s",
  645. std::string((*i).first, (*i).second).c_str()));
  646. }
  647. }
  648. std::sort(indexes.begin(), indexes.end());
  649. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  650. result.insert(result.end(), indexes.begin(), indexes.end());
  651. }
  652. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  653. // character not in ISO/IEC 8859-1, returns empty string.
  654. std::string iso8859ToUtf8(const std::string& src)
  655. {
  656. std::string dest;
  657. for(std::string::const_iterator itr = src.begin(), eoi = src.end();
  658. itr != eoi; ++itr) {
  659. unsigned char c = *itr;
  660. if(0xa0u <= c) {
  661. if(c <= 0xbfu) {
  662. dest += 0xc2u;
  663. } else {
  664. dest += 0xc3u;
  665. }
  666. dest += c&(~0x40u);
  667. } else if(0x80u <= c && c <= 0x9fu) {
  668. return A2STR::NIL;
  669. } else {
  670. dest += c;
  671. }
  672. }
  673. return dest;
  674. }
  675. namespace {
  676. template<typename OutputIterator>
  677. void parseParam(OutputIterator out, const std::string& header)
  678. {
  679. for(std::string::const_iterator i = header.begin(), eoi = header.end();
  680. i != eoi;) {
  681. std::string::const_iterator paramFirst = i;
  682. std::string::const_iterator paramLast = paramFirst;
  683. for(; paramLast != eoi && *paramLast != '=' && *paramLast != ';';
  684. ++paramLast);
  685. std::string param;
  686. if(paramLast == eoi || *paramLast == ';') {
  687. // No value, parmname only
  688. param = std::string(paramFirst, paramLast);
  689. } else {
  690. for(; paramLast != eoi && *paramLast != '"' && *paramLast != ';';
  691. ++paramLast);
  692. if(paramLast != eoi && *paramLast == '"') {
  693. // quoted-string
  694. ++paramLast;
  695. for(; paramLast != eoi && *paramLast != '"'; ++paramLast);
  696. if(paramLast != eoi) {
  697. ++paramLast;
  698. }
  699. param = std::string(paramFirst, paramLast);
  700. for(; paramLast != eoi && *paramLast != ';'; ++paramLast);
  701. } else {
  702. param = std::string(paramFirst, paramLast);
  703. }
  704. }
  705. param = strip(param);
  706. *out++ = param;
  707. if(paramLast == eoi) {
  708. break;
  709. }
  710. i = paramLast;
  711. ++i;
  712. }
  713. }
  714. } // namespace
  715. std::string getContentDispositionFilename(const std::string& header)
  716. {
  717. const char A2_KEYNAME[] = "filename";
  718. std::string filename;
  719. std::vector<std::string> params;
  720. parseParam(std::back_inserter(params), header);
  721. for(std::vector<std::string>::const_iterator i = params.begin(),
  722. eoi = params.end(); i != eoi; ++i) {
  723. const std::string& param = *i;
  724. std::string lowparam = toLower(param);
  725. if(!startsWith(lowparam.begin(), lowparam.end(),
  726. A2_KEYNAME, vend(A2_KEYNAME)-1) ||
  727. param.size() == sizeof(A2_KEYNAME)-1) {
  728. continue;
  729. }
  730. std::string::const_iterator markeritr = param.begin()+sizeof(A2_KEYNAME)-1;
  731. if(*markeritr == '*') {
  732. // See RFC2231 Section4 and draft-reschke-rfc2231-in-http.
  733. // Please note that this function doesn't do charset conversion
  734. // except that if iso-8859-1 is specified, it is converted to
  735. // utf-8.
  736. ++markeritr;
  737. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  738. if(markeritr == param.end() || *markeritr != '=') {
  739. continue;
  740. }
  741. std::vector<Scip> extValues;
  742. splitIter(markeritr+1, param.end(), std::back_inserter(extValues),
  743. '\'', true, true);
  744. if(extValues.size() != 3) {
  745. continue;
  746. }
  747. bool bad = false;
  748. for(std::string::const_iterator j = extValues[0].first,
  749. eoj = extValues[0].second; j != eoj; ++j) {
  750. // Since we first split parameter by ', we can safely assume
  751. // that ' is not included in charset.
  752. if(!inRFC2978MIMECharset(*j)) {
  753. bad = true;
  754. break;
  755. }
  756. }
  757. if(bad) {
  758. continue;
  759. }
  760. bad = false;
  761. for(std::string::const_iterator j = extValues[2].first,
  762. eoj = extValues[2].second; j != eoj; ++j){
  763. if(*j == '%') {
  764. if(j+1 != eoj && isHexDigit(*(j+1)) &&
  765. j+2 != eoj && isHexDigit(*(j+2))) {
  766. j += 2;
  767. } else {
  768. bad = true;
  769. break;
  770. }
  771. } else {
  772. if(*j == '*' || *j == '\'' || !inRFC2616HttpToken(*j)) {
  773. bad = true;
  774. break;
  775. }
  776. }
  777. }
  778. if(bad) {
  779. continue;
  780. }
  781. std::string value =
  782. percentDecode(extValues[2].first, extValues[2].second);
  783. const char A2_ISO88591[] = "iso-8859-1";
  784. if(util::strieq(extValues[0].first, extValues[0].second,
  785. A2_ISO88591, vend(A2_ISO88591)-1)) {
  786. value = iso8859ToUtf8(value);
  787. }
  788. if(!detectDirTraversal(value) &&
  789. value.find(A2STR::SLASH_C) == std::string::npos) {
  790. filename = value;
  791. }
  792. if(!filename.empty()) {
  793. break;
  794. }
  795. } else {
  796. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  797. if(markeritr == param.end() || markeritr+1 == param.end() ||
  798. *markeritr != '=') {
  799. continue;
  800. }
  801. Scip p = stripIter(markeritr+1, param.end());
  802. if(p.first == p.second) {
  803. continue;
  804. }
  805. std::string value(p.first, p.second);
  806. std::string::iterator filenameLast;
  807. if(value[0] == '\'' || value[0] == '"') {
  808. char qc = *value.begin();
  809. for(filenameLast = value.begin()+1;
  810. filenameLast != value.end() && *filenameLast != qc;
  811. ++filenameLast);
  812. } else {
  813. filenameLast = value.end();
  814. }
  815. static const std::string TRIMMED("\r\n\t '\"");
  816. value = percentDecode(value.begin(), filenameLast);
  817. value = strip(value, TRIMMED);
  818. value.erase(std::remove(value.begin(), value.end(), '\\'), value.end());
  819. if(!detectDirTraversal(value) &&
  820. value.find(A2STR::SLASH_C) == std::string::npos) {
  821. filename = value;
  822. }
  823. // continue because there is a chance we can find filename*=...
  824. }
  825. }
  826. return filename;
  827. }
  828. std::string randomAlpha(size_t length, const RandomizerHandle& randomizer) {
  829. static const char *random_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  830. std::string str;
  831. for(size_t i = 0; i < length; ++i) {
  832. size_t index = randomizer->getRandomNumber(strlen(random_chars));
  833. str += random_chars[index];
  834. }
  835. return str;
  836. }
  837. std::string toUpper(const std::string& src) {
  838. std::string temp = src;
  839. std::transform(temp.begin(), temp.end(), temp.begin(), ::toupper);
  840. return temp;
  841. }
  842. std::string toLower(const std::string& src) {
  843. std::string temp = src;
  844. std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
  845. return temp;
  846. }
  847. void uppercase(std::string& s)
  848. {
  849. std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  850. }
  851. void lowercase(std::string& s)
  852. {
  853. std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  854. }
  855. bool isNumericHost(const std::string& name)
  856. {
  857. struct addrinfo hints;
  858. struct addrinfo* res;
  859. memset(&hints, 0, sizeof(hints));
  860. hints.ai_family = AF_UNSPEC;
  861. hints.ai_flags = AI_NUMERICHOST;
  862. if(getaddrinfo(name.c_str(), 0, &hints, &res)) {
  863. return false;
  864. }
  865. freeaddrinfo(res);
  866. return true;
  867. }
  868. void setGlobalSignalHandler(int sig, void (*handler)(int), int flags) {
  869. #ifdef HAVE_SIGACTION
  870. struct sigaction sigact;
  871. sigact.sa_handler = handler;
  872. sigact.sa_flags = flags;
  873. sigemptyset(&sigact.sa_mask);
  874. sigaction(sig, &sigact, NULL);
  875. #else
  876. signal(sig, handler);
  877. #endif // HAVE_SIGACTION
  878. }
  879. std::string getHomeDir()
  880. {
  881. const char* p = getenv("HOME");
  882. if(p) {
  883. return p;
  884. } else {
  885. #ifdef __MINGW32__
  886. p = getenv("USERPROFILE");
  887. if(p) {
  888. return p;
  889. } else {
  890. p = getenv("HOMEDRIVE");
  891. if(p) {
  892. std::string homeDir = p;
  893. p = getenv("HOMEPATH");
  894. if(p) {
  895. homeDir += p;
  896. return homeDir;
  897. }
  898. }
  899. }
  900. #endif
  901. return A2STR::NIL;
  902. }
  903. }
  904. int64_t getRealSize(const std::string& sizeWithUnit)
  905. {
  906. std::string::size_type p = sizeWithUnit.find_first_of("KM");
  907. std::string size;
  908. int32_t mult = 1;
  909. if(p == std::string::npos) {
  910. size = sizeWithUnit;
  911. } else {
  912. if(sizeWithUnit[p] == 'K') {
  913. mult = 1024;
  914. } else if(sizeWithUnit[p] == 'M') {
  915. mult = 1024*1024;
  916. }
  917. size = sizeWithUnit.substr(0, p);
  918. }
  919. int64_t v = parseLLInt(size.begin(), size.end());
  920. if(v < 0) {
  921. throw DL_ABORT_EX(fmt("Negative value detected: %s", sizeWithUnit.c_str()));
  922. } else if(INT64_MAX/mult < v) {
  923. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  924. "overflow/underflow"));
  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&0x3ffu;
  937. size >>= 10;
  938. for(; i < numUnit-1 && size >= 1024; ++i) {
  939. r = size&0x3ffu;
  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.mkdirs()) {
  1048. int errNum = errno;
  1049. if(!dir.isDir()) {
  1050. throw DL_ABORT_EX3
  1051. (errNum,
  1052. fmt(EX_MAKE_DIR, dir.getPath().c_str(),
  1053. safeStrerror(errNum).c_str()),
  1054. error_code::DIR_CREATE_ERROR);
  1055. }
  1056. }
  1057. }
  1058. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1059. {
  1060. size_t numBlock = dest->countBlock();
  1061. for(size_t index = 0; index < numBlock; ++index) {
  1062. if(src->isBitSetOffsetRange((uint64_t)index*dest->getBlockLength(),
  1063. dest->getBlockLength())) {
  1064. dest->setBit(index);
  1065. }
  1066. }
  1067. }
  1068. std::string toString(const BinaryStreamHandle& binaryStream)
  1069. {
  1070. std::stringstream strm;
  1071. char data[2048];
  1072. while(1) {
  1073. int32_t dataLength = binaryStream->readData
  1074. (reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1075. strm.write(data, dataLength);
  1076. if(dataLength == 0) {
  1077. break;
  1078. }
  1079. }
  1080. return strm.str();
  1081. }
  1082. #ifdef HAVE_POSIX_MEMALIGN
  1083. /**
  1084. * In linux 2.6, alignment and size should be a multiple of 512.
  1085. */
  1086. void* allocateAlignedMemory(size_t alignment, size_t size)
  1087. {
  1088. void* buffer;
  1089. int res;
  1090. if((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1091. throw FATAL_EXCEPTION
  1092. (fmt("Error in posix_memalign: %s",
  1093. util::safeStrerror(res).c_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(fmt("Failed to get hostname and port. cause: %s",
  1107. gai_strerror(s)));
  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::pair<size_t, std::string>
  1134. parseIndexPath(const std::string& line)
  1135. {
  1136. std::pair<Scip, Scip> p;
  1137. divide(p, line.begin(), line.end(), '=');
  1138. size_t index = parseUInt(p.first.first, p.first.second);
  1139. if(p.second.first == p.second.second) {
  1140. throw DL_ABORT_EX(fmt("Path with index=%u is empty.",
  1141. static_cast<unsigned int>(index)));
  1142. }
  1143. return std::make_pair(index, std::string(p.second.first, p.second.second));
  1144. }
  1145. std::vector<std::pair<size_t, std::string> > createIndexPaths(std::istream& i)
  1146. {
  1147. std::vector<std::pair<size_t, std::string> > indexPaths;
  1148. std::string line;
  1149. while(getline(i, line)) {
  1150. indexPaths.push_back(parseIndexPath(line));
  1151. }
  1152. return indexPaths;
  1153. }
  1154. namespace {
  1155. void generateRandomDataRandom(unsigned char* data, size_t length)
  1156. {
  1157. const SharedHandle<SimpleRandomizer>& rd = SimpleRandomizer::getInstance();
  1158. for(size_t i = 0; i < length; ++i) {
  1159. data[i] = static_cast<unsigned long>(rd->getRandomNumber(256));
  1160. }
  1161. }
  1162. } // namespace
  1163. namespace {
  1164. void generateRandomDataUrandom(unsigned char* data, size_t length, int fd)
  1165. {
  1166. while(length > 0) {
  1167. ssize_t r;
  1168. while((r = read(fd, data, length)) == -1 && errno == EINTR);
  1169. if(r <= 0) {
  1170. generateRandomDataRandom(data, length);
  1171. return;
  1172. }
  1173. length -= r;
  1174. data += r;
  1175. }
  1176. }
  1177. } // namespace
  1178. void generateRandomData(unsigned char* data, size_t length)
  1179. {
  1180. #ifdef __MINGW32__
  1181. generateRandomDataRandom(data, length);
  1182. #else // !__MINGW32__
  1183. static int method = -1;
  1184. static int fd;
  1185. if(method == 0) {
  1186. generateRandomDataUrandom(data, length, fd);
  1187. } else if(method == 1) {
  1188. generateRandomDataRandom(data, length);
  1189. } else {
  1190. while((fd = open("/dev/urandom", O_RDONLY)) == -1 && errno == EINTR);
  1191. if(fd == -1) {
  1192. method = 1;
  1193. } else {
  1194. method = 0;
  1195. }
  1196. generateRandomData(data, length);
  1197. }
  1198. #endif // !__MINGW32__
  1199. }
  1200. bool saveAs
  1201. (const std::string& filename, const std::string& data, bool overwrite)
  1202. {
  1203. if(!overwrite && File(filename).exists()) {
  1204. return false;
  1205. }
  1206. std::string tempFilename = strconcat(filename, "__temp");
  1207. {
  1208. BufferedFile fp(tempFilename, BufferedFile::WRITE);
  1209. if(!fp) {
  1210. return false;
  1211. }
  1212. if(fp.write(data.data(), data.size()) != data.size()) {
  1213. return false;
  1214. }
  1215. if(fp.close() == EOF) {
  1216. return false;
  1217. }
  1218. }
  1219. return File(tempFilename).renameTo(filename);
  1220. }
  1221. std::string applyDir(const std::string& dir, const std::string& relPath)
  1222. {
  1223. std::string s;
  1224. if(dir.empty()) {
  1225. s = strconcat(A2STR::DOT_C, A2STR::SLASH_C, relPath);
  1226. } else if(dir == A2STR::SLASH_C) {
  1227. s = strconcat(A2STR::SLASH_C, relPath);
  1228. } else {
  1229. s = strconcat(dir, A2STR::SLASH_C, relPath);
  1230. }
  1231. #ifdef __MINGW32__
  1232. for(std::string::iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1233. if(*i == '\\') {
  1234. *i = '/';
  1235. }
  1236. }
  1237. #endif // __MINGW32__
  1238. return s;
  1239. }
  1240. std::string fixTaintedBasename(const std::string& src)
  1241. {
  1242. static std::string SLASH_REP = "%2F";
  1243. return escapePath(replace(src, A2STR::SLASH_C, SLASH_REP));
  1244. }
  1245. void generateRandomKey(unsigned char* key)
  1246. {
  1247. #ifdef ENABLE_MESSAGE_DIGEST
  1248. unsigned char bytes[40];
  1249. generateRandomData(bytes, sizeof(bytes));
  1250. message_digest::digest(key, 20, MessageDigest::sha1(), bytes, sizeof(bytes));
  1251. #else // !ENABLE_MESSAGE_DIGEST
  1252. generateRandomData(key, 20);
  1253. #endif // !ENABLE_MESSAGE_DIGEST
  1254. }
  1255. // Returns true is given numeric ipv4addr is in Private Address Space.
  1256. //
  1257. // From Section.3 RFC1918
  1258. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1259. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1260. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1261. bool inPrivateAddress(const std::string& ipv4addr)
  1262. {
  1263. const char A2_IP10[] = "10.";
  1264. const char A2_IP192[] = "192.168.";
  1265. if(util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1266. A2_IP10, vend(A2_IP10)-1) ||
  1267. util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1268. A2_IP192, vend(A2_IP192)-1)) {
  1269. return true;
  1270. }
  1271. std::string p172("172.");
  1272. if(util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1273. p172.begin(), p172.end())) {
  1274. for(int i = 16; i <= 31; ++i) {
  1275. std::string t(p172);
  1276. t += util::itos(i);
  1277. t += '.';
  1278. if(util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1279. t.begin(), t.end())) {
  1280. return true;
  1281. }
  1282. }
  1283. }
  1284. return false;
  1285. }
  1286. bool detectDirTraversal(const std::string& s)
  1287. {
  1288. if(s.empty()) {
  1289. return false;
  1290. }
  1291. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1292. unsigned char c = *i;
  1293. if(in(c, 0x00u, 0x1fu) || c == 0x7fu) {
  1294. return true;
  1295. }
  1296. }
  1297. const char A2_DS[] = "./";
  1298. const char A2_DDS[] = "../";
  1299. const char A2_SD[] = "/.";
  1300. const char A2_SDD[] = "/..";
  1301. const char A2_SDDS[] = "/../";
  1302. const char A2_SDS[] = "/./";
  1303. const char A2_DD[] = "..";
  1304. return s == A2STR::DOT_C ||
  1305. s == A2_DD ||
  1306. s[0] == '/' ||
  1307. util::startsWith(s.begin(), s.end(), A2_DS, vend(A2_DS)-1) ||
  1308. util::startsWith(s.begin(), s.end(), A2_DDS, vend(A2_DDS)-1) ||
  1309. s.find(A2_SDDS) != std::string::npos ||
  1310. s.find(A2_SDS) != std::string::npos ||
  1311. s[s.size()-1] == '/' ||
  1312. util::endsWith(s.begin(), s.end(), A2_SD, vend(A2_SD)-1) ||
  1313. util::endsWith(s.begin(), s.end(), A2_SDD, vend(A2_SDD)-1);
  1314. }
  1315. std::string escapePath(const std::string& s)
  1316. {
  1317. // We don't escape '/' because we use it as a path separator.
  1318. #ifdef __MINGW32__
  1319. static const char WIN_INVALID_PATH_CHARS[] =
  1320. { '"', '*', ':', '<', '>', '?', '\\', '|' };
  1321. #endif // __MINGW32__
  1322. std::string d;
  1323. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1324. unsigned char c = *i;
  1325. if(in(c, 0x00u, 0x1fu) || c == 0x7fu
  1326. #ifdef __MINGW32__
  1327. || std::find(vbegin(WIN_INVALID_PATH_CHARS),
  1328. vend(WIN_INVALID_PATH_CHARS),
  1329. c) != vend(WIN_INVALID_PATH_CHARS)
  1330. #endif // __MINGW32__
  1331. ){
  1332. d += fmt("%%%02X", c);
  1333. } else {
  1334. d += *i;
  1335. }
  1336. }
  1337. return d;
  1338. }
  1339. bool inSameCidrBlock
  1340. (const std::string& ip1, const std::string& ip2, size_t bits)
  1341. {
  1342. unsigned char s1[16], s2[16];
  1343. size_t len1, len2;
  1344. if((len1 = net::getBinAddr(s1, ip1)) == 0 ||
  1345. (len2 = net::getBinAddr(s2, ip2)) == 0 ||
  1346. len1 != len2) {
  1347. return false;
  1348. }
  1349. if(bits > 8*len1) {
  1350. bits = 8*len1;
  1351. }
  1352. int last = (bits-1)/8;
  1353. for(int i = 0; i < last; ++i) {
  1354. if(s1[i] != s2[i]) {
  1355. return false;
  1356. }
  1357. }
  1358. unsigned char mask = bitfield::lastByteMask(bits);
  1359. return (s1[last] & mask) == (s2[last] & mask);
  1360. }
  1361. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group)
  1362. {
  1363. removeMetalinkContentTypes(group.get());
  1364. }
  1365. void removeMetalinkContentTypes(RequestGroup* group)
  1366. {
  1367. for(std::vector<std::string>::const_iterator i =
  1368. DownloadHandlerConstants::getMetalinkContentTypes().begin(),
  1369. eoi = DownloadHandlerConstants::getMetalinkContentTypes().end();
  1370. i != eoi; ++i) {
  1371. group->removeAcceptType(*i);
  1372. }
  1373. }
  1374. namespace {
  1375. void executeHook
  1376. (const std::string& command,
  1377. a2_gid_t gid,
  1378. size_t numFiles,
  1379. const std::string& firstFilename)
  1380. {
  1381. const std::string gidStr = util::itos(gid);
  1382. const std::string numFilesStr = util::uitos(numFiles);
  1383. #ifndef __MINGW32__
  1384. A2_LOG_INFO(fmt("Executing user command: %s %s %s %s",
  1385. command.c_str(),
  1386. gidStr.c_str(),
  1387. numFilesStr.c_str(),
  1388. firstFilename.c_str()));
  1389. pid_t cpid = fork();
  1390. if(cpid == -1) {
  1391. A2_LOG_ERROR("fork() failed. Cannot execute user command.");
  1392. } else if(cpid == 0) {
  1393. execl(command.c_str(),
  1394. command.c_str(),
  1395. gidStr.c_str(),
  1396. numFilesStr.c_str(),
  1397. firstFilename.c_str(),
  1398. reinterpret_cast<char*>(0));
  1399. perror(("Could not execute user command: "+command).c_str());
  1400. exit(EXIT_FAILURE);
  1401. }
  1402. #else
  1403. PROCESS_INFORMATION pi;
  1404. STARTUPINFO si;
  1405. memset(&si, 0, sizeof (si));
  1406. si.cb = sizeof(STARTUPINFO);
  1407. memset(&pi, 0, sizeof (pi));
  1408. bool batch = util::endsWith(util::toLower(command), ".bat");
  1409. std::string cmdline;
  1410. std::string cmdexe;
  1411. if(batch) {
  1412. const char* p = getenv("windir");
  1413. if(p) {
  1414. cmdexe = std::string(p);
  1415. cmdexe += "\\system32\\cmd.exe";
  1416. } else {
  1417. A2_LOG_INFO("Failed to get windir environment variable."
  1418. " Executing batch file will fail.");
  1419. // TODO Might be useless.
  1420. cmdexe = "cmd.exe";
  1421. }
  1422. cmdline += "/C \"";
  1423. }
  1424. strappend(cmdline, "\"", command, "\"");
  1425. strappend(cmdline, " ", gidStr, " ", numFilesStr, " \"", firstFilename, "\"");
  1426. if(batch) {
  1427. cmdline += "\"";
  1428. }
  1429. A2_LOG_INFO(fmt("Executing user command: %s", cmdline.c_str()));
  1430. DWORD rc = CreateProcess(
  1431. batch ? cmdexe.c_str() : NULL,
  1432. (LPSTR)cmdline.c_str(),
  1433. NULL,
  1434. NULL,
  1435. true,
  1436. NULL,
  1437. NULL,
  1438. 0,
  1439. &si,
  1440. &pi);
  1441. if(!rc) {
  1442. A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command.");
  1443. }
  1444. #endif
  1445. }
  1446. } // namespace
  1447. void executeHookByOptName
  1448. (const SharedHandle<RequestGroup>& group, const Option* option,
  1449. const Pref* pref)
  1450. {
  1451. executeHookByOptName(group.get(), option, pref);
  1452. }
  1453. void executeHookByOptName
  1454. (const RequestGroup* group, const Option* option, const Pref* pref)
  1455. {
  1456. const std::string& cmd = option->get(pref);
  1457. if(!cmd.empty()) {
  1458. const SharedHandle<DownloadContext> dctx = group->getDownloadContext();
  1459. std::string firstFilename;
  1460. size_t numFiles = 0;
  1461. if(!group->inMemoryDownload()) {
  1462. SharedHandle<FileEntry> file = dctx->getFirstRequestedFileEntry();
  1463. if(file) {
  1464. firstFilename = file->getPath();
  1465. }
  1466. numFiles = dctx->countRequestedFileEntry();
  1467. }
  1468. executeHook(cmd, group->getGID(), numFiles, firstFilename);
  1469. }
  1470. }
  1471. std::string createSafePath
  1472. (const std::string& dir, const std::string& filename)
  1473. {
  1474. return util::applyDir
  1475. (dir,
  1476. util::isUtf8(filename)?
  1477. util::fixTaintedBasename(filename):
  1478. util::escapePath(util::percentEncode(filename)));
  1479. }
  1480. std::string encodeNonUtf8(const std::string& s)
  1481. {
  1482. return util::isUtf8(s)?s:util::percentEncode(s);
  1483. }
  1484. std::string makeString(const char* str)
  1485. {
  1486. if(str) {
  1487. return str;
  1488. } else {
  1489. return A2STR::NIL;
  1490. }
  1491. }
  1492. std::string safeStrerror(int errNum)
  1493. {
  1494. return makeString(strerror(errNum));
  1495. }
  1496. bool noProxyDomainMatch
  1497. (const std::string& hostname,
  1498. const std::string& domain)
  1499. {
  1500. if(!domain.empty() && domain[0] == '.' && !util::isNumericHost(hostname)) {
  1501. return util::endsWith(hostname, domain);
  1502. } else {
  1503. return hostname == domain;
  1504. }
  1505. }
  1506. } // namespace util
  1507. } // namespace aria2