util.cc 40 KB

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