util.cc 52 KB

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