util.cc 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684
  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. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr) {
  212. if(target.empty() || oldstr.empty()) {
  213. return target;
  214. }
  215. std::string result;
  216. std::string::size_type p = 0;
  217. std::string::size_type np = target.find(oldstr);
  218. while(np != std::string::npos) {
  219. result.append(target.begin()+p, target.begin()+np);
  220. result += newstr;
  221. p = np+oldstr.size();
  222. np = target.find(oldstr, p);
  223. }
  224. result.append(target.begin()+p, target.end());
  225. return result;
  226. }
  227. bool isAlpha(const char c)
  228. {
  229. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  230. }
  231. bool isDigit(const char c)
  232. {
  233. return '0' <= c && c <= '9';
  234. }
  235. bool isHexDigit(const char c)
  236. {
  237. return isDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
  238. }
  239. bool isHexDigit(const std::string& s)
  240. {
  241. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  242. if(!isHexDigit(*i)) {
  243. return false;
  244. }
  245. }
  246. return true;
  247. }
  248. bool inRFC3986ReservedChars(const char c)
  249. {
  250. static const char reserved[] = {
  251. ':' , '/' , '?' , '#' , '[' , ']' , '@',
  252. '!' , '$' , '&' , '\'' , '(' , ')',
  253. '*' , '+' , ',' , ';' , '=' };
  254. return std::find(vbegin(reserved), vend(reserved), c) != vend(reserved);
  255. }
  256. bool inRFC3986UnreservedChars(const char c)
  257. {
  258. static const char unreserved[] = { '-', '.', '_', '~' };
  259. return isAlpha(c) || isDigit(c) ||
  260. std::find(vbegin(unreserved), vend(unreserved), c) != vend(unreserved);
  261. }
  262. bool inRFC2978MIMECharset(const char c)
  263. {
  264. static const char chars[] = {
  265. '!', '#', '$', '%', '&',
  266. '\'', '+', '-', '^', '_',
  267. '`', '{', '}', '~'
  268. };
  269. return isAlpha(c) || isDigit(c) ||
  270. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  271. }
  272. bool inRFC2616HttpToken(const char c)
  273. {
  274. static const char chars[] = {
  275. '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.',
  276. '^', '_', '`', '|', '~'
  277. };
  278. return isAlpha(c) || isDigit(c) ||
  279. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  280. }
  281. namespace {
  282. bool isUtf8Tail(unsigned char ch)
  283. {
  284. return in(ch, 0x80u, 0xbfu);
  285. }
  286. } // namespace
  287. bool isUtf8(const std::string& str)
  288. {
  289. for(std::string::const_iterator s = str.begin(), eos = str.end(); s != eos;
  290. ++s) {
  291. unsigned char firstChar = *s;
  292. // See ABNF in http://tools.ietf.org/search/rfc3629#section-4
  293. if(in(firstChar, 0x20u, 0x7eu) ||
  294. firstChar == 0x08u || // \b
  295. firstChar == 0x09u || // \t
  296. firstChar == 0x0au || // \n
  297. firstChar == 0x0cu || // \f
  298. firstChar == 0x0du // \r
  299. ) {
  300. // UTF8-1 (without ctrl chars)
  301. } else if(in(firstChar, 0xc2u, 0xdfu)) {
  302. // UTF8-2
  303. if(++s == eos || !isUtf8Tail(*s)) {
  304. return false;
  305. }
  306. } else if(0xe0u == firstChar) {
  307. // UTF8-3
  308. if(++s == eos || !in(static_cast<unsigned char>(*s), 0xa0u, 0xbfu) ||
  309. ++s == eos || !isUtf8Tail(*s)) {
  310. return false;
  311. }
  312. } else if(in(firstChar, 0xe1u, 0xecu) || in(firstChar, 0xeeu, 0xefu)) {
  313. // UTF8-3
  314. if(++s == eos || !isUtf8Tail(*s) ||
  315. ++s == eos || !isUtf8Tail(*s)) {
  316. return false;
  317. }
  318. } else if(0xedu == firstChar) {
  319. // UTF8-3
  320. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x9fu) ||
  321. ++s == eos || !isUtf8Tail(*s)) {
  322. return false;
  323. }
  324. } else if(0xf0u == firstChar) {
  325. // UTF8-4
  326. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x90u, 0xbfu) ||
  327. ++s == eos || !isUtf8Tail(*s) ||
  328. ++s == eos || !isUtf8Tail(*s)) {
  329. return false;
  330. }
  331. } else if(in(firstChar, 0xf1u, 0xf3u)) {
  332. // UTF8-4
  333. if(++s == eos || !isUtf8Tail(*s) ||
  334. ++s == eos || !isUtf8Tail(*s) ||
  335. ++s == eos || !isUtf8Tail(*s)) {
  336. return false;
  337. }
  338. } else if(0xf4u == firstChar) {
  339. // UTF8-4
  340. if(++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x8fu) ||
  341. ++s == eos || !isUtf8Tail(*s) ||
  342. ++s == eos || !isUtf8Tail(*s)) {
  343. return false;
  344. }
  345. } else {
  346. return false;
  347. }
  348. }
  349. return true;
  350. }
  351. std::string percentEncode(const unsigned char* target, size_t len)
  352. {
  353. std::string dest;
  354. for(size_t i = 0; i < len; ++i) {
  355. if(inRFC3986UnreservedChars(target[i])) {
  356. dest += target[i];
  357. } else {
  358. dest.append(fmt("%%%02X", target[i]));
  359. }
  360. }
  361. return dest;
  362. }
  363. std::string percentEncode(const std::string& target)
  364. {
  365. return percentEncode(reinterpret_cast<const unsigned char*>(target.c_str()),
  366. target.size());
  367. }
  368. std::string percentEncodeMini(const std::string& src)
  369. {
  370. std::string result;
  371. for(std::string::const_iterator i = src.begin(), eoi = src.end(); i != eoi;
  372. ++i) {
  373. // Non-Printable ASCII and non-ASCII chars + some ASCII chars.
  374. unsigned char c = *i;
  375. if(in(c, 0x00u, 0x20u) || c >= 0x7fu ||
  376. // Chromium escapes following characters. Firefox4 escapes
  377. // more.
  378. c == '"' || c == '<' || c == '>') {
  379. result += fmt("%%%02X", c);
  380. } else {
  381. result += c;
  382. }
  383. }
  384. return result;
  385. }
  386. std::string torrentPercentEncode(const unsigned char* target, size_t len) {
  387. std::string dest;
  388. for(size_t i = 0; i < len; ++i) {
  389. if(isAlpha(target[i]) || isDigit(target[i])) {
  390. dest += target[i];
  391. } else {
  392. dest.append(fmt("%%%02X", target[i]));
  393. }
  394. }
  395. return dest;
  396. }
  397. std::string torrentPercentEncode(const std::string& target)
  398. {
  399. return torrentPercentEncode
  400. (reinterpret_cast<const unsigned char*>(target.c_str()), target.size());
  401. }
  402. std::string percentDecode
  403. (std::string::const_iterator first, std::string::const_iterator last)
  404. {
  405. std::string result;
  406. for(; first != last; ++first) {
  407. if(*first == '%') {
  408. if(first+1 != last && first+2 != last &&
  409. isHexDigit(*(first+1)) && isHexDigit(*(first+2))) {
  410. result += parseInt(std::string(first+1, first+3), 16);
  411. first += 2;
  412. } else {
  413. result += *first;
  414. }
  415. } else {
  416. result += *first;
  417. }
  418. }
  419. return result;
  420. }
  421. std::string toHex(const unsigned char* src, size_t len) {
  422. std::string out(len*2, '\0');
  423. std::string::iterator o = out.begin();
  424. const unsigned char* last = src+len;
  425. for(const unsigned char* i = src; i != last; ++i) {
  426. *o = (*i >> 4);
  427. *(o+1) = (*i)&0x0fu;
  428. for(int j = 0; j < 2; ++j) {
  429. if(*o < 10) {
  430. *o += '0';
  431. } else {
  432. *o += 'a'-10;
  433. }
  434. ++o;
  435. }
  436. }
  437. return out;
  438. }
  439. std::string toHex(const char* src, size_t len)
  440. {
  441. return toHex(reinterpret_cast<const unsigned char*>(src), len);
  442. }
  443. std::string toHex(const std::string& src)
  444. {
  445. return toHex(reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
  446. }
  447. unsigned int hexCharToUInt(unsigned char ch)
  448. {
  449. if('a' <= ch && ch <= 'f') {
  450. ch -= 'a';
  451. ch += 10;
  452. } else if('A' <= ch && ch <= 'F') {
  453. ch -= 'A';
  454. ch += 10;
  455. } else if('0' <= ch && ch <= '9') {
  456. ch -= '0';
  457. } else {
  458. ch = 255;
  459. }
  460. return ch;
  461. }
  462. FILE* openFile(const std::string& filename, const std::string& mode) {
  463. FILE* file = fopen(filename.c_str(), mode.c_str());
  464. return file;
  465. }
  466. bool isPowerOf(int num, int base) {
  467. if(base <= 0) { return false; }
  468. if(base == 1) { return true; }
  469. while(num%base == 0) {
  470. num /= base;
  471. if(num == 1) {
  472. return true;
  473. }
  474. }
  475. return false;
  476. }
  477. std::string secfmt(time_t sec) {
  478. time_t tsec = sec;
  479. std::string str;
  480. if(sec >= 3600) {
  481. str = fmt("%lldh", static_cast<long long int>(sec/3600));
  482. sec %= 3600;
  483. }
  484. if(sec >= 60) {
  485. str += fmt("%dm", static_cast<int>(sec/60));
  486. sec %= 60;
  487. }
  488. if(sec || tsec == 0) {
  489. str += fmt("%ds", static_cast<int>(sec));
  490. }
  491. return str;
  492. }
  493. int getNum(const char* buf, int offset, size_t length) {
  494. char* temp = new char[length+1];
  495. memcpy(temp, buf+offset, length);
  496. temp[length] = '\0';
  497. int x = strtol(temp, 0, 10);
  498. delete [] temp;
  499. return x;
  500. }
  501. namespace {
  502. template<typename T, typename F>
  503. bool parseLong(T& res, F f, const std::string& s, int base)
  504. {
  505. if(s.empty()) {
  506. return false;
  507. }
  508. char* endptr;
  509. errno = 0;
  510. res = f(s.c_str(), &endptr, base);
  511. if(errno == ERANGE) {
  512. return false;
  513. }
  514. if(*endptr != '\0') {
  515. for(const char* i = endptr, *eoi = s.c_str()+s.size(); i < eoi; ++i) {
  516. if(!isspace(*i)) {
  517. return false;
  518. }
  519. }
  520. }
  521. return true;
  522. }
  523. } // namespace
  524. bool parseIntNoThrow(int32_t& res, const std::string& s, int base)
  525. {
  526. long int t;
  527. if(parseLong(t, strtol, s, base) &&
  528. t >= std::numeric_limits<int32_t>::min() &&
  529. t <= std::numeric_limits<int32_t>::max()) {
  530. res = t;
  531. return true;
  532. } else {
  533. return false;
  534. }
  535. }
  536. int32_t parseInt(const std::string& s, int base)
  537. {
  538. int32_t res;
  539. if(parseIntNoThrow(res, s, base)) {
  540. return res;
  541. } else {
  542. throw DL_ABORT_EX
  543. (fmt("Failed to convert string into 32bit signed integer. '%s'",
  544. s.c_str()));
  545. }
  546. }
  547. bool parseUIntNoThrow(uint32_t& res, const std::string& s, int base)
  548. {
  549. long int t;
  550. if(parseLong(t, strtol, s, base) &&
  551. t >= 0 &&
  552. t <= std::numeric_limits<int32_t>::max()) {
  553. res = t;
  554. return true;
  555. } else {
  556. return false;
  557. }
  558. }
  559. uint32_t parseUInt(const std::string& s, int base)
  560. {
  561. uint32_t res;
  562. if(parseUIntNoThrow(res, s, base)) {
  563. return res;
  564. } else {
  565. throw DL_ABORT_EX
  566. (fmt("Failed to convert string into 32bit unsigned integer. '%s'",
  567. s.c_str()));
  568. }
  569. }
  570. bool parseLLIntNoThrow(int64_t& res, const std::string& s, int base)
  571. {
  572. long long int t;
  573. if(parseLong(t, strtoll, s, base) &&
  574. t >= std::numeric_limits<int64_t>::min() &&
  575. t <= std::numeric_limits<int64_t>::max()) {
  576. res = t;
  577. return true;
  578. } else {
  579. return false;
  580. }
  581. }
  582. int64_t parseLLInt(const std::string& s, int base)
  583. {
  584. int64_t res;
  585. if(parseLLIntNoThrow(res, s, base)) {
  586. return res;
  587. } else {
  588. throw DL_ABORT_EX
  589. (fmt("Failed to convert string into 64bit signed integer. '%s'",
  590. s.c_str()));
  591. }
  592. }
  593. bool parseULLIntNoThrow(uint64_t& res, const std::string& s, int base)
  594. {
  595. long int t;
  596. if(parseLong(t, strtoll, s, base) &&
  597. t >= 0 &&
  598. t <= std::numeric_limits<int64_t>::max()) {
  599. res = t;
  600. return true;
  601. } else {
  602. return false;
  603. }
  604. }
  605. uint64_t parseULLInt(const std::string& s, int base)
  606. {
  607. uint64_t res;
  608. if(parseULLIntNoThrow(res, s, base)) {
  609. return res;
  610. } else {
  611. throw DL_ABORT_EX
  612. (fmt("Failed to convert string into 64bit unsigned integer. '%s'",
  613. s.c_str()));
  614. }
  615. }
  616. void parseIntSegments(SegList<int>& sgl, const std::string& src)
  617. {
  618. for(std::string::const_iterator i = src.begin(), eoi = src.end(); i != eoi;) {
  619. std::string::const_iterator j = std::find(i, eoi, ',');
  620. if(j == i) {
  621. ++i;
  622. continue;
  623. }
  624. std::string::const_iterator p = std::find(i, j, '-');
  625. if(p == j) {
  626. int a = parseInt(std::string(i, j));
  627. sgl.add(a, a+1);
  628. } else if(p == i || p+1 == j) {
  629. throw DL_ABORT_EX(fmt(MSG_INCOMPLETE_RANGE, std::string(i, j).c_str()));
  630. } else {
  631. int a = parseInt(std::string(i, p));
  632. int b = parseInt(std::string(p+1, j));
  633. sgl.add(a, b+1);
  634. }
  635. if(j == eoi) {
  636. break;
  637. }
  638. i = j+1;
  639. }
  640. }
  641. namespace {
  642. void computeHeadPieces
  643. (std::vector<size_t>& indexes,
  644. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  645. size_t pieceLength,
  646. uint64_t head)
  647. {
  648. if(head == 0) {
  649. return;
  650. }
  651. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  652. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  653. if((*fi)->getLength() == 0) {
  654. continue;
  655. }
  656. size_t lastIndex =
  657. ((*fi)->getOffset()+std::min(head, (*fi)->getLength())-1)/pieceLength;
  658. for(size_t index = (*fi)->getOffset()/pieceLength;
  659. index <= lastIndex; ++index) {
  660. indexes.push_back(index);
  661. }
  662. }
  663. }
  664. } // namespace
  665. namespace {
  666. void computeTailPieces
  667. (std::vector<size_t>& indexes,
  668. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  669. size_t pieceLength,
  670. uint64_t tail)
  671. {
  672. if(tail == 0) {
  673. return;
  674. }
  675. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  676. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  677. if((*fi)->getLength() == 0) {
  678. continue;
  679. }
  680. uint64_t endOffset = (*fi)->getLastOffset();
  681. size_t fromIndex =
  682. (endOffset-1-(std::min(tail, (*fi)->getLength())-1))/pieceLength;
  683. for(size_t index = fromIndex; index <= (endOffset-1)/pieceLength;
  684. ++index) {
  685. indexes.push_back(index);
  686. }
  687. }
  688. }
  689. } // namespace
  690. void parsePrioritizePieceRange
  691. (std::vector<size_t>& result, const std::string& src,
  692. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  693. size_t pieceLength,
  694. uint64_t defaultSize)
  695. {
  696. std::vector<size_t> indexes;
  697. std::vector<Scip> parts;
  698. static const char A2_HEAD[] = "head";
  699. static const char A2_HEADEQ[] = "head=";
  700. static const char A2_TAIL[] = "tail";
  701. static const char A2_TAILEQ[] = "tail=";
  702. splitIter(src.begin(), src.end(), std::back_inserter(parts), ',', true);
  703. for(std::vector<Scip>::const_iterator i = parts.begin(),
  704. eoi = parts.end(); i != eoi; ++i) {
  705. if(util::streq((*i).first, (*i).second, A2_HEAD, vend(A2_HEAD)-1)) {
  706. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  707. } else if(util::startsWith((*i).first, (*i).second,
  708. A2_HEADEQ, vend(A2_HEADEQ)-1)) {
  709. std::string sizestr((*i).first+5, (*i).second);
  710. computeHeadPieces(indexes, fileEntries, pieceLength,
  711. std::max((int64_t)0, getRealSize(sizestr)));
  712. } else if(util::streq((*i).first, (*i).second, A2_TAIL, vend(A2_TAIL)-1)) {
  713. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  714. } else if(util::startsWith((*i).first, (*i).second,
  715. A2_TAILEQ, vend(A2_TAILEQ)-1)) {
  716. std::string sizestr((*i).first+5, (*i).second);
  717. computeTailPieces(indexes, fileEntries, pieceLength,
  718. std::max((int64_t)0, getRealSize(sizestr)));
  719. } else {
  720. throw DL_ABORT_EX(fmt("Unrecognized token %s",
  721. std::string((*i).first, (*i).second).c_str()));
  722. }
  723. }
  724. std::sort(indexes.begin(), indexes.end());
  725. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  726. result.insert(result.end(), indexes.begin(), indexes.end());
  727. }
  728. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  729. // character not in ISO/IEC 8859-1, returns empty string.
  730. std::string iso8859ToUtf8(const std::string& src)
  731. {
  732. std::string dest;
  733. for(std::string::const_iterator itr = src.begin(), eoi = src.end();
  734. itr != eoi; ++itr) {
  735. unsigned char c = *itr;
  736. if(0xa0u <= c) {
  737. if(c <= 0xbfu) {
  738. dest += 0xc2u;
  739. } else {
  740. dest += 0xc3u;
  741. }
  742. dest += c&(~0x40u);
  743. } else if(0x80u <= c && c <= 0x9fu) {
  744. return A2STR::NIL;
  745. } else {
  746. dest += c;
  747. }
  748. }
  749. return dest;
  750. }
  751. namespace {
  752. template<typename OutputIterator>
  753. void parseParam(OutputIterator out, const std::string& header)
  754. {
  755. for(std::string::const_iterator i = header.begin(), eoi = header.end();
  756. i != eoi;) {
  757. std::string::const_iterator paramFirst = i;
  758. std::string::const_iterator paramLast = paramFirst;
  759. for(; paramLast != eoi && *paramLast != '=' && *paramLast != ';';
  760. ++paramLast);
  761. std::string param;
  762. if(paramLast == eoi || *paramLast == ';') {
  763. // No value, parmname only
  764. param.assign(paramFirst, paramLast);
  765. } else {
  766. for(; paramLast != eoi && *paramLast != '"' && *paramLast != ';';
  767. ++paramLast);
  768. if(paramLast != eoi && *paramLast == '"') {
  769. // quoted-string
  770. ++paramLast;
  771. for(; paramLast != eoi && *paramLast != '"'; ++paramLast);
  772. if(paramLast != eoi) {
  773. ++paramLast;
  774. }
  775. param.assign(paramFirst, paramLast);
  776. for(; paramLast != eoi && *paramLast != ';'; ++paramLast);
  777. } else {
  778. param.assign(paramFirst, paramLast);
  779. }
  780. }
  781. param = strip(param);
  782. *out++ = param;
  783. if(paramLast == eoi) {
  784. break;
  785. }
  786. i = paramLast;
  787. ++i;
  788. }
  789. }
  790. } // namespace
  791. std::string getContentDispositionFilename(const std::string& header)
  792. {
  793. static const char A2_KEYNAME[] = "filename";
  794. std::string filename;
  795. std::vector<std::string> params;
  796. parseParam(std::back_inserter(params), header);
  797. for(std::vector<std::string>::const_iterator i = params.begin(),
  798. eoi = params.end(); i != eoi; ++i) {
  799. const std::string& param = *i;
  800. if(!istartsWith(param.begin(), param.end(),
  801. A2_KEYNAME, vend(A2_KEYNAME)-1) ||
  802. param.size() == sizeof(A2_KEYNAME)-1) {
  803. continue;
  804. }
  805. std::string::const_iterator markeritr = param.begin()+sizeof(A2_KEYNAME)-1;
  806. if(*markeritr == '*') {
  807. // See RFC2231 Section4 and draft-reschke-rfc2231-in-http.
  808. // Please note that this function doesn't do charset conversion
  809. // except that if iso-8859-1 is specified, it is converted to
  810. // utf-8.
  811. ++markeritr;
  812. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  813. if(markeritr == param.end() || *markeritr != '=') {
  814. continue;
  815. }
  816. std::vector<Scip> extValues;
  817. splitIter(markeritr+1, param.end(), std::back_inserter(extValues),
  818. '\'', true, true);
  819. if(extValues.size() != 3) {
  820. continue;
  821. }
  822. bool bad = false;
  823. for(std::string::const_iterator j = extValues[0].first,
  824. eoj = extValues[0].second; j != eoj; ++j) {
  825. // Since we first split parameter by ', we can safely assume
  826. // that ' is not included in charset.
  827. if(!inRFC2978MIMECharset(*j)) {
  828. bad = true;
  829. break;
  830. }
  831. }
  832. if(bad) {
  833. continue;
  834. }
  835. bad = false;
  836. for(std::string::const_iterator j = extValues[2].first,
  837. eoj = extValues[2].second; j != eoj; ++j){
  838. if(*j == '%') {
  839. if(j+1 != eoj && isHexDigit(*(j+1)) &&
  840. j+2 != eoj && isHexDigit(*(j+2))) {
  841. j += 2;
  842. } else {
  843. bad = true;
  844. break;
  845. }
  846. } else {
  847. if(*j == '*' || *j == '\'' || !inRFC2616HttpToken(*j)) {
  848. bad = true;
  849. break;
  850. }
  851. }
  852. }
  853. if(bad) {
  854. continue;
  855. }
  856. std::string value =
  857. percentDecode(extValues[2].first, extValues[2].second);
  858. static const char A2_ISO88591[] = "iso-8859-1";
  859. if(util::strieq(extValues[0].first, extValues[0].second,
  860. A2_ISO88591, vend(A2_ISO88591)-1)) {
  861. value = iso8859ToUtf8(value);
  862. }
  863. if(!detectDirTraversal(value) &&
  864. value.find(A2STR::SLASH_C) == std::string::npos) {
  865. filename = value;
  866. }
  867. if(!filename.empty()) {
  868. break;
  869. }
  870. } else {
  871. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  872. if(markeritr == param.end() || markeritr+1 == param.end() ||
  873. *markeritr != '=') {
  874. continue;
  875. }
  876. Scip p = stripIter(markeritr+1, param.end());
  877. if(p.first == p.second) {
  878. continue;
  879. }
  880. std::string value(p.first, p.second);
  881. std::string::iterator filenameLast;
  882. if(value[0] == '\'' || value[0] == '"') {
  883. char qc = *value.begin();
  884. for(filenameLast = value.begin()+1;
  885. filenameLast != value.end() && *filenameLast != qc;
  886. ++filenameLast);
  887. } else {
  888. filenameLast = value.end();
  889. }
  890. static const std::string TRIMMED("\r\n\t '\"");
  891. value = percentDecode(value.begin(), filenameLast);
  892. value = strip(value, TRIMMED);
  893. value.erase(std::remove(value.begin(), value.end(), '\\'), value.end());
  894. if(!detectDirTraversal(value) &&
  895. value.find(A2STR::SLASH_C) == std::string::npos) {
  896. filename = value;
  897. }
  898. // continue because there is a chance we can find filename*=...
  899. }
  900. }
  901. return filename;
  902. }
  903. std::string randomAlpha(size_t length, const RandomizerHandle& randomizer) {
  904. static const char *random_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  905. std::string str;
  906. for(size_t i = 0; i < length; ++i) {
  907. size_t index = randomizer->getRandomNumber(strlen(random_chars));
  908. str += random_chars[index];
  909. }
  910. return str;
  911. }
  912. std::string toUpper(const std::string& src) {
  913. std::string temp = src;
  914. std::transform(temp.begin(), temp.end(), temp.begin(), ::toupper);
  915. return temp;
  916. }
  917. std::string toLower(const std::string& src) {
  918. std::string temp = src;
  919. std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
  920. return temp;
  921. }
  922. void uppercase(std::string& s)
  923. {
  924. std::transform(s.begin(), s.end(), s.begin(), ::toupper);
  925. }
  926. void lowercase(std::string& s)
  927. {
  928. std::transform(s.begin(), s.end(), s.begin(), ::tolower);
  929. }
  930. bool isNumericHost(const std::string& name)
  931. {
  932. struct addrinfo hints;
  933. struct addrinfo* res;
  934. memset(&hints, 0, sizeof(hints));
  935. hints.ai_family = AF_UNSPEC;
  936. hints.ai_flags = AI_NUMERICHOST;
  937. if(getaddrinfo(name.c_str(), 0, &hints, &res)) {
  938. return false;
  939. }
  940. freeaddrinfo(res);
  941. return true;
  942. }
  943. void setGlobalSignalHandler(int sig, void (*handler)(int), int flags) {
  944. #ifdef HAVE_SIGACTION
  945. struct sigaction sigact;
  946. sigact.sa_handler = handler;
  947. sigact.sa_flags = flags;
  948. sigemptyset(&sigact.sa_mask);
  949. sigaction(sig, &sigact, NULL);
  950. #else
  951. signal(sig, handler);
  952. #endif // HAVE_SIGACTION
  953. }
  954. std::string getHomeDir()
  955. {
  956. const char* p = getenv("HOME");
  957. if(p) {
  958. return p;
  959. } else {
  960. #ifdef __MINGW32__
  961. p = getenv("USERPROFILE");
  962. if(p) {
  963. return p;
  964. } else {
  965. p = getenv("HOMEDRIVE");
  966. if(p) {
  967. std::string homeDir = p;
  968. p = getenv("HOMEPATH");
  969. if(p) {
  970. homeDir += p;
  971. return homeDir;
  972. }
  973. }
  974. }
  975. #endif
  976. return A2STR::NIL;
  977. }
  978. }
  979. int64_t getRealSize(const std::string& sizeWithUnit)
  980. {
  981. std::string::size_type p = sizeWithUnit.find_first_of("KM");
  982. std::string size;
  983. int32_t mult = 1;
  984. if(p == std::string::npos) {
  985. size = sizeWithUnit;
  986. } else {
  987. if(sizeWithUnit[p] == 'K') {
  988. mult = 1024;
  989. } else if(sizeWithUnit[p] == 'M') {
  990. mult = 1024*1024;
  991. }
  992. size.assign(sizeWithUnit.begin(), sizeWithUnit.begin()+p);
  993. }
  994. int64_t v = parseLLInt(size);
  995. if(v < 0) {
  996. throw DL_ABORT_EX(fmt("Negative value detected: %s", sizeWithUnit.c_str()));
  997. } else if(INT64_MAX/mult < v) {
  998. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  999. "overflow/underflow"));
  1000. }
  1001. return v*mult;
  1002. }
  1003. std::string abbrevSize(int64_t size)
  1004. {
  1005. if(size < 1024) {
  1006. return itos(size, true);
  1007. }
  1008. static const char units[] = { 'K', 'M' };
  1009. size_t i = 0;
  1010. int r = size&0x3ffu;
  1011. size >>= 10;
  1012. for(; i < sizeof(units)-1 && size >= 1024; ++i) {
  1013. r = size&0x3ffu;
  1014. size >>= 10;
  1015. }
  1016. std::string result = itos(size, true);
  1017. result += fmt(".%d%ci", r*10/1024, units[i]);
  1018. return result;
  1019. }
  1020. void sleep(long seconds) {
  1021. #ifdef HAVE_SLEEP
  1022. ::sleep(seconds);
  1023. #elif defined(HAVE_USLEEP)
  1024. ::usleep(seconds * 1000000);
  1025. #elif defined(HAVE_WINSOCK2_H)
  1026. ::Sleep(seconds * 1000);
  1027. #else
  1028. #error no sleep function is available (nanosleep?)
  1029. #endif
  1030. }
  1031. void usleep(long microseconds) {
  1032. #ifdef HAVE_USLEEP
  1033. ::usleep(microseconds);
  1034. #elif defined(HAVE_WINSOCK2_H)
  1035. LARGE_INTEGER current, freq, end;
  1036. static enum {GET_FREQUENCY, GET_MICROSECONDS, SKIP_MICROSECONDS} state = GET_FREQUENCY;
  1037. if (state == GET_FREQUENCY) {
  1038. if (QueryPerformanceFrequency(&freq))
  1039. state = GET_MICROSECONDS;
  1040. else
  1041. state = SKIP_MICROSECONDS;
  1042. }
  1043. long msec = microseconds / 1000;
  1044. microseconds %= 1000;
  1045. if (state == GET_MICROSECONDS && microseconds) {
  1046. QueryPerformanceCounter(&end);
  1047. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  1048. while (QueryPerformanceCounter(&current) && (current.QuadPart <= end.QuadPart))
  1049. /* noop */ ;
  1050. }
  1051. if (msec)
  1052. Sleep(msec);
  1053. #else
  1054. #error no usleep function is available (nanosleep?)
  1055. #endif
  1056. }
  1057. unsigned int alphaToNum(const std::string& alphabets)
  1058. {
  1059. if(alphabets.empty()) {
  1060. return 0;
  1061. }
  1062. char base;
  1063. if(islower(alphabets[0])) {
  1064. base = 'a';
  1065. } else {
  1066. base = 'A';
  1067. }
  1068. uint64_t num = 0;
  1069. for(size_t i = 0, eoi = alphabets.size(); i < eoi; ++i) {
  1070. unsigned int v = alphabets[i]-base;
  1071. num = num*26+v;
  1072. if(num > UINT32_MAX) {
  1073. return 0;
  1074. }
  1075. }
  1076. return num;
  1077. }
  1078. void mkdirs(const std::string& dirpath)
  1079. {
  1080. File dir(dirpath);
  1081. if(!dir.mkdirs()) {
  1082. int errNum = errno;
  1083. if(!dir.isDir()) {
  1084. throw DL_ABORT_EX3
  1085. (errNum,
  1086. fmt(EX_MAKE_DIR, dir.getPath().c_str(),
  1087. safeStrerror(errNum).c_str()),
  1088. error_code::DIR_CREATE_ERROR);
  1089. }
  1090. }
  1091. }
  1092. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1093. {
  1094. size_t numBlock = dest->countBlock();
  1095. for(size_t index = 0; index < numBlock; ++index) {
  1096. if(src->isBitSetOffsetRange((uint64_t)index*dest->getBlockLength(),
  1097. dest->getBlockLength())) {
  1098. dest->setBit(index);
  1099. }
  1100. }
  1101. }
  1102. std::string toString(const BinaryStreamHandle& binaryStream)
  1103. {
  1104. std::stringstream strm;
  1105. char data[2048];
  1106. while(1) {
  1107. int32_t dataLength = binaryStream->readData
  1108. (reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1109. strm.write(data, dataLength);
  1110. if(dataLength == 0) {
  1111. break;
  1112. }
  1113. }
  1114. return strm.str();
  1115. }
  1116. #ifdef HAVE_POSIX_MEMALIGN
  1117. /**
  1118. * In linux 2.6, alignment and size should be a multiple of 512.
  1119. */
  1120. void* allocateAlignedMemory(size_t alignment, size_t size)
  1121. {
  1122. void* buffer;
  1123. int res;
  1124. if((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1125. throw FATAL_EXCEPTION
  1126. (fmt("Error in posix_memalign: %s",
  1127. util::safeStrerror(res).c_str()));
  1128. }
  1129. return buffer;
  1130. }
  1131. #endif // HAVE_POSIX_MEMALIGN
  1132. std::pair<std::string, uint16_t>
  1133. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1134. {
  1135. char host[NI_MAXHOST];
  1136. char service[NI_MAXSERV];
  1137. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1138. NI_NUMERICHOST|NI_NUMERICSERV);
  1139. if(s != 0) {
  1140. throw DL_ABORT_EX(fmt("Failed to get hostname and port. cause: %s",
  1141. gai_strerror(s)));
  1142. }
  1143. return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO
  1144. }
  1145. std::string htmlEscape(const std::string& src)
  1146. {
  1147. std::string dest;
  1148. for(std::string::const_iterator i = src.begin(), eoi = src.end();
  1149. i != eoi; ++i) {
  1150. char ch = *i;
  1151. if(ch == '<') {
  1152. dest += "&lt;";
  1153. } else if(ch == '>') {
  1154. dest += "&gt;";
  1155. } else if(ch == '&') {
  1156. dest += "&amp;";
  1157. } else if(ch == '\'') {
  1158. dest += "&#39;";
  1159. } else if(ch == '"') {
  1160. dest += "&quot;";
  1161. } else {
  1162. dest += ch;
  1163. }
  1164. }
  1165. return dest;
  1166. }
  1167. std::pair<size_t, std::string>
  1168. parseIndexPath(const std::string& line)
  1169. {
  1170. std::pair<Scip, Scip> p;
  1171. divide(p, line.begin(), line.end(), '=');
  1172. size_t index = parseUInt(std::string(p.first.first, p.first.second));
  1173. if(p.second.first == p.second.second) {
  1174. throw DL_ABORT_EX(fmt("Path with index=%u is empty.",
  1175. static_cast<unsigned int>(index)));
  1176. }
  1177. return std::make_pair(index, std::string(p.second.first, p.second.second));
  1178. }
  1179. std::vector<std::pair<size_t, std::string> > createIndexPaths(std::istream& i)
  1180. {
  1181. std::vector<std::pair<size_t, std::string> > indexPaths;
  1182. std::string line;
  1183. while(getline(i, line)) {
  1184. indexPaths.push_back(parseIndexPath(line));
  1185. }
  1186. return indexPaths;
  1187. }
  1188. namespace {
  1189. void generateRandomDataRandom(unsigned char* data, size_t length)
  1190. {
  1191. const SharedHandle<SimpleRandomizer>& rd = SimpleRandomizer::getInstance();
  1192. for(size_t i = 0; i < length; ++i) {
  1193. data[i] = static_cast<unsigned long>(rd->getRandomNumber(256));
  1194. }
  1195. }
  1196. } // namespace
  1197. namespace {
  1198. void generateRandomDataUrandom(unsigned char* data, size_t length, int fd)
  1199. {
  1200. while(length > 0) {
  1201. ssize_t r;
  1202. while((r = read(fd, data, length)) == -1 && errno == EINTR);
  1203. if(r <= 0) {
  1204. generateRandomDataRandom(data, length);
  1205. return;
  1206. }
  1207. length -= r;
  1208. data += r;
  1209. }
  1210. }
  1211. } // namespace
  1212. void generateRandomData(unsigned char* data, size_t length)
  1213. {
  1214. #ifdef __MINGW32__
  1215. generateRandomDataRandom(data, length);
  1216. #else // !__MINGW32__
  1217. static int method = -1;
  1218. static int fd;
  1219. if(method == 0) {
  1220. generateRandomDataUrandom(data, length, fd);
  1221. } else if(method == 1) {
  1222. generateRandomDataRandom(data, length);
  1223. } else {
  1224. while((fd = open("/dev/urandom", O_RDONLY)) == -1 && errno == EINTR);
  1225. if(fd == -1) {
  1226. method = 1;
  1227. } else {
  1228. method = 0;
  1229. }
  1230. generateRandomData(data, length);
  1231. }
  1232. #endif // !__MINGW32__
  1233. }
  1234. bool saveAs
  1235. (const std::string& filename, const std::string& data, bool overwrite)
  1236. {
  1237. if(!overwrite && File(filename).exists()) {
  1238. return false;
  1239. }
  1240. std::string tempFilename = filename;
  1241. tempFilename += "__temp";
  1242. {
  1243. BufferedFile fp(tempFilename, BufferedFile::WRITE);
  1244. if(!fp) {
  1245. return false;
  1246. }
  1247. if(fp.write(data.data(), data.size()) != data.size()) {
  1248. return false;
  1249. }
  1250. if(fp.close() == EOF) {
  1251. return false;
  1252. }
  1253. }
  1254. return File(tempFilename).renameTo(filename);
  1255. }
  1256. std::string applyDir(const std::string& dir, const std::string& relPath)
  1257. {
  1258. std::string s;
  1259. if(dir.empty()) {
  1260. s = "./";
  1261. s += relPath;
  1262. } else {
  1263. s = dir;
  1264. if(dir == "/") {
  1265. s += relPath;
  1266. } else {
  1267. s += "/";
  1268. s += relPath;
  1269. }
  1270. }
  1271. #ifdef __MINGW32__
  1272. for(std::string::iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1273. if(*i == '\\') {
  1274. *i = '/';
  1275. }
  1276. }
  1277. #endif // __MINGW32__
  1278. return s;
  1279. }
  1280. std::string fixTaintedBasename(const std::string& src)
  1281. {
  1282. static std::string SLASH_REP = "%2F";
  1283. return escapePath(replace(src, A2STR::SLASH_C, SLASH_REP));
  1284. }
  1285. void generateRandomKey(unsigned char* key)
  1286. {
  1287. #ifdef ENABLE_MESSAGE_DIGEST
  1288. unsigned char bytes[40];
  1289. generateRandomData(bytes, sizeof(bytes));
  1290. message_digest::digest(key, 20, MessageDigest::sha1(), bytes, sizeof(bytes));
  1291. #else // !ENABLE_MESSAGE_DIGEST
  1292. generateRandomData(key, 20);
  1293. #endif // !ENABLE_MESSAGE_DIGEST
  1294. }
  1295. // Returns true is given numeric ipv4addr is in Private Address Space.
  1296. //
  1297. // From Section.3 RFC1918
  1298. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1299. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1300. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1301. bool inPrivateAddress(const std::string& ipv4addr)
  1302. {
  1303. static const char A2_IP10[] = "10.";
  1304. static const char A2_IP192[] = "192.168.";
  1305. static const char A2_IP172[] = "172.";
  1306. if(util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1307. A2_IP10, vend(A2_IP10)-1) ||
  1308. util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1309. A2_IP192, vend(A2_IP192)-1)) {
  1310. return true;
  1311. }
  1312. if(util::startsWith(ipv4addr.begin(), ipv4addr.end(),
  1313. A2_IP172, vend(A2_IP172)-1)) {
  1314. for(int i = 16; i <= 31; ++i) {
  1315. std::string t(fmt("%d.", i));
  1316. if(util::startsWith(ipv4addr.begin()+4, ipv4addr.end(),
  1317. t.begin(), t.end())) {
  1318. return true;
  1319. }
  1320. }
  1321. }
  1322. return false;
  1323. }
  1324. bool detectDirTraversal(const std::string& s)
  1325. {
  1326. if(s.empty()) {
  1327. return false;
  1328. }
  1329. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1330. unsigned char c = *i;
  1331. if(in(c, 0x00u, 0x1fu) || c == 0x7fu) {
  1332. return true;
  1333. }
  1334. }
  1335. static const char A2_DS[] = "./";
  1336. static const char A2_DDS[] = "../";
  1337. static const char A2_SD[] = "/.";
  1338. static const char A2_SDD[] = "/..";
  1339. static const char A2_SDDS[] = "/../";
  1340. static const char A2_SDS[] = "/./";
  1341. static const char A2_DD[] = "..";
  1342. return s == A2STR::DOT_C ||
  1343. s == A2_DD ||
  1344. s[0] == '/' ||
  1345. util::startsWith(s.begin(), s.end(), A2_DS, vend(A2_DS)-1) ||
  1346. util::startsWith(s.begin(), s.end(), A2_DDS, vend(A2_DDS)-1) ||
  1347. s.find(A2_SDDS) != std::string::npos ||
  1348. s.find(A2_SDS) != std::string::npos ||
  1349. s[s.size()-1] == '/' ||
  1350. util::endsWith(s.begin(), s.end(), A2_SD, vend(A2_SD)-1) ||
  1351. util::endsWith(s.begin(), s.end(), A2_SDD, vend(A2_SDD)-1);
  1352. }
  1353. std::string escapePath(const std::string& s)
  1354. {
  1355. // We don't escape '/' because we use it as a path separator.
  1356. #ifdef __MINGW32__
  1357. static const char WIN_INVALID_PATH_CHARS[] =
  1358. { '"', '*', ':', '<', '>', '?', '\\', '|' };
  1359. #endif // __MINGW32__
  1360. std::string d;
  1361. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1362. unsigned char c = *i;
  1363. if(in(c, 0x00u, 0x1fu) || c == 0x7fu
  1364. #ifdef __MINGW32__
  1365. || std::find(vbegin(WIN_INVALID_PATH_CHARS),
  1366. vend(WIN_INVALID_PATH_CHARS),
  1367. c) != vend(WIN_INVALID_PATH_CHARS)
  1368. #endif // __MINGW32__
  1369. ){
  1370. d += fmt("%%%02X", c);
  1371. } else {
  1372. d += *i;
  1373. }
  1374. }
  1375. return d;
  1376. }
  1377. bool inSameCidrBlock
  1378. (const std::string& ip1, const std::string& ip2, size_t bits)
  1379. {
  1380. unsigned char s1[16], s2[16];
  1381. size_t len1, len2;
  1382. if((len1 = net::getBinAddr(s1, ip1)) == 0 ||
  1383. (len2 = net::getBinAddr(s2, ip2)) == 0 ||
  1384. len1 != len2) {
  1385. return false;
  1386. }
  1387. if(bits == 0) {
  1388. return true;
  1389. }
  1390. if(bits > 8*len1) {
  1391. bits = 8*len1;
  1392. }
  1393. int last = (bits-1)/8;
  1394. for(int i = 0; i < last; ++i) {
  1395. if(s1[i] != s2[i]) {
  1396. return false;
  1397. }
  1398. }
  1399. unsigned char mask = bitfield::lastByteMask(bits);
  1400. return (s1[last] & mask) == (s2[last] & mask);
  1401. }
  1402. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group)
  1403. {
  1404. removeMetalinkContentTypes(group.get());
  1405. }
  1406. void removeMetalinkContentTypes(RequestGroup* group)
  1407. {
  1408. for(std::vector<std::string>::const_iterator i =
  1409. DownloadHandlerConstants::getMetalinkContentTypes().begin(),
  1410. eoi = DownloadHandlerConstants::getMetalinkContentTypes().end();
  1411. i != eoi; ++i) {
  1412. group->removeAcceptType(*i);
  1413. }
  1414. }
  1415. namespace {
  1416. void executeHook
  1417. (const std::string& command,
  1418. a2_gid_t gid,
  1419. size_t numFiles,
  1420. const std::string& firstFilename)
  1421. {
  1422. const std::string gidStr = util::itos(gid);
  1423. const std::string numFilesStr = util::uitos(numFiles);
  1424. #ifndef __MINGW32__
  1425. A2_LOG_INFO(fmt("Executing user command: %s %s %s %s",
  1426. command.c_str(),
  1427. gidStr.c_str(),
  1428. numFilesStr.c_str(),
  1429. firstFilename.c_str()));
  1430. pid_t cpid = fork();
  1431. if(cpid == -1) {
  1432. A2_LOG_ERROR("fork() failed. Cannot execute user command.");
  1433. } else if(cpid == 0) {
  1434. execl(command.c_str(),
  1435. command.c_str(),
  1436. gidStr.c_str(),
  1437. numFilesStr.c_str(),
  1438. firstFilename.c_str(),
  1439. reinterpret_cast<char*>(0));
  1440. perror(("Could not execute user command: "+command).c_str());
  1441. exit(EXIT_FAILURE);
  1442. }
  1443. #else
  1444. PROCESS_INFORMATION pi;
  1445. STARTUPINFO si;
  1446. memset(&si, 0, sizeof (si));
  1447. si.cb = sizeof(STARTUPINFO);
  1448. memset(&pi, 0, sizeof (pi));
  1449. static const char A2_BAT[] = ".bat";
  1450. bool batch = util::iendsWith(command.begin(), command.end(),
  1451. A2_BAT, vend(A2_BAT)-1);
  1452. std::string cmdline;
  1453. std::string cmdexe;
  1454. if(batch) {
  1455. const char* p = getenv("windir");
  1456. if(p) {
  1457. cmdexe = p;
  1458. cmdexe += "\\system32\\cmd.exe";
  1459. } else {
  1460. A2_LOG_INFO("Failed to get windir environment variable."
  1461. " Executing batch file will fail.");
  1462. // TODO Might be useless.
  1463. cmdexe = "cmd.exe";
  1464. }
  1465. cmdline += "/C \"";
  1466. }
  1467. cmdline += "\"";
  1468. cmdline += command;
  1469. cmdline += "\"";
  1470. cmdline += " ";
  1471. cmdline += gidStr;
  1472. cmdline += " ";
  1473. cmdline += numFilesStr;
  1474. cmdline += " \"";
  1475. cmdline += firstFilename;
  1476. cmdline += "\"";
  1477. if(batch) {
  1478. cmdline += "\"";
  1479. }
  1480. A2_LOG_INFO(fmt("Executing user command: %s", cmdline.c_str()));
  1481. DWORD rc = CreateProcess(
  1482. batch ? cmdexe.c_str() : NULL,
  1483. (LPSTR)cmdline.c_str(),
  1484. NULL,
  1485. NULL,
  1486. true,
  1487. NULL,
  1488. NULL,
  1489. 0,
  1490. &si,
  1491. &pi);
  1492. if(!rc) {
  1493. A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command.");
  1494. }
  1495. #endif
  1496. }
  1497. } // namespace
  1498. void executeHookByOptName
  1499. (const SharedHandle<RequestGroup>& group, const Option* option,
  1500. const Pref* pref)
  1501. {
  1502. executeHookByOptName(group.get(), option, pref);
  1503. }
  1504. void executeHookByOptName
  1505. (const RequestGroup* group, const Option* option, const Pref* pref)
  1506. {
  1507. const std::string& cmd = option->get(pref);
  1508. if(!cmd.empty()) {
  1509. const SharedHandle<DownloadContext> dctx = group->getDownloadContext();
  1510. std::string firstFilename;
  1511. size_t numFiles = 0;
  1512. if(!group->inMemoryDownload()) {
  1513. SharedHandle<FileEntry> file = dctx->getFirstRequestedFileEntry();
  1514. if(file) {
  1515. firstFilename = file->getPath();
  1516. }
  1517. numFiles = dctx->countRequestedFileEntry();
  1518. }
  1519. executeHook(cmd, group->getGID(), numFiles, firstFilename);
  1520. }
  1521. }
  1522. std::string createSafePath
  1523. (const std::string& dir, const std::string& filename)
  1524. {
  1525. return util::applyDir
  1526. (dir,
  1527. util::isUtf8(filename)?
  1528. util::fixTaintedBasename(filename):
  1529. util::escapePath(util::percentEncode(filename)));
  1530. }
  1531. std::string encodeNonUtf8(const std::string& s)
  1532. {
  1533. return util::isUtf8(s)?s:util::percentEncode(s);
  1534. }
  1535. std::string makeString(const char* str)
  1536. {
  1537. if(str) {
  1538. return str;
  1539. } else {
  1540. return A2STR::NIL;
  1541. }
  1542. }
  1543. std::string safeStrerror(int errNum)
  1544. {
  1545. return makeString(strerror(errNum));
  1546. }
  1547. bool noProxyDomainMatch
  1548. (const std::string& hostname,
  1549. const std::string& domain)
  1550. {
  1551. if(!domain.empty() && domain[0] == '.' && !util::isNumericHost(hostname)) {
  1552. return util::endsWith(hostname.begin(), hostname.end(),
  1553. domain.begin(), domain.end());
  1554. } else {
  1555. return hostname == domain;
  1556. }
  1557. }
  1558. } // namespace util
  1559. } // namespace aria2