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