util.cc 41 KB

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