util.cc 44 KB

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