util.h 21 KB

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