util.cc 50 KB

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