util.cc 52 KB

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