util.cc 50 KB

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