util.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. void divide
  97. (std::pair<std::string, std::string>& hp, const std::string& src, char delim);
  98. template<typename T>
  99. std::string uitos(T value, bool comma = false)
  100. {
  101. std::string str;
  102. if(value == 0) {
  103. str = "0";
  104. return str;
  105. }
  106. unsigned int count = 0;
  107. while(value) {
  108. ++count;
  109. char digit = value%10+'0';
  110. if(comma && count > 3 && count%3 == 1) {
  111. str += ',';
  112. }
  113. str += digit;
  114. value /= 10;
  115. }
  116. std::reverse(str.begin(), str.end());
  117. return str;
  118. }
  119. std::string itos(int64_t value, bool comma = false);
  120. /**
  121. * Computes difference in micro-seconds between tv1 and tv2,
  122. * assuming tv1 is newer than tv2.
  123. * If tv1 is older than tv2, then this method returns 0.
  124. */
  125. int64_t difftv(struct timeval tv1, struct timeval tv2);
  126. int32_t difftvsec(struct timeval tv1, struct timeval tv2);
  127. extern const std::string DEFAULT_STRIP_CHARSET;
  128. template<typename InputIterator>
  129. std::pair<InputIterator, InputIterator> stripIter
  130. (InputIterator first, InputIterator last,
  131. const std::string& chars = DEFAULT_STRIP_CHARSET)
  132. {
  133. for(; first != last &&
  134. std::find(chars.begin(), chars.end(), *first) != chars.end(); ++first);
  135. if(first == last) {
  136. return std::make_pair(first, last);
  137. }
  138. InputIterator left = last-1;
  139. for(; left != first &&
  140. std::find(chars.begin(), chars.end(), *left) != chars.end(); --left);
  141. return std::make_pair(first, left+1);
  142. }
  143. std::string strip
  144. (const std::string& str, const std::string& chars = DEFAULT_STRIP_CHARSET);
  145. bool startsWith(const std::string& target, const std::string& part);
  146. bool endsWith(const std::string& target, const std::string& part);
  147. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr);
  148. std::string percentEncode(const unsigned char* target, size_t len);
  149. std::string percentEncode(const std::string& target);
  150. std::string percentEncodeMini(const std::string& target);
  151. bool inRFC3986ReservedChars(const char c);
  152. bool inRFC3986UnreservedChars(const char c);
  153. bool isUtf8(const std::string& str);
  154. std::string percentDecode
  155. (std::string::const_iterator first, std::string::const_iterator last);
  156. std::string torrentPercentEncode(const unsigned char* target, size_t len);
  157. std::string torrentPercentEncode(const std::string& target);
  158. std::string toHex(const unsigned char* src, size_t len);
  159. std::string toHex(const char* src, size_t len);
  160. std::string toHex(const std::string& src);
  161. // Converts hexadecimal ascii string 'src' into packed binary form and
  162. // return the result. If src is not well formed, then empty string is
  163. // returned.
  164. std::string fromHex(const std::string& src);
  165. FILE* openFile(const std::string& filename, const std::string& mode);
  166. bool isPowerOf(int num, int base);
  167. std::string secfmt(time_t sec);
  168. template<typename InputIterator>
  169. bool parseIntNoThrow
  170. (int32_t& result, InputIterator first, InputIterator last, int base = 10)
  171. {
  172. // Without strip, strtol(" -1 ",..) emits error.
  173. Scip p = util::stripIter(first, last);
  174. if(p.first == p.second) {
  175. return false;
  176. }
  177. char buf[32];
  178. size_t len = std::distance(p.first, p.second);
  179. if(len+1 > sizeof(buf)) {
  180. return false;
  181. }
  182. std::copy(p.first, p.second, &buf[0]);
  183. buf[len] = '\0';
  184. char* stop;
  185. errno = 0;
  186. long int v = strtol(buf, &stop, base);
  187. if(*stop != '\0') {
  188. return false;
  189. } else if(((v == LONG_MAX || v == LONG_MIN) && (errno == ERANGE)) ||
  190. v < INT32_MIN || INT32_MAX < v) {
  191. return false;
  192. }
  193. result = v;
  194. return true;
  195. }
  196. template<typename InputIterator>
  197. bool parseUIntNoThrow
  198. (uint32_t& result, InputIterator first, InputIterator last, int base = 10)
  199. {
  200. // Without strip, strtol(" -1 ",..) emits error.
  201. Scip p = util::stripIter(first, last);
  202. if(p.first == p.second) {
  203. return false;
  204. }
  205. char buf[32];
  206. size_t len = std::distance(p.first, p.second);
  207. if(len+1 > sizeof(buf)) {
  208. return false;
  209. }
  210. std::copy(p.first, p.second, &buf[0]);
  211. buf[len] = '\0';
  212. // We don't allow negative number.
  213. if(buf[0] == '-') {
  214. return false;
  215. }
  216. char* stop;
  217. errno = 0;
  218. unsigned long int v = strtoul(buf, &stop, base);
  219. if(*stop != '\0') {
  220. return false;
  221. } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
  222. return false;
  223. }
  224. result = v;
  225. return true;
  226. }
  227. template<typename InputIterator>
  228. bool parseLLIntNoThrow
  229. (int64_t& result, InputIterator first, InputIterator last, int base = 10)
  230. {
  231. // Without strip, strtol(" -1 ",..) emits error.
  232. Scip p = util::stripIter(first, last);
  233. if(p.first == p.second) {
  234. return false;
  235. }
  236. char buf[32];
  237. size_t len = std::distance(p.first, p.second);
  238. if(len+1 > sizeof(buf)) {
  239. return false;
  240. }
  241. std::copy(p.first, p.second, &buf[0]);
  242. buf[len] = '\0';
  243. char* stop;
  244. errno = 0;
  245. int64_t v = strtoll(buf, &stop, base);
  246. if(*stop != '\0') {
  247. return false;
  248. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  249. return false;
  250. }
  251. result = v;
  252. return true;
  253. }
  254. template<typename InputIterator>
  255. int64_t parseLLInt(InputIterator first, InputIterator last, int base = 10)
  256. {
  257. Scip p = util::stripIter(first, last);
  258. if(p.first == p.second) {
  259. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  260. "empty string"));
  261. }
  262. char buf[32];
  263. size_t len = std::distance(p.first, p.second);
  264. if(len+1 > sizeof(buf)) {
  265. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  266. "too large"));
  267. }
  268. std::copy(p.first, p.second, &buf[0]);
  269. buf[len] = '\0';
  270. char* stop;
  271. errno = 0;
  272. int64_t v = strtoll(buf, &stop, base);
  273. if(*stop != '\0') {
  274. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  275. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  276. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  277. }
  278. return v;
  279. }
  280. template<typename InputIterator>
  281. int32_t parseInt(InputIterator first, InputIterator last, int base = 10)
  282. {
  283. int64_t v = util::parseLLInt(first, last, base);
  284. if(v < INT32_MIN || INT32_MAX < v) {
  285. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  286. std::string(first, last).c_str()));
  287. }
  288. return v;
  289. }
  290. template<typename InputIterator>
  291. uint64_t parseULLInt(InputIterator first, InputIterator last, int base = 10)
  292. {
  293. Scip p = util::stripIter(first, last);
  294. if(p.first == p.second) {
  295. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  296. "empty string"));
  297. }
  298. char buf[32];
  299. size_t len = std::distance(p.first, p.second);
  300. if(len+1 > sizeof(buf)) {
  301. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  302. "too large"));
  303. }
  304. std::copy(p.first, p.second, &buf[0]);
  305. buf[len] = '\0';
  306. // We don't allow negative number.
  307. if(buf[0] == '-') {
  308. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  309. }
  310. char* stop;
  311. errno = 0;
  312. uint64_t v = strtoull(buf, &stop, base);
  313. if(*stop != '\0') {
  314. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  315. } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
  316. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE, buf));
  317. }
  318. return v;
  319. }
  320. template<typename InputIterator>
  321. uint32_t parseUInt(InputIterator first, InputIterator last, int base = 10)
  322. {
  323. uint64_t v = util::parseULLInt(first, last, base);
  324. if(UINT32_MAX < v) {
  325. throw DL_ABORT_EX(fmt(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  326. std::string(first, last).c_str()));
  327. }
  328. return v;
  329. }
  330. void parseIntSegments(SegList<int>& sgl, const std::string& src);
  331. // Parses string which specifies the range of piece index for higher
  332. // priority and appends those indexes into result. The input string
  333. // src can contain 2 keywords "head" and "tail". To include both
  334. // keywords, they must be separated by comma. "head" means the pieces
  335. // where the first byte of each file sits. "tail" means the pieces
  336. // where the last byte of each file sits. These keywords can take one
  337. // parameter, SIZE. For example, if "head=SIZE" is specified, pieces
  338. // in the range of first SIZE bytes of each file get higher
  339. // priority. SIZE can include K or M(1K = 1024, 1M = 1024K).
  340. // If SIZE is omitted, SIZE=defaultSize is used.
  341. //
  342. // sample: head=512K,tail=512K
  343. void parsePrioritizePieceRange
  344. (std::vector<size_t>& result, const std::string& src,
  345. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  346. size_t pieceLength,
  347. uint64_t defaultSize = 1048576 /* 1MiB */);
  348. // Converts ISO/IEC 8859-1 string src to utf-8.
  349. std::string iso8859ToUtf8(const std::string& src);
  350. std::string getContentDispositionFilename(const std::string& header);
  351. std::string randomAlpha(size_t length,
  352. const SharedHandle<Randomizer>& randomizer);
  353. std::string toUpper(const std::string& src);
  354. std::string toLower(const std::string& src);
  355. void uppercase(std::string& s);
  356. void lowercase(std::string& s);
  357. bool isNumericHost(const std::string& name);
  358. void setGlobalSignalHandler(int signal, void (*handler)(int), int flags);
  359. std::string getHomeDir();
  360. int64_t getRealSize(const std::string& sizeWithUnit);
  361. std::string abbrevSize(int64_t size);
  362. template<typename InputIterator, typename Output>
  363. void toStream
  364. (InputIterator first, InputIterator last, Output& os)
  365. {
  366. os.printf("%s\n"
  367. "idx|path/length\n"
  368. "===+===========================================================================\n", _("Files:"));
  369. int32_t count = 1;
  370. for(; first != last; ++first, ++count) {
  371. os.printf("%3d|%s\n"
  372. " |%sB (%s)\n"
  373. "---+---------------------------------------------------------------------------\n",
  374. count,
  375. (*first)->getPath().c_str(),
  376. util::abbrevSize((*first)->getLength()).c_str(),
  377. util::uitos((*first)->getLength(), true).c_str());
  378. }
  379. }
  380. void sleep(long seconds);
  381. void usleep(long microseconds);
  382. bool isNumber(const std::string& what);
  383. bool isDigit(const char c);
  384. bool isHexDigit(const char c);
  385. bool isHexDigit(const std::string& s);
  386. bool isLowercase(const std::string& what);
  387. bool isUppercase(const std::string& what);
  388. /**
  389. * Converts alphabets to unsigned int, assuming alphabets as a base 26
  390. * integer and 'a' or 'A' is 0.
  391. * This function assumes alphabets includes only a-z.
  392. * Upper case are allowed but all letters must be upper case.
  393. * If overflow occurs, returns 0.
  394. */
  395. unsigned int alphaToNum(const std::string& alphabets);
  396. void mkdirs(const std::string& dirpath);
  397. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src);
  398. // binaryStream has to be opened before calling this function.
  399. std::string toString(const SharedHandle<BinaryStream>& binaryStream);
  400. #ifdef HAVE_POSIX_MEMALIGN
  401. void* allocateAlignedMemory(size_t alignment, size_t size);
  402. #endif // HAVE_POSIX_MEMALIGN
  403. std::pair<std::string, uint16_t>
  404. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len);
  405. std::string htmlEscape(const std::string& src);
  406. // Joins path element specified in [first, last). If ".." is found,
  407. // it eats the previous element if it exists. If "." is found, it
  408. // is just ignored and it is not appeared in the result.
  409. template<typename InputIterator>
  410. std::string joinPath(InputIterator first, InputIterator last)
  411. {
  412. std::vector<std::string> elements;
  413. for(;first != last; ++first) {
  414. if(*first == "..") {
  415. if(!elements.empty()) {
  416. elements.pop_back();
  417. }
  418. } else if(*first == ".") {
  419. // do nothing
  420. } else {
  421. elements.push_back(*first);
  422. }
  423. }
  424. return strjoin(elements.begin(), elements.end(), "/");
  425. }
  426. // Parses INDEX=PATH format string. INDEX must be an unsigned
  427. // integer.
  428. std::pair<size_t, std::string>
  429. parseIndexPath(const std::string& line);
  430. std::vector<std::pair<size_t, std::string> > createIndexPaths(std::istream& i);
  431. /**
  432. * Take a string src which is a delimited list and add its elements
  433. * into result. result is stored in out.
  434. */
  435. template<typename OutputIterator>
  436. OutputIterator split(const std::string& src, OutputIterator out,
  437. const std::string& delims, bool doStrip = false,
  438. bool allowEmpty = false)
  439. {
  440. std::string::const_iterator first = src.begin();
  441. std::string::const_iterator last = src.end();
  442. for(std::string::const_iterator i = first; i != last;) {
  443. std::string::const_iterator j = i;
  444. for(; j != last &&
  445. std::find(delims.begin(), delims.end(), *j) == delims.end(); ++j);
  446. std::pair<std::string::const_iterator,
  447. std::string::const_iterator> p(i, j);
  448. if(doStrip) {
  449. p = stripIter(i, j);
  450. }
  451. if(allowEmpty || p.first != p.second) {
  452. *out++ = std::string(p.first, p.second);
  453. }
  454. i = j;
  455. if(j != last) {
  456. ++i;
  457. }
  458. }
  459. if(allowEmpty &&
  460. (src.empty() ||
  461. std::find(delims.begin(), delims.end(),
  462. src[src.size()-1]) != delims.end())) {
  463. *out++ = A2STR::NIL;
  464. }
  465. return out;
  466. }
  467. void generateRandomData(unsigned char* data, size_t length);
  468. // Saves data to file whose name is filename. If overwrite is true,
  469. // existing file is overwritten. Otherwise, this function doesn't do
  470. // nothing. If data is saved successfully, return true. Otherwise
  471. // returns false.
  472. bool saveAs
  473. (const std::string& filename, const std::string& data, bool overwrite=false);
  474. // Prepend dir to relPath. If dir is empty, it prepends "." to relPath.
  475. //
  476. // dir = "/dir", relPath = "foo" => "/dir/foo"
  477. // dir = "", relPath = "foo" => "./foo"
  478. // dir = "/", relPath = "foo" => "/foo"
  479. std::string applyDir(const std::string& dir, const std::string& relPath);
  480. // In HTTP/FTP, file name is file component in URI. In HTTP, filename
  481. // may be a value of Content-Disposition header. They are likely
  482. // percent encoded. If they contains, for example, %2F, when decoded,
  483. // basename contains dir component. This should be avoided. This
  484. // function is created to fix these issues. This function expects src
  485. // should be non-percent-encoded basename. Currently, this function
  486. // replaces '/' with '_' and result string is passed to escapePath()
  487. // function and its result is returned.
  488. std::string fixTaintedBasename(const std::string& src);
  489. // Generates 20 bytes random key and store it to the address pointed
  490. // by key. Caller must allocate at least 20 bytes for generated key.
  491. void generateRandomKey(unsigned char* key);
  492. // Returns true is given numeric ipv4addr is in Private Address Space.
  493. bool inPrivateAddress(const std::string& ipv4addr);
  494. // Returns true if s contains directory traversal path component such
  495. // as '..' or it contains null or control character which may fool
  496. // user.
  497. bool detectDirTraversal(const std::string& s);
  498. // Replaces null(0x00) and control character(0x01-0x1f) with '_'. If
  499. // __MINGW32__ is defined, following characters are also replaced with
  500. // '_': '"', '*', ':', '<', '>', '?', '\', '|'.
  501. std::string escapePath(const std::string& s);
  502. // Returns true if ip1 and ip2 are in the same CIDR block. ip1 and
  503. // ip2 must be numeric IPv4 or IPv6 address. If either of them or both
  504. // of them is not valid numeric address, then returns false. bits is
  505. // prefix bits. If bits is out of range, then bits is set to the
  506. // length of binary representation of the address*8.
  507. bool inSameCidrBlock
  508. (const std::string& ip1, const std::string& ip2, size_t bits);
  509. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group);
  510. void removeMetalinkContentTypes(RequestGroup* group);
  511. // No throw
  512. void executeHookByOptName
  513. (const SharedHandle<RequestGroup>& group, const Option* option,
  514. const Pref* pref);
  515. // No throw
  516. void executeHookByOptName
  517. (const RequestGroup* group, const Option* option, const Pref* pref);
  518. std::string createSafePath(const std::string& dir, const std::string& filename);
  519. std::string encodeNonUtf8(const std::string& s);
  520. // Create string safely. If str is NULL, returns empty string.
  521. // Otherwise, returns std::string(str).
  522. std::string makeString(const char* str);
  523. // This function is basically the same with strerror(errNum) but when
  524. // strerror returns NULL, this function returns empty string.
  525. std::string safeStrerror(int errNum);
  526. // Parses sequence [first, last) and find name=value pair delimited by
  527. // delim character. If name(and optionally value) is found, returns
  528. // pair of iterator which can use as first parameter of next call of
  529. // this function, and true. If no name is found, returns the pair of
  530. // last and false.
  531. template<typename Iterator>
  532. std::pair<Iterator, bool>
  533. nextParam
  534. (std::string& name,
  535. std::string& value,
  536. Iterator first,
  537. Iterator last,
  538. char delim)
  539. {
  540. Iterator end = last;
  541. while(first != end) {
  542. last = first;
  543. Iterator parmnameFirst = first;
  544. Iterator parmnameLast = first;
  545. bool eqFound = false;
  546. for(; last != end; ++last) {
  547. if(*last == delim) {
  548. break;
  549. } else if(!eqFound && *last == '=') {
  550. eqFound = true;
  551. parmnameFirst = first;
  552. parmnameLast = last;
  553. }
  554. }
  555. std::pair<std::string::const_iterator,
  556. std::string::const_iterator> namep;
  557. std::pair<std::string::const_iterator,
  558. std::string::const_iterator> valuep;
  559. if(parmnameFirst == parmnameLast) {
  560. if(!eqFound) {
  561. parmnameFirst = first;
  562. parmnameLast = last;
  563. namep = stripIter(parmnameFirst, parmnameLast);
  564. }
  565. } else {
  566. first = parmnameLast+1;
  567. namep = stripIter(parmnameFirst, parmnameLast);
  568. valuep = stripIter(first, last);
  569. }
  570. if(last != end) {
  571. ++last;
  572. }
  573. if(namep.first != namep.second) {
  574. name.assign(namep.first, namep.second);
  575. value.assign(valuep.first, valuep.second);
  576. return std::make_pair(last, true);
  577. }
  578. first = last;
  579. }
  580. return std::make_pair(end, false);
  581. }
  582. template<typename T>
  583. SharedHandle<T> copy(const SharedHandle<T>& a)
  584. {
  585. return SharedHandle<T>(new T(*a.get()));
  586. }
  587. // This is a bit different from cookie_helper::domainMatch(). If
  588. // hostname is numeric host, then returns true if domain == hostname.
  589. // That is if domain starts with ".", then returns true if domain is a
  590. // suffix of hostname. If domain does not start with ".", then
  591. // returns true if domain == hostname. Otherwise returns true.
  592. // For example,
  593. //
  594. // * noProxyDomainMatch("aria2.sf.net", ".sf.net") returns true.
  595. // * noProxyDomainMatch("sf.net", ".sf.net") returns false.
  596. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain);
  597. } // namespace util
  598. } // namespace aria2
  599. #endif // D_UTIL_H