util.cc 57 KB

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