util.cc 41 KB

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