util.cc 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  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. #ifdef __sun
  37. // For opensolaris, just include signal.h which includes sys/signal.h
  38. #ifdef HAVE_SIGNAL_H
  39. #include <signal.h>
  40. #endif // HAVE_SIGNAL_H
  41. #else // !__sun
  42. #ifdef HAVE_SYS_SIGNAL_H
  43. #include <sys/signal.h>
  44. #endif // HAVE_SYS_SIGNAL_H
  45. #ifdef HAVE_SIGNAL_H
  46. #include <signal.h>
  47. #endif // HAVE_SIGNAL_H
  48. #endif // !__sun
  49. #include <sys/types.h>
  50. #ifdef HAVE_PWD_H
  51. #include <pwd.h>
  52. #endif // HAVE_PWD_H
  53. #include <array>
  54. #include <cerrno>
  55. #include <cassert>
  56. #include <cstring>
  57. #include <cstdio>
  58. #include <cstdlib>
  59. #include <sstream>
  60. #include <ostream>
  61. #include <algorithm>
  62. #include <fstream>
  63. #include <iomanip>
  64. #include "SimpleRandomizer.h"
  65. #include "File.h"
  66. #include "Randomizer.h"
  67. #include "a2netcompat.h"
  68. #include "BitfieldMan.h"
  69. #include "DefaultDiskWriter.h"
  70. #include "FatalException.h"
  71. #include "FileEntry.h"
  72. #include "A2STR.h"
  73. #include "array_fun.h"
  74. #include "bitfield.h"
  75. #include "DownloadHandlerConstants.h"
  76. #include "RequestGroup.h"
  77. #include "LogFactory.h"
  78. #include "Logger.h"
  79. #include "Option.h"
  80. #include "DownloadContext.h"
  81. #include "BufferedFile.h"
  82. #include "SocketCore.h"
  83. #include "Lock.h"
  84. #include "MessageDigest.h"
  85. #include "message_digest_helper.h"
  86. // For libc6 which doesn't define ULLONG_MAX properly because of broken limits.h
  87. #ifndef ULLONG_MAX
  88. #define ULLONG_MAX 18446744073709551615ULL
  89. #endif // ULLONG_MAX
  90. namespace aria2 {
  91. #ifdef __MINGW32__
  92. namespace {
  93. int utf8ToWChar(wchar_t* out, size_t outLength, const char* src)
  94. {
  95. return MultiByteToWideChar(CP_UTF8, 0, src, -1, out, outLength);
  96. }
  97. } // namespace
  98. namespace {
  99. int wCharToUtf8(char* out, size_t outLength, const wchar_t* src)
  100. {
  101. return WideCharToMultiByte(CP_UTF8, 0, src, -1, out, outLength, nullptr,
  102. nullptr);
  103. }
  104. } // namespace
  105. std::wstring utf8ToWChar(const char* src)
  106. {
  107. int len = utf8ToWChar(nullptr, 0, src);
  108. if (len <= 0) {
  109. abort();
  110. }
  111. auto buf = make_unique<wchar_t[]>((size_t)len);
  112. len = utf8ToWChar(buf.get(), len, src);
  113. if (len <= 0) {
  114. abort();
  115. }
  116. else {
  117. return buf.get();
  118. }
  119. }
  120. std::wstring utf8ToWChar(const std::string& src)
  121. {
  122. return utf8ToWChar(src.c_str());
  123. }
  124. std::string wCharToUtf8(const std::wstring& wsrc)
  125. {
  126. int len = wCharToUtf8(nullptr, 0, wsrc.c_str());
  127. if (len <= 0) {
  128. abort();
  129. }
  130. auto buf = make_unique<char[]>((size_t)len);
  131. len = wCharToUtf8(buf.get(), len, wsrc.c_str());
  132. if (len <= 0) {
  133. abort();
  134. }
  135. else {
  136. return buf.get();
  137. }
  138. }
  139. std::string toForwardSlash(const std::string& src)
  140. {
  141. auto dst = src;
  142. std::transform(std::begin(dst), std::end(dst), std::begin(dst),
  143. [](char c) { return c == '\\' ? '/' : c; });
  144. return dst;
  145. }
  146. #endif // __MINGW32__
  147. namespace util {
  148. const char DEFAULT_STRIP_CHARSET[] = "\r\n\t ";
  149. std::string strip(const std::string& str, const char* chars)
  150. {
  151. std::pair<std::string::const_iterator, std::string::const_iterator> p =
  152. stripIter(str.begin(), str.end(), chars);
  153. return std::string(p.first, p.second);
  154. }
  155. std::string itos(int64_t value, bool comma)
  156. {
  157. bool flag = false;
  158. std::string str;
  159. if (value < 0) {
  160. if (value == INT64_MIN) {
  161. if (comma) {
  162. str = "-9,223,372,036,854,775,808";
  163. }
  164. else {
  165. str = "-9223372036854775808";
  166. }
  167. return str;
  168. }
  169. flag = true;
  170. value = -value;
  171. }
  172. str = uitos(value, comma);
  173. if (flag) {
  174. str.insert(str.begin(), '-');
  175. }
  176. return str;
  177. }
  178. int64_t difftv(struct timeval tv1, struct timeval tv2)
  179. {
  180. if ((tv1.tv_sec < tv2.tv_sec) ||
  181. ((tv1.tv_sec == tv2.tv_sec) && (tv1.tv_usec < tv2.tv_usec))) {
  182. return 0;
  183. }
  184. return ((int64_t)(tv1.tv_sec - tv2.tv_sec) * 1000000 + tv1.tv_usec -
  185. tv2.tv_usec);
  186. }
  187. int32_t difftvsec(struct timeval tv1, struct timeval tv2)
  188. {
  189. if (tv1.tv_sec < tv2.tv_sec) {
  190. return 0;
  191. }
  192. return tv1.tv_sec - tv2.tv_sec;
  193. }
  194. std::string replace(const std::string& target, const std::string& oldstr,
  195. const std::string& newstr)
  196. {
  197. if (target.empty() || oldstr.empty()) {
  198. return target;
  199. }
  200. std::string result;
  201. std::string::size_type p = 0;
  202. std::string::size_type np = target.find(oldstr);
  203. while (np != std::string::npos) {
  204. result.append(target.begin() + p, target.begin() + np);
  205. result += newstr;
  206. p = np + oldstr.size();
  207. np = target.find(oldstr, p);
  208. }
  209. result.append(target.begin() + p, target.end());
  210. return result;
  211. }
  212. bool isAlpha(const char c)
  213. {
  214. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  215. }
  216. bool isDigit(const char c) { return '0' <= c && c <= '9'; }
  217. bool isHexDigit(const char c)
  218. {
  219. return isDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
  220. }
  221. bool isHexDigit(const std::string& s)
  222. {
  223. for (const auto& c : s) {
  224. if (!isHexDigit(c)) {
  225. return false;
  226. }
  227. }
  228. return true;
  229. }
  230. bool inRFC3986ReservedChars(const char c)
  231. {
  232. static const char reserved[] = {':', '/', '?', '#', '[', ']', '@', '!', '$',
  233. '&', '\'', '(', ')', '*', '+', ',', ';', '='};
  234. return std::find(std::begin(reserved), std::end(reserved), c) !=
  235. std::end(reserved);
  236. }
  237. bool inRFC3986UnreservedChars(const char c)
  238. {
  239. static const char unreserved[] = {'-', '.', '_', '~'};
  240. return isAlpha(c) || isDigit(c) ||
  241. std::find(std::begin(unreserved), std::end(unreserved), c) !=
  242. std::end(unreserved);
  243. }
  244. bool inRFC2978MIMECharset(const char c)
  245. {
  246. static const char chars[] = {'!', '#', '$', '%', '&', '\'', '+',
  247. '-', '^', '_', '`', '{', '}', '~'};
  248. return isAlpha(c) || isDigit(c) ||
  249. std::find(std::begin(chars), std::end(chars), c) != std::end(chars);
  250. }
  251. bool inRFC2616HttpToken(const char c)
  252. {
  253. static const char chars[] = {'!', '#', '$', '%', '&', '\'', '*', '+',
  254. '-', '.', '^', '_', '`', '|', '~'};
  255. return isAlpha(c) || isDigit(c) ||
  256. std::find(std::begin(chars), std::end(chars), c) != std::end(chars);
  257. }
  258. bool inRFC5987AttrChar(const char c)
  259. {
  260. return inRFC2616HttpToken(c) && c != '*' && c != '\'' && c != '%';
  261. }
  262. // Returns nonzero if |c| is in ISO/IEC 8859-1 character set.
  263. bool isIso8859p1(unsigned char c)
  264. {
  265. return (0x20u <= c && c <= 0x7eu) || 0xa0u <= c;
  266. }
  267. bool isLws(const char c) { return c == ' ' || c == '\t'; }
  268. bool isCRLF(const char c) { return c == '\r' || c == '\n'; }
  269. namespace {
  270. bool isUtf8Tail(unsigned char ch) { return in(ch, 0x80u, 0xbfu); }
  271. bool inPercentEncodeMini(const unsigned char c)
  272. {
  273. return c > 0x20 && c < 0x7fu &&
  274. // Chromium escapes following characters. Firefox4 escapes more.
  275. c != '"' && c != '<' && c != '>';
  276. }
  277. } // namespace
  278. bool isUtf8(const std::string& str)
  279. {
  280. for (std::string::const_iterator s = str.begin(), eos = str.end(); s != eos;
  281. ++s) {
  282. unsigned char firstChar = *s;
  283. // See ABNF in http://tools.ietf.org/search/rfc3629#section-4
  284. if (in(firstChar, 0x20u, 0x7eu) || firstChar == 0x08u || // \b
  285. firstChar == 0x09u || // \t
  286. firstChar == 0x0au || // \n
  287. firstChar == 0x0cu || // \f
  288. firstChar == 0x0du // \r
  289. ) {
  290. // UTF8-1 (without ctrl chars)
  291. }
  292. else if (in(firstChar, 0xc2u, 0xdfu)) {
  293. // UTF8-2
  294. if (++s == eos || !isUtf8Tail(*s)) {
  295. return false;
  296. }
  297. }
  298. else if (0xe0u == firstChar) {
  299. // UTF8-3
  300. if (++s == eos || !in(static_cast<unsigned char>(*s), 0xa0u, 0xbfu) ||
  301. ++s == eos || !isUtf8Tail(*s)) {
  302. return false;
  303. }
  304. }
  305. else if (in(firstChar, 0xe1u, 0xecu) || in(firstChar, 0xeeu, 0xefu)) {
  306. // UTF8-3
  307. if (++s == eos || !isUtf8Tail(*s) || ++s == eos || !isUtf8Tail(*s)) {
  308. return false;
  309. }
  310. }
  311. else if (0xedu == firstChar) {
  312. // UTF8-3
  313. if (++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x9fu) ||
  314. ++s == eos || !isUtf8Tail(*s)) {
  315. return false;
  316. }
  317. }
  318. else if (0xf0u == firstChar) {
  319. // UTF8-4
  320. if (++s == eos || !in(static_cast<unsigned char>(*s), 0x90u, 0xbfu) ||
  321. ++s == eos || !isUtf8Tail(*s) || ++s == eos || !isUtf8Tail(*s)) {
  322. return false;
  323. }
  324. }
  325. else if (in(firstChar, 0xf1u, 0xf3u)) {
  326. // UTF8-4
  327. if (++s == eos || !isUtf8Tail(*s) || ++s == eos || !isUtf8Tail(*s) ||
  328. ++s == eos || !isUtf8Tail(*s)) {
  329. return false;
  330. }
  331. }
  332. else if (0xf4u == firstChar) {
  333. // UTF8-4
  334. if (++s == eos || !in(static_cast<unsigned char>(*s), 0x80u, 0x8fu) ||
  335. ++s == eos || !isUtf8Tail(*s) || ++s == eos || !isUtf8Tail(*s)) {
  336. return false;
  337. }
  338. }
  339. else {
  340. return false;
  341. }
  342. }
  343. return true;
  344. }
  345. std::string percentEncode(const unsigned char* target, size_t len)
  346. {
  347. std::string dest;
  348. for (size_t i = 0; i < len; ++i) {
  349. if (inRFC3986UnreservedChars(target[i])) {
  350. dest += target[i];
  351. }
  352. else {
  353. dest.append(fmt("%%%02X", target[i]));
  354. }
  355. }
  356. return dest;
  357. }
  358. std::string percentEncode(const std::string& target)
  359. {
  360. if (std::find_if_not(target.begin(), target.end(),
  361. inRFC3986UnreservedChars) == target.end()) {
  362. return target;
  363. }
  364. return percentEncode(reinterpret_cast<const unsigned char*>(target.c_str()),
  365. target.size());
  366. }
  367. std::string percentEncodeMini(const std::string& src)
  368. {
  369. if (std::find_if_not(src.begin(), src.end(), inPercentEncodeMini) ==
  370. src.end()) {
  371. return src;
  372. }
  373. std::string result;
  374. for (auto c : src) {
  375. if (!inPercentEncodeMini(c)) {
  376. result += fmt("%%%02X", static_cast<unsigned char>(c));
  377. }
  378. else {
  379. result += c;
  380. }
  381. }
  382. return result;
  383. }
  384. std::string torrentPercentEncode(const unsigned char* target, size_t len)
  385. {
  386. std::string dest;
  387. for (size_t i = 0; i < len; ++i) {
  388. if (isAlpha(target[i]) || isDigit(target[i])) {
  389. dest += target[i];
  390. }
  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(std::string::const_iterator first,
  403. 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 && isHexDigit(*(first + 1)) &&
  409. isHexDigit(*(first + 2))) {
  410. result +=
  411. hexCharToUInt(*(first + 1)) * 16 + hexCharToUInt(*(first + 2));
  412. first += 2;
  413. }
  414. else {
  415. result += *first;
  416. }
  417. }
  418. else {
  419. result += *first;
  420. }
  421. }
  422. return result;
  423. }
  424. std::string toHex(const unsigned char* src, size_t len)
  425. {
  426. std::string out(len * 2, '\0');
  427. std::string::iterator o = out.begin();
  428. const unsigned char* last = src + len;
  429. for (const unsigned char* i = src; i != last; ++i) {
  430. *o = (*i >> 4);
  431. *(o + 1) = (*i) & 0x0fu;
  432. for (int j = 0; j < 2; ++j) {
  433. if (*o < 10) {
  434. *o += '0';
  435. }
  436. else {
  437. *o += 'a' - 10;
  438. }
  439. ++o;
  440. }
  441. }
  442. return out;
  443. }
  444. std::string toHex(const char* src, size_t len)
  445. {
  446. return toHex(reinterpret_cast<const unsigned char*>(src), len);
  447. }
  448. std::string toHex(const std::string& src)
  449. {
  450. return toHex(reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
  451. }
  452. unsigned int hexCharToUInt(unsigned char ch)
  453. {
  454. if ('a' <= ch && ch <= 'f') {
  455. ch -= 'a';
  456. ch += 10;
  457. }
  458. else if ('A' <= ch && ch <= 'F') {
  459. ch -= 'A';
  460. ch += 10;
  461. }
  462. else if ('0' <= ch && ch <= '9') {
  463. ch -= '0';
  464. }
  465. else {
  466. ch = 255;
  467. }
  468. return ch;
  469. }
  470. std::string secfmt(time_t sec)
  471. {
  472. time_t tsec = sec;
  473. std::string str;
  474. if (sec >= 3600) {
  475. str = fmt("%" PRId64 "h", static_cast<int64_t>(sec / 3600));
  476. sec %= 3600;
  477. }
  478. if (sec >= 60) {
  479. str += fmt("%dm", static_cast<int>(sec / 60));
  480. sec %= 60;
  481. }
  482. if (sec || tsec == 0) {
  483. str += fmt("%ds", static_cast<int>(sec));
  484. }
  485. return str;
  486. }
  487. namespace {
  488. template <typename T, typename F>
  489. bool parseLong(T& res, F f, const std::string& s, int base)
  490. {
  491. if (s.empty()) {
  492. return false;
  493. }
  494. char* endptr;
  495. errno = 0;
  496. res = f(s.c_str(), &endptr, base);
  497. if (errno == ERANGE) {
  498. return false;
  499. }
  500. if (*endptr != '\0') {
  501. for (const char *i = endptr, *eoi = s.c_str() + s.size(); i < eoi; ++i) {
  502. if (!isspace(*i)) {
  503. return false;
  504. }
  505. }
  506. }
  507. return true;
  508. }
  509. } // namespace
  510. bool parseIntNoThrow(int32_t& res, const std::string& s, int base)
  511. {
  512. long int t;
  513. if (parseLong(t, strtol, s, base) &&
  514. t >= std::numeric_limits<int32_t>::min() &&
  515. t <= std::numeric_limits<int32_t>::max()) {
  516. res = t;
  517. return true;
  518. }
  519. else {
  520. return false;
  521. }
  522. }
  523. bool parseUIntNoThrow(uint32_t& res, const std::string& s, int base)
  524. {
  525. long int t;
  526. if (parseLong(t, strtol, s, base) && t >= 0 &&
  527. t <= std::numeric_limits<int32_t>::max()) {
  528. res = t;
  529. return true;
  530. }
  531. else {
  532. return false;
  533. }
  534. }
  535. bool parseLLIntNoThrow(int64_t& res, const std::string& s, int base)
  536. {
  537. int64_t t;
  538. if (parseLong(t, strtoll, s, base)) {
  539. res = t;
  540. return true;
  541. }
  542. else {
  543. return false;
  544. }
  545. }
  546. bool parseDoubleNoThrow(double& res, const std::string& s)
  547. {
  548. if (s.empty()) {
  549. return false;
  550. }
  551. errno = 0;
  552. char* endptr;
  553. auto d = strtod(s.c_str(), &endptr);
  554. if (errno == ERANGE) {
  555. return false;
  556. }
  557. if (endptr != s.c_str() + s.size()) {
  558. for (auto i = std::begin(s) + (endptr - s.c_str()); i != std::end(s); ++i) {
  559. if (!isspace(*i)) {
  560. return false;
  561. }
  562. }
  563. }
  564. res = d;
  565. return true;
  566. }
  567. SegList<int> parseIntSegments(const std::string& src)
  568. {
  569. SegList<int> sgl;
  570. for (std::string::const_iterator i = src.begin(), eoi = src.end();
  571. i != eoi;) {
  572. std::string::const_iterator j = std::find(i, eoi, ',');
  573. if (j == i) {
  574. ++i;
  575. continue;
  576. }
  577. std::string::const_iterator p = std::find(i, j, '-');
  578. if (p == j) {
  579. int a;
  580. if (parseIntNoThrow(a, std::string(i, j))) {
  581. sgl.add(a, a + 1);
  582. }
  583. else {
  584. throw DL_ABORT_EX(fmt("Bad range %s", std::string(i, j).c_str()));
  585. }
  586. }
  587. else if (p == i || p + 1 == j) {
  588. throw DL_ABORT_EX(fmt(MSG_INCOMPLETE_RANGE, std::string(i, j).c_str()));
  589. }
  590. else {
  591. int a, b;
  592. if (parseIntNoThrow(a, std::string(i, p)) &&
  593. parseIntNoThrow(b, (std::string(p + 1, j)))) {
  594. sgl.add(a, b + 1);
  595. }
  596. else {
  597. throw DL_ABORT_EX(fmt("Bad range %s", std::string(i, j).c_str()));
  598. }
  599. }
  600. if (j == eoi) {
  601. break;
  602. }
  603. i = j + 1;
  604. }
  605. return sgl;
  606. }
  607. namespace {
  608. void computeHeadPieces(
  609. std::vector<size_t>& indexes,
  610. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  611. size_t pieceLength, int64_t head)
  612. {
  613. if (head == 0) {
  614. return;
  615. }
  616. for (const auto& fi : fileEntries) {
  617. if (fi->getLength() == 0) {
  618. continue;
  619. }
  620. const size_t lastIndex =
  621. (fi->getOffset() + std::min(head, fi->getLength()) - 1) / pieceLength;
  622. for (size_t idx = fi->getOffset() / pieceLength; idx <= lastIndex; ++idx) {
  623. indexes.push_back(idx);
  624. }
  625. }
  626. }
  627. } // namespace
  628. namespace {
  629. void computeTailPieces(
  630. std::vector<size_t>& indexes,
  631. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  632. size_t pieceLength, int64_t tail)
  633. {
  634. if (tail == 0) {
  635. return;
  636. }
  637. for (const auto& fi : fileEntries) {
  638. if (fi->getLength() == 0) {
  639. continue;
  640. }
  641. int64_t endOffset = fi->getLastOffset();
  642. size_t fromIndex =
  643. (endOffset - 1 - (std::min(tail, fi->getLength()) - 1)) / pieceLength;
  644. const size_t toIndex = (endOffset - 1) / pieceLength;
  645. while (fromIndex <= toIndex) {
  646. indexes.push_back(fromIndex++);
  647. }
  648. }
  649. }
  650. } // namespace
  651. void parsePrioritizePieceRange(
  652. std::vector<size_t>& result, const std::string& src,
  653. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  654. size_t pieceLength, int64_t defaultSize)
  655. {
  656. std::vector<size_t> indexes;
  657. std::vector<Scip> parts;
  658. splitIter(src.begin(), src.end(), std::back_inserter(parts), ',', true);
  659. for (const auto& i : parts) {
  660. if (util::streq(i.first, i.second, "head")) {
  661. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  662. }
  663. else if (util::startsWith(i.first, i.second, "head=")) {
  664. std::string sizestr(i.first + 5, i.second);
  665. computeHeadPieces(indexes, fileEntries, pieceLength,
  666. std::max((int64_t)0, getRealSize(sizestr)));
  667. }
  668. else if (util::streq(i.first, i.second, "tail")) {
  669. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  670. }
  671. else if (util::startsWith(i.first, i.second, "tail=")) {
  672. std::string sizestr(i.first + 5, i.second);
  673. computeTailPieces(indexes, fileEntries, pieceLength,
  674. std::max((int64_t)0, getRealSize(sizestr)));
  675. }
  676. else {
  677. throw DL_ABORT_EX(
  678. fmt("Unrecognized token %s", std::string(i.first, i.second).c_str()));
  679. }
  680. }
  681. std::sort(indexes.begin(), indexes.end());
  682. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  683. result.insert(result.end(), indexes.begin(), indexes.end());
  684. }
  685. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  686. // character not in ISO/IEC 8859-1, returns empty string.
  687. std::string iso8859p1ToUtf8(const char* src, size_t len)
  688. {
  689. std::string dest;
  690. for (const char *p = src, *last = src + len; p != last; ++p) {
  691. unsigned char c = *p;
  692. if (0xa0u <= c) {
  693. if (c <= 0xbfu) {
  694. dest += 0xc2u;
  695. }
  696. else {
  697. dest += 0xc3u;
  698. }
  699. dest += c & (~0x40u);
  700. }
  701. else if (0x80u <= c && c <= 0x9fu) {
  702. return "";
  703. }
  704. else {
  705. dest += c;
  706. }
  707. }
  708. return dest;
  709. }
  710. std::string iso8859p1ToUtf8(const std::string& src)
  711. {
  712. return iso8859p1ToUtf8(src.c_str(), src.size());
  713. }
  714. /* Start of utf8 dfa */
  715. /* Copyright (c) 2008-2010 Bjoern Hoehrmann <[email protected]>
  716. * See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
  717. *
  718. * Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
  719. *
  720. * Permission is hereby granted, free of charge, to any person
  721. * obtaining a copy of this software and associated documentation
  722. * files (the "Software"), to deal in the Software without
  723. * restriction, including without limitation the rights to use, copy,
  724. * modify, merge, publish, distribute, sublicense, and/or sell copies
  725. * of the Software, and to permit persons to whom the Software is
  726. * furnished to do so, subject to the following conditions:
  727. *
  728. * The above copyright notice and this permission notice shall be
  729. * included in all copies or substantial portions of the Software.
  730. *
  731. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  732. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  733. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  734. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  735. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  736. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  737. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  738. * SOFTWARE.
  739. */
  740. #define UTF8_ACCEPT 0
  741. #define UTF8_REJECT 12
  742. static const uint8_t utf8d[] = {
  743. /*
  744. * The first part of the table maps bytes to character classes that
  745. * to reduce the size of the transition table and create bitmasks.
  746. */
  747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  752. 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9,
  753. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  754. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 2, 2, 2, 2, 2, 2,
  755. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10,
  756. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8, 8, 8, 8,
  757. 8, 8, 8, 8, 8, 8,
  758. /*
  759. * The second part is a transition table that maps a combination
  760. * of a state of the automaton and a character class to a state.
  761. */
  762. 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12,
  763. 12, 12, 12, 12, 12, 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24, 12,
  764. 12, 12, 12, 12, 24, 12, 24, 12, 12, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12,
  765. 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12,
  766. 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12, 12,
  767. 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  768. };
  769. static uint32_t utf8dfa(uint32_t* state, uint32_t* codep, uint32_t byte)
  770. {
  771. uint32_t type = utf8d[byte];
  772. *codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6)
  773. : (0xff >> type) & (byte);
  774. *state = utf8d[256 + *state + type];
  775. return *state;
  776. }
  777. /* End of utf8 dfa */
  778. typedef enum {
  779. CD_BEFORE_DISPOSITION_TYPE,
  780. CD_AFTER_DISPOSITION_TYPE,
  781. CD_DISPOSITION_TYPE,
  782. CD_BEFORE_DISPOSITION_PARM_NAME,
  783. CD_AFTER_DISPOSITION_PARM_NAME,
  784. CD_DISPOSITION_PARM_NAME,
  785. CD_BEFORE_VALUE,
  786. CD_AFTER_VALUE,
  787. CD_QUOTED_STRING,
  788. CD_TOKEN,
  789. CD_BEFORE_EXT_VALUE,
  790. CD_CHARSET,
  791. CD_LANGUAGE,
  792. CD_VALUE_CHARS,
  793. CD_VALUE_CHARS_PCT_ENCODED1,
  794. CD_VALUE_CHARS_PCT_ENCODED2
  795. } content_disposition_parse_state;
  796. typedef enum {
  797. CD_FILENAME_FOUND = 1,
  798. CD_EXT_FILENAME_FOUND = 1 << 1
  799. } content_disposition_parse_flag;
  800. typedef enum {
  801. CD_ENC_UNKNOWN,
  802. CD_ENC_UTF8,
  803. CD_ENC_ISO_8859_1
  804. } content_disposition_charset;
  805. ssize_t parse_content_disposition(char* dest, size_t destlen,
  806. const char** charsetp, size_t* charsetlenp,
  807. const char* in, size_t len)
  808. {
  809. const char *p = in, *eop = in + len, *mark_first = nullptr,
  810. *mark_last = nullptr;
  811. int state = CD_BEFORE_DISPOSITION_TYPE;
  812. int in_file_parm = 0;
  813. int flags = 0;
  814. int quoted_seen = 0;
  815. int charset = 0;
  816. /* To suppress warnings */
  817. char* dp = dest;
  818. size_t dlen = destlen;
  819. uint32_t dfa_state = 0;
  820. uint32_t dfa_code = 0;
  821. uint8_t pctval = 0;
  822. *charsetp = nullptr;
  823. *charsetlenp = 0;
  824. for (; p != eop; ++p) {
  825. switch (state) {
  826. case CD_BEFORE_DISPOSITION_TYPE:
  827. if (inRFC2616HttpToken(*p)) {
  828. state = CD_DISPOSITION_TYPE;
  829. }
  830. else if (!isLws(*p)) {
  831. return -1;
  832. }
  833. break;
  834. case CD_AFTER_DISPOSITION_TYPE:
  835. case CD_DISPOSITION_TYPE:
  836. if (*p == ';') {
  837. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  838. }
  839. else if (isLws(*p)) {
  840. state = CD_AFTER_DISPOSITION_TYPE;
  841. }
  842. else if (state == CD_AFTER_DISPOSITION_TYPE || !inRFC2616HttpToken(*p)) {
  843. return -1;
  844. }
  845. break;
  846. case CD_BEFORE_DISPOSITION_PARM_NAME:
  847. if (inRFC2616HttpToken(*p)) {
  848. mark_first = p;
  849. state = CD_DISPOSITION_PARM_NAME;
  850. }
  851. else if (!isLws(*p)) {
  852. return -1;
  853. }
  854. break;
  855. case CD_AFTER_DISPOSITION_PARM_NAME:
  856. case CD_DISPOSITION_PARM_NAME:
  857. if (*p == '=') {
  858. if (state == CD_DISPOSITION_PARM_NAME) {
  859. mark_last = p;
  860. }
  861. in_file_parm = 0;
  862. if (strieq(mark_first, mark_last, "filename*")) {
  863. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  864. in_file_parm = 1;
  865. }
  866. else {
  867. return -1;
  868. }
  869. state = CD_BEFORE_EXT_VALUE;
  870. }
  871. else if (strieq(mark_first, mark_last, "filename")) {
  872. if (flags & CD_FILENAME_FOUND) {
  873. return -1;
  874. }
  875. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  876. in_file_parm = 1;
  877. }
  878. state = CD_BEFORE_VALUE;
  879. }
  880. else {
  881. /* ext-token must be characters in token, followed by "*" */
  882. if (mark_first != mark_last - 1 && *(mark_last - 1) == '*') {
  883. state = CD_BEFORE_EXT_VALUE;
  884. }
  885. else {
  886. state = CD_BEFORE_VALUE;
  887. }
  888. }
  889. if (in_file_parm) {
  890. dp = dest;
  891. dlen = destlen;
  892. }
  893. }
  894. else if (isLws(*p)) {
  895. mark_last = p;
  896. state = CD_AFTER_DISPOSITION_PARM_NAME;
  897. }
  898. else if (state == CD_AFTER_DISPOSITION_PARM_NAME ||
  899. !inRFC2616HttpToken(*p)) {
  900. return -1;
  901. }
  902. break;
  903. case CD_BEFORE_VALUE:
  904. if (*p == '"') {
  905. quoted_seen = 0;
  906. state = CD_QUOTED_STRING;
  907. }
  908. else if (inRFC2616HttpToken(*p)) {
  909. if (in_file_parm) {
  910. if (dlen == 0) {
  911. return -1;
  912. }
  913. else {
  914. *dp++ = *p;
  915. --dlen;
  916. }
  917. }
  918. state = CD_TOKEN;
  919. }
  920. else if (!isLws(*p)) {
  921. return -1;
  922. }
  923. break;
  924. case CD_AFTER_VALUE:
  925. if (*p == ';') {
  926. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  927. }
  928. else if (!isLws(*p)) {
  929. return -1;
  930. }
  931. break;
  932. case CD_QUOTED_STRING:
  933. if (*p == '\\' && quoted_seen == 0) {
  934. quoted_seen = 1;
  935. }
  936. else if (*p == '"' && quoted_seen == 0) {
  937. if (in_file_parm) {
  938. flags |= CD_FILENAME_FOUND;
  939. }
  940. state = CD_AFTER_VALUE;
  941. }
  942. else {
  943. /* TEXT which is OCTET except CTLs, but including LWS. We only
  944. accept ISO-8859-1 chars. */
  945. quoted_seen = 0;
  946. if (!isIso8859p1(*p)) {
  947. return -1;
  948. }
  949. if (in_file_parm) {
  950. if (dlen == 0) {
  951. return -1;
  952. }
  953. else {
  954. *dp++ = *p;
  955. --dlen;
  956. }
  957. }
  958. }
  959. break;
  960. case CD_TOKEN:
  961. if (inRFC2616HttpToken(*p)) {
  962. if (in_file_parm) {
  963. if (dlen == 0) {
  964. return -1;
  965. }
  966. else {
  967. *dp++ = *p;
  968. --dlen;
  969. }
  970. }
  971. }
  972. else if (*p == ';') {
  973. if (in_file_parm) {
  974. flags |= CD_FILENAME_FOUND;
  975. }
  976. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  977. }
  978. else if (isLws(*p)) {
  979. if (in_file_parm) {
  980. flags |= CD_FILENAME_FOUND;
  981. }
  982. state = CD_AFTER_VALUE;
  983. }
  984. else {
  985. return -1;
  986. }
  987. break;
  988. case CD_BEFORE_EXT_VALUE:
  989. if (*p == '\'') {
  990. /* Empty charset is not allowed */
  991. return -1;
  992. }
  993. else if (inRFC2978MIMECharset(*p)) {
  994. mark_first = p;
  995. state = CD_CHARSET;
  996. }
  997. else if (!isLws(*p)) {
  998. return -1;
  999. }
  1000. break;
  1001. case CD_CHARSET:
  1002. if (*p == '\'') {
  1003. mark_last = p;
  1004. *charsetp = mark_first;
  1005. *charsetlenp = mark_last - mark_first;
  1006. if (strieq(mark_first, mark_last, "utf-8")) {
  1007. charset = CD_ENC_UTF8;
  1008. dfa_state = UTF8_ACCEPT;
  1009. dfa_code = 0;
  1010. }
  1011. else if (strieq(mark_first, mark_last, "iso-8859-1")) {
  1012. charset = CD_ENC_ISO_8859_1;
  1013. }
  1014. else {
  1015. charset = CD_ENC_UNKNOWN;
  1016. }
  1017. state = CD_LANGUAGE;
  1018. }
  1019. else if (!inRFC2978MIMECharset(*p)) {
  1020. return -1;
  1021. }
  1022. break;
  1023. case CD_LANGUAGE:
  1024. if (*p == '\'') {
  1025. if (in_file_parm) {
  1026. dp = dest;
  1027. dlen = destlen;
  1028. }
  1029. state = CD_VALUE_CHARS;
  1030. }
  1031. else if (*p != '-' && !isAlpha(*p) && !isDigit(*p)) {
  1032. return -1;
  1033. }
  1034. break;
  1035. case CD_VALUE_CHARS:
  1036. if (inRFC5987AttrChar(*p)) {
  1037. if (charset == CD_ENC_UTF8) {
  1038. if (utf8dfa(&dfa_state, &dfa_code, *p) == UTF8_REJECT) {
  1039. return -1;
  1040. }
  1041. }
  1042. if (in_file_parm) {
  1043. if (dlen == 0) {
  1044. return -1;
  1045. }
  1046. else {
  1047. *dp++ = *p;
  1048. --dlen;
  1049. }
  1050. }
  1051. }
  1052. else if (*p == '%') {
  1053. if (in_file_parm) {
  1054. if (dlen == 0) {
  1055. return -1;
  1056. }
  1057. }
  1058. pctval = 0;
  1059. state = CD_VALUE_CHARS_PCT_ENCODED1;
  1060. }
  1061. else if (*p == ';' || isLws(*p)) {
  1062. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1063. return -1;
  1064. }
  1065. if (in_file_parm) {
  1066. flags |= CD_EXT_FILENAME_FOUND;
  1067. }
  1068. if (*p == ';') {
  1069. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1070. }
  1071. else {
  1072. state = CD_AFTER_VALUE;
  1073. }
  1074. }
  1075. else if (!inRFC5987AttrChar(*p)) {
  1076. return -1;
  1077. }
  1078. break;
  1079. case CD_VALUE_CHARS_PCT_ENCODED1:
  1080. if (isHexDigit(*p)) {
  1081. pctval |= hexCharToUInt(*p) << 4;
  1082. state = CD_VALUE_CHARS_PCT_ENCODED2;
  1083. }
  1084. else {
  1085. return -1;
  1086. }
  1087. break;
  1088. case CD_VALUE_CHARS_PCT_ENCODED2:
  1089. if (isHexDigit(*p)) {
  1090. pctval |= hexCharToUInt(*p);
  1091. if (charset == CD_ENC_UTF8) {
  1092. if (utf8dfa(&dfa_state, &dfa_code, pctval) == UTF8_REJECT) {
  1093. return -1;
  1094. }
  1095. }
  1096. else if (charset == CD_ENC_ISO_8859_1) {
  1097. if (!isIso8859p1(pctval)) {
  1098. return -1;
  1099. }
  1100. }
  1101. if (in_file_parm) {
  1102. *dp++ = pctval;
  1103. --dlen;
  1104. }
  1105. state = CD_VALUE_CHARS;
  1106. }
  1107. else {
  1108. return -1;
  1109. }
  1110. break;
  1111. }
  1112. }
  1113. switch (state) {
  1114. case CD_BEFORE_DISPOSITION_TYPE:
  1115. case CD_AFTER_DISPOSITION_TYPE:
  1116. case CD_DISPOSITION_TYPE:
  1117. case CD_AFTER_VALUE:
  1118. case CD_TOKEN:
  1119. return destlen - dlen;
  1120. case CD_VALUE_CHARS:
  1121. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1122. return -1;
  1123. }
  1124. return destlen - dlen;
  1125. default:
  1126. return -1;
  1127. }
  1128. }
  1129. std::string getContentDispositionFilename(const std::string& header)
  1130. {
  1131. std::array<char, 1_k> cdval;
  1132. size_t cdvallen = cdval.size();
  1133. const char* charset;
  1134. size_t charsetlen;
  1135. ssize_t rv =
  1136. parse_content_disposition(cdval.data(), cdvallen, &charset, &charsetlen,
  1137. header.c_str(), header.size());
  1138. if (rv == -1) {
  1139. return "";
  1140. }
  1141. std::string res;
  1142. if (!charset || strieq(charset, charset + charsetlen, "iso-8859-1")) {
  1143. res = iso8859p1ToUtf8(cdval.data(), rv);
  1144. }
  1145. else {
  1146. res.assign(cdval.data(), rv);
  1147. }
  1148. if (!detectDirTraversal(res) &&
  1149. res.find_first_of("/\\") == std::string::npos) {
  1150. return res;
  1151. }
  1152. return "";
  1153. }
  1154. std::string toUpper(std::string src)
  1155. {
  1156. uppercase(src);
  1157. return src;
  1158. }
  1159. std::string toLower(std::string src)
  1160. {
  1161. lowercase(src);
  1162. return src;
  1163. }
  1164. void uppercase(std::string& s)
  1165. {
  1166. std::transform(s.begin(), s.end(), s.begin(), toUpperChar);
  1167. }
  1168. void lowercase(std::string& s)
  1169. {
  1170. std::transform(s.begin(), s.end(), s.begin(), toLowerChar);
  1171. }
  1172. char toUpperChar(char c)
  1173. {
  1174. if ('a' <= c && c <= 'z') {
  1175. c += 'A' - 'a';
  1176. }
  1177. return c;
  1178. }
  1179. char toLowerChar(char c)
  1180. {
  1181. if ('A' <= c && c <= 'Z') {
  1182. c += 'a' - 'A';
  1183. }
  1184. return c;
  1185. }
  1186. bool isNumericHost(const std::string& name)
  1187. {
  1188. struct addrinfo hints;
  1189. struct addrinfo* res;
  1190. memset(&hints, 0, sizeof(hints));
  1191. hints.ai_family = AF_UNSPEC;
  1192. hints.ai_flags = AI_NUMERICHOST;
  1193. if (getaddrinfo(name.c_str(), nullptr, &hints, &res)) {
  1194. return false;
  1195. }
  1196. freeaddrinfo(res);
  1197. return true;
  1198. }
  1199. #if _WIN32
  1200. namespace {
  1201. static Lock win_signal_lock;
  1202. static signal_handler_t win_int_handler = nullptr;
  1203. static signal_handler_t win_term_handler = nullptr;
  1204. static void win_ign_handler(int) {}
  1205. static BOOL WINAPI HandlerRoutine(DWORD ctrlType)
  1206. {
  1207. void (*handler)(int) = nullptr;
  1208. switch (ctrlType) {
  1209. case CTRL_C_EVENT:
  1210. case CTRL_BREAK_EVENT: {
  1211. // Handler will be called on a new/different thread.
  1212. LockGuard lg(win_signal_lock);
  1213. handler = win_int_handler;
  1214. }
  1215. if (handler) {
  1216. handler(SIGINT);
  1217. return TRUE;
  1218. }
  1219. return FALSE;
  1220. case CTRL_LOGOFF_EVENT:
  1221. case CTRL_CLOSE_EVENT:
  1222. case CTRL_SHUTDOWN_EVENT: {
  1223. // Handler will be called on a new/different thread.
  1224. LockGuard lg(win_signal_lock);
  1225. handler = win_term_handler;
  1226. ;
  1227. }
  1228. if (handler) {
  1229. handler(SIGTERM);
  1230. return TRUE;
  1231. }
  1232. return FALSE;
  1233. }
  1234. return FALSE;
  1235. }
  1236. }
  1237. #endif
  1238. void setGlobalSignalHandler(int sig, sigset_t* mask, signal_handler_t handler,
  1239. int flags)
  1240. {
  1241. #if _WIN32
  1242. if (sig == SIGINT || sig == SIGTERM) {
  1243. // Handler will be called on a new/different thread.
  1244. LockGuard lg(win_signal_lock);
  1245. if (handler == SIG_DFL) {
  1246. handler = nullptr;
  1247. }
  1248. else if (handler == SIG_IGN) {
  1249. handler = win_ign_handler;
  1250. }
  1251. // Not yet in use: add console handler.
  1252. if (handler && !win_int_handler && !win_term_handler) {
  1253. ::SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  1254. }
  1255. if (sig == SIGINT) {
  1256. win_int_handler = handler;
  1257. }
  1258. else {
  1259. win_term_handler = handler;
  1260. }
  1261. // No handlers set: remove.
  1262. if (!win_int_handler && !win_term_handler) {
  1263. ::SetConsoleCtrlHandler(HandlerRoutine, FALSE);
  1264. }
  1265. return;
  1266. }
  1267. #endif
  1268. #ifdef HAVE_SIGACTION
  1269. struct sigaction sigact;
  1270. sigact.sa_handler = handler;
  1271. sigact.sa_flags = flags;
  1272. sigact.sa_mask = *mask;
  1273. if (sigaction(sig, &sigact, nullptr) == -1) {
  1274. auto errNum = errno;
  1275. A2_LOG_ERROR(fmt("sigaction() failed for signal %d: %s", sig,
  1276. safeStrerror(errNum).c_str()));
  1277. }
  1278. #else
  1279. if (signal(sig, handler) == SIG_ERR) {
  1280. auto errNum = errno;
  1281. A2_LOG_ERROR(fmt("signal() failed for signal %d: %s", sig,
  1282. safeStrerror(errNum).c_str()));
  1283. }
  1284. #endif // HAVE_SIGACTION
  1285. }
  1286. #ifndef __MINGW32__
  1287. std::string getHomeDir()
  1288. {
  1289. const char* p = getenv("HOME");
  1290. if (p) {
  1291. return p;
  1292. }
  1293. #ifdef HAVE_PWD_H
  1294. auto pw = getpwuid(geteuid());
  1295. if (pw && pw->pw_dir) {
  1296. return pw->pw_dir;
  1297. }
  1298. #endif // HAVE_PWD_H
  1299. return A2STR::NIL;
  1300. }
  1301. #else // __MINGW32__
  1302. std::string getHomeDir()
  1303. {
  1304. auto p = _wgetenv(L"HOME");
  1305. if (p) {
  1306. return toForwardSlash(wCharToUtf8(p));
  1307. }
  1308. p = _wgetenv(L"USERPROFILE");
  1309. if (p) {
  1310. return toForwardSlash(wCharToUtf8(p));
  1311. }
  1312. p = _wgetenv(L"HOMEDRIVE");
  1313. if (p) {
  1314. std::wstring homeDir = p;
  1315. p = _wgetenv(L"HOMEPATH");
  1316. if (p) {
  1317. homeDir += p;
  1318. return toForwardSlash(wCharToUtf8(homeDir));
  1319. }
  1320. }
  1321. return A2STR::NIL;
  1322. }
  1323. #endif // __MINGW32__
  1324. std::string getXDGDir(const std::string& environmentVariable,
  1325. const std::string& fallbackDirectory)
  1326. {
  1327. std::string filename;
  1328. const char* p = getenv(environmentVariable.c_str());
  1329. if (p && p[0] == '/') {
  1330. filename = p;
  1331. }
  1332. else {
  1333. filename = fallbackDirectory;
  1334. }
  1335. return filename;
  1336. }
  1337. std::string getConfigFile()
  1338. {
  1339. std::string filename = getHomeDir() + "/.aria2/aria2.conf";
  1340. if (!File(filename).exists()) {
  1341. filename = getXDGDir("XDG_CONFIG_HOME", getHomeDir() + "/.config") +
  1342. "/aria2/aria2.conf";
  1343. }
  1344. return filename;
  1345. }
  1346. std::string getDHTFile(bool ipv6)
  1347. {
  1348. std::string filename =
  1349. getHomeDir() + (ipv6 ? "/.aria2/dht6.dat" : "/.aria2/dht.dat");
  1350. if (!File(filename).exists()) {
  1351. filename = getXDGDir("XDG_CACHE_HOME", getHomeDir() + "/.cache") +
  1352. (ipv6 ? "/aria2/dht6.dat" : "/aria2/dht.dat");
  1353. }
  1354. return filename;
  1355. }
  1356. int64_t getRealSize(const std::string& sizeWithUnit)
  1357. {
  1358. std::string::size_type p = sizeWithUnit.find_first_of("KMkm");
  1359. std::string size;
  1360. int32_t mult = 1;
  1361. if (p == std::string::npos) {
  1362. size = sizeWithUnit;
  1363. }
  1364. else {
  1365. switch (sizeWithUnit[p]) {
  1366. case 'K':
  1367. case 'k':
  1368. mult = 1_k;
  1369. break;
  1370. case 'M':
  1371. case 'm':
  1372. mult = 1_m;
  1373. break;
  1374. }
  1375. size.assign(sizeWithUnit.begin(), sizeWithUnit.begin() + p);
  1376. }
  1377. int64_t v;
  1378. if (!parseLLIntNoThrow(v, size) || v < 0) {
  1379. throw DL_ABORT_EX(
  1380. fmt("Bad or negative value detected: %s", sizeWithUnit.c_str()));
  1381. }
  1382. if (INT64_MAX / mult < v) {
  1383. throw DL_ABORT_EX(
  1384. fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, "overflow/underflow"));
  1385. }
  1386. return v * mult;
  1387. }
  1388. std::string abbrevSize(int64_t size)
  1389. {
  1390. static const char* UNITS[] = {"", "Ki", "Mi", "Gi"};
  1391. int64_t t = size;
  1392. size_t uidx = 0;
  1393. int r = 0;
  1394. while (t >= static_cast<int64_t>(1_k) &&
  1395. uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0])) {
  1396. lldiv_t d = lldiv(t, 1_k);
  1397. t = d.quot;
  1398. r = d.rem;
  1399. ++uidx;
  1400. }
  1401. if (uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0]) && t >= 922) {
  1402. ++uidx;
  1403. r = t;
  1404. t = 0;
  1405. }
  1406. std::string res;
  1407. res += itos(t, true);
  1408. if (t < 10 && uidx > 0) {
  1409. res += ".";
  1410. res += itos(r * 10 / 1_k);
  1411. }
  1412. res += UNITS[uidx];
  1413. return res;
  1414. }
  1415. void sleep(long seconds)
  1416. {
  1417. #if defined(HAVE_WINSOCK2_H)
  1418. ::Sleep(seconds * 1000);
  1419. #elif HAVE_SLEEP
  1420. ::sleep(seconds);
  1421. #elif defined(HAVE_USLEEP)
  1422. ::usleep(seconds * 1000000);
  1423. #else
  1424. #error no sleep function is available (nanosleep?)
  1425. #endif
  1426. }
  1427. void usleep(long microseconds)
  1428. {
  1429. #ifdef HAVE_USLEEP
  1430. ::usleep(microseconds);
  1431. #elif defined(HAVE_WINSOCK2_H)
  1432. LARGE_INTEGER current, freq, end;
  1433. static enum {
  1434. GET_FREQUENCY,
  1435. GET_MICROSECONDS,
  1436. SKIP_MICROSECONDS
  1437. } state = GET_FREQUENCY;
  1438. if (state == GET_FREQUENCY) {
  1439. if (QueryPerformanceFrequency(&freq))
  1440. state = GET_MICROSECONDS;
  1441. else
  1442. state = SKIP_MICROSECONDS;
  1443. }
  1444. long msec = microseconds / 1000;
  1445. microseconds %= 1000;
  1446. if (state == GET_MICROSECONDS && microseconds) {
  1447. QueryPerformanceCounter(&end);
  1448. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  1449. while (QueryPerformanceCounter(&current) &&
  1450. (current.QuadPart <= end.QuadPart))
  1451. /* noop */;
  1452. }
  1453. if (msec)
  1454. Sleep(msec);
  1455. #else
  1456. #error no usleep function is available (nanosleep?)
  1457. #endif
  1458. }
  1459. void mkdirs(const std::string& dirpath)
  1460. {
  1461. File dir(dirpath);
  1462. if (!dir.mkdirs()) {
  1463. int errNum = errno;
  1464. if (!dir.isDir()) {
  1465. throw DL_ABORT_EX3(errNum, fmt(EX_MAKE_DIR, dir.getPath().c_str(),
  1466. safeStrerror(errNum).c_str()),
  1467. error_code::DIR_CREATE_ERROR);
  1468. }
  1469. }
  1470. }
  1471. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1472. {
  1473. size_t numBlock = dest->countBlock();
  1474. for (size_t index = 0; index < numBlock; ++index) {
  1475. if (src->isBitSetOffsetRange((int64_t)index * dest->getBlockLength(),
  1476. dest->getBlockLength())) {
  1477. dest->setBit(index);
  1478. }
  1479. }
  1480. }
  1481. std::string toString(const std::shared_ptr<BinaryStream>& binaryStream)
  1482. {
  1483. std::stringstream strm;
  1484. char data[2048];
  1485. while (1) {
  1486. int32_t dataLength = binaryStream->readData(
  1487. reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1488. strm.write(data, dataLength);
  1489. if (dataLength == 0) {
  1490. break;
  1491. }
  1492. }
  1493. return strm.str();
  1494. }
  1495. #ifdef HAVE_POSIX_MEMALIGN
  1496. /**
  1497. * In linux 2.6, alignment and size should be a multiple of 512.
  1498. */
  1499. void* allocateAlignedMemory(size_t alignment, size_t size)
  1500. {
  1501. void* buffer;
  1502. int res;
  1503. if ((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1504. throw FATAL_EXCEPTION(
  1505. fmt("Error in posix_memalign: %s", util::safeStrerror(res).c_str()));
  1506. }
  1507. return buffer;
  1508. }
  1509. #endif // HAVE_POSIX_MEMALIGN
  1510. Endpoint getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1511. {
  1512. char host[NI_MAXHOST];
  1513. char service[NI_MAXSERV];
  1514. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1515. NI_NUMERICHOST | NI_NUMERICSERV);
  1516. if (s != 0) {
  1517. throw DL_ABORT_EX(
  1518. fmt("Failed to get hostname and port. cause: %s", gai_strerror(s)));
  1519. }
  1520. return {host, sockaddr->sa_family,
  1521. static_cast<uint16_t>(strtoul(service, nullptr, 10))};
  1522. }
  1523. std::string htmlEscape(const std::string& src)
  1524. {
  1525. std::string dest;
  1526. dest.reserve(src.size());
  1527. auto j = std::begin(src);
  1528. for (auto i = std::begin(src); i != std::end(src); ++i) {
  1529. char ch = *i;
  1530. const char* repl;
  1531. if (ch == '<') {
  1532. repl = "&lt;";
  1533. }
  1534. else if (ch == '>') {
  1535. repl = "&gt;";
  1536. }
  1537. else if (ch == '&') {
  1538. repl = "&amp;";
  1539. }
  1540. else if (ch == '\'') {
  1541. repl = "&#39;";
  1542. }
  1543. else if (ch == '"') {
  1544. repl = "&quot;";
  1545. }
  1546. else {
  1547. continue;
  1548. }
  1549. dest.append(j, i);
  1550. j = i + 1;
  1551. dest += repl;
  1552. }
  1553. dest.append(j, std::end(src));
  1554. return dest;
  1555. }
  1556. std::pair<size_t, std::string> parseIndexPath(const std::string& line)
  1557. {
  1558. auto p = divide(std::begin(line), std::end(line), '=');
  1559. uint32_t index;
  1560. if (!parseUIntNoThrow(index, std::string(p.first.first, p.first.second))) {
  1561. throw DL_ABORT_EX("Bad path index");
  1562. }
  1563. if (p.second.first == p.second.second) {
  1564. throw DL_ABORT_EX(fmt("Path with index=%u is empty.", index));
  1565. }
  1566. return std::make_pair(index, std::string(p.second.first, p.second.second));
  1567. }
  1568. std::vector<std::pair<size_t, std::string>> createIndexPaths(std::istream& i)
  1569. {
  1570. std::vector<std::pair<size_t, std::string>> indexPaths;
  1571. std::string line;
  1572. while (getline(i, line)) {
  1573. indexPaths.push_back(parseIndexPath(line));
  1574. }
  1575. return indexPaths;
  1576. }
  1577. void generateRandomData(unsigned char* data, size_t length)
  1578. {
  1579. const auto& rd = SimpleRandomizer::getInstance();
  1580. return rd->getRandomBytes(data, length);
  1581. }
  1582. bool saveAs(const std::string& filename, const std::string& data,
  1583. bool overwrite)
  1584. {
  1585. if (!overwrite && File(filename).exists()) {
  1586. return false;
  1587. }
  1588. std::string tempFilename = filename;
  1589. tempFilename += "__temp";
  1590. {
  1591. BufferedFile fp(tempFilename.c_str(), BufferedFile::WRITE);
  1592. if (!fp) {
  1593. return false;
  1594. }
  1595. if (fp.write(data.data(), data.size()) != data.size()) {
  1596. return false;
  1597. }
  1598. if (fp.close() == EOF) {
  1599. return false;
  1600. }
  1601. }
  1602. return File(tempFilename).renameTo(filename);
  1603. }
  1604. std::string applyDir(const std::string& dir, const std::string& relPath)
  1605. {
  1606. std::string s;
  1607. if (dir.empty()) {
  1608. s = "./";
  1609. s += relPath;
  1610. }
  1611. else {
  1612. s = dir;
  1613. if (dir == "/") {
  1614. s += relPath;
  1615. }
  1616. else {
  1617. s += "/";
  1618. s += relPath;
  1619. }
  1620. }
  1621. #ifdef __MINGW32__
  1622. for (std::string::iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1623. if (*i == '\\') {
  1624. *i = '/';
  1625. }
  1626. }
  1627. #endif // __MINGW32__
  1628. return s;
  1629. }
  1630. std::string fixTaintedBasename(const std::string& src)
  1631. {
  1632. return escapePath(replace(src, "/", "%2F"));
  1633. }
  1634. void generateRandomKey(unsigned char* key)
  1635. {
  1636. unsigned char bytes[40];
  1637. generateRandomData(bytes, sizeof(bytes));
  1638. message_digest::digest(key, 20, MessageDigest::sha1().get(), bytes,
  1639. sizeof(bytes));
  1640. }
  1641. // Returns true is given numeric ipv4addr is in Private Address Space.
  1642. //
  1643. // From Section.3 RFC1918
  1644. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1645. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1646. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1647. bool inPrivateAddress(const std::string& ipv4addr)
  1648. {
  1649. if (util::startsWith(ipv4addr, "10.") ||
  1650. util::startsWith(ipv4addr, "192.168.")) {
  1651. return true;
  1652. }
  1653. if (util::startsWith(ipv4addr, "172.")) {
  1654. for (int i = 16; i <= 31; ++i) {
  1655. std::string t(fmt("%d.", i));
  1656. if (util::startsWith(ipv4addr.begin() + 4, ipv4addr.end(), t.begin(),
  1657. t.end())) {
  1658. return true;
  1659. }
  1660. }
  1661. }
  1662. return false;
  1663. }
  1664. bool detectDirTraversal(const std::string& s)
  1665. {
  1666. if (s.empty()) {
  1667. return false;
  1668. }
  1669. for (auto c : s) {
  1670. unsigned char ch = c;
  1671. if (in(ch, 0x00u, 0x1fu) || ch == 0x7fu) {
  1672. return true;
  1673. }
  1674. }
  1675. return s == "." || s == ".." || s[0] == '/' || util::startsWith(s, "./") ||
  1676. util::startsWith(s, "../") || s.find("/../") != std::string::npos ||
  1677. s.find("/./") != std::string::npos || s[s.size() - 1] == '/' ||
  1678. util::endsWith(s, "/.") || util::endsWith(s, "/..");
  1679. }
  1680. std::string escapePath(const std::string& s)
  1681. {
  1682. // We don't escape '/' because we use it as a path separator.
  1683. #ifdef __MINGW32__
  1684. static const char WIN_INVALID_PATH_CHARS[] = {'"', '*', ':', '<',
  1685. '>', '?', '\\', '|'};
  1686. #endif // __MINGW32__
  1687. std::string d;
  1688. for (auto cc : s) {
  1689. unsigned char c = cc;
  1690. if (in(c, 0x00u, 0x1fu) || c == 0x7fu
  1691. #ifdef __MINGW32__
  1692. ||
  1693. std::find(std::begin(WIN_INVALID_PATH_CHARS),
  1694. std::end(WIN_INVALID_PATH_CHARS),
  1695. c) != std::end(WIN_INVALID_PATH_CHARS)
  1696. #endif // __MINGW32__
  1697. ) {
  1698. d += fmt("%%%02X", c);
  1699. }
  1700. else {
  1701. d += c;
  1702. }
  1703. }
  1704. return d;
  1705. }
  1706. bool inSameCidrBlock(const std::string& ip1, const std::string& ip2,
  1707. size_t bits)
  1708. {
  1709. unsigned char s1[16], s2[16];
  1710. size_t len1, len2;
  1711. if ((len1 = net::getBinAddr(s1, ip1)) == 0 ||
  1712. (len2 = net::getBinAddr(s2, ip2)) == 0 || len1 != len2) {
  1713. return false;
  1714. }
  1715. if (bits == 0) {
  1716. return true;
  1717. }
  1718. if (bits > 8 * len1) {
  1719. bits = 8 * len1;
  1720. }
  1721. int last = (bits - 1) / 8;
  1722. for (int i = 0; i < last; ++i) {
  1723. if (s1[i] != s2[i]) {
  1724. return false;
  1725. }
  1726. }
  1727. unsigned char mask = bitfield::lastByteMask(bits);
  1728. return (s1[last] & mask) == (s2[last] & mask);
  1729. }
  1730. namespace {
  1731. void executeHook(const std::string& command, a2_gid_t gid, size_t numFiles,
  1732. const std::string& firstFilename)
  1733. {
  1734. const std::string gidStr = GroupId::toHex(gid);
  1735. const std::string numFilesStr = util::uitos(numFiles);
  1736. #ifndef __MINGW32__
  1737. A2_LOG_INFO(fmt("Executing user command: %s %s %s %s", command.c_str(),
  1738. gidStr.c_str(), numFilesStr.c_str(), firstFilename.c_str()));
  1739. pid_t cpid = fork();
  1740. if (cpid == 0) {
  1741. // child!
  1742. execlp(command.c_str(), command.c_str(), gidStr.c_str(),
  1743. numFilesStr.c_str(), firstFilename.c_str(),
  1744. reinterpret_cast<char*>(0));
  1745. perror(("Could not execute user command: " + command).c_str());
  1746. _exit(EXIT_FAILURE);
  1747. return;
  1748. }
  1749. if (cpid == -1) {
  1750. A2_LOG_ERROR("fork() failed. Cannot execute user command.");
  1751. }
  1752. return;
  1753. #else // __MINGW32__
  1754. PROCESS_INFORMATION pi;
  1755. STARTUPINFOW si;
  1756. memset(&si, 0, sizeof(si));
  1757. si.cb = sizeof(STARTUPINFO);
  1758. memset(&pi, 0, sizeof(pi));
  1759. bool batch = util::iendsWith(command, ".bat");
  1760. std::string cmdline;
  1761. std::string cmdexe;
  1762. // XXX batch handling, in particular quoting, correct?
  1763. if (batch) {
  1764. const char* p = getenv("windir");
  1765. if (p) {
  1766. cmdexe = p;
  1767. cmdexe += "\\system32\\cmd.exe";
  1768. }
  1769. else {
  1770. A2_LOG_INFO("Failed to get windir environment variable."
  1771. " Executing batch file will fail.");
  1772. // TODO Might be useless.
  1773. cmdexe = "cmd.exe";
  1774. }
  1775. cmdline += "/C \"";
  1776. }
  1777. cmdline += "\"";
  1778. cmdline += command;
  1779. cmdline += "\"";
  1780. cmdline += " ";
  1781. cmdline += gidStr;
  1782. cmdline += " ";
  1783. cmdline += numFilesStr;
  1784. cmdline += " \"";
  1785. cmdline += firstFilename;
  1786. cmdline += "\"";
  1787. if (batch) {
  1788. cmdline += "\"";
  1789. }
  1790. int cmdlineLen = utf8ToWChar(nullptr, 0, cmdline.c_str());
  1791. assert(cmdlineLen > 0);
  1792. auto wcharCmdline = make_unique<wchar_t[]>(cmdlineLen);
  1793. cmdlineLen = utf8ToWChar(wcharCmdline.get(), cmdlineLen, cmdline.c_str());
  1794. assert(cmdlineLen > 0);
  1795. A2_LOG_INFO(fmt("Executing user command: %s", cmdline.c_str()));
  1796. DWORD rc = CreateProcessW(batch ? utf8ToWChar(cmdexe).c_str() : nullptr,
  1797. wcharCmdline.get(), nullptr, nullptr, false, 0,
  1798. nullptr, 0, &si, &pi);
  1799. if (!rc) {
  1800. A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command.");
  1801. }
  1802. return;
  1803. #endif
  1804. }
  1805. } // namespace
  1806. void executeHookByOptName(const std::shared_ptr<RequestGroup>& group,
  1807. const Option* option, PrefPtr pref)
  1808. {
  1809. executeHookByOptName(group.get(), option, pref);
  1810. }
  1811. void executeHookByOptName(const RequestGroup* group, const Option* option,
  1812. PrefPtr pref)
  1813. {
  1814. const std::string& cmd = option->get(pref);
  1815. if (!cmd.empty()) {
  1816. const std::shared_ptr<DownloadContext> dctx = group->getDownloadContext();
  1817. std::string firstFilename;
  1818. size_t numFiles = 0;
  1819. if (!group->inMemoryDownload()) {
  1820. std::shared_ptr<FileEntry> file = dctx->getFirstRequestedFileEntry();
  1821. if (file) {
  1822. firstFilename = file->getPath();
  1823. }
  1824. numFiles = dctx->countRequestedFileEntry();
  1825. }
  1826. executeHook(cmd, group->getGID(), numFiles, firstFilename);
  1827. }
  1828. }
  1829. std::string createSafePath(const std::string& dir, const std::string& filename)
  1830. {
  1831. return util::applyDir(dir,
  1832. util::isUtf8(filename)
  1833. ? util::fixTaintedBasename(filename)
  1834. : util::escapePath(util::percentEncode(filename)));
  1835. }
  1836. std::string createSafePath(const std::string& filename)
  1837. {
  1838. return util::isUtf8(filename)
  1839. ? util::fixTaintedBasename(filename)
  1840. : util::escapePath(util::percentEncode(filename));
  1841. }
  1842. std::string encodeNonUtf8(const std::string& s)
  1843. {
  1844. return util::isUtf8(s) ? s : util::percentEncode(s);
  1845. }
  1846. std::string makeString(const char* str)
  1847. {
  1848. if (!str) {
  1849. return A2STR::NIL;
  1850. }
  1851. return str;
  1852. }
  1853. std::string safeStrerror(int errNum) { return makeString(strerror(errNum)); }
  1854. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain)
  1855. {
  1856. if (!domain.empty() && domain[0] == '.' && !util::isNumericHost(hostname)) {
  1857. return util::endsWith(hostname, domain);
  1858. }
  1859. return hostname == domain;
  1860. }
  1861. bool tlsHostnameMatch(const std::string& pattern, const std::string& hostname)
  1862. {
  1863. std::string::const_iterator ptWildcard =
  1864. std::find(pattern.begin(), pattern.end(), '*');
  1865. if (ptWildcard == pattern.end()) {
  1866. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  1867. hostname.end());
  1868. }
  1869. std::string::const_iterator ptLeftLabelEnd =
  1870. std::find(pattern.begin(), pattern.end(), '.');
  1871. bool wildcardEnabled = true;
  1872. // Do case-insensitive match. At least 2 dots are required to enable
  1873. // wildcard match. Also wildcard must be in the left-most label.
  1874. // Don't attempt to match a presented identifier where the wildcard
  1875. // character is embedded within an A-label.
  1876. if (ptLeftLabelEnd == pattern.end() ||
  1877. std::find(ptLeftLabelEnd + 1, pattern.end(), '.') == pattern.end() ||
  1878. ptLeftLabelEnd < ptWildcard || istartsWith(pattern, "xn--")) {
  1879. wildcardEnabled = false;
  1880. }
  1881. if (!wildcardEnabled) {
  1882. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  1883. hostname.end());
  1884. }
  1885. std::string::const_iterator hnLeftLabelEnd =
  1886. std::find(hostname.begin(), hostname.end(), '.');
  1887. if (!strieq(ptLeftLabelEnd, pattern.end(), hnLeftLabelEnd, hostname.end())) {
  1888. return false;
  1889. }
  1890. // Perform wildcard match. Here '*' must match at least one
  1891. // character.
  1892. if (hnLeftLabelEnd - hostname.begin() < ptLeftLabelEnd - pattern.begin()) {
  1893. return false;
  1894. }
  1895. return istartsWith(hostname.begin(), hnLeftLabelEnd, pattern.begin(),
  1896. ptWildcard) &&
  1897. iendsWith(hostname.begin(), hnLeftLabelEnd, ptWildcard + 1,
  1898. ptLeftLabelEnd);
  1899. }
  1900. bool strieq(const std::string& a, const char* b)
  1901. {
  1902. return strieq(a.begin(), a.end(), b);
  1903. }
  1904. bool strieq(const std::string& a, const std::string& b)
  1905. {
  1906. return strieq(a.begin(), a.end(), b.begin(), b.end());
  1907. }
  1908. bool startsWith(const std::string& a, const char* b)
  1909. {
  1910. return startsWith(a.begin(), a.end(), b);
  1911. }
  1912. bool startsWith(const std::string& a, const std::string& b)
  1913. {
  1914. return startsWith(a.begin(), a.end(), b.begin(), b.end());
  1915. }
  1916. bool istartsWith(const std::string& a, const char* b)
  1917. {
  1918. return istartsWith(a.begin(), a.end(), b);
  1919. }
  1920. bool istartsWith(const std::string& a, const std::string& b)
  1921. {
  1922. return istartsWith(std::begin(a), std::end(a), std::begin(b), std::end(b));
  1923. }
  1924. bool endsWith(const std::string& a, const char* b)
  1925. {
  1926. return endsWith(a.begin(), a.end(), b, b + strlen(b));
  1927. }
  1928. bool endsWith(const std::string& a, const std::string& b)
  1929. {
  1930. return endsWith(a.begin(), a.end(), b.begin(), b.end());
  1931. }
  1932. bool iendsWith(const std::string& a, const char* b)
  1933. {
  1934. return iendsWith(a.begin(), a.end(), b, b + strlen(b));
  1935. }
  1936. bool iendsWith(const std::string& a, const std::string& b)
  1937. {
  1938. return iendsWith(a.begin(), a.end(), b.begin(), b.end());
  1939. }
  1940. bool strless(const char* a, const char* b) { return strcmp(a, b) < 0; }
  1941. #ifdef ENABLE_SSL
  1942. TLSVersion toTLSVersion(const std::string& ver)
  1943. {
  1944. if (ver == A2_V_SSL3) {
  1945. return TLS_PROTO_SSL3;
  1946. }
  1947. if (ver == A2_V_TLS10) {
  1948. return TLS_PROTO_TLS10;
  1949. }
  1950. if (ver == A2_V_TLS11) {
  1951. return TLS_PROTO_TLS11;
  1952. }
  1953. if (ver == A2_V_TLS12) {
  1954. return TLS_PROTO_TLS12;
  1955. }
  1956. return TLS_PROTO_TLS10;
  1957. }
  1958. #endif // ENABLE_SSL
  1959. #ifdef __MINGW32__
  1960. std::string formatLastError(int errNum)
  1961. {
  1962. std::array<char, 4_k> buf;
  1963. if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  1964. nullptr, errNum,
  1965. // Default language
  1966. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  1967. static_cast<LPTSTR>(buf.data()), buf.size(),
  1968. nullptr) == 0) {
  1969. return "";
  1970. }
  1971. return buf.data();
  1972. }
  1973. #endif // __MINGW32__
  1974. void make_fd_cloexec(int fd)
  1975. {
  1976. #ifndef __MINGW32__
  1977. int flags;
  1978. // TODO from linux man page, fcntl() with F_GETFD or F_SETFD does
  1979. // not return -1 with errno == EINTR. Historically, aria2 code base
  1980. // checks this case. Probably, it is not needed.
  1981. while ((flags = fcntl(fd, F_GETFD)) == -1 && errno == EINTR)
  1982. ;
  1983. if (flags == -1) {
  1984. return;
  1985. }
  1986. while (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1 && errno == EINTR)
  1987. ;
  1988. #endif // !__MINGW32__
  1989. }
  1990. #ifdef __MINGW32__
  1991. bool gainPrivilege(LPCTSTR privName)
  1992. {
  1993. LUID luid;
  1994. TOKEN_PRIVILEGES tp;
  1995. if (!LookupPrivilegeValue(nullptr, privName, &luid)) {
  1996. auto errNum = GetLastError();
  1997. A2_LOG_WARN(fmt("Lookup for privilege name %s failed. cause: %s", privName,
  1998. util::formatLastError(errNum).c_str()));
  1999. return false;
  2000. }
  2001. tp.PrivilegeCount = 1;
  2002. tp.Privileges[0].Luid = luid;
  2003. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2004. HANDLE token;
  2005. if (!OpenProcessToken(GetCurrentProcess(),
  2006. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
  2007. auto errNum = GetLastError();
  2008. A2_LOG_WARN(fmt("Getting process token failed. cause: %s",
  2009. util::formatLastError(errNum).c_str()));
  2010. return false;
  2011. }
  2012. auto tokenCloser = defer(token, CloseHandle);
  2013. if (!AdjustTokenPrivileges(token, FALSE, &tp, 0, NULL, NULL)) {
  2014. auto errNum = GetLastError();
  2015. A2_LOG_WARN(fmt("Gaining privilege %s failed. cause: %s", privName,
  2016. util::formatLastError(errNum).c_str()));
  2017. return false;
  2018. }
  2019. // Check privilege was really gained
  2020. DWORD bufsize = 0;
  2021. GetTokenInformation(token, TokenPrivileges, nullptr, 0, &bufsize);
  2022. if (bufsize == 0) {
  2023. A2_LOG_WARN("Checking privilege failed.");
  2024. return false;
  2025. }
  2026. auto buf = make_unique<char[]>(bufsize);
  2027. if (!GetTokenInformation(token, TokenPrivileges, buf.get(), bufsize,
  2028. &bufsize)) {
  2029. auto errNum = GetLastError();
  2030. A2_LOG_WARN(fmt("Checking privilege failed. cause: %s",
  2031. util::formatLastError(errNum).c_str()));
  2032. return false;
  2033. }
  2034. auto privs = reinterpret_cast<TOKEN_PRIVILEGES*>(buf.get());
  2035. for (size_t i = 0; i < privs->PrivilegeCount; ++i) {
  2036. auto& priv = privs->Privileges[i];
  2037. if (memcmp(&priv.Luid, &luid, sizeof(luid)) != 0) {
  2038. continue;
  2039. }
  2040. if (priv.Attributes == SE_PRIVILEGE_ENABLED) {
  2041. return true;
  2042. }
  2043. break;
  2044. }
  2045. A2_LOG_WARN(fmt("Gaining privilege %s failed.", privName));
  2046. return false;
  2047. }
  2048. #endif // __MINGW32__
  2049. } // namespace util
  2050. } // namespace aria2