util.cc 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087
  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. long long int t;
  538. if (parseLong(t, strtoll, s, base) &&
  539. t >= std::numeric_limits<int64_t>::min() &&
  540. t <= std::numeric_limits<int64_t>::max()) {
  541. res = t;
  542. return true;
  543. }
  544. else {
  545. return false;
  546. }
  547. }
  548. SegList<int> parseIntSegments(const std::string& src)
  549. {
  550. SegList<int> sgl;
  551. for (std::string::const_iterator i = src.begin(), eoi = src.end();
  552. i != eoi;) {
  553. std::string::const_iterator j = std::find(i, eoi, ',');
  554. if (j == i) {
  555. ++i;
  556. continue;
  557. }
  558. std::string::const_iterator p = std::find(i, j, '-');
  559. if (p == j) {
  560. int a;
  561. if (parseIntNoThrow(a, std::string(i, j))) {
  562. sgl.add(a, a + 1);
  563. }
  564. else {
  565. throw DL_ABORT_EX(fmt("Bad range %s", std::string(i, j).c_str()));
  566. }
  567. }
  568. else if (p == i || p + 1 == j) {
  569. throw DL_ABORT_EX(fmt(MSG_INCOMPLETE_RANGE, std::string(i, j).c_str()));
  570. }
  571. else {
  572. int a, b;
  573. if (parseIntNoThrow(a, std::string(i, p)) &&
  574. parseIntNoThrow(b, (std::string(p + 1, j)))) {
  575. sgl.add(a, b + 1);
  576. }
  577. else {
  578. throw DL_ABORT_EX(fmt("Bad range %s", std::string(i, j).c_str()));
  579. }
  580. }
  581. if (j == eoi) {
  582. break;
  583. }
  584. i = j + 1;
  585. }
  586. return sgl;
  587. }
  588. namespace {
  589. void computeHeadPieces(
  590. std::vector<size_t>& indexes,
  591. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  592. size_t pieceLength, int64_t head)
  593. {
  594. if (head == 0) {
  595. return;
  596. }
  597. for (const auto& fi : fileEntries) {
  598. if (fi->getLength() == 0) {
  599. continue;
  600. }
  601. const size_t lastIndex =
  602. (fi->getOffset() + std::min(head, fi->getLength()) - 1) / pieceLength;
  603. for (size_t idx = fi->getOffset() / pieceLength; idx <= lastIndex; ++idx) {
  604. indexes.push_back(idx);
  605. }
  606. }
  607. }
  608. } // namespace
  609. namespace {
  610. void computeTailPieces(
  611. std::vector<size_t>& indexes,
  612. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  613. size_t pieceLength, int64_t tail)
  614. {
  615. if (tail == 0) {
  616. return;
  617. }
  618. for (const auto& fi : fileEntries) {
  619. if (fi->getLength() == 0) {
  620. continue;
  621. }
  622. int64_t endOffset = fi->getLastOffset();
  623. size_t fromIndex =
  624. (endOffset - 1 - (std::min(tail, fi->getLength()) - 1)) / pieceLength;
  625. const size_t toIndex = (endOffset - 1) / pieceLength;
  626. while (fromIndex <= toIndex) {
  627. indexes.push_back(fromIndex++);
  628. }
  629. }
  630. }
  631. } // namespace
  632. void parsePrioritizePieceRange(
  633. std::vector<size_t>& result, const std::string& src,
  634. const std::vector<std::shared_ptr<FileEntry>>& fileEntries,
  635. size_t pieceLength, int64_t defaultSize)
  636. {
  637. std::vector<size_t> indexes;
  638. std::vector<Scip> parts;
  639. splitIter(src.begin(), src.end(), std::back_inserter(parts), ',', true);
  640. for (const auto& i : parts) {
  641. if (util::streq(i.first, i.second, "head")) {
  642. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  643. }
  644. else if (util::startsWith(i.first, i.second, "head=")) {
  645. std::string sizestr(i.first + 5, i.second);
  646. computeHeadPieces(indexes, fileEntries, pieceLength,
  647. std::max((int64_t)0, getRealSize(sizestr)));
  648. }
  649. else if (util::streq(i.first, i.second, "tail")) {
  650. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  651. }
  652. else if (util::startsWith(i.first, i.second, "tail=")) {
  653. std::string sizestr(i.first + 5, i.second);
  654. computeTailPieces(indexes, fileEntries, pieceLength,
  655. std::max((int64_t)0, getRealSize(sizestr)));
  656. }
  657. else {
  658. throw DL_ABORT_EX(
  659. fmt("Unrecognized token %s", std::string(i.first, i.second).c_str()));
  660. }
  661. }
  662. std::sort(indexes.begin(), indexes.end());
  663. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  664. result.insert(result.end(), indexes.begin(), indexes.end());
  665. }
  666. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  667. // character not in ISO/IEC 8859-1, returns empty string.
  668. std::string iso8859p1ToUtf8(const char* src, size_t len)
  669. {
  670. std::string dest;
  671. for (const char* p = src, * last = src + len; p != last; ++p) {
  672. unsigned char c = *p;
  673. if (0xa0u <= c) {
  674. if (c <= 0xbfu) {
  675. dest += 0xc2u;
  676. }
  677. else {
  678. dest += 0xc3u;
  679. }
  680. dest += c & (~0x40u);
  681. }
  682. else if (0x80u <= c && c <= 0x9fu) {
  683. return "";
  684. }
  685. else {
  686. dest += c;
  687. }
  688. }
  689. return dest;
  690. }
  691. std::string iso8859p1ToUtf8(const std::string& src)
  692. {
  693. return iso8859p1ToUtf8(src.c_str(), src.size());
  694. }
  695. /* Start of utf8 dfa */
  696. /* Copyright (c) 2008-2010 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  697. * See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
  698. *
  699. * Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de>
  700. *
  701. * Permission is hereby granted, free of charge, to any person
  702. * obtaining a copy of this software and associated documentation
  703. * files (the "Software"), to deal in the Software without
  704. * restriction, including without limitation the rights to use, copy,
  705. * modify, merge, publish, distribute, sublicense, and/or sell copies
  706. * of the Software, and to permit persons to whom the Software is
  707. * furnished to do so, subject to the following conditions:
  708. *
  709. * The above copyright notice and this permission notice shall be
  710. * included in all copies or substantial portions of the Software.
  711. *
  712. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  713. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  714. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  715. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  716. * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  717. * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  718. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  719. * SOFTWARE.
  720. */
  721. #define UTF8_ACCEPT 0
  722. #define UTF8_REJECT 12
  723. static const uint8_t utf8d[] = {
  724. /*
  725. * The first part of the table maps bytes to character classes that
  726. * to reduce the size of the transition table and create bitmasks.
  727. */
  728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
  735. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9,
  736. 9, 9, 9, 9, 9, 9, 9, 9, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  737. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  738. 7, 7, 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  739. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10, 3, 3, 3,
  740. 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 3, 3, 11, 6, 6, 6, 5, 8, 8,
  741. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  742. /*
  743. * The second part is a transition table that maps a combination
  744. * of a state of the automaton and a character class to a state.
  745. */
  746. 0, 12, 24, 36, 60, 96, 84, 12, 12, 12, 48, 72, 12, 12, 12, 12, 12, 12, 12,
  747. 12, 12, 12, 12, 12, 12, 0, 12, 12, 12, 12, 12, 0, 12, 0, 12, 12, 12, 24,
  748. 12, 12, 12, 12, 12, 24, 12, 24, 12, 12, 12, 12, 12, 12, 12, 12, 12, 24, 12,
  749. 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12, 12, 24, 12, 12, 12, 12, 12, 12,
  750. 12, 12, 12, 36, 12, 36, 12, 12, 12, 36, 12, 12, 12, 12, 12, 36, 12, 36, 12,
  751. 12, 12, 36, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  752. };
  753. static uint32_t utf8dfa(uint32_t* state, uint32_t* codep, uint32_t byte)
  754. {
  755. uint32_t type = utf8d[byte];
  756. *codep = (*state != UTF8_ACCEPT) ? (byte & 0x3fu) | (*codep << 6)
  757. : (0xff >> type) & (byte);
  758. *state = utf8d[256 + *state + type];
  759. return *state;
  760. }
  761. /* End of utf8 dfa */
  762. typedef enum {
  763. CD_BEFORE_DISPOSITION_TYPE,
  764. CD_AFTER_DISPOSITION_TYPE,
  765. CD_DISPOSITION_TYPE,
  766. CD_BEFORE_DISPOSITION_PARM_NAME,
  767. CD_AFTER_DISPOSITION_PARM_NAME,
  768. CD_DISPOSITION_PARM_NAME,
  769. CD_BEFORE_VALUE,
  770. CD_AFTER_VALUE,
  771. CD_QUOTED_STRING,
  772. CD_TOKEN,
  773. CD_BEFORE_EXT_VALUE,
  774. CD_CHARSET,
  775. CD_LANGUAGE,
  776. CD_VALUE_CHARS,
  777. CD_VALUE_CHARS_PCT_ENCODED1,
  778. CD_VALUE_CHARS_PCT_ENCODED2
  779. } content_disposition_parse_state;
  780. typedef enum {
  781. CD_FILENAME_FOUND = 1,
  782. CD_EXT_FILENAME_FOUND = 1 << 1
  783. } content_disposition_parse_flag;
  784. typedef enum {
  785. CD_ENC_UNKNOWN,
  786. CD_ENC_UTF8,
  787. CD_ENC_ISO_8859_1
  788. } content_disposition_charset;
  789. ssize_t parse_content_disposition(char* dest, size_t destlen,
  790. const char** charsetp, size_t* charsetlenp,
  791. const char* in, size_t len)
  792. {
  793. const char* p = in, * eop = in + len, * mark_first = nullptr,
  794. * mark_last = nullptr;
  795. int state = CD_BEFORE_DISPOSITION_TYPE;
  796. int in_file_parm = 0;
  797. int flags = 0;
  798. int quoted_seen = 0;
  799. int charset = 0;
  800. /* To suppress warnings */
  801. char* dp = dest;
  802. size_t dlen = destlen;
  803. uint32_t dfa_state = 0;
  804. uint32_t dfa_code = 0;
  805. uint8_t pctval = 0;
  806. *charsetp = nullptr;
  807. *charsetlenp = 0;
  808. for (; p != eop; ++p) {
  809. switch (state) {
  810. case CD_BEFORE_DISPOSITION_TYPE:
  811. if (inRFC2616HttpToken(*p)) {
  812. state = CD_DISPOSITION_TYPE;
  813. }
  814. else if (!isLws(*p)) {
  815. return -1;
  816. }
  817. break;
  818. case CD_AFTER_DISPOSITION_TYPE:
  819. case CD_DISPOSITION_TYPE:
  820. if (*p == ';') {
  821. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  822. }
  823. else if (isLws(*p)) {
  824. state = CD_AFTER_DISPOSITION_TYPE;
  825. }
  826. else if (state == CD_AFTER_DISPOSITION_TYPE || !inRFC2616HttpToken(*p)) {
  827. return -1;
  828. }
  829. break;
  830. case CD_BEFORE_DISPOSITION_PARM_NAME:
  831. if (inRFC2616HttpToken(*p)) {
  832. mark_first = p;
  833. state = CD_DISPOSITION_PARM_NAME;
  834. }
  835. else if (!isLws(*p)) {
  836. return -1;
  837. }
  838. break;
  839. case CD_AFTER_DISPOSITION_PARM_NAME:
  840. case CD_DISPOSITION_PARM_NAME:
  841. if (*p == '=') {
  842. if (state == CD_DISPOSITION_PARM_NAME) {
  843. mark_last = p;
  844. }
  845. in_file_parm = 0;
  846. if (strieq(mark_first, mark_last, "filename*")) {
  847. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  848. in_file_parm = 1;
  849. }
  850. else {
  851. return -1;
  852. }
  853. state = CD_BEFORE_EXT_VALUE;
  854. }
  855. else if (strieq(mark_first, mark_last, "filename")) {
  856. if (flags & CD_FILENAME_FOUND) {
  857. return -1;
  858. }
  859. if ((flags & CD_EXT_FILENAME_FOUND) == 0) {
  860. in_file_parm = 1;
  861. }
  862. state = CD_BEFORE_VALUE;
  863. }
  864. else {
  865. /* ext-token must be characters in token, followed by "*" */
  866. if (mark_first != mark_last - 1 && *(mark_last - 1) == '*') {
  867. state = CD_BEFORE_EXT_VALUE;
  868. }
  869. else {
  870. state = CD_BEFORE_VALUE;
  871. }
  872. }
  873. if (in_file_parm) {
  874. dp = dest;
  875. dlen = destlen;
  876. }
  877. }
  878. else if (isLws(*p)) {
  879. mark_last = p;
  880. state = CD_AFTER_DISPOSITION_PARM_NAME;
  881. }
  882. else if (state == CD_AFTER_DISPOSITION_PARM_NAME ||
  883. !inRFC2616HttpToken(*p)) {
  884. return -1;
  885. }
  886. break;
  887. case CD_BEFORE_VALUE:
  888. if (*p == '"') {
  889. quoted_seen = 0;
  890. state = CD_QUOTED_STRING;
  891. }
  892. else if (inRFC2616HttpToken(*p)) {
  893. if (in_file_parm) {
  894. if (dlen == 0) {
  895. return -1;
  896. }
  897. else {
  898. *dp++ = *p;
  899. --dlen;
  900. }
  901. }
  902. state = CD_TOKEN;
  903. }
  904. else if (!isLws(*p)) {
  905. return -1;
  906. }
  907. break;
  908. case CD_AFTER_VALUE:
  909. if (*p == ';') {
  910. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  911. }
  912. else if (!isLws(*p)) {
  913. return -1;
  914. }
  915. break;
  916. case CD_QUOTED_STRING:
  917. if (*p == '\\' && quoted_seen == 0) {
  918. quoted_seen = 1;
  919. }
  920. else if (*p == '"' && quoted_seen == 0) {
  921. if (in_file_parm) {
  922. flags |= CD_FILENAME_FOUND;
  923. }
  924. state = CD_AFTER_VALUE;
  925. }
  926. else {
  927. /* TEXT which is OCTET except CTLs, but including LWS. We only
  928. accept ISO-8859-1 chars. */
  929. quoted_seen = 0;
  930. if (!isIso8859p1(*p)) {
  931. return -1;
  932. }
  933. if (in_file_parm) {
  934. if (dlen == 0) {
  935. return -1;
  936. }
  937. else {
  938. *dp++ = *p;
  939. --dlen;
  940. }
  941. }
  942. }
  943. break;
  944. case CD_TOKEN:
  945. if (inRFC2616HttpToken(*p)) {
  946. if (in_file_parm) {
  947. if (dlen == 0) {
  948. return -1;
  949. }
  950. else {
  951. *dp++ = *p;
  952. --dlen;
  953. }
  954. }
  955. }
  956. else if (*p == ';') {
  957. if (in_file_parm) {
  958. flags |= CD_FILENAME_FOUND;
  959. }
  960. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  961. }
  962. else if (isLws(*p)) {
  963. if (in_file_parm) {
  964. flags |= CD_FILENAME_FOUND;
  965. }
  966. state = CD_AFTER_VALUE;
  967. }
  968. else {
  969. return -1;
  970. }
  971. break;
  972. case CD_BEFORE_EXT_VALUE:
  973. if (*p == '\'') {
  974. /* Empty charset is not allowed */
  975. return -1;
  976. }
  977. else if (inRFC2978MIMECharset(*p)) {
  978. mark_first = p;
  979. state = CD_CHARSET;
  980. }
  981. else if (!isLws(*p)) {
  982. return -1;
  983. }
  984. break;
  985. case CD_CHARSET:
  986. if (*p == '\'') {
  987. mark_last = p;
  988. *charsetp = mark_first;
  989. *charsetlenp = mark_last - mark_first;
  990. if (strieq(mark_first, mark_last, "utf-8")) {
  991. charset = CD_ENC_UTF8;
  992. dfa_state = UTF8_ACCEPT;
  993. dfa_code = 0;
  994. }
  995. else if (strieq(mark_first, mark_last, "iso-8859-1")) {
  996. charset = CD_ENC_ISO_8859_1;
  997. }
  998. else {
  999. charset = CD_ENC_UNKNOWN;
  1000. }
  1001. state = CD_LANGUAGE;
  1002. }
  1003. else if (!inRFC2978MIMECharset(*p)) {
  1004. return -1;
  1005. }
  1006. break;
  1007. case CD_LANGUAGE:
  1008. if (*p == '\'') {
  1009. if (in_file_parm) {
  1010. dp = dest;
  1011. dlen = destlen;
  1012. }
  1013. state = CD_VALUE_CHARS;
  1014. }
  1015. else if (*p != '-' && !isAlpha(*p) && !isDigit(*p)) {
  1016. return -1;
  1017. }
  1018. break;
  1019. case CD_VALUE_CHARS:
  1020. if (inRFC5987AttrChar(*p)) {
  1021. if (charset == CD_ENC_UTF8) {
  1022. if (utf8dfa(&dfa_state, &dfa_code, *p) == UTF8_REJECT) {
  1023. return -1;
  1024. }
  1025. }
  1026. if (in_file_parm) {
  1027. if (dlen == 0) {
  1028. return -1;
  1029. }
  1030. else {
  1031. *dp++ = *p;
  1032. --dlen;
  1033. }
  1034. }
  1035. }
  1036. else if (*p == '%') {
  1037. if (in_file_parm) {
  1038. if (dlen == 0) {
  1039. return -1;
  1040. }
  1041. }
  1042. pctval = 0;
  1043. state = CD_VALUE_CHARS_PCT_ENCODED1;
  1044. }
  1045. else if (*p == ';' || isLws(*p)) {
  1046. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1047. return -1;
  1048. }
  1049. if (in_file_parm) {
  1050. flags |= CD_EXT_FILENAME_FOUND;
  1051. }
  1052. if (*p == ';') {
  1053. state = CD_BEFORE_DISPOSITION_PARM_NAME;
  1054. }
  1055. else {
  1056. state = CD_AFTER_VALUE;
  1057. }
  1058. }
  1059. else if (!inRFC5987AttrChar(*p)) {
  1060. return -1;
  1061. }
  1062. break;
  1063. case CD_VALUE_CHARS_PCT_ENCODED1:
  1064. if (isHexDigit(*p)) {
  1065. pctval |= hexCharToUInt(*p) << 4;
  1066. state = CD_VALUE_CHARS_PCT_ENCODED2;
  1067. }
  1068. else {
  1069. return -1;
  1070. }
  1071. break;
  1072. case CD_VALUE_CHARS_PCT_ENCODED2:
  1073. if (isHexDigit(*p)) {
  1074. pctval |= hexCharToUInt(*p);
  1075. if (charset == CD_ENC_UTF8) {
  1076. if (utf8dfa(&dfa_state, &dfa_code, pctval) == UTF8_REJECT) {
  1077. return -1;
  1078. }
  1079. }
  1080. else if (charset == CD_ENC_ISO_8859_1) {
  1081. if (!isIso8859p1(pctval)) {
  1082. return -1;
  1083. }
  1084. }
  1085. if (in_file_parm) {
  1086. *dp++ = pctval;
  1087. --dlen;
  1088. }
  1089. state = CD_VALUE_CHARS;
  1090. }
  1091. else {
  1092. return -1;
  1093. }
  1094. break;
  1095. }
  1096. }
  1097. switch (state) {
  1098. case CD_BEFORE_DISPOSITION_TYPE:
  1099. case CD_AFTER_DISPOSITION_TYPE:
  1100. case CD_DISPOSITION_TYPE:
  1101. case CD_AFTER_VALUE:
  1102. case CD_TOKEN:
  1103. return destlen - dlen;
  1104. case CD_VALUE_CHARS:
  1105. if (charset == CD_ENC_UTF8 && dfa_state != UTF8_ACCEPT) {
  1106. return -1;
  1107. }
  1108. return destlen - dlen;
  1109. default:
  1110. return -1;
  1111. }
  1112. }
  1113. std::string getContentDispositionFilename(const std::string& header)
  1114. {
  1115. std::array<char, 1_k> cdval;
  1116. size_t cdvallen = cdval.size();
  1117. const char* charset;
  1118. size_t charsetlen;
  1119. ssize_t rv =
  1120. parse_content_disposition(cdval.data(), cdvallen, &charset, &charsetlen,
  1121. header.c_str(), header.size());
  1122. if (rv == -1) {
  1123. return "";
  1124. }
  1125. std::string res;
  1126. if (!charset || strieq(charset, charset + charsetlen, "iso-8859-1")) {
  1127. res = iso8859p1ToUtf8(cdval.data(), rv);
  1128. }
  1129. else {
  1130. res.assign(cdval.data(), rv);
  1131. }
  1132. if (!detectDirTraversal(res) &&
  1133. res.find_first_of("/\\") == std::string::npos) {
  1134. return res;
  1135. }
  1136. return "";
  1137. }
  1138. std::string toUpper(std::string src)
  1139. {
  1140. uppercase(src);
  1141. return src;
  1142. }
  1143. std::string toLower(std::string src)
  1144. {
  1145. lowercase(src);
  1146. return src;
  1147. }
  1148. void uppercase(std::string& s)
  1149. {
  1150. std::transform(s.begin(), s.end(), s.begin(), toUpperChar);
  1151. }
  1152. void lowercase(std::string& s)
  1153. {
  1154. std::transform(s.begin(), s.end(), s.begin(), toLowerChar);
  1155. }
  1156. char toUpperChar(char c)
  1157. {
  1158. if ('a' <= c && c <= 'z') {
  1159. c += 'A' - 'a';
  1160. }
  1161. return c;
  1162. }
  1163. char toLowerChar(char c)
  1164. {
  1165. if ('A' <= c && c <= 'Z') {
  1166. c += 'a' - 'A';
  1167. }
  1168. return c;
  1169. }
  1170. bool isNumericHost(const std::string& name)
  1171. {
  1172. struct addrinfo hints;
  1173. struct addrinfo* res;
  1174. memset(&hints, 0, sizeof(hints));
  1175. hints.ai_family = AF_UNSPEC;
  1176. hints.ai_flags = AI_NUMERICHOST;
  1177. if (getaddrinfo(name.c_str(), nullptr, &hints, &res)) {
  1178. return false;
  1179. }
  1180. freeaddrinfo(res);
  1181. return true;
  1182. }
  1183. #if _WIN32
  1184. namespace {
  1185. static Lock win_signal_lock;
  1186. static signal_handler_t win_int_handler = nullptr;
  1187. static signal_handler_t win_term_handler = nullptr;
  1188. static void win_ign_handler(int) {}
  1189. static BOOL WINAPI HandlerRoutine(DWORD ctrlType)
  1190. {
  1191. void (*handler)(int) = nullptr;
  1192. switch (ctrlType) {
  1193. case CTRL_C_EVENT:
  1194. case CTRL_BREAK_EVENT: {
  1195. // Handler will be called on a new/different thread.
  1196. LockGuard lg(win_signal_lock);
  1197. handler = win_int_handler;
  1198. }
  1199. if (handler) {
  1200. handler(SIGINT);
  1201. return TRUE;
  1202. }
  1203. return FALSE;
  1204. case CTRL_LOGOFF_EVENT:
  1205. case CTRL_CLOSE_EVENT:
  1206. case CTRL_SHUTDOWN_EVENT: {
  1207. // Handler will be called on a new/different thread.
  1208. LockGuard lg(win_signal_lock);
  1209. handler = win_term_handler;
  1210. ;
  1211. }
  1212. if (handler) {
  1213. handler(SIGTERM);
  1214. return TRUE;
  1215. }
  1216. return FALSE;
  1217. }
  1218. return FALSE;
  1219. }
  1220. }
  1221. #endif
  1222. void setGlobalSignalHandler(int sig, sigset_t* mask, signal_handler_t handler,
  1223. int flags)
  1224. {
  1225. #if _WIN32
  1226. if (sig == SIGINT || sig == SIGTERM) {
  1227. // Handler will be called on a new/different thread.
  1228. LockGuard lg(win_signal_lock);
  1229. if (handler == SIG_DFL) {
  1230. handler = nullptr;
  1231. }
  1232. else if (handler == SIG_IGN) {
  1233. handler = win_ign_handler;
  1234. }
  1235. // Not yet in use: add console handler.
  1236. if (handler && !win_int_handler && !win_term_handler) {
  1237. ::SetConsoleCtrlHandler(HandlerRoutine, TRUE);
  1238. }
  1239. if (sig == SIGINT) {
  1240. win_int_handler = handler;
  1241. }
  1242. else {
  1243. win_term_handler = handler;
  1244. }
  1245. // No handlers set: remove.
  1246. if (!win_int_handler && !win_term_handler) {
  1247. ::SetConsoleCtrlHandler(HandlerRoutine, FALSE);
  1248. }
  1249. return;
  1250. }
  1251. #endif
  1252. #ifdef HAVE_SIGACTION
  1253. struct sigaction sigact;
  1254. sigact.sa_handler = handler;
  1255. sigact.sa_flags = flags;
  1256. sigact.sa_mask = *mask;
  1257. sigaction(sig, &sigact, nullptr);
  1258. #else
  1259. signal(sig, handler);
  1260. #endif // HAVE_SIGACTION
  1261. }
  1262. #ifndef __MINGW32__
  1263. std::string getHomeDir()
  1264. {
  1265. const char* p = getenv("HOME");
  1266. if (p) {
  1267. return p;
  1268. }
  1269. #ifdef HAVE_PWD_H
  1270. auto pw = getpwuid(geteuid());
  1271. if (pw && pw->pw_dir) {
  1272. return pw->pw_dir;
  1273. }
  1274. #endif // HAVE_PWD_H
  1275. return A2STR::NIL;
  1276. }
  1277. #else // __MINGW32__
  1278. std::string getHomeDir()
  1279. {
  1280. auto p = _wgetenv(L"HOME");
  1281. if (p) {
  1282. return toForwardSlash(wCharToUtf8(p));
  1283. }
  1284. p = _wgetenv(L"USERPROFILE");
  1285. if (p) {
  1286. return toForwardSlash(wCharToUtf8(p));
  1287. }
  1288. p = _wgetenv(L"HOMEDRIVE");
  1289. if (p) {
  1290. std::wstring homeDir = p;
  1291. p = _wgetenv(L"HOMEPATH");
  1292. if (p) {
  1293. homeDir += p;
  1294. return toForwardSlash(wCharToUtf8(homeDir));
  1295. }
  1296. }
  1297. return A2STR::NIL;
  1298. }
  1299. #endif // __MINGW32__
  1300. std::string getXDGDir(const std::string& environmentVariable,
  1301. const std::string& fallbackDirectory)
  1302. {
  1303. std::string filename;
  1304. const char* p = getenv(environmentVariable.c_str());
  1305. if (p && p[0] == '/') {
  1306. filename = p;
  1307. }
  1308. else {
  1309. filename = fallbackDirectory;
  1310. }
  1311. return filename;
  1312. }
  1313. std::string getConfigFile()
  1314. {
  1315. std::string filename = getHomeDir() + "/.aria2/aria2.conf";
  1316. if (!File(filename).exists()) {
  1317. filename = getXDGDir("XDG_CONFIG_HOME", getHomeDir() + "/.config") +
  1318. "/aria2/aria2.conf";
  1319. }
  1320. return filename;
  1321. }
  1322. std::string getDHTFile(bool ipv6)
  1323. {
  1324. std::string filename =
  1325. getHomeDir() + (ipv6 ? "/.aria2/dht6.dat" : "/.aria2/dht.dat");
  1326. if (!File(filename).exists()) {
  1327. filename = getXDGDir("XDG_CACHE_HOME", getHomeDir() + "/.cache") +
  1328. (ipv6 ? "/aria2/dht6.dat" : "/aria2/dht.dat");
  1329. }
  1330. return filename;
  1331. }
  1332. int64_t getRealSize(const std::string& sizeWithUnit)
  1333. {
  1334. std::string::size_type p = sizeWithUnit.find_first_of("KMkm");
  1335. std::string size;
  1336. int32_t mult = 1;
  1337. if (p == std::string::npos) {
  1338. size = sizeWithUnit;
  1339. }
  1340. else {
  1341. switch (sizeWithUnit[p]) {
  1342. case 'K':
  1343. case 'k':
  1344. mult = 1_k;
  1345. break;
  1346. case 'M':
  1347. case 'm':
  1348. mult = 1_m;
  1349. break;
  1350. }
  1351. size.assign(sizeWithUnit.begin(), sizeWithUnit.begin() + p);
  1352. }
  1353. int64_t v;
  1354. if (!parseLLIntNoThrow(v, size) || v < 0) {
  1355. throw DL_ABORT_EX(
  1356. fmt("Bad or negative value detected: %s", sizeWithUnit.c_str()));
  1357. }
  1358. if (INT64_MAX / mult < v) {
  1359. throw DL_ABORT_EX(
  1360. fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, "overflow/underflow"));
  1361. }
  1362. return v * mult;
  1363. }
  1364. std::string abbrevSize(int64_t size)
  1365. {
  1366. static const char* UNITS[] = {"", "Ki", "Mi", "Gi"};
  1367. int64_t t = size;
  1368. size_t uidx = 0;
  1369. int r = 0;
  1370. while (t >= static_cast<int64_t>(1_k) &&
  1371. uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0])) {
  1372. lldiv_t d = lldiv(t, 1_k);
  1373. t = d.quot;
  1374. r = d.rem;
  1375. ++uidx;
  1376. }
  1377. if (uidx + 1 < sizeof(UNITS) / sizeof(UNITS[0]) && t >= 922) {
  1378. ++uidx;
  1379. r = t;
  1380. t = 0;
  1381. }
  1382. std::string res;
  1383. res += itos(t, true);
  1384. if (t < 10 && uidx > 0) {
  1385. res += ".";
  1386. res += itos(r * 10 / 1_k);
  1387. }
  1388. res += UNITS[uidx];
  1389. return res;
  1390. }
  1391. void sleep(long seconds)
  1392. {
  1393. #if defined(HAVE_WINSOCK2_H)
  1394. ::Sleep(seconds * 1000);
  1395. #elif HAVE_SLEEP
  1396. ::sleep(seconds);
  1397. #elif defined(HAVE_USLEEP)
  1398. ::usleep(seconds * 1000000);
  1399. #else
  1400. #error no sleep function is available (nanosleep?)
  1401. #endif
  1402. }
  1403. void usleep(long microseconds)
  1404. {
  1405. #ifdef HAVE_USLEEP
  1406. ::usleep(microseconds);
  1407. #elif defined(HAVE_WINSOCK2_H)
  1408. LARGE_INTEGER current, freq, end;
  1409. static enum {
  1410. GET_FREQUENCY,
  1411. GET_MICROSECONDS,
  1412. SKIP_MICROSECONDS
  1413. } state = GET_FREQUENCY;
  1414. if (state == GET_FREQUENCY) {
  1415. if (QueryPerformanceFrequency(&freq))
  1416. state = GET_MICROSECONDS;
  1417. else
  1418. state = SKIP_MICROSECONDS;
  1419. }
  1420. long msec = microseconds / 1000;
  1421. microseconds %= 1000;
  1422. if (state == GET_MICROSECONDS && microseconds) {
  1423. QueryPerformanceCounter(&end);
  1424. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  1425. while (QueryPerformanceCounter(&current) &&
  1426. (current.QuadPart <= end.QuadPart))
  1427. /* noop */;
  1428. }
  1429. if (msec)
  1430. Sleep(msec);
  1431. #else
  1432. #error no usleep function is available (nanosleep?)
  1433. #endif
  1434. }
  1435. void mkdirs(const std::string& dirpath)
  1436. {
  1437. File dir(dirpath);
  1438. if (!dir.mkdirs()) {
  1439. int errNum = errno;
  1440. if (!dir.isDir()) {
  1441. throw DL_ABORT_EX3(errNum, fmt(EX_MAKE_DIR, dir.getPath().c_str(),
  1442. safeStrerror(errNum).c_str()),
  1443. error_code::DIR_CREATE_ERROR);
  1444. }
  1445. }
  1446. }
  1447. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  1448. {
  1449. size_t numBlock = dest->countBlock();
  1450. for (size_t index = 0; index < numBlock; ++index) {
  1451. if (src->isBitSetOffsetRange((int64_t)index * dest->getBlockLength(),
  1452. dest->getBlockLength())) {
  1453. dest->setBit(index);
  1454. }
  1455. }
  1456. }
  1457. std::string toString(const std::shared_ptr<BinaryStream>& binaryStream)
  1458. {
  1459. std::stringstream strm;
  1460. char data[2048];
  1461. while (1) {
  1462. int32_t dataLength = binaryStream->readData(
  1463. reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1464. strm.write(data, dataLength);
  1465. if (dataLength == 0) {
  1466. break;
  1467. }
  1468. }
  1469. return strm.str();
  1470. }
  1471. #ifdef HAVE_POSIX_MEMALIGN
  1472. /**
  1473. * In linux 2.6, alignment and size should be a multiple of 512.
  1474. */
  1475. void* allocateAlignedMemory(size_t alignment, size_t size)
  1476. {
  1477. void* buffer;
  1478. int res;
  1479. if ((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1480. throw FATAL_EXCEPTION(
  1481. fmt("Error in posix_memalign: %s", util::safeStrerror(res).c_str()));
  1482. }
  1483. return buffer;
  1484. }
  1485. #endif // HAVE_POSIX_MEMALIGN
  1486. Endpoint getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1487. {
  1488. char host[NI_MAXHOST];
  1489. char service[NI_MAXSERV];
  1490. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1491. NI_NUMERICHOST | NI_NUMERICSERV);
  1492. if (s != 0) {
  1493. throw DL_ABORT_EX(
  1494. fmt("Failed to get hostname and port. cause: %s", gai_strerror(s)));
  1495. }
  1496. return {host, sockaddr->sa_family,
  1497. static_cast<uint16_t>(strtoul(service, nullptr, 10))};
  1498. }
  1499. std::string htmlEscape(const std::string& src)
  1500. {
  1501. std::string dest;
  1502. dest.reserve(src.size());
  1503. auto j = std::begin(src);
  1504. for (auto i = std::begin(src); i != std::end(src); ++i) {
  1505. char ch = *i;
  1506. const char* repl;
  1507. if (ch == '<') {
  1508. repl = "&lt;";
  1509. }
  1510. else if (ch == '>') {
  1511. repl = "&gt;";
  1512. }
  1513. else if (ch == '&') {
  1514. repl = "&amp;";
  1515. }
  1516. else if (ch == '\'') {
  1517. repl = "&#39;";
  1518. }
  1519. else if (ch == '"') {
  1520. repl = "&quot;";
  1521. }
  1522. else {
  1523. continue;
  1524. }
  1525. dest.append(j, i);
  1526. j = i + 1;
  1527. dest += repl;
  1528. }
  1529. dest.append(j, std::end(src));
  1530. return dest;
  1531. }
  1532. std::pair<size_t, std::string> parseIndexPath(const std::string& line)
  1533. {
  1534. auto p = divide(std::begin(line), std::end(line), '=');
  1535. uint32_t index;
  1536. if (!parseUIntNoThrow(index, std::string(p.first.first, p.first.second))) {
  1537. throw DL_ABORT_EX("Bad path index");
  1538. }
  1539. if (p.second.first == p.second.second) {
  1540. throw DL_ABORT_EX(fmt("Path with index=%u is empty.", index));
  1541. }
  1542. return std::make_pair(index, std::string(p.second.first, p.second.second));
  1543. }
  1544. std::vector<std::pair<size_t, std::string>> createIndexPaths(std::istream& i)
  1545. {
  1546. std::vector<std::pair<size_t, std::string>> indexPaths;
  1547. std::string line;
  1548. while (getline(i, line)) {
  1549. indexPaths.push_back(parseIndexPath(line));
  1550. }
  1551. return indexPaths;
  1552. }
  1553. void generateRandomData(unsigned char* data, size_t length)
  1554. {
  1555. const auto& rd = SimpleRandomizer::getInstance();
  1556. return rd->getRandomBytes(data, length);
  1557. }
  1558. bool saveAs(const std::string& filename, const std::string& data,
  1559. bool overwrite)
  1560. {
  1561. if (!overwrite && File(filename).exists()) {
  1562. return false;
  1563. }
  1564. std::string tempFilename = filename;
  1565. tempFilename += "__temp";
  1566. {
  1567. BufferedFile fp(tempFilename.c_str(), BufferedFile::WRITE);
  1568. if (!fp) {
  1569. return false;
  1570. }
  1571. if (fp.write(data.data(), data.size()) != data.size()) {
  1572. return false;
  1573. }
  1574. if (fp.close() == EOF) {
  1575. return false;
  1576. }
  1577. }
  1578. return File(tempFilename).renameTo(filename);
  1579. }
  1580. std::string applyDir(const std::string& dir, const std::string& relPath)
  1581. {
  1582. std::string s;
  1583. if (dir.empty()) {
  1584. s = "./";
  1585. s += relPath;
  1586. }
  1587. else {
  1588. s = dir;
  1589. if (dir == "/") {
  1590. s += relPath;
  1591. }
  1592. else {
  1593. s += "/";
  1594. s += relPath;
  1595. }
  1596. }
  1597. #ifdef __MINGW32__
  1598. for (std::string::iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1599. if (*i == '\\') {
  1600. *i = '/';
  1601. }
  1602. }
  1603. #endif // __MINGW32__
  1604. return s;
  1605. }
  1606. std::string fixTaintedBasename(const std::string& src)
  1607. {
  1608. return escapePath(replace(src, "/", "%2F"));
  1609. }
  1610. void generateRandomKey(unsigned char* key)
  1611. {
  1612. unsigned char bytes[40];
  1613. generateRandomData(bytes, sizeof(bytes));
  1614. message_digest::digest(key, 20, MessageDigest::sha1().get(), bytes,
  1615. sizeof(bytes));
  1616. }
  1617. // Returns true is given numeric ipv4addr is in Private Address Space.
  1618. //
  1619. // From Section.3 RFC1918
  1620. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1621. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1622. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1623. bool inPrivateAddress(const std::string& ipv4addr)
  1624. {
  1625. if (util::startsWith(ipv4addr, "10.") ||
  1626. util::startsWith(ipv4addr, "192.168.")) {
  1627. return true;
  1628. }
  1629. if (util::startsWith(ipv4addr, "172.")) {
  1630. for (int i = 16; i <= 31; ++i) {
  1631. std::string t(fmt("%d.", i));
  1632. if (util::startsWith(ipv4addr.begin() + 4, ipv4addr.end(), t.begin(),
  1633. t.end())) {
  1634. return true;
  1635. }
  1636. }
  1637. }
  1638. return false;
  1639. }
  1640. bool detectDirTraversal(const std::string& s)
  1641. {
  1642. if (s.empty()) {
  1643. return false;
  1644. }
  1645. for (auto c : s) {
  1646. unsigned char ch = c;
  1647. if (in(ch, 0x00u, 0x1fu) || ch == 0x7fu) {
  1648. return true;
  1649. }
  1650. }
  1651. return s == "." || s == ".." || s[0] == '/' || util::startsWith(s, "./") ||
  1652. util::startsWith(s, "../") || s.find("/../") != std::string::npos ||
  1653. s.find("/./") != std::string::npos || s[s.size() - 1] == '/' ||
  1654. util::endsWith(s, "/.") || util::endsWith(s, "/..");
  1655. }
  1656. std::string escapePath(const std::string& s)
  1657. {
  1658. // We don't escape '/' because we use it as a path separator.
  1659. #ifdef __MINGW32__
  1660. static const char WIN_INVALID_PATH_CHARS[] = {'"', '*', ':', '<',
  1661. '>', '?', '\\', '|'};
  1662. #endif // __MINGW32__
  1663. std::string d;
  1664. for (auto cc : s) {
  1665. unsigned char c = cc;
  1666. if (in(c, 0x00u, 0x1fu) || c == 0x7fu
  1667. #ifdef __MINGW32__
  1668. ||
  1669. std::find(std::begin(WIN_INVALID_PATH_CHARS),
  1670. std::end(WIN_INVALID_PATH_CHARS),
  1671. c) != std::end(WIN_INVALID_PATH_CHARS)
  1672. #endif // __MINGW32__
  1673. ) {
  1674. d += fmt("%%%02X", c);
  1675. }
  1676. else {
  1677. d += c;
  1678. }
  1679. }
  1680. return d;
  1681. }
  1682. bool inSameCidrBlock(const std::string& ip1, const std::string& ip2,
  1683. size_t bits)
  1684. {
  1685. unsigned char s1[16], s2[16];
  1686. size_t len1, len2;
  1687. if ((len1 = net::getBinAddr(s1, ip1)) == 0 ||
  1688. (len2 = net::getBinAddr(s2, ip2)) == 0 || len1 != len2) {
  1689. return false;
  1690. }
  1691. if (bits == 0) {
  1692. return true;
  1693. }
  1694. if (bits > 8 * len1) {
  1695. bits = 8 * len1;
  1696. }
  1697. int last = (bits - 1) / 8;
  1698. for (int i = 0; i < last; ++i) {
  1699. if (s1[i] != s2[i]) {
  1700. return false;
  1701. }
  1702. }
  1703. unsigned char mask = bitfield::lastByteMask(bits);
  1704. return (s1[last] & mask) == (s2[last] & mask);
  1705. }
  1706. namespace {
  1707. void executeHook(const std::string& command, a2_gid_t gid, size_t numFiles,
  1708. const std::string& firstFilename)
  1709. {
  1710. const std::string gidStr = GroupId::toHex(gid);
  1711. const std::string numFilesStr = util::uitos(numFiles);
  1712. #ifndef __MINGW32__
  1713. A2_LOG_INFO(fmt("Executing user command: %s %s %s %s", command.c_str(),
  1714. gidStr.c_str(), numFilesStr.c_str(), firstFilename.c_str()));
  1715. pid_t cpid = fork();
  1716. if (cpid == 0) {
  1717. // child!
  1718. execlp(command.c_str(), command.c_str(), gidStr.c_str(),
  1719. numFilesStr.c_str(), firstFilename.c_str(),
  1720. reinterpret_cast<char*>(0));
  1721. perror(("Could not execute user command: " + command).c_str());
  1722. _exit(EXIT_FAILURE);
  1723. return;
  1724. }
  1725. if (cpid == -1) {
  1726. A2_LOG_ERROR("fork() failed. Cannot execute user command.");
  1727. }
  1728. return;
  1729. #else // __MINGW32__
  1730. PROCESS_INFORMATION pi;
  1731. STARTUPINFOW si;
  1732. memset(&si, 0, sizeof(si));
  1733. si.cb = sizeof(STARTUPINFO);
  1734. memset(&pi, 0, sizeof(pi));
  1735. bool batch = util::iendsWith(command, ".bat");
  1736. std::string cmdline;
  1737. std::string cmdexe;
  1738. // XXX batch handling, in particular quoting, correct?
  1739. if (batch) {
  1740. const char* p = getenv("windir");
  1741. if (p) {
  1742. cmdexe = p;
  1743. cmdexe += "\\system32\\cmd.exe";
  1744. }
  1745. else {
  1746. A2_LOG_INFO("Failed to get windir environment variable."
  1747. " Executing batch file will fail.");
  1748. // TODO Might be useless.
  1749. cmdexe = "cmd.exe";
  1750. }
  1751. cmdline += "/C \"";
  1752. }
  1753. cmdline += "\"";
  1754. cmdline += command;
  1755. cmdline += "\"";
  1756. cmdline += " ";
  1757. cmdline += gidStr;
  1758. cmdline += " ";
  1759. cmdline += numFilesStr;
  1760. cmdline += " \"";
  1761. cmdline += firstFilename;
  1762. cmdline += "\"";
  1763. if (batch) {
  1764. cmdline += "\"";
  1765. }
  1766. int cmdlineLen = utf8ToWChar(nullptr, 0, cmdline.c_str());
  1767. assert(cmdlineLen > 0);
  1768. auto wcharCmdline = make_unique<wchar_t[]>(cmdlineLen);
  1769. cmdlineLen = utf8ToWChar(wcharCmdline.get(), cmdlineLen, cmdline.c_str());
  1770. assert(cmdlineLen > 0);
  1771. A2_LOG_INFO(fmt("Executing user command: %s", cmdline.c_str()));
  1772. DWORD rc = CreateProcessW(batch ? utf8ToWChar(cmdexe).c_str() : nullptr,
  1773. wcharCmdline.get(), nullptr, nullptr, true, 0,
  1774. nullptr, 0, &si, &pi);
  1775. if (!rc) {
  1776. A2_LOG_ERROR("CreateProcess() failed. Cannot execute user command.");
  1777. }
  1778. return;
  1779. #endif
  1780. }
  1781. } // namespace
  1782. void executeHookByOptName(const std::shared_ptr<RequestGroup>& group,
  1783. const Option* option, PrefPtr pref)
  1784. {
  1785. executeHookByOptName(group.get(), option, pref);
  1786. }
  1787. void executeHookByOptName(const RequestGroup* group, const Option* option,
  1788. PrefPtr pref)
  1789. {
  1790. const std::string& cmd = option->get(pref);
  1791. if (!cmd.empty()) {
  1792. const std::shared_ptr<DownloadContext> dctx = group->getDownloadContext();
  1793. std::string firstFilename;
  1794. size_t numFiles = 0;
  1795. if (!group->inMemoryDownload()) {
  1796. std::shared_ptr<FileEntry> file = dctx->getFirstRequestedFileEntry();
  1797. if (file) {
  1798. firstFilename = file->getPath();
  1799. }
  1800. numFiles = dctx->countRequestedFileEntry();
  1801. }
  1802. executeHook(cmd, group->getGID(), numFiles, firstFilename);
  1803. }
  1804. }
  1805. std::string createSafePath(const std::string& dir, const std::string& filename)
  1806. {
  1807. return util::applyDir(dir,
  1808. util::isUtf8(filename)
  1809. ? util::fixTaintedBasename(filename)
  1810. : util::escapePath(util::percentEncode(filename)));
  1811. }
  1812. std::string createSafePath(const std::string& filename)
  1813. {
  1814. return util::isUtf8(filename)
  1815. ? util::fixTaintedBasename(filename)
  1816. : util::escapePath(util::percentEncode(filename));
  1817. }
  1818. std::string encodeNonUtf8(const std::string& s)
  1819. {
  1820. return util::isUtf8(s) ? s : util::percentEncode(s);
  1821. }
  1822. std::string makeString(const char* str)
  1823. {
  1824. if (!str) {
  1825. return A2STR::NIL;
  1826. }
  1827. return str;
  1828. }
  1829. std::string safeStrerror(int errNum) { return makeString(strerror(errNum)); }
  1830. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain)
  1831. {
  1832. if (!domain.empty() && domain[0] == '.' && !util::isNumericHost(hostname)) {
  1833. return util::endsWith(hostname, domain);
  1834. }
  1835. return hostname == domain;
  1836. }
  1837. bool tlsHostnameMatch(const std::string& pattern, const std::string& hostname)
  1838. {
  1839. std::string::const_iterator ptWildcard =
  1840. std::find(pattern.begin(), pattern.end(), '*');
  1841. if (ptWildcard == pattern.end()) {
  1842. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  1843. hostname.end());
  1844. }
  1845. std::string::const_iterator ptLeftLabelEnd =
  1846. std::find(pattern.begin(), pattern.end(), '.');
  1847. bool wildcardEnabled = true;
  1848. // Do case-insensitive match. At least 2 dots are required to enable
  1849. // wildcard match. Also wildcard must be in the left-most label.
  1850. // Don't attempt to match a presented identifier where the wildcard
  1851. // character is embedded within an A-label.
  1852. if (ptLeftLabelEnd == pattern.end() ||
  1853. std::find(ptLeftLabelEnd + 1, pattern.end(), '.') == pattern.end() ||
  1854. ptLeftLabelEnd < ptWildcard || istartsWith(pattern, "xn--")) {
  1855. wildcardEnabled = false;
  1856. }
  1857. if (!wildcardEnabled) {
  1858. return strieq(pattern.begin(), pattern.end(), hostname.begin(),
  1859. hostname.end());
  1860. }
  1861. std::string::const_iterator hnLeftLabelEnd =
  1862. std::find(hostname.begin(), hostname.end(), '.');
  1863. if (!strieq(ptLeftLabelEnd, pattern.end(), hnLeftLabelEnd, hostname.end())) {
  1864. return false;
  1865. }
  1866. // Perform wildcard match. Here '*' must match at least one
  1867. // character.
  1868. if (hnLeftLabelEnd - hostname.begin() < ptLeftLabelEnd - pattern.begin()) {
  1869. return false;
  1870. }
  1871. return istartsWith(hostname.begin(), hnLeftLabelEnd, pattern.begin(),
  1872. ptWildcard) &&
  1873. iendsWith(hostname.begin(), hnLeftLabelEnd, ptWildcard + 1,
  1874. ptLeftLabelEnd);
  1875. }
  1876. bool strieq(const std::string& a, const char* b)
  1877. {
  1878. return strieq(a.begin(), a.end(), b);
  1879. }
  1880. bool strieq(const std::string& a, const std::string& b)
  1881. {
  1882. return strieq(a.begin(), a.end(), b.begin(), b.end());
  1883. }
  1884. bool startsWith(const std::string& a, const char* b)
  1885. {
  1886. return startsWith(a.begin(), a.end(), b);
  1887. }
  1888. bool startsWith(const std::string& a, const std::string& b)
  1889. {
  1890. return startsWith(a.begin(), a.end(), b.begin(), b.end());
  1891. }
  1892. bool istartsWith(const std::string& a, const char* b)
  1893. {
  1894. return istartsWith(a.begin(), a.end(), b);
  1895. }
  1896. bool endsWith(const std::string& a, const char* b)
  1897. {
  1898. return endsWith(a.begin(), a.end(), b, b + strlen(b));
  1899. }
  1900. bool endsWith(const std::string& a, const std::string& b)
  1901. {
  1902. return endsWith(a.begin(), a.end(), b.begin(), b.end());
  1903. }
  1904. bool iendsWith(const std::string& a, const char* b)
  1905. {
  1906. return iendsWith(a.begin(), a.end(), b, b + strlen(b));
  1907. }
  1908. bool iendsWith(const std::string& a, const std::string& b)
  1909. {
  1910. return iendsWith(a.begin(), a.end(), b.begin(), b.end());
  1911. }
  1912. bool strless(const char* a, const char* b) { return strcmp(a, b) < 0; }
  1913. #ifdef ENABLE_SSL
  1914. TLSVersion toTLSVersion(const std::string& ver)
  1915. {
  1916. if (ver == A2_V_SSL3) {
  1917. return TLS_PROTO_SSL3;
  1918. }
  1919. if (ver == A2_V_TLS10) {
  1920. return TLS_PROTO_TLS10;
  1921. }
  1922. if (ver == A2_V_TLS11) {
  1923. return TLS_PROTO_TLS11;
  1924. }
  1925. if (ver == A2_V_TLS12) {
  1926. return TLS_PROTO_TLS12;
  1927. }
  1928. return TLS_PROTO_TLS10;
  1929. }
  1930. #endif // ENABLE_SSL
  1931. } // namespace util
  1932. } // namespace aria2