util.cc 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598
  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 <bjoern@hoehrmann.de>
  716. * See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
  717. *
  718. * Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  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,
  748. 0,
  749. 0,
  750. 0,
  751. 0,
  752. 0,
  753. 0,
  754. 0,
  755. 0,
  756. 0,
  757. 0,
  758. 0,
  759. 0,
  760. 0,
  761. 0,
  762. 0,
  763. 0,
  764. 0,
  765. 0,
  766. 0,
  767. 0,
  768. 0,
  769. 0,
  770. 0,
  771. 0,
  772. 0,
  773. 0,
  774. 0,
  775. 0,
  776. 0,
  777. 0,
  778. 0,
  779. 0,
  780. 0,
  781. 0,
  782. 0,
  783. 0,
  784. 0,
  785. 0,
  786. 0,
  787. 0,
  788. 0,
  789. 0,
  790. 0,
  791. 0,
  792. 0,
  793. 0,
  794. 0,
  795. 0,
  796. 0,
  797. 0,
  798. 0,
  799. 0,
  800. 0,
  801. 0,
  802. 0,
  803. 0,
  804. 0,
  805. 0,
  806. 0,
  807. 0,
  808. 0,
  809. 0,
  810. 0,
  811. 0,
  812. 0,
  813. 0,
  814. 0,
  815. 0,
  816. 0,
  817. 0,
  818. 0,
  819. 0,
  820. 0,
  821. 0,
  822. 0,
  823. 0,
  824. 0,
  825. 0,
  826. 0,
  827. 0,
  828. 0,
  829. 0,
  830. 0,
  831. 0,
  832. 0,
  833. 0,
  834. 0,
  835. 0,
  836. 0,
  837. 0,
  838. 0,
  839. 0,
  840. 0,
  841. 0,
  842. 0,
  843. 0,
  844. 0,
  845. 0,
  846. 0,
  847. 0,
  848. 0,
  849. 0,
  850. 0,
  851. 0,
  852. 0,
  853. 0,
  854. 0,
  855. 0,
  856. 0,
  857. 0,
  858. 0,
  859. 0,
  860. 0,
  861. 0,
  862. 0,
  863. 0,
  864. 0,
  865. 0,
  866. 0,
  867. 0,
  868. 0,
  869. 0,
  870. 0,
  871. 0,
  872. 0,
  873. 0,
  874. 0,
  875. 1,
  876. 1,
  877. 1,
  878. 1,
  879. 1,
  880. 1,
  881. 1,
  882. 1,
  883. 1,
  884. 1,
  885. 1,
  886. 1,
  887. 1,
  888. 1,
  889. 1,
  890. 1,
  891. 9,
  892. 9,
  893. 9,
  894. 9,
  895. 9,
  896. 9,
  897. 9,
  898. 9,
  899. 9,
  900. 9,
  901. 9,
  902. 9,
  903. 9,
  904. 9,
  905. 9,
  906. 9,
  907. 7,
  908. 7,
  909. 7,
  910. 7,
  911. 7,
  912. 7,
  913. 7,
  914. 7,
  915. 7,
  916. 7,
  917. 7,
  918. 7,
  919. 7,
  920. 7,
  921. 7,
  922. 7,
  923. 7,
  924. 7,
  925. 7,
  926. 7,
  927. 7,
  928. 7,
  929. 7,
  930. 7,
  931. 7,
  932. 7,
  933. 7,
  934. 7,
  935. 7,
  936. 7,
  937. 7,
  938. 7,
  939. 8,
  940. 8,
  941. 2,
  942. 2,
  943. 2,
  944. 2,
  945. 2,
  946. 2,
  947. 2,
  948. 2,
  949. 2,
  950. 2,
  951. 2,
  952. 2,
  953. 2,
  954. 2,
  955. 2,
  956. 2,
  957. 2,
  958. 2,
  959. 2,
  960. 2,
  961. 2,
  962. 2,
  963. 2,
  964. 2,
  965. 2,
  966. 2,
  967. 2,
  968. 2,
  969. 2,
  970. 2,
  971. 10,
  972. 3,
  973. 3,
  974. 3,
  975. 3,
  976. 3,
  977. 3,
  978. 3,
  979. 3,
  980. 3,
  981. 3,
  982. 3,
  983. 3,
  984. 4,
  985. 3,
  986. 3,
  987. 11,
  988. 6,
  989. 6,
  990. 6,
  991. 5,
  992. 8,
  993. 8,
  994. 8,
  995. 8,
  996. 8,
  997. 8,
  998. 8,
  999. 8,
  1000. 8,
  1001. 8,
  1002. 8,
  1003. /*
  1004. * The second part is a transition table that maps a combination
  1005. * of a state of the automaton and a character class to a state.
  1006. */
  1007. 0,
  1008. 12,
  1009. 24,
  1010. 36,
  1011. 60,
  1012. 96,
  1013. 84,
  1014. 12,
  1015. 12,
  1016. 12,
  1017. 48,
  1018. 72,
  1019. 12,
  1020. 12,
  1021. 12,
  1022. 12,
  1023. 12,
  1024. 12,
  1025. 12,
  1026. 12,
  1027. 12,
  1028. 12,
  1029. 12,
  1030. 12,
  1031. 12,
  1032. 0,
  1033. 12,
  1034. 12,
  1035. 12,
  1036. 12,
  1037. 12,
  1038. 0,
  1039. 12,
  1040. 0,
  1041. 12,
  1042. 12,
  1043. 12,
  1044. 24,
  1045. 12,
  1046. 12,
  1047. 12,
  1048. 12,
  1049. 12,
  1050. 24,
  1051. 12,
  1052. 24,
  1053. 12,
  1054. 12,
  1055. 12,
  1056. 12,
  1057. 12,
  1058. 12,
  1059. 12,
  1060. 12,
  1061. 12,
  1062. 24,
  1063. 12,
  1064. 12,
  1065. 12,
  1066. 12,
  1067. 12,
  1068. 24,
  1069. 12,
  1070. 12,
  1071. 12,
  1072. 12,
  1073. 12,
  1074. 12,
  1075. 12,
  1076. 24,
  1077. 12,
  1078. 12,
  1079. 12,
  1080. 12,
  1081. 12,
  1082. 12,
  1083. 12,
  1084. 12,
  1085. 12,
  1086. 36,
  1087. 12,
  1088. 36,
  1089. 12,
  1090. 12,
  1091. 12,
  1092. 36,
  1093. 12,
  1094. 12,
  1095. 12,
  1096. 12,
  1097. 12,
  1098. 36,
  1099. 12,
  1100. 36,
  1101. 12,
  1102. 12,
  1103. 12,
  1104. 36,
  1105. 12,
  1106. 12,
  1107. 12,
  1108. 12,
  1109. 12,
  1110. 12,
  1111. 12,
  1112. 12,
  1113. 12,
  1114. 12,
  1115. };
  1116. static uint32_t utf8dfa(uint32_t* state, uint32_t* codep, uint32_t byte)
  1117. {
  1118. uint32_t type = utf8d[byte];
  1119. *codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6)
  1120. : (0xff >> type) & (byte);
  1121. *state = utf8d[256 + *state + type];
  1122. return *state;
  1123. }
  1124. /* End of utf8 dfa */
  1125. typedef enum {
  1126. CD_BEFORE_DISPOSITION_TYPE,
  1127. CD_AFTER_DISPOSITION_TYPE,
  1128. CD_DISPOSITION_TYPE,
  1129. CD_BEFORE_DISPOSITION_PARM_NAME,
  1130. CD_AFTER_DISPOSITION_PARM_NAME,
  1131. CD_DISPOSITION_PARM_NAME,
  1132. CD_BEFORE_VALUE,
  1133. CD_AFTER_VALUE,
  1134. CD_QUOTED_STRING,
  1135. CD_TOKEN,
  1136. CD_BEFORE_EXT_VALUE,
  1137. CD_CHARSET,
  1138. CD_LANGUAGE,
  1139. CD_VALUE_CHARS,
  1140. CD_VALUE_CHARS_PCT_ENCODED1,
  1141. CD_VALUE_CHARS_PCT_ENCODED2
  1142. } content_disposition_parse_state;
  1143. typedef enum {
  1144. CD_FILENAME_FOUND = 1,
  1145. CD_EXT_FILENAME_FOUND = 1 << 1
  1146. } content_disposition_parse_flag;
  1147. typedef enum {
  1148. CD_ENC_UNKNOWN,
  1149. CD_ENC_UTF8,
  1150. CD_ENC_ISO_8859_1
  1151. } content_disposition_charset;
  1152. ssize_t parse_content_disposition(char* dest, size_t destlen,
  1153. const char** charsetp, size_t* charsetlenp,
  1154. const char* in, size_t len, bool defaultUTF8)
  1155. {
  1156. const char *p = in, *eop = in + len, *mark_first = nullptr,
  1157. *mark_last = nullptr;
  1158. int state = CD_BEFORE_DISPOSITION_TYPE;
  1159. int in_file_parm = 0;
  1160. int flags = 0;
  1161. int quoted_seen = 0;
  1162. int charset = 0;
  1163. /* To suppress warnings */
  1164. char* dp = dest;
  1165. size_t dlen = destlen;
  1166. uint32_t dfa_state = UTF8_ACCEPT;
  1167. uint32_t dfa_code = 0;
  1168. uint8_t pctval = 0;
  1169. *charsetp = nullptr;
  1170. *charsetlenp = 0;
  1171. for (; p != eop; ++p) {
  1172. switch (state) {
  1173. case CD_BEFORE_DISPOSITION_TYPE:
  1174. if (inRFC2616HttpToken(*p)) {
  1175. state = CD_DISPOSITION_TYPE;
  1176. }
  1177. else if (!isLws(*p)) {
  1178. return -1;
  1179. }
  1180. break;
  1181. case CD_AFTER_DISPOSITION_TYPE:
  1182. case CD_DISPOSITION_TYPE:
  1183. if (*p == ';') {
  1184. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1185. }
  1186. else if (isLws(*p)) {
  1187. state = CD_AFTER_DISPOSITION_TYPE;
  1188. }
  1189. else if (state == CD_AFTER_DISPOSITION_TYPE || !inRFC2616HttpToken(*p)) {
  1190. return -1;
  1191. }
  1192. break;
  1193. case CD_BEFORE_DISPOSITION_PARM_NAME:
  1194. if (inRFC2616HttpToken(*p)) {
  1195. mark_first = p;
  1196. state = CD_DISPOSITION_PARM_NAME;
  1197. }
  1198. else if (!isLws(*p)) {
  1199. return -1;
  1200. }
  1201. break;
  1202. case CD_AFTER_DISPOSITION_PARM_NAME:
  1203. case CD_DISPOSITION_PARM_NAME:
  1204. if (*p == '=') {
  1205. if (state == CD_DISPOSITION_PARM_NAME) {
  1206. mark_last = p;
  1207. }
  1208. in_file_parm = 0;
  1209. if (strieq(mark_first, mark_last, "filename*")) {
  1210. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  1211. in_file_parm = 1;
  1212. }
  1213. else {
  1214. return -1;
  1215. }
  1216. state = CD_BEFORE_EXT_VALUE;
  1217. }
  1218. else if (strieq(mark_first, mark_last, "filename")) {
  1219. if (flags & CD_FILENAME_FOUND) {
  1220. return -1;
  1221. }
  1222. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  1223. in_file_parm = 1;
  1224. }
  1225. state = CD_BEFORE_VALUE;
  1226. }
  1227. else {
  1228. /* ext-token must be characters in token, followed by "*" */
  1229. if (mark_first != mark_last - 1 && *(mark_last - 1) == '*') {
  1230. state = CD_BEFORE_EXT_VALUE;
  1231. }
  1232. else {
  1233. state = CD_BEFORE_VALUE;
  1234. }
  1235. }
  1236. if (in_file_parm) {
  1237. dp = dest;
  1238. dlen = destlen;
  1239. }
  1240. }
  1241. else if (isLws(*p)) {
  1242. mark_last = p;
  1243. state = CD_AFTER_DISPOSITION_PARM_NAME;
  1244. }
  1245. else if (state == CD_AFTER_DISPOSITION_PARM_NAME ||
  1246. !inRFC2616HttpToken(*p)) {
  1247. return -1;
  1248. }
  1249. break;
  1250. case CD_BEFORE_VALUE:
  1251. if (*p == '"') {
  1252. quoted_seen = 0;
  1253. state = CD_QUOTED_STRING;
  1254. if (defaultUTF8) {
  1255. dfa_state = UTF8_ACCEPT;
  1256. dfa_code = 0;
  1257. }
  1258. }
  1259. else if (inRFC2616HttpToken(*p)) {
  1260. if (in_file_parm) {
  1261. if (dlen == 0) {
  1262. return -1;
  1263. }
  1264. else {
  1265. *dp++ = *p;
  1266. --dlen;
  1267. }
  1268. }
  1269. state = CD_TOKEN;
  1270. }
  1271. else if (!isLws(*p)) {
  1272. return -1;
  1273. }
  1274. break;
  1275. case CD_AFTER_VALUE:
  1276. if (*p == ';') {
  1277. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1278. }
  1279. else if (!isLws(*p)) {
  1280. return -1;
  1281. }
  1282. break;
  1283. case CD_QUOTED_STRING:
  1284. if (*p == '\\' && quoted_seen == 0) {
  1285. quoted_seen = 1;
  1286. }
  1287. else if (*p == '"' && quoted_seen == 0) {
  1288. if (defaultUTF8 && dfa_state != UTF8_ACCEPT) {
  1289. return -1;
  1290. }
  1291. if (in_file_parm) {
  1292. flags |= CD_FILENAME_FOUND;
  1293. }
  1294. state = CD_AFTER_VALUE;
  1295. }
  1296. else {
  1297. /* TEXT which is OCTET except CTLs, but including LWS. Accept
  1298. ISO-8859-1 chars, or UTF-8 if defaultUTF8 is set */
  1299. quoted_seen = 0;
  1300. if (defaultUTF8) {
  1301. if (utf8dfa(&dfa_state, &dfa_code, (unsigned char)*p) ==
  1302. UTF8_REJECT) {
  1303. return -1;
  1304. }
  1305. }
  1306. else if (!isIso8859p1(*p)) {
  1307. return -1;
  1308. }
  1309. if (in_file_parm) {
  1310. if (dlen == 0) {
  1311. return -1;
  1312. }
  1313. else {
  1314. *dp++ = *p;
  1315. --dlen;
  1316. }
  1317. }
  1318. }
  1319. break;
  1320. case CD_TOKEN:
  1321. if (inRFC2616HttpToken(*p)) {
  1322. if (in_file_parm) {
  1323. if (dlen == 0) {
  1324. return -1;
  1325. }
  1326. else {
  1327. *dp++ = *p;
  1328. --dlen;
  1329. }
  1330. }
  1331. }
  1332. else if (*p == ';') {
  1333. if (in_file_parm) {
  1334. flags |= CD_FILENAME_FOUND;
  1335. }
  1336. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1337. }
  1338. else if (isLws(*p)) {
  1339. if (in_file_parm) {
  1340. flags |= CD_FILENAME_FOUND;
  1341. }
  1342. state = CD_AFTER_VALUE;
  1343. }
  1344. else {
  1345. return -1;
  1346. }
  1347. break;
  1348. case CD_BEFORE_EXT_VALUE:
  1349. if (*p == '\'') {
  1350. /* Empty charset is not allowed */
  1351. return -1;
  1352. }
  1353. else if (inRFC2978MIMECharset(*p)) {
  1354. mark_first = p;
  1355. state = CD_CHARSET;
  1356. }
  1357. else if (!isLws(*p)) {
  1358. return -1;
  1359. }
  1360. break;
  1361. case CD_CHARSET:
  1362. if (*p == '\'') {
  1363. mark_last = p;
  1364. *charsetp = mark_first;
  1365. *charsetlenp = mark_last - mark_first;
  1366. if (strieq(mark_first, mark_last, "utf-8")) {
  1367. charset = CD_ENC_UTF8;
  1368. dfa_state = UTF8_ACCEPT;
  1369. dfa_code = 0;
  1370. }
  1371. else if (strieq(mark_first, mark_last, "iso-8859-1")) {
  1372. charset = CD_ENC_ISO_8859_1;
  1373. }
  1374. else {
  1375. charset = CD_ENC_UNKNOWN;
  1376. }
  1377. state = CD_LANGUAGE;
  1378. }
  1379. else if (!inRFC2978MIMECharset(*p)) {
  1380. return -1;
  1381. }
  1382. break;
  1383. case CD_LANGUAGE:
  1384. if (*p == '\'') {
  1385. if (in_file_parm) {
  1386. dp = dest;
  1387. dlen = destlen;
  1388. }
  1389. state = CD_VALUE_CHARS;
  1390. }
  1391. else if (*p != '-' && !isAlpha(*p) && !isDigit(*p)) {
  1392. return -1;
  1393. }
  1394. break;
  1395. case CD_VALUE_CHARS:
  1396. if (inRFC5987AttrChar(*p)) {
  1397. if (charset == CD_ENC_UTF8) {
  1398. if (utf8dfa(&dfa_state, &dfa_code, static_cast<unsigned char>(*p)) ==
  1399. UTF8_REJECT) {
  1400. return -1;
  1401. }
  1402. }
  1403. if (in_file_parm) {
  1404. if (dlen == 0) {
  1405. return -1;
  1406. }
  1407. else {
  1408. *dp++ = *p;
  1409. --dlen;
  1410. }
  1411. }
  1412. }
  1413. else if (*p == '%') {
  1414. if (in_file_parm) {
  1415. if (dlen == 0) {
  1416. return -1;
  1417. }
  1418. }
  1419. pctval = 0;
  1420. state = CD_VALUE_CHARS_PCT_ENCODED1;
  1421. }
  1422. else if (*p == ';' || isLws(*p)) {
  1423. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1424. return -1;
  1425. }
  1426. if (in_file_parm) {
  1427. flags |= CD_EXT_FILENAME_FOUND;
  1428. }
  1429. if (*p == ';') {
  1430. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1431. }
  1432. else {
  1433. state = CD_AFTER_VALUE;
  1434. }
  1435. }
  1436. else if (!inRFC5987AttrChar(*p)) {
  1437. return -1;
  1438. }
  1439. break;
  1440. case CD_VALUE_CHARS_PCT_ENCODED1:
  1441. if (isHexDigit(*p)) {
  1442. pctval |= hexCharToUInt(*p) << 4;
  1443. state = CD_VALUE_CHARS_PCT_ENCODED2;
  1444. }
  1445. else {
  1446. return -1;
  1447. }
  1448. break;
  1449. case CD_VALUE_CHARS_PCT_ENCODED2:
  1450. if (isHexDigit(*p)) {
  1451. pctval |= hexCharToUInt(*p);
  1452. if (charset == CD_ENC_UTF8) {
  1453. if (utf8dfa(&dfa_state, &dfa_code, pctval) == UTF8_REJECT) {
  1454. return -1;
  1455. }
  1456. }
  1457. else if (charset == CD_ENC_ISO_8859_1) {
  1458. if (!isIso8859p1(pctval)) {
  1459. return -1;
  1460. }
  1461. }
  1462. if (in_file_parm) {
  1463. *dp++ = pctval;
  1464. --dlen;
  1465. }
  1466. state = CD_VALUE_CHARS;
  1467. }
  1468. else {
  1469. return -1;
  1470. }
  1471. break;
  1472. }
  1473. }
  1474. switch (state) {
  1475. case CD_BEFORE_DISPOSITION_TYPE:
  1476. case CD_AFTER_DISPOSITION_TYPE:
  1477. case CD_DISPOSITION_TYPE:
  1478. case CD_AFTER_VALUE:
  1479. case CD_TOKEN:
  1480. return destlen - dlen;
  1481. case CD_VALUE_CHARS:
  1482. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1483. return -1;
  1484. }
  1485. return destlen - dlen;
  1486. default:
  1487. return -1;
  1488. }
  1489. }
  1490. std::string getContentDispositionFilename(const std::string& header,
  1491. bool defaultUTF8)
  1492. {
  1493. std::array<char, 1_k> cdval;
  1494. size_t cdvallen = cdval.size();
  1495. const char* charset;
  1496. size_t charsetlen;
  1497. ssize_t rv =
  1498. parse_content_disposition(cdval.data(), cdvallen, &charset, &charsetlen,
  1499. header.c_str(), header.size(), defaultUTF8);
  1500. if (rv == -1) {
  1501. return "";
  1502. }
  1503. std::string res;
  1504. if ((charset && strieq(charset, charset + charsetlen, "iso-8859-1")) ||
  1505. (!charset && !defaultUTF8)) {
  1506. res = iso8859p1ToUtf8(cdval.data(), rv);
  1507. }
  1508. else {
  1509. res.assign(cdval.data(), rv);
  1510. }
  1511. if (!detectDirTraversal(res) &&
  1512. res.find_first_of("/\\") == std::string::npos) {
  1513. return res;
  1514. }
  1515. return "";
  1516. }
  1517. std::string toUpper(std::string src)
  1518. {
  1519. uppercase(src);
  1520. return src;
  1521. }
  1522. std::string toLower(std::string src)
  1523. {
  1524. lowercase(src);
  1525. return src;
  1526. }
  1527. void uppercase(std::string& s)
  1528. {
  1529. std::transform(s.begin(), s.end(), s.begin(), toUpperChar);
  1530. }
  1531. void lowercase(std::string& s)
  1532. {
  1533. std::transform(s.begin(), s.end(), s.begin(), toLowerChar);
  1534. }
  1535. char toUpperChar(char c)
  1536. {
  1537. if ('a' <= c && c <= 'z') {
  1538. c += 'A' - 'a';
  1539. }
  1540. return c;
  1541. }
  1542. char toLowerChar(char c)
  1543. {
  1544. if ('A' <= c && c <= 'Z') {
  1545. c += 'a' - 'A';
  1546. }
  1547. return c;
  1548. }
  1549. bool isNumericHost(const std::string& name)
  1550. {
  1551. struct addrinfo hints;
  1552. struct addrinfo* res;
  1553. memset(&hints, 0, sizeof(hints));
  1554. hints.ai_family = AF_UNSPEC;
  1555. hints.ai_flags = AI_NUMERICHOST;
  1556. if (getaddrinfo(name.c_str(), nullptr, &hints, &res)) {
  1557. return false;
  1558. }
  1559. freeaddrinfo(res);
  1560. return true;
  1561. }
  1562. #if _WIN32
  1563. namespace {
  1564. static Lock win_signal_lock;
  1565. static signal_handler_t win_int_handler = nullptr;
  1566. static signal_handler_t win_term_handler = nullptr;
  1567. static void win_ign_handler(int) {}
  1568. static BOOL WINAPI HandlerRoutine(DWORD ctrlType)
  1569. {
  1570. void (*handler)(int) = nullptr;
  1571. switch (ctrlType) {
  1572. case CTRL_C_EVENT:
  1573. case CTRL_BREAK_EVENT: {
  1574. // Handler will be called on a new/different thread.
  1575. LockGuard lg(win_signal_lock);
  1576. handler = win_int_handler;
  1577. }
  1578. if (handler) {
  1579. handler(SIGINT);
  1580. return TRUE;
  1581. }
  1582. return FALSE;
  1583. case CTRL_LOGOFF_EVENT:
  1584. case CTRL_CLOSE_EVENT:
  1585. case CTRL_SHUTDOWN_EVENT: {
  1586. // Handler will be called on a new/different thread.
  1587. LockGuard lg(win_signal_lock);
  1588. handler = win_term_handler;
  1589. ;
  1590. }
  1591. if (handler) {
  1592. handler(SIGTERM);
  1593. return TRUE;
  1594. }
  1595. return FALSE;
  1596. }
  1597. return FALSE;
  1598. }
  1599. } // namespace
  1600. #endif
  1601. void setGlobalSignalHandler(int sig, sigset_t* mask, signal_handler_t handler,
  1602. int flags)
  1603. {
  1604. #if _WIN32
  1605. if (sig == SIGINT || sig == SIGTERM) {
  1606. // Handler will be called on a new/different thread.
  1607. LockGuard lg(win_signal_lock);
  1608. if (handler == SIG_DFL) {
  1609. handler = nullptr;
  1610. }
  1611. else if (handler == SIG_IGN) {
  1612. handler = win_ign_handler;
  1613. }
  1614. // Not yet in use: add console handler.
  1615. if (handler && !win_int_handler && !win_term_handler) {
  1616. ::SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  1617. }
  1618. if (sig == SIGINT) {
  1619. win_int_handler = handler;
  1620. }
  1621. else {
  1622. win_term_handler = handler;
  1623. }
  1624. // No handlers set: remove.
  1625. if (!win_int_handler && !win_term_handler) {
  1626. ::SetConsoleCtrlHandler(HandlerRoutine, FALSE);
  1627. }
  1628. return;
  1629. }
  1630. #endif
  1631. #ifdef HAVE_SIGACTION
  1632. struct sigaction sigact;
  1633. sigact.sa_handler = handler;
  1634. sigact.sa_flags = flags;
  1635. sigact.sa_mask = *mask;
  1636. if (sigaction(sig, &sigact, nullptr) == -1) {
  1637. auto errNum = errno;
  1638. A2_LOG_ERROR(fmt("sigaction() failed for signal %d: %s", sig,
  1639. safeStrerror(errNum).c_str()));
  1640. }
  1641. #else
  1642. if (signal(sig, handler) == SIG_ERR) {
  1643. auto errNum = errno;
  1644. A2_LOG_ERROR(fmt("signal() failed for signal %d: %s", sig,
  1645. safeStrerror(errNum).c_str()));
  1646. }
  1647. #endif // HAVE_SIGACTION
  1648. }
  1649. #ifndef __MINGW32__
  1650. std::string getHomeDir()
  1651. {
  1652. const char* p = getenv("HOME");
  1653. if (p) {
  1654. return p;
  1655. }
  1656. #ifdef HAVE_PWD_H
  1657. auto pw = getpwuid(geteuid());
  1658. if (pw && pw->pw_dir) {
  1659. return pw->pw_dir;
  1660. }
  1661. #endif // HAVE_PWD_H
  1662. return A2STR::NIL;
  1663. }
  1664. #else // __MINGW32__
  1665. std::string getHomeDir()
  1666. {
  1667. auto p = _wgetenv(L"HOME");
  1668. if (p) {
  1669. return toForwardSlash(wCharToUtf8(p));
  1670. }
  1671. p = _wgetenv(L"USERPROFILE");
  1672. if (p) {
  1673. return toForwardSlash(wCharToUtf8(p));
  1674. }
  1675. p = _wgetenv(L"HOMEDRIVE");
  1676. if (p) {
  1677. std::wstring homeDir = p;
  1678. p = _wgetenv(L"HOMEPATH");
  1679. if (p) {
  1680. homeDir += p;
  1681. return toForwardSlash(wCharToUtf8(homeDir));
  1682. }
  1683. }
  1684. return A2STR::NIL;
  1685. }
  1686. #endif // __MINGW32__
  1687. std::string getXDGDir(const std::string& environmentVariable,
  1688. const std::string& fallbackDirectory)
  1689. {
  1690. std::string filename;
  1691. const char* p = getenv(environmentVariable.c_str());
  1692. if (p &&
  1693. #ifndef __MINGW32__
  1694. p[0] == '/'
  1695. #else // __MINGW32__
  1696. p[0] && p[1] == ':'
  1697. #endif // __MINGW32__
  1698. ) {
  1699. filename = p;
  1700. }
  1701. else {
  1702. filename = fallbackDirectory;
  1703. }
  1704. return filename;
  1705. }
  1706. std::string getConfigFile()
  1707. {
  1708. std::string filename = getHomeDir() + "/.aria2/aria2.conf";
  1709. if (!File(filename).exists()) {
  1710. filename = getXDGDir("XDG_CONFIG_HOME", getHomeDir() + "/.config") +
  1711. "/aria2/aria2.conf";
  1712. }
  1713. return filename;
  1714. }
  1715. std::string getDHTFile(bool ipv6)
  1716. {
  1717. std::string filename =
  1718. getHomeDir() + (ipv6 ? "/.aria2/dht6.dat" : "/.aria2/dht.dat");
  1719. if (!File(filename).exists()) {
  1720. filename = getXDGDir("XDG_CACHE_HOME", getHomeDir() + "/.cache") +
  1721. (ipv6 ? "/aria2/dht6.dat" : "/aria2/dht.dat");
  1722. }
  1723. return filename;
  1724. }
  1725. int64_t getRealSize(const std::string& sizeWithUnit)
  1726. {
  1727. std::string::size_type p = sizeWithUnit.find_first_of("KMkm");
  1728. std::string size;
  1729. int32_t mult = 1;
  1730. if (p == std::string::npos) {
  1731. size = sizeWithUnit;
  1732. }
  1733. else {
  1734. switch (sizeWithUnit[p]) {
  1735. case 'K':
  1736. case 'k':
  1737. mult = 1_k;
  1738. break;
  1739. case 'M':
  1740. case 'm':
  1741. mult = 1_m;
  1742. break;
  1743. }
  1744. size.assign(sizeWithUnit.begin(), sizeWithUnit.begin() + p);
  1745. }
  1746. int64_t v;
  1747. if (!parseLLIntNoThrow(v, size) || v < 0) {
  1748. throw DL_ABORT_EX(
  1749. fmt("Bad or negative value detected: %s", sizeWithUnit.c_str()));
  1750. }
  1751. if (INT64_MAX / mult < v) {
  1752. throw DL_ABORT_EX(
  1753. fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, "overflow/underflow"));
  1754. }
  1755. return v * mult;
  1756. }
  1757. std::string abbrevSize(int64_t size)
  1758. {
  1759. static const char* UNITS[] = {"", "Ki", "Mi", "Gi"};
  1760. int64_t t = size;
  1761. size_t uidx = 0;
  1762. int r = 0;
  1763. while (t >= static_cast<int64_t>(1_k) &&
  1764. uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0])) {
  1765. lldiv_t d = lldiv(t, 1_k);
  1766. t = d.quot;
  1767. r = d.rem;
  1768. ++uidx;
  1769. }
  1770. if (uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0]) && t >= 922) {
  1771. ++uidx;
  1772. r = t;
  1773. t = 0;
  1774. }
  1775. std::string res;
  1776. res += itos(t, true);
  1777. if (t < 10 && uidx > 0) {
  1778. res += ".";
  1779. res += itos(r * 10 / 1_k);
  1780. }
  1781. res += UNITS[uidx];
  1782. return res;
  1783. }
  1784. void sleep(long seconds)
  1785. {
  1786. #if defined(HAVE_WINSOCK2_H)
  1787. ::Sleep(seconds * 1000);
  1788. #elif HAVE_SLEEP
  1789. ::sleep(seconds);
  1790. #elif defined(HAVE_USLEEP)
  1791. ::usleep(seconds * 1000000);
  1792. #else
  1793. #error no sleep function is available (nanosleep?)
  1794. #endif
  1795. }
  1796. void usleep(long microseconds)
  1797. {
  1798. #ifdef HAVE_USLEEP
  1799. ::usleep(microseconds);
  1800. #elif defined(HAVE_WINSOCK2_H)
  1801. LARGE_INTEGER current, freq, end;
  1802. static enum {
  1803. GET_FREQUENCY,
  1804. GET_MICROSECONDS,
  1805. SKIP_MICROSECONDS
  1806. } state = GET_FREQUENCY;
  1807. if (state == GET_FREQUENCY) {
  1808. if (QueryPerformanceFrequency(&freq))
  1809. state = GET_MICROSECONDS;
  1810. else
  1811. state = SKIP_MICROSECONDS;
  1812. }
  1813. long msec = microseconds / 1000;
  1814. microseconds %= 1000;
  1815. if (state == GET_MICROSECONDS && microseconds) {
  1816. QueryPerformanceCounter(&end);
  1817. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  1818. while (QueryPerformanceCounter(&current) &&
  1819. (current.QuadPart <= end.QuadPart))
  1820. /* noop */;
  1821. }
  1822. if (msec)
  1823. Sleep(msec);
  1824. #else
  1825. #error no usleep function is available (nanosleep?)
  1826. #endif
  1827. }
  1828. void mkdirs(const std::string& dirpath)
  1829. {
  1830. File dir(dirpath);
  1831. if (!dir.mkdirs()) {
  1832. int errNum = errno;
  1833. if (!dir.isDir()) {
  1834. throw DL_ABORT_EX3(
  1835. errNum,
  1836. fmt(EX_MAKE_DIR, dir.getPath().c_str(), safeStrerror(errNum).c_str()),
  1837. error_code::DIR_CREATE_ERROR);
  1838. }
  1839. }
  1840. }
  1841. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1842. {
  1843. size_t numBlock = dest->countBlock();
  1844. for (size_t index = 0; index < numBlock; ++index) {
  1845. if (src->isBitSetOffsetRange((int64_t)index * dest->getBlockLength(),
  1846. dest->getBlockLength())) {
  1847. dest->setBit(index);
  1848. }
  1849. }
  1850. }
  1851. std::string toString(const std::shared_ptr<BinaryStream>& binaryStream)
  1852. {
  1853. std::stringstream strm;
  1854. char data[2048];
  1855. while (1) {
  1856. int32_t dataLength = binaryStream->readData(
  1857. reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1858. strm.write(data, dataLength);
  1859. if (dataLength == 0) {
  1860. break;
  1861. }
  1862. }
  1863. return strm.str();
  1864. }
  1865. #ifdef HAVE_POSIX_MEMALIGN
  1866. /**
  1867. * In linux 2.6, alignment and size should be a multiple of 512.
  1868. */
  1869. void* allocateAlignedMemory(size_t alignment, size_t size)
  1870. {
  1871. void* buffer;
  1872. int res;
  1873. if ((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1874. throw FATAL_EXCEPTION(
  1875. fmt("Error in posix_memalign: %s", util::safeStrerror(res).c_str()));
  1876. }
  1877. return buffer;
  1878. }
  1879. #endif // HAVE_POSIX_MEMALIGN
  1880. Endpoint getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1881. {
  1882. char host[NI_MAXHOST];
  1883. char service[NI_MAXSERV];
  1884. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1885. NI_NUMERICHOST | NI_NUMERICSERV);
  1886. if (s != 0) {
  1887. throw DL_ABORT_EX(
  1888. fmt("Failed to get hostname and port. cause: %s", gai_strerror(s)));
  1889. }
  1890. return {host, sockaddr->sa_family,
  1891. static_cast<uint16_t>(strtoul(service, nullptr, 10))};
  1892. }
  1893. std::string htmlEscape(const std::string& src)
  1894. {
  1895. std::string dest;
  1896. dest.reserve(src.size());
  1897. auto j = std::begin(src);
  1898. for (auto i = std::begin(src); i != std::end(src); ++i) {
  1899. char ch = *i;
  1900. const char* repl;
  1901. if (ch == '<') {
  1902. repl = "&lt;";
  1903. }
  1904. else if (ch == '>') {
  1905. repl = "&gt;";
  1906. }
  1907. else if (ch == '&') {
  1908. repl = "&amp;";
  1909. }
  1910. else if (ch == '\'') {
  1911. repl = "&#39;";
  1912. }
  1913. else if (ch == '"') {
  1914. repl = "&quot;";
  1915. }
  1916. else {
  1917. continue;
  1918. }
  1919. dest.append(j, i);
  1920. j = i + 1;
  1921. dest += repl;
  1922. }
  1923. dest.append(j, std::end(src));
  1924. return dest;
  1925. }
  1926. std::pair<size_t, std::string> parseIndexPath(const std::string& line)
  1927. {
  1928. auto p = divide(std::begin(line), std::end(line), '=');
  1929. uint32_t index;
  1930. if (!parseUIntNoThrow(index, std::string(p.first.first, p.first.second))) {
  1931. throw DL_ABORT_EX("Bad path index");
  1932. }
  1933. if (p.second.first == p.second.second) {
  1934. throw DL_ABORT_EX(fmt("Path with index=%u is empty.", index));
  1935. }
  1936. return std::make_pair(index, std::string(p.second.first, p.second.second));
  1937. }
  1938. std::vector<std::pair<size_t, std::string>> createIndexPaths(std::istream& i)
  1939. {
  1940. std::vector<std::pair<size_t, std::string>> indexPaths;
  1941. std::string line;
  1942. while (getline(i, line)) {
  1943. indexPaths.push_back(parseIndexPath(line));
  1944. }
  1945. return indexPaths;
  1946. }
  1947. void generateRandomData(unsigned char* data, size_t length)
  1948. {
  1949. const auto& rd = SimpleRandomizer::getInstance();
  1950. return rd->getRandomBytes(data, length);
  1951. }
  1952. bool saveAs(const std::string& filename, const std::string& data,
  1953. bool overwrite)
  1954. {
  1955. if (!overwrite && File(filename).exists()) {
  1956. return false;
  1957. }
  1958. std::string tempFilename = filename;
  1959. tempFilename += "__temp";
  1960. {
  1961. BufferedFile fp(tempFilename.c_str(), BufferedFile::WRITE);
  1962. if (!fp) {
  1963. return false;
  1964. }
  1965. if (fp.write(data.data(), data.size()) != data.size()) {
  1966. return false;
  1967. }
  1968. if (fp.close() == EOF) {
  1969. return false;
  1970. }
  1971. }
  1972. return File(tempFilename).renameTo(filename);
  1973. }
  1974. std::string applyDir(const std::string& dir, const std::string& relPath)
  1975. {
  1976. std::string s;
  1977. if (dir.empty()) {
  1978. s = "./";
  1979. s += relPath;
  1980. }
  1981. else {
  1982. s = dir;
  1983. if (dir == "/") {
  1984. s += relPath;
  1985. }
  1986. else {
  1987. s += "/";
  1988. s += relPath;
  1989. }
  1990. }
  1991. #ifdef __MINGW32__
  1992. for (std::string::iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1993. if (*i == '\\') {
  1994. *i = '/';
  1995. }
  1996. }
  1997. #endif // __MINGW32__
  1998. return s;
  1999. }
  2000. std::string fixTaintedBasename(const std::string& src)
  2001. {
  2002. return escapePath(replace(src, "/", "%2F"));
  2003. }
  2004. void generateRandomKey(unsigned char* key)
  2005. {
  2006. unsigned char bytes[40];
  2007. generateRandomData(bytes, sizeof(bytes));
  2008. message_digest::digest(key, 20, MessageDigest::sha1().get(), bytes,
  2009. sizeof(bytes));
  2010. }
  2011. // Returns true is given numeric ipv4addr is in Private Address Space.
  2012. //
  2013. // From Section.3 RFC1918
  2014. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  2015. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  2016. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  2017. bool inPrivateAddress(const std::string& ipv4addr)
  2018. {
  2019. if (util::startsWith(ipv4addr, "10.") ||
  2020. util::startsWith(ipv4addr, "192.168.")) {
  2021. return true;
  2022. }
  2023. if (util::startsWith(ipv4addr, "172.")) {
  2024. for (int i = 16; i <= 31; ++i) {
  2025. std::string t(fmt("%d.", i));
  2026. if (util::startsWith(ipv4addr.begin() + 4, ipv4addr.end(), t.begin(),
  2027. t.end())) {
  2028. return true;
  2029. }
  2030. }
  2031. }
  2032. return false;
  2033. }
  2034. bool detectDirTraversal(const std::string& s)
  2035. {
  2036. if (s.empty()) {
  2037. return false;
  2038. }
  2039. for (auto c : s) {
  2040. unsigned char ch = c;
  2041. if (in(ch, 0x00u, 0x1fu) || ch == 0x7fu) {
  2042. return true;
  2043. }
  2044. }
  2045. return s == "." || s == ".." || s[0] == '/' || util::startsWith(s, "./") ||
  2046. util::startsWith(s, "../") || s.find("/../") != std::string::npos ||
  2047. s.find("/./") != std::string::npos || s[s.size() - 1] == '/' ||
  2048. util::endsWith(s, "/.") || util::endsWith(s, "/..");
  2049. }
  2050. std::string escapePath(const std::string& s)
  2051. {
  2052. // We don't escape '/' because we use it as a path separator.
  2053. #ifdef __MINGW32__
  2054. static const char WIN_INVALID_PATH_CHARS[] = {'"', '*', ':', '<',
  2055. '>', '?', '\\', '|'};
  2056. #endif // __MINGW32__
  2057. std::string d;
  2058. for (auto cc : s) {
  2059. unsigned char c = cc;
  2060. if (in(c, 0x00u, 0x1fu) || c == 0x7fu
  2061. #ifdef __MINGW32__
  2062. || std::find(std::begin(WIN_INVALID_PATH_CHARS),
  2063. std::end(WIN_INVALID_PATH_CHARS),
  2064. c) != std::end(WIN_INVALID_PATH_CHARS)
  2065. #endif // __MINGW32__
  2066. ) {
  2067. d += fmt("%%%02X", c);
  2068. }
  2069. else {
  2070. d += c;
  2071. }
  2072. }
  2073. return d;
  2074. }
  2075. bool inSameCidrBlock(const std::string& ip1, const std::string& ip2,
  2076. size_t bits)
  2077. {
  2078. unsigned char s1[16], s2[16];
  2079. size_t len1, len2;
  2080. if ((len1 = net::getBinAddr(s1, ip1)) == 0 ||
  2081. (len2 = net::getBinAddr(s2, ip2)) == 0 || len1 != len2) {
  2082. return false;
  2083. }
  2084. if (bits == 0) {
  2085. return true;
  2086. }
  2087. if (bits > 8 * len1) {
  2088. bits = 8 * len1;
  2089. }
  2090. int last = (bits - 1) / 8;
  2091. for (int i = 0; i < last; ++i) {
  2092. if (s1[i] != s2[i]) {
  2093. return false;
  2094. }
  2095. }
  2096. unsigned char mask = bitfield::lastByteMask(bits);
  2097. return (s1[last] & mask) == (s2[last] & mask);
  2098. }
  2099. namespace {
  2100. void executeHook(const std::string& command, a2_gid_t gid, size_t numFiles,
  2101. const std::string& firstFilename)
  2102. {
  2103. const std::string gidStr = GroupId::toHex(gid);
  2104. const std::string numFilesStr = util::uitos(numFiles);
  2105. #ifndef __MINGW32__
  2106. A2_LOG_INFO(fmt("Executing user command: %s %s %s %s", command.c_str(),
  2107. gidStr.c_str(), numFilesStr.c_str(), firstFilename.c_str()));
  2108. pid_t cpid = fork();
  2109. if (cpid == 0) {
  2110. // child!
  2111. execlp(command.c_str(), command.c_str(), gidStr.c_str(),
  2112. numFilesStr.c_str(), firstFilename.c_str(),
  2113. reinterpret_cast<char*>(0));
  2114. perror(("Could not execute user command: " + command).c_str());
  2115. _exit(EXIT_FAILURE);
  2116. return;
  2117. }
  2118. if (cpid == -1) {
  2119. A2_LOG_ERROR("fork() failed. Cannot execute user command.");
  2120. }
  2121. return;
  2122. #else // __MINGW32__
  2123. PROCESS_INFORMATION pi;
  2124. STARTUPINFOW si;
  2125. memset(&si, 0, sizeof(si));
  2126. si.cb = sizeof(STARTUPINFO);
  2127. memset(&pi, 0, sizeof(pi));
  2128. bool batch = util::iendsWith(command, ".bat");
  2129. std::string cmdline;
  2130. std::string cmdexe;
  2131. // XXX batch handling, in particular quoting, correct?
  2132. if (batch) {
  2133. const char* p = getenv("windir");
  2134. if (p) {
  2135. cmdexe = p;
  2136. cmdexe += "\\system32\\cmd.exe";
  2137. }
  2138. else {
  2139. A2_LOG_INFO("Failed to get windir environment variable."
  2140. " Executing batch file will fail.");
  2141. // TODO Might be useless.
  2142. cmdexe = "cmd.exe";
  2143. }
  2144. cmdline += "/C \"";
  2145. }
  2146. cmdline += "\"";
  2147. cmdline += command;
  2148. cmdline += "\"";
  2149. cmdline += " ";
  2150. cmdline += gidStr;
  2151. cmdline += " ";
  2152. cmdline += numFilesStr;
  2153. cmdline += " \"";
  2154. cmdline += firstFilename;
  2155. cmdline += "\"";
  2156. if (batch) {
  2157. cmdline += "\"";
  2158. }
  2159. int cmdlineLen = utf8ToWChar(nullptr, 0, cmdline.c_str());
  2160. assert(cmdlineLen > 0);
  2161. auto wcharCmdline = make_unique<wchar_t[]>(cmdlineLen);
  2162. cmdlineLen = utf8ToWChar(wcharCmdline.get(), cmdlineLen, cmdline.c_str());
  2163. assert(cmdlineLen > 0);
  2164. A2_LOG_INFO(fmt("Executing user command: %s", cmdline.c_str()));
  2165. DWORD rc = CreateProcessW(batch ? utf8ToWChar(cmdexe).c_str() : nullptr,
  2166. wcharCmdline.get(), nullptr, nullptr, false, 0,
  2167. nullptr, 0, &si, &pi);
  2168. if (!rc) {
  2169. A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command.");
  2170. }
  2171. return;
  2172. #endif
  2173. }
  2174. } // namespace
  2175. void executeHookByOptName(const std::shared_ptr<RequestGroup>& group,
  2176. const Option* option, PrefPtr pref)
  2177. {
  2178. executeHookByOptName(group.get(), option, pref);
  2179. }
  2180. void executeHookByOptName(const RequestGroup* group, const Option* option,
  2181. PrefPtr pref)
  2182. {
  2183. const std::string& cmd = option->get(pref);
  2184. if (!cmd.empty()) {
  2185. const std::shared_ptr<DownloadContext> dctx = group->getDownloadContext();
  2186. std::string firstFilename;
  2187. size_t numFiles = 0;
  2188. if (!group->inMemoryDownload()) {
  2189. std::shared_ptr<FileEntry> file = dctx->getFirstRequestedFileEntry();
  2190. if (file) {
  2191. firstFilename = file->getPath();
  2192. }
  2193. numFiles = dctx->countRequestedFileEntry();
  2194. }
  2195. executeHook(cmd, group->getGID(), numFiles, firstFilename);
  2196. }
  2197. }
  2198. std::string createSafePath(const std::string& dir, const std::string& filename)
  2199. {
  2200. return util::applyDir(dir,
  2201. util::isUtf8(filename)
  2202. ? util::fixTaintedBasename(filename)
  2203. : util::escapePath(util::percentEncode(filename)));
  2204. }
  2205. std::string createSafePath(const std::string& filename)
  2206. {
  2207. return util::isUtf8(filename)
  2208. ? util::fixTaintedBasename(filename)
  2209. : util::escapePath(util::percentEncode(filename));
  2210. }
  2211. std::string encodeNonUtf8(const std::string& s)
  2212. {
  2213. return util::isUtf8(s) ? s : util::percentEncode(s);
  2214. }
  2215. std::string makeString(const char* str)
  2216. {
  2217. if (!str) {
  2218. return A2STR::NIL;
  2219. }
  2220. return str;
  2221. }
  2222. std::string safeStrerror(int errNum) { return makeString(strerror(errNum)); }
  2223. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain)
  2224. {
  2225. if (!domain.empty() && domain[0] == '.' && !util::isNumericHost(hostname)) {
  2226. return util::endsWith(hostname, domain);
  2227. }
  2228. return hostname == domain;
  2229. }
  2230. bool tlsHostnameMatch(const std::string& pattern, const std::string& hostname)
  2231. {
  2232. std::string::const_iterator ptWildcard =
  2233. std::find(pattern.begin(), pattern.end(), '*');
  2234. if (ptWildcard == pattern.end()) {
  2235. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  2236. hostname.end());
  2237. }
  2238. std::string::const_iterator ptLeftLabelEnd =
  2239. std::find(pattern.begin(), pattern.end(), '.');
  2240. bool wildcardEnabled = true;
  2241. // Do case-insensitive match. At least 2 dots are required to enable
  2242. // wildcard match. Also wildcard must be in the left-most label.
  2243. // Don't attempt to match a presented identifier where the wildcard
  2244. // character is embedded within an A-label.
  2245. if (ptLeftLabelEnd == pattern.end() ||
  2246. std::find(ptLeftLabelEnd + 1, pattern.end(), '.') == pattern.end() ||
  2247. ptLeftLabelEnd < ptWildcard || istartsWith(pattern, "xn--")) {
  2248. wildcardEnabled = false;
  2249. }
  2250. if (!wildcardEnabled) {
  2251. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  2252. hostname.end());
  2253. }
  2254. std::string::const_iterator hnLeftLabelEnd =
  2255. std::find(hostname.begin(), hostname.end(), '.');
  2256. if (!strieq(ptLeftLabelEnd, pattern.end(), hnLeftLabelEnd, hostname.end())) {
  2257. return false;
  2258. }
  2259. // Perform wildcard match. Here '*' must match at least one
  2260. // character.
  2261. if (hnLeftLabelEnd - hostname.begin() < ptLeftLabelEnd - pattern.begin()) {
  2262. return false;
  2263. }
  2264. return istartsWith(hostname.begin(), hnLeftLabelEnd, pattern.begin(),
  2265. ptWildcard) &&
  2266. iendsWith(hostname.begin(), hnLeftLabelEnd, ptWildcard + 1,
  2267. ptLeftLabelEnd);
  2268. }
  2269. bool strieq(const std::string& a, const char* b)
  2270. {
  2271. return strieq(a.begin(), a.end(), b);
  2272. }
  2273. bool strieq(const std::string& a, const std::string& b)
  2274. {
  2275. return strieq(a.begin(), a.end(), b.begin(), b.end());
  2276. }
  2277. bool startsWith(const std::string& a, const char* b)
  2278. {
  2279. return startsWith(a.begin(), a.end(), b);
  2280. }
  2281. bool startsWith(const std::string& a, const std::string& b)
  2282. {
  2283. return startsWith(a.begin(), a.end(), b.begin(), b.end());
  2284. }
  2285. bool istartsWith(const std::string& a, const char* b)
  2286. {
  2287. return istartsWith(a.begin(), a.end(), b);
  2288. }
  2289. bool istartsWith(const std::string& a, const std::string& b)
  2290. {
  2291. return istartsWith(std::begin(a), std::end(a), std::begin(b), std::end(b));
  2292. }
  2293. bool endsWith(const std::string& a, const char* b)
  2294. {
  2295. return endsWith(a.begin(), a.end(), b, b + strlen(b));
  2296. }
  2297. bool endsWith(const std::string& a, const std::string& b)
  2298. {
  2299. return endsWith(a.begin(), a.end(), b.begin(), b.end());
  2300. }
  2301. bool iendsWith(const std::string& a, const char* b)
  2302. {
  2303. return iendsWith(a.begin(), a.end(), b, b + strlen(b));
  2304. }
  2305. bool iendsWith(const std::string& a, const std::string& b)
  2306. {
  2307. return iendsWith(a.begin(), a.end(), b.begin(), b.end());
  2308. }
  2309. bool strless(const char* a, const char* b) { return strcmp(a, b) < 0; }
  2310. #ifdef ENABLE_SSL
  2311. TLSVersion toTLSVersion(const std::string& ver)
  2312. {
  2313. if (ver == A2_V_SSL3) {
  2314. return TLS_PROTO_SSL3;
  2315. }
  2316. if (ver == A2_V_TLS10) {
  2317. return TLS_PROTO_TLS10;
  2318. }
  2319. if (ver == A2_V_TLS11) {
  2320. return TLS_PROTO_TLS11;
  2321. }
  2322. if (ver == A2_V_TLS12) {
  2323. return TLS_PROTO_TLS12;
  2324. }
  2325. return TLS_PROTO_TLS10;
  2326. }
  2327. #endif // ENABLE_SSL
  2328. #ifdef __MINGW32__
  2329. std::string formatLastError(int errNum)
  2330. {
  2331. std::array<char, 4_k> buf;
  2332. if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
  2333. nullptr, errNum,
  2334. // Default language
  2335. MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
  2336. static_cast<LPTSTR>(buf.data()), buf.size(),
  2337. nullptr) == 0) {
  2338. return "";
  2339. }
  2340. return buf.data();
  2341. }
  2342. #endif // __MINGW32__
  2343. void make_fd_cloexec(int fd)
  2344. {
  2345. #ifndef __MINGW32__
  2346. int flags;
  2347. // TODO from linux man page, fcntl() with F_GETFD or F_SETFD does
  2348. // not return -1 with errno == EINTR. Historically, aria2 code base
  2349. // checks this case. Probably, it is not needed.
  2350. while ((flags = fcntl(fd, F_GETFD)) == -1 && errno == EINTR)
  2351. ;
  2352. if (flags == -1) {
  2353. return;
  2354. }
  2355. while (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1 && errno == EINTR)
  2356. ;
  2357. #endif // !__MINGW32__
  2358. }
  2359. #ifdef __MINGW32__
  2360. bool gainPrivilege(LPCTSTR privName)
  2361. {
  2362. LUID luid;
  2363. TOKEN_PRIVILEGES tp;
  2364. if (!LookupPrivilegeValue(nullptr, privName, &luid)) {
  2365. auto errNum = GetLastError();
  2366. A2_LOG_WARN(fmt("Lookup for privilege name %s failed. cause: %s", privName,
  2367. util::formatLastError(errNum).c_str()));
  2368. return false;
  2369. }
  2370. tp.PrivilegeCount = 1;
  2371. tp.Privileges[0].Luid = luid;
  2372. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  2373. HANDLE token;
  2374. if (!OpenProcessToken(GetCurrentProcess(),
  2375. TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token)) {
  2376. auto errNum = GetLastError();
  2377. A2_LOG_WARN(fmt("Getting process token failed. cause: %s",
  2378. util::formatLastError(errNum).c_str()));
  2379. return false;
  2380. }
  2381. auto tokenCloser = defer(token, CloseHandle);
  2382. if (!AdjustTokenPrivileges(token, FALSE, &tp, 0, NULL, NULL)) {
  2383. auto errNum = GetLastError();
  2384. A2_LOG_WARN(fmt("Gaining privilege %s failed. cause: %s", privName,
  2385. util::formatLastError(errNum).c_str()));
  2386. return false;
  2387. }
  2388. // Check privilege was really gained
  2389. DWORD bufsize = 0;
  2390. GetTokenInformation(token, TokenPrivileges, nullptr, 0, &bufsize);
  2391. if (bufsize == 0) {
  2392. A2_LOG_WARN("Checking privilege failed.");
  2393. return false;
  2394. }
  2395. auto buf = make_unique<char[]>(bufsize);
  2396. if (!GetTokenInformation(token, TokenPrivileges, buf.get(), bufsize,
  2397. &bufsize)) {
  2398. auto errNum = GetLastError();
  2399. A2_LOG_WARN(fmt("Checking privilege failed. cause: %s",
  2400. util::formatLastError(errNum).c_str()));
  2401. return false;
  2402. }
  2403. auto privs = reinterpret_cast<TOKEN_PRIVILEGES*>(buf.get());
  2404. for (size_t i = 0; i < privs->PrivilegeCount; ++i) {
  2405. auto& priv = privs->Privileges[i];
  2406. if (memcmp(&priv.Luid, &luid, sizeof(luid)) != 0) {
  2407. continue;
  2408. }
  2409. if (priv.Attributes == SE_PRIVILEGE_ENABLED) {
  2410. return true;
  2411. }
  2412. break;
  2413. }
  2414. A2_LOG_WARN(fmt("Gaining privilege %s failed.", privName));
  2415. return false;
  2416. }
  2417. #endif // __MINGW32__
  2418. } // namespace util
  2419. } // namespace aria2