util.h 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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. #ifndef D_UTIL_H
  36. #define D_UTIL_H
  37. #include "common.h"
  38. #include <sys/time.h>
  39. #include <limits.h>
  40. #include <stdint.h>
  41. #include <cstdio>
  42. #include <string>
  43. #include <utility>
  44. #include <iosfwd>
  45. #include <ostream>
  46. #include <numeric>
  47. #include <map>
  48. #include <iomanip>
  49. #include <algorithm>
  50. #include <vector>
  51. #include "SharedHandle.h"
  52. #include "a2time.h"
  53. #include "a2netcompat.h"
  54. #include "a2functional.h"
  55. #include "SegList.h"
  56. #include "a2iterator.h"
  57. #include "message.h"
  58. #include "DlAbortEx.h"
  59. #include "fmt.h"
  60. namespace aria2 {
  61. class Randomizer;
  62. class BitfieldMan;
  63. class BinaryStream;
  64. class FileEntry;
  65. class RequestGroup;
  66. class Option;
  67. class Pref;
  68. #define STRTOLL(X) strtoll(X, reinterpret_cast<char**>(0), 10)
  69. #define STRTOULL(X) strtoull(X, reinterpret_cast<char**>(0), 10)
  70. #define START_INDEX(OFFSET, PIECE_LENGTH) ((OFFSET)/(PIECE_LENGTH))
  71. #define END_INDEX(OFFSET, LENGTH, PIECE_LENGTH) (((OFFSET)+(LENGTH)-1)/(PIECE_LENGTH))
  72. #define DIV_FLOOR(X,Y) ((X)/(Y)+((X)%(Y)? 1:0))
  73. #ifdef WORDS_BIGENDIAN
  74. inline uint64_t ntoh64(uint64_t x) { return x; }
  75. inline uint64_t hton64(uint64_t x) { return x; }
  76. #else // !WORDS_BIGENDIAN
  77. inline uint64_t byteswap64(uint64_t x) {
  78. uint64_t v1 = ntohl(x & 0x00000000ffffffffllu);
  79. uint64_t v2 = ntohl(x >> 32);
  80. return (v1 << 32)|v2;
  81. }
  82. inline uint64_t ntoh64(uint64_t x) { return byteswap64(x); }
  83. inline uint64_t hton64(uint64_t x) { return byteswap64(x); }
  84. #endif // !WORDS_BIGENDIAN
  85. #ifdef __MINGW32__
  86. std::wstring utf8ToWChar(const std::string& src);
  87. std::wstring utf8ToWChar(const char* str);
  88. std::string utf8ToNative(const std::string& src);
  89. std::string wCharToUtf8(const std::wstring& wsrc);
  90. std::string nativeToUtf8(const std::string& src);
  91. #else // !__MINGW32__
  92. # define utf8ToWChar(src) src
  93. # define utf8ToNative(src) src
  94. #endif // !__MINGW32__
  95. namespace util {
  96. template<typename InputIterator>
  97. void divide
  98. (std::pair<Scip, Scip>& hp,
  99. InputIterator first,
  100. InputIterator last,
  101. char delim)
  102. {
  103. InputIterator dpos = std::find(first, last, delim);
  104. if(dpos == last) {
  105. hp.first = stripIter(first, last);
  106. hp.second.first = hp.second.second;
  107. } else {
  108. hp.first = stripIter(first, dpos);
  109. hp.second = stripIter(dpos+1, last);
  110. }
  111. }
  112. template<typename T>
  113. std::string uitos(T value, bool comma = false)
  114. {
  115. std::string str;
  116. if(value == 0) {
  117. str = "0";
  118. return str;
  119. }
  120. unsigned int count = 0;
  121. while(value) {
  122. ++count;
  123. char digit = value%10+'0';
  124. if(comma && count > 3 && count%3 == 1) {
  125. str += ',';
  126. }
  127. str += digit;
  128. value /= 10;
  129. }
  130. std::reverse(str.begin(), str.end());
  131. return str;
  132. }
  133. std::string itos(int64_t value, bool comma = false);
  134. /**
  135. * Computes difference in micro-seconds between tv1 and tv2,
  136. * assuming tv1 is newer than tv2.
  137. * If tv1 is older than tv2, then this method returns 0.
  138. */
  139. int64_t difftv(struct timeval tv1, struct timeval tv2);
  140. int32_t difftvsec(struct timeval tv1, struct timeval tv2);
  141. extern const std::string DEFAULT_STRIP_CHARSET;
  142. template<typename InputIterator>
  143. std::pair<InputIterator, InputIterator> stripIter
  144. (InputIterator first, InputIterator last,
  145. const std::string& chars = DEFAULT_STRIP_CHARSET)
  146. {
  147. for(; first != last &&
  148. std::find(chars.begin(), chars.end(), *first) != chars.end(); ++first);
  149. if(first == last) {
  150. return std::make_pair(first, last);
  151. }
  152. InputIterator left = last-1;
  153. for(; left != first &&
  154. std::find(chars.begin(), chars.end(), *left) != chars.end(); --left);
  155. return std::make_pair(first, left+1);
  156. }
  157. template<typename InputIterator>
  158. InputIterator lstripIter
  159. (InputIterator first, InputIterator last, char ch)
  160. {
  161. for(; first != last && *first == ch; ++first);
  162. return first;
  163. }
  164. template<typename InputIterator, typename InputIterator2>
  165. InputIterator lstripIter
  166. (InputIterator first, InputIterator last,
  167. InputIterator2 cfirst, InputIterator2 clast)
  168. {
  169. for(; first != last && std::find(cfirst, clast, *first) != clast; ++first);
  170. return first;
  171. }
  172. template<typename InputIterator>
  173. InputIterator lstripIter
  174. (InputIterator first, InputIterator last)
  175. {
  176. return lstripIter(first, last,
  177. DEFAULT_STRIP_CHARSET.begin(), DEFAULT_STRIP_CHARSET.end());
  178. }
  179. std::string strip
  180. (const std::string& str, const std::string& chars = DEFAULT_STRIP_CHARSET);
  181. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr);
  182. std::string percentEncode(const unsigned char* target, size_t len);
  183. std::string percentEncode(const std::string& target);
  184. std::string percentEncodeMini(const std::string& target);
  185. bool inRFC3986ReservedChars(const char c);
  186. bool inRFC3986UnreservedChars(const char c);
  187. bool isUtf8(const std::string& str);
  188. std::string percentDecode
  189. (std::string::const_iterator first, std::string::const_iterator last);
  190. std::string torrentPercentEncode(const unsigned char* target, size_t len);
  191. std::string torrentPercentEncode(const std::string& target);
  192. std::string toHex(const unsigned char* src, size_t len);
  193. std::string toHex(const char* src, size_t len);
  194. std::string toHex(const std::string& src);
  195. // Converts hexadecimal ascii string 'src' into packed binary form and
  196. // return the result. If src is not well formed, then empty string is
  197. // returned.
  198. std::string fromHex(const std::string& src);
  199. FILE* openFile(const std::string& filename, const std::string& mode);
  200. bool isPowerOf(int num, int base);
  201. std::string secfmt(time_t sec);
  202. template<typename InputIterator>
  203. bool parseIntNoThrow
  204. (int32_t& result, InputIterator first, InputIterator last, int base = 10)
  205. {
  206. // Without strip, strtol(" -1 ",..) emits error.
  207. Scip p = util::stripIter(first, last);
  208. if(p.first == p.second) {
  209. return false;
  210. }
  211. char buf[32];
  212. size_t len = std::distance(p.first, p.second);
  213. if(len+1 > sizeof(buf)) {
  214. return false;
  215. }
  216. std::copy(p.first, p.second, &buf[0]);
  217. buf[len] = '\0';
  218. char* stop;
  219. errno = 0;
  220. long int v = strtol(buf, &stop, base);
  221. if(*stop != '\0') {
  222. return false;
  223. } else if(((v == LONG_MAX || v == LONG_MIN) && (errno == ERANGE)) ||
  224. v < INT32_MIN || INT32_MAX < v) {
  225. return false;
  226. }
  227. result = v;
  228. return true;
  229. }
  230. template<typename InputIterator>
  231. bool parseUIntNoThrow
  232. (uint32_t& result, InputIterator first, InputIterator last, int base = 10)
  233. {
  234. // Without strip, strtol(" -1 ",..) emits error.
  235. Scip p = util::stripIter(first, last);
  236. if(p.first == p.second) {
  237. return false;
  238. }
  239. char buf[32];
  240. size_t len = std::distance(p.first, p.second);
  241. if(len+1 > sizeof(buf)) {
  242. return false;
  243. }
  244. std::copy(p.first, p.second, &buf[0]);
  245. buf[len] = '\0';
  246. // We don't allow negative number.
  247. if(buf[0] == '-') {
  248. return false;
  249. }
  250. char* stop;
  251. errno = 0;
  252. unsigned long int v = strtoul(buf, &stop, base);
  253. if(*stop != '\0') {
  254. return false;
  255. } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
  256. return false;
  257. }
  258. result = v;
  259. return true;
  260. }
  261. template<typename InputIterator>
  262. bool parseLLIntNoThrow
  263. (int64_t& result, InputIterator first, InputIterator last, int base = 10)
  264. {
  265. // Without strip, strtol(" -1 ",..) emits error.
  266. Scip p = util::stripIter(first, last);
  267. if(p.first == p.second) {
  268. return false;
  269. }
  270. char buf[32];
  271. size_t len = std::distance(p.first, p.second);
  272. if(len+1 > sizeof(buf)) {
  273. return false;
  274. }
  275. std::copy(p.first, p.second, &buf[0]);
  276. buf[len] = '\0';
  277. char* stop;
  278. errno = 0;
  279. int64_t v = strtoll(buf, &stop, base);
  280. if(*stop != '\0') {
  281. return false;
  282. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  283. return false;
  284. }
  285. result = v;
  286. return true;
  287. }
  288. template<typename InputIterator>
  289. int64_t parseLLInt(InputIterator first, InputIterator last, int base = 10)
  290. {
  291. Scip p = util::stripIter(first, last);
  292. if(p.first == p.second) {
  293. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  294. "empty string"));
  295. }
  296. char buf[32];
  297. size_t len = std::distance(p.first, p.second);
  298. if(len+1 > sizeof(buf)) {
  299. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  300. "too large"));
  301. }
  302. std::copy(p.first, p.second, &buf[0]);
  303. buf[len] = '\0';
  304. char* stop;
  305. errno = 0;
  306. int64_t v = strtoll(buf, &stop, base);
  307. if(*stop != '\0') {
  308. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  309. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  310. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  311. }
  312. return v;
  313. }
  314. template<typename InputIterator>
  315. int32_t parseInt(InputIterator first, InputIterator last, int base = 10)
  316. {
  317. int64_t v = util::parseLLInt(first, last, base);
  318. if(v < INT32_MIN || INT32_MAX < v) {
  319. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  320. std::string(first, last).c_str()));
  321. }
  322. return v;
  323. }
  324. template<typename InputIterator>
  325. uint64_t parseULLInt(InputIterator first, InputIterator last, int base = 10)
  326. {
  327. Scip p = util::stripIter(first, last);
  328. if(p.first == p.second) {
  329. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  330. "empty string"));
  331. }
  332. char buf[32];
  333. size_t len = std::distance(p.first, p.second);
  334. if(len+1 > sizeof(buf)) {
  335. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  336. "too large"));
  337. }
  338. std::copy(p.first, p.second, &buf[0]);
  339. buf[len] = '\0';
  340. // We don't allow negative number.
  341. if(buf[0] == '-') {
  342. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  343. }
  344. char* stop;
  345. errno = 0;
  346. uint64_t v = strtoull(buf, &stop, base);
  347. if(*stop != '\0') {
  348. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  349. } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
  350. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  351. }
  352. return v;
  353. }
  354. template<typename InputIterator>
  355. uint32_t parseUInt(InputIterator first, InputIterator last, int base = 10)
  356. {
  357. uint64_t v = util::parseULLInt(first, last, base);
  358. if(UINT32_MAX < v) {
  359. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  360. std::string(first, last).c_str()));
  361. }
  362. return v;
  363. }
  364. void parseIntSegments(SegList<int>& sgl, const std::string& src);
  365. // Parses string which specifies the range of piece index for higher
  366. // priority and appends those indexes into result. The input string
  367. // src can contain 2 keywords "head" and "tail". To include both
  368. // keywords, they must be separated by comma. "head" means the pieces
  369. // where the first byte of each file sits. "tail" means the pieces
  370. // where the last byte of each file sits. These keywords can take one
  371. // parameter, SIZE. For example, if "head=SIZE" is specified, pieces
  372. // in the range of first SIZE bytes of each file get higher
  373. // priority. SIZE can include K or M(1K = 1024, 1M = 1024K).
  374. // If SIZE is omitted, SIZE=defaultSize is used.
  375. //
  376. // sample: head=512K,tail=512K
  377. void parsePrioritizePieceRange
  378. (std::vector<size_t>& result, const std::string& src,
  379. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  380. size_t pieceLength,
  381. uint64_t defaultSize = 1048576 /* 1MiB */);
  382. // Converts ISO/IEC 8859-1 string src to utf-8.
  383. std::string iso8859ToUtf8(const std::string& src);
  384. std::string getContentDispositionFilename(const std::string& header);
  385. std::string randomAlpha(size_t length,
  386. const SharedHandle<Randomizer>& randomizer);
  387. std::string toUpper(const std::string& src);
  388. std::string toLower(const std::string& src);
  389. void uppercase(std::string& s);
  390. void lowercase(std::string& s);
  391. bool isNumericHost(const std::string& name);
  392. void setGlobalSignalHandler(int signal, void (*handler)(int), int flags);
  393. std::string getHomeDir();
  394. int64_t getRealSize(const std::string& sizeWithUnit);
  395. std::string abbrevSize(int64_t size);
  396. template<typename InputIterator, typename Output>
  397. void toStream
  398. (InputIterator first, InputIterator last, Output& os)
  399. {
  400. os.printf("%s\n"
  401. "idx|path/length\n"
  402. "===+===========================================================================\n", _("Files:"));
  403. int32_t count = 1;
  404. for(; first != last; ++first, ++count) {
  405. os.printf("%3d|%s\n"
  406. " |%sB (%s)\n"
  407. "---+---------------------------------------------------------------------------\n",
  408. count,
  409. (*first)->getPath().c_str(),
  410. util::abbrevSize((*first)->getLength()).c_str(),
  411. util::uitos((*first)->getLength(), true).c_str());
  412. }
  413. }
  414. void sleep(long seconds);
  415. void usleep(long microseconds);
  416. bool isNumber(const std::string& what);
  417. bool isDigit(const char c);
  418. bool isHexDigit(const char c);
  419. bool isHexDigit(const std::string& s);
  420. bool isLowercase(const std::string& what);
  421. bool isUppercase(const std::string& what);
  422. /**
  423. * Converts alphabets to unsigned int, assuming alphabets as a base 26
  424. * integer and 'a' or 'A' is 0.
  425. * This function assumes alphabets includes only a-z.
  426. * Upper case are allowed but all letters must be upper case.
  427. * If overflow occurs, returns 0.
  428. */
  429. unsigned int alphaToNum(const std::string& alphabets);
  430. void mkdirs(const std::string& dirpath);
  431. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src);
  432. // binaryStream has to be opened before calling this function.
  433. std::string toString(const SharedHandle<BinaryStream>& binaryStream);
  434. #ifdef HAVE_POSIX_MEMALIGN
  435. void* allocateAlignedMemory(size_t alignment, size_t size);
  436. #endif // HAVE_POSIX_MEMALIGN
  437. std::pair<std::string, uint16_t>
  438. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len);
  439. std::string htmlEscape(const std::string& src);
  440. // Joins path element specified in [first, last). If ".." is found,
  441. // it eats the previous element if it exists. If "." is found, it
  442. // is just ignored and it is not appeared in the result.
  443. template<typename InputIterator>
  444. std::string joinPath(InputIterator first, InputIterator last)
  445. {
  446. std::vector<std::string> elements;
  447. for(;first != last; ++first) {
  448. if(*first == "..") {
  449. if(!elements.empty()) {
  450. elements.pop_back();
  451. }
  452. } else if(*first == ".") {
  453. // do nothing
  454. } else {
  455. elements.push_back(*first);
  456. }
  457. }
  458. return strjoin(elements.begin(), elements.end(), "/");
  459. }
  460. // Parses INDEX=PATH format string. INDEX must be an unsigned
  461. // integer.
  462. std::pair<size_t, std::string>
  463. parseIndexPath(const std::string& line);
  464. std::vector<std::pair<size_t, std::string> > createIndexPaths(std::istream& i);
  465. /**
  466. * Take a string [first, last) which is a delimited list and add its
  467. * elements into result as iterator pair. result is stored in out.
  468. */
  469. template<typename InputIterator, typename OutputIterator>
  470. OutputIterator splitIter
  471. (InputIterator first,
  472. InputIterator last,
  473. OutputIterator out,
  474. char delim,
  475. bool doStrip = false,
  476. bool allowEmpty = false)
  477. {
  478. for(InputIterator i = first; i != last;) {
  479. InputIterator j = std::find(i, last, delim);
  480. std::pair<InputIterator, InputIterator> p(i, j);
  481. if(doStrip) {
  482. p = stripIter(i, j);
  483. }
  484. if(allowEmpty || p.first != p.second) {
  485. *out++ = p;
  486. }
  487. i = j;
  488. if(j != last) {
  489. ++i;
  490. }
  491. }
  492. if(allowEmpty &&
  493. (first == last || *(last-1) == delim)) {
  494. *out++ = std::make_pair(last, last);
  495. }
  496. return out;
  497. }
  498. template<typename InputIterator,
  499. typename InputIterator2,
  500. typename OutputIterator>
  501. OutputIterator splitIterM
  502. (InputIterator first,
  503. InputIterator last,
  504. OutputIterator out,
  505. InputIterator2 dfirst,
  506. InputIterator2 dlast,
  507. bool doStrip = false,
  508. bool allowEmpty = false)
  509. {
  510. for(InputIterator i = first; i != last;) {
  511. InputIterator j = i;
  512. for(; j != last && std::find(dfirst, dlast, *j) == dlast; ++j);
  513. std::pair<InputIterator, InputIterator> p(i, j);
  514. if(doStrip) {
  515. p = stripIter(i, j);
  516. }
  517. if(allowEmpty || p.first != p.second) {
  518. *out++ = p;
  519. }
  520. i = j;
  521. if(j != last) {
  522. ++i;
  523. }
  524. }
  525. if(allowEmpty &&
  526. (first == last ||
  527. std::find(dfirst, dlast, *(last-1)) != dlast)) {
  528. *out++ = std::make_pair(last, last);
  529. }
  530. return out;
  531. }
  532. template<typename InputIterator, typename OutputIterator>
  533. OutputIterator split
  534. (InputIterator first,
  535. InputIterator last,
  536. OutputIterator out,
  537. char delim,
  538. bool doStrip = false,
  539. bool allowEmpty = false)
  540. {
  541. for(InputIterator i = first; i != last;) {
  542. InputIterator j = std::find(i, last, delim);
  543. std::pair<InputIterator, InputIterator> p(i, j);
  544. if(doStrip) {
  545. p = stripIter(i, j);
  546. }
  547. if(allowEmpty || p.first != p.second) {
  548. *out++ = std::string(p.first, p.second);
  549. }
  550. i = j;
  551. if(j != last) {
  552. ++i;
  553. }
  554. }
  555. if(allowEmpty &&
  556. (first == last || *(last-1) == delim)) {
  557. *out++ = std::string(last, last);
  558. }
  559. return out;
  560. }
  561. template<typename InputIterator1, typename InputIterator2>
  562. bool streq
  563. (InputIterator1 first1,
  564. InputIterator1 last1,
  565. InputIterator2 first2,
  566. InputIterator2 last2)
  567. {
  568. if(last1-first1 != last2-first2) {
  569. return false;
  570. }
  571. return std::equal(first1, last1, first2);
  572. }
  573. template<typename InputIterator1, typename InputIterator2>
  574. bool strieq
  575. (InputIterator1 first1,
  576. InputIterator1 last1,
  577. InputIterator2 first2,
  578. InputIterator2 last2)
  579. {
  580. if(last1-first1 != last2-first2) {
  581. return false;
  582. }
  583. for(; first1 != last1; ++first1, ++first2) {
  584. char c1 = *first1;
  585. char c2 = *first2;
  586. if('A' <= c1 && c1 <= 'Z') {
  587. c1 = c1-'A'+'a';
  588. }
  589. if('A' <= c2 && c2 <= 'Z') {
  590. c2 = c2-'A'+'a';
  591. }
  592. if(c1 != c2) {
  593. return false;
  594. }
  595. }
  596. return true;
  597. }
  598. template<typename InputIterator1, typename InputIterator2>
  599. bool startsWith
  600. (InputIterator1 first1,
  601. InputIterator1 last1,
  602. InputIterator2 first2,
  603. InputIterator2 last2)
  604. {
  605. if(last1-first1 < last2-first2) {
  606. return false;
  607. }
  608. return std::equal(first2, last2, first1);
  609. }
  610. template<typename InputIterator1, typename InputIterator2>
  611. bool istartsWith
  612. (InputIterator1 first1,
  613. InputIterator1 last1,
  614. InputIterator2 first2,
  615. InputIterator2 last2)
  616. {
  617. if(last1-first1 < last2-first2) {
  618. return false;
  619. }
  620. return strieq(first1, first1+(last2-first2), first2, last2);
  621. }
  622. template<typename InputIterator1, typename InputIterator2>
  623. bool endsWith
  624. (InputIterator1 first1,
  625. InputIterator1 last1,
  626. InputIterator2 first2,
  627. InputIterator2 last2)
  628. {
  629. if(last1-first1 < last2-first2) {
  630. return false;
  631. }
  632. return std::equal(first2, last2, last1-(last2-first2));
  633. }
  634. template<typename InputIterator1, typename InputIterator2>
  635. bool iendsWith
  636. (InputIterator1 first1,
  637. InputIterator1 last1,
  638. InputIterator2 first2,
  639. InputIterator2 last2)
  640. {
  641. if(last1-first1 < last2-first2) {
  642. return false;
  643. }
  644. return strieq(last1-(last2-first2), last1, first2, last2);
  645. }
  646. void generateRandomData(unsigned char* data, size_t length);
  647. // Saves data to file whose name is filename. If overwrite is true,
  648. // existing file is overwritten. Otherwise, this function doesn't do
  649. // nothing. If data is saved successfully, return true. Otherwise
  650. // returns false.
  651. bool saveAs
  652. (const std::string& filename, const std::string& data, bool overwrite=false);
  653. // Prepend dir to relPath. If dir is empty, it prepends "." to relPath.
  654. //
  655. // dir = "/dir", relPath = "foo" => "/dir/foo"
  656. // dir = "", relPath = "foo" => "./foo"
  657. // dir = "/", relPath = "foo" => "/foo"
  658. std::string applyDir(const std::string& dir, const std::string& relPath);
  659. // In HTTP/FTP, file name is file component in URI. In HTTP, filename
  660. // may be a value of Content-Disposition header. They are likely
  661. // percent encoded. If they contains, for example, %2F, when decoded,
  662. // basename contains dir component. This should be avoided. This
  663. // function is created to fix these issues. This function expects src
  664. // should be non-percent-encoded basename. Currently, this function
  665. // replaces '/' with '_' and result string is passed to escapePath()
  666. // function and its result is returned.
  667. std::string fixTaintedBasename(const std::string& src);
  668. // Generates 20 bytes random key and store it to the address pointed
  669. // by key. Caller must allocate at least 20 bytes for generated key.
  670. void generateRandomKey(unsigned char* key);
  671. // Returns true is given numeric ipv4addr is in Private Address Space.
  672. bool inPrivateAddress(const std::string& ipv4addr);
  673. // Returns true if s contains directory traversal path component such
  674. // as '..' or it contains null or control character which may fool
  675. // user.
  676. bool detectDirTraversal(const std::string& s);
  677. // Replaces null(0x00) and control character(0x01-0x1f) with '_'. If
  678. // __MINGW32__ is defined, following characters are also replaced with
  679. // '_': '"', '*', ':', '<', '>', '?', '\', '|'.
  680. std::string escapePath(const std::string& s);
  681. // Returns true if ip1 and ip2 are in the same CIDR block. ip1 and
  682. // ip2 must be numeric IPv4 or IPv6 address. If either of them or both
  683. // of them is not valid numeric address, then returns false. bits is
  684. // prefix bits. If bits is out of range, then bits is set to the
  685. // length of binary representation of the address*8.
  686. bool inSameCidrBlock
  687. (const std::string& ip1, const std::string& ip2, size_t bits);
  688. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group);
  689. void removeMetalinkContentTypes(RequestGroup* group);
  690. // No throw
  691. void executeHookByOptName
  692. (const SharedHandle<RequestGroup>& group, const Option* option,
  693. const Pref* pref);
  694. // No throw
  695. void executeHookByOptName
  696. (const RequestGroup* group, const Option* option, const Pref* pref);
  697. std::string createSafePath(const std::string& dir, const std::string& filename);
  698. std::string encodeNonUtf8(const std::string& s);
  699. // Create string safely. If str is NULL, returns empty string.
  700. // Otherwise, returns std::string(str).
  701. std::string makeString(const char* str);
  702. // This function is basically the same with strerror(errNum) but when
  703. // strerror returns NULL, this function returns empty string.
  704. std::string safeStrerror(int errNum);
  705. // Parses sequence [first, last) and find name=value pair delimited by
  706. // delim character. If name(and optionally value) is found, returns
  707. // pair of iterator which can use as first parameter of next call of
  708. // this function, and true. If no name is found, returns the pair of
  709. // last and false.
  710. template<typename Iterator>
  711. std::pair<Iterator, bool>
  712. nextParam
  713. (std::string& name,
  714. std::string& value,
  715. Iterator first,
  716. Iterator last,
  717. char delim)
  718. {
  719. Iterator end = last;
  720. while(first != end) {
  721. last = first;
  722. Iterator parmnameFirst = first;
  723. Iterator parmnameLast = first;
  724. bool eqFound = false;
  725. for(; last != end; ++last) {
  726. if(*last == delim) {
  727. break;
  728. } else if(!eqFound && *last == '=') {
  729. eqFound = true;
  730. parmnameFirst = first;
  731. parmnameLast = last;
  732. }
  733. }
  734. std::pair<std::string::const_iterator,
  735. std::string::const_iterator> namep;
  736. std::pair<std::string::const_iterator,
  737. std::string::const_iterator> valuep;
  738. if(parmnameFirst == parmnameLast) {
  739. if(!eqFound) {
  740. parmnameFirst = first;
  741. parmnameLast = last;
  742. namep = stripIter(parmnameFirst, parmnameLast);
  743. }
  744. } else {
  745. first = parmnameLast+1;
  746. namep = stripIter(parmnameFirst, parmnameLast);
  747. valuep = stripIter(first, last);
  748. }
  749. if(last != end) {
  750. ++last;
  751. }
  752. if(namep.first != namep.second) {
  753. name.assign(namep.first, namep.second);
  754. value.assign(valuep.first, valuep.second);
  755. return std::make_pair(last, true);
  756. }
  757. first = last;
  758. }
  759. return std::make_pair(end, false);
  760. }
  761. template<typename T>
  762. SharedHandle<T> copy(const SharedHandle<T>& a)
  763. {
  764. return SharedHandle<T>(new T(*a.get()));
  765. }
  766. // This is a bit different from cookie_helper::domainMatch(). If
  767. // hostname is numeric host, then returns true if domain == hostname.
  768. // That is if domain starts with ".", then returns true if domain is a
  769. // suffix of hostname. If domain does not start with ".", then
  770. // returns true if domain == hostname. Otherwise returns true.
  771. // For example,
  772. //
  773. // * noProxyDomainMatch("aria2.sf.net", ".sf.net") returns true.
  774. // * noProxyDomainMatch("sf.net", ".sf.net") returns false.
  775. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain);
  776. } // namespace util
  777. } // namespace aria2
  778. #endif // D_UTIL_H