util.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 <cstdio>
  40. #include <string>
  41. #include <utility>
  42. #include <iosfwd>
  43. #include <ostream>
  44. #include <numeric>
  45. #include <map>
  46. #include <iomanip>
  47. #include <algorithm>
  48. #include <vector>
  49. #include "SharedHandle.h"
  50. #include "IntSequence.h"
  51. #include "a2time.h"
  52. #include "a2netcompat.h"
  53. #include "a2functional.h"
  54. #include "SegList.h"
  55. namespace aria2 {
  56. class Randomizer;
  57. class BitfieldMan;
  58. class BinaryStream;
  59. class FileEntry;
  60. class RequestGroup;
  61. class Option;
  62. class Pref;
  63. #define STRTOLL(X) strtoll(X, reinterpret_cast<char**>(0), 10)
  64. #define STRTOULL(X) strtoull(X, reinterpret_cast<char**>(0), 10)
  65. #define START_INDEX(OFFSET, PIECE_LENGTH) ((OFFSET)/(PIECE_LENGTH))
  66. #define END_INDEX(OFFSET, LENGTH, PIECE_LENGTH) (((OFFSET)+(LENGTH)-1)/(PIECE_LENGTH))
  67. #define DIV_FLOOR(X,Y) ((X)/(Y)+((X)%(Y)? 1:0))
  68. #ifdef WORDS_BIGENDIAN
  69. inline uint64_t ntoh64(uint64_t x) { return x; }
  70. inline uint64_t hton64(uint64_t x) { return x; }
  71. #else // !WORDS_BIGENDIAN
  72. inline uint64_t byteswap64(uint64_t x) {
  73. uint64_t v1 = ntohl(x & 0x00000000ffffffffllu);
  74. uint64_t v2 = ntohl(x >> 32);
  75. return (v1 << 32)|v2;
  76. }
  77. inline uint64_t ntoh64(uint64_t x) { return byteswap64(x); }
  78. inline uint64_t hton64(uint64_t x) { return byteswap64(x); }
  79. #endif // !WORDS_BIGENDIAN
  80. #ifdef __MINGW32__
  81. std::wstring utf8ToWChar(const std::string& src);
  82. std::wstring utf8ToWChar(const char* str);
  83. std::string utf8ToNative(const std::string& src);
  84. std::string wCharToUtf8(const std::wstring& wsrc);
  85. std::string nativeToUtf8(const std::string& src);
  86. #else // !__MINGW32__
  87. # define utf8ToWChar(src) src
  88. # define utf8ToNative(src) src
  89. #endif // !__MINGW32__
  90. namespace util {
  91. void divide
  92. (std::pair<std::string, std::string>& hp, const std::string& src, char delim);
  93. template<typename T>
  94. std::string uitos(T value, bool comma = false)
  95. {
  96. std::string str;
  97. if(value == 0) {
  98. str = "0";
  99. return str;
  100. }
  101. unsigned int count = 0;
  102. while(value) {
  103. ++count;
  104. char digit = value%10+'0';
  105. if(comma && count > 3 && count%3 == 1) {
  106. str += ',';
  107. }
  108. str += digit;
  109. value /= 10;
  110. }
  111. std::reverse(str.begin(), str.end());
  112. return str;
  113. }
  114. std::string itos(int64_t value, bool comma = false);
  115. /**
  116. * Computes difference in micro-seconds between tv1 and tv2,
  117. * assuming tv1 is newer than tv2.
  118. * If tv1 is older than tv2, then this method returns 0.
  119. */
  120. int64_t difftv(struct timeval tv1, struct timeval tv2);
  121. int32_t difftvsec(struct timeval tv1, struct timeval tv2);
  122. extern const std::string DEFAULT_STRIP_CHARSET;
  123. template<typename InputIterator>
  124. std::string stripIter
  125. (InputIterator first, InputIterator last,
  126. const std::string& chars = DEFAULT_STRIP_CHARSET)
  127. {
  128. if(std::distance(first, last) == 0) {
  129. return A2STR::NIL;
  130. }
  131. for(; first != last &&
  132. std::find(chars.begin(), chars.end(), *first) != chars.end(); ++first);
  133. if(first == last) {
  134. return A2STR::NIL;
  135. }
  136. InputIterator left = last-1;
  137. for(; left != first &&
  138. std::find(chars.begin(), chars.end(), *left) != chars.end(); --left);
  139. return std::string(first, left+1);
  140. }
  141. std::string strip
  142. (const std::string& str, const std::string& chars = DEFAULT_STRIP_CHARSET);
  143. bool startsWith(const std::string& target, const std::string& part);
  144. bool endsWith(const std::string& target, const std::string& part);
  145. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr);
  146. std::string percentEncode(const unsigned char* target, size_t len);
  147. std::string percentEncode(const std::string& target);
  148. std::string percentEncodeMini(const std::string& target);
  149. bool inRFC3986ReservedChars(const char c);
  150. bool inRFC3986UnreservedChars(const char c);
  151. bool isUtf8(const std::string& str);
  152. std::string percentDecode(const std::string& target);
  153. std::string torrentPercentEncode(const unsigned char* target, size_t len);
  154. std::string torrentPercentEncode(const std::string& target);
  155. std::string toHex(const unsigned char* src, size_t len);
  156. std::string toHex(const char* src, size_t len);
  157. std::string toHex(const std::string& src);
  158. // Converts hexadecimal ascii string 'src' into packed binary form and
  159. // return the result. If src is not well formed, then empty string is
  160. // returned.
  161. std::string fromHex(const std::string& src);
  162. FILE* openFile(const std::string& filename, const std::string& mode);
  163. bool isPowerOf(int num, int base);
  164. std::string secfmt(time_t sec);
  165. int32_t parseInt(const std::string& s, int32_t base = 10);
  166. bool parseIntNoThrow(int32_t& result, const std::string& s, int base = 10);
  167. uint32_t parseUInt(const std::string& s, int base = 10);
  168. bool parseUIntNoThrow(uint32_t& result, const std::string& s, int base = 10);
  169. int64_t parseLLInt(const std::string& s, int32_t base = 10);
  170. bool parseLLIntNoThrow(int64_t& result, const std::string& s, int base = 10);
  171. uint64_t parseULLInt(const std::string& s, int base = 10);
  172. IntSequence parseIntRange(const std::string& src);
  173. void parseIntSegments(SegList<int>& sgl, const std::string& src);
  174. // Parses string which specifies the range of piece index for higher
  175. // priority and appends those indexes into result. The input string
  176. // src can contain 2 keywords "head" and "tail". To include both
  177. // keywords, they must be separated by comma. "head" means the pieces
  178. // where the first byte of each file sits. "tail" means the pieces
  179. // where the last byte of each file sits. These keywords can take one
  180. // parameter, SIZE. For example, if "head=SIZE" is specified, pieces
  181. // in the range of first SIZE bytes of each file get higher
  182. // priority. SIZE can include K or M(1K = 1024, 1M = 1024K).
  183. // If SIZE is omitted, SIZE=defaultSize is used.
  184. //
  185. // sample: head=512K,tail=512K
  186. void parsePrioritizePieceRange
  187. (std::vector<size_t>& result, const std::string& src,
  188. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  189. size_t pieceLength,
  190. uint64_t defaultSize = 1048576 /* 1MiB */);
  191. // Converts ISO/IEC 8859-1 string src to utf-8.
  192. std::string iso8859ToUtf8(const std::string& src);
  193. std::string getContentDispositionFilename(const std::string& header);
  194. std::string randomAlpha(size_t length,
  195. const SharedHandle<Randomizer>& randomizer);
  196. std::string toUpper(const std::string& src);
  197. std::string toLower(const std::string& src);
  198. void uppercase(std::string& s);
  199. void lowercase(std::string& s);
  200. bool isNumericHost(const std::string& name);
  201. void setGlobalSignalHandler(int signal, void (*handler)(int), int flags);
  202. std::string getHomeDir();
  203. int64_t getRealSize(const std::string& sizeWithUnit);
  204. std::string abbrevSize(int64_t size);
  205. template<typename InputIterator, typename Output>
  206. void toStream
  207. (InputIterator first, InputIterator last, Output& os)
  208. {
  209. os.printf("%s\n"
  210. "idx|path/length\n"
  211. "===+===========================================================================\n", _("Files:"));
  212. int32_t count = 1;
  213. for(; first != last; ++first, ++count) {
  214. os.printf("%3d|%s\n"
  215. " |%sB (%s)\n"
  216. "---+---------------------------------------------------------------------------\n",
  217. count,
  218. (*first)->getPath().c_str(),
  219. util::abbrevSize((*first)->getLength()).c_str(),
  220. util::uitos((*first)->getLength(), true).c_str());
  221. }
  222. }
  223. void sleep(long seconds);
  224. void usleep(long microseconds);
  225. bool isNumber(const std::string& what);
  226. bool isDigit(const char c);
  227. bool isHexDigit(const char c);
  228. bool isHexDigit(const std::string& s);
  229. bool isLowercase(const std::string& what);
  230. bool isUppercase(const std::string& what);
  231. /**
  232. * Converts alphabets to unsigned int, assuming alphabets as a base 26
  233. * integer and 'a' or 'A' is 0.
  234. * This function assumes alphabets includes only a-z.
  235. * Upper case are allowed but all letters must be upper case.
  236. * If overflow occurs, returns 0.
  237. */
  238. unsigned int alphaToNum(const std::string& alphabets);
  239. void mkdirs(const std::string& dirpath);
  240. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src);
  241. // binaryStream has to be opened before calling this function.
  242. std::string toString(const SharedHandle<BinaryStream>& binaryStream);
  243. #ifdef HAVE_POSIX_MEMALIGN
  244. void* allocateAlignedMemory(size_t alignment, size_t size);
  245. #endif // HAVE_POSIX_MEMALIGN
  246. std::pair<std::string, uint16_t>
  247. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len);
  248. std::string htmlEscape(const std::string& src);
  249. // Joins path element specified in [first, last). If ".." is found,
  250. // it eats the previous element if it exists. If "." is found, it
  251. // is just ignored and it is not appeared in the result.
  252. template<typename InputIterator>
  253. std::string joinPath(InputIterator first, InputIterator last)
  254. {
  255. std::vector<std::string> elements;
  256. for(;first != last; ++first) {
  257. if(*first == "..") {
  258. if(!elements.empty()) {
  259. elements.pop_back();
  260. }
  261. } else if(*first == ".") {
  262. // do nothing
  263. } else {
  264. elements.push_back(*first);
  265. }
  266. }
  267. return strjoin(elements.begin(), elements.end(), "/");
  268. }
  269. // Parses INDEX=PATH format string. INDEX must be an unsigned
  270. // integer.
  271. std::map<size_t, std::string>::value_type
  272. parseIndexPath(const std::string& line);
  273. std::map<size_t, std::string> createIndexPathMap(std::istream& i);
  274. /**
  275. * Take a string src which is a delimited list and add its elements
  276. * into result. result is stored in out.
  277. */
  278. template<typename OutputIterator>
  279. OutputIterator split(const std::string& src, OutputIterator out,
  280. const std::string& delims, bool doStrip = false,
  281. bool allowEmpty = false)
  282. {
  283. std::string::const_iterator first = src.begin();
  284. std::string::const_iterator last = src.end();
  285. for(std::string::const_iterator i = first; i != last;) {
  286. std::string::const_iterator j = i;
  287. for(; j != last &&
  288. std::find(delims.begin(), delims.end(), *j) == delims.end(); ++j);
  289. std::string t = doStrip?util::stripIter(i, j):std::string(i, j);
  290. if(allowEmpty || !t.empty()) {
  291. *out++ = t;
  292. }
  293. i = j;
  294. if(j != last) {
  295. ++i;
  296. }
  297. }
  298. if(allowEmpty &&
  299. (src.empty() ||
  300. std::find(delims.begin(), delims.end(),
  301. src[src.size()-1]) != delims.end())) {
  302. *out++ = A2STR::NIL;
  303. }
  304. return out;
  305. }
  306. void generateRandomData(unsigned char* data, size_t length);
  307. // Saves data to file whose name is filename. If overwrite is true,
  308. // existing file is overwritten. Otherwise, this function doesn't do
  309. // nothing. If data is saved successfully, return true. Otherwise
  310. // returns false.
  311. bool saveAs
  312. (const std::string& filename, const std::string& data, bool overwrite=false);
  313. // Prepend dir to relPath. If dir is empty, it prepends "." to relPath.
  314. //
  315. // dir = "/dir", relPath = "foo" => "/dir/foo"
  316. // dir = "", relPath = "foo" => "./foo"
  317. // dir = "/", relPath = "foo" => "/foo"
  318. std::string applyDir(const std::string& dir, const std::string& relPath);
  319. // In HTTP/FTP, file name is file component in URI. In HTTP, filename
  320. // may be a value of Content-Disposition header. They are likely
  321. // percent encoded. If they contains, for example, %2F, when decoded,
  322. // basename contains dir component. This should be avoided. This
  323. // function is created to fix these issues. This function expects src
  324. // should be non-percent-encoded basename. Currently, this function
  325. // replaces '/' with '_' and result string is passed to escapePath()
  326. // function and its result is returned.
  327. std::string fixTaintedBasename(const std::string& src);
  328. // Generates 20 bytes random key and store it to the address pointed
  329. // by key. Caller must allocate at least 20 bytes for generated key.
  330. void generateRandomKey(unsigned char* key);
  331. // Returns true is given numeric ipv4addr is in Private Address Space.
  332. bool inPrivateAddress(const std::string& ipv4addr);
  333. // Returns true if s contains directory traversal path component such
  334. // as '..' or it contains null or control character which may fool
  335. // user.
  336. bool detectDirTraversal(const std::string& s);
  337. // Replaces null(0x00) and control character(0x01-0x1f) with '_'. If
  338. // __MINGW32__ is defined, following characters are also replaced with
  339. // '_': '"', '*', ':', '<', '>', '?', '\', '|'.
  340. std::string escapePath(const std::string& s);
  341. // Returns true if ip1 and ip2 are in the same CIDR block. ip1 and
  342. // ip2 must be numeric IPv4 or IPv6 address. If either of them or both
  343. // of them is not valid numeric address, then returns false. bits is
  344. // prefix bits. If bits is out of range, then bits is set to the
  345. // length of binary representation of the address*8.
  346. bool inSameCidrBlock
  347. (const std::string& ip1, const std::string& ip2, size_t bits);
  348. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group);
  349. void removeMetalinkContentTypes(RequestGroup* group);
  350. // No throw
  351. void executeHookByOptName
  352. (const SharedHandle<RequestGroup>& group, const Option* option,
  353. const Pref* pref);
  354. // No throw
  355. void executeHookByOptName
  356. (const RequestGroup* group, const Option* option, const Pref* pref);
  357. std::string createSafePath(const std::string& dir, const std::string& filename);
  358. std::string encodeNonUtf8(const std::string& s);
  359. // Create string safely. If str is NULL, returns empty string.
  360. // Otherwise, returns std::string(str).
  361. std::string makeString(const char* str);
  362. // This function is basically the same with strerror(errNum) but when
  363. // strerror returns NULL, this function returns empty string.
  364. std::string safeStrerror(int errNum);
  365. // Parses sequence [first, last) and find name=value pair delimited by
  366. // delim character. If name(and optionally value) is found, returns
  367. // pair of iterator which can use as first parameter of next call of
  368. // this function, and true. If no name is found, returns the pair of
  369. // last and false.
  370. template<typename Iterator>
  371. std::pair<Iterator, bool>
  372. nextParam
  373. (std::string& name,
  374. std::string& value,
  375. Iterator first,
  376. Iterator last,
  377. char delim)
  378. {
  379. Iterator end = last;
  380. while(first != end) {
  381. last = first;
  382. Iterator parmnameFirst = first;
  383. Iterator parmnameLast = first;
  384. bool eqFound = false;
  385. for(; last != end; ++last) {
  386. if(*last == delim) {
  387. break;
  388. } else if(!eqFound && *last == '=') {
  389. eqFound = true;
  390. parmnameFirst = first;
  391. parmnameLast = last;
  392. }
  393. }
  394. std::string tname, tvalue;
  395. if(parmnameFirst == parmnameLast) {
  396. if(!eqFound) {
  397. parmnameFirst = first;
  398. parmnameLast = last;
  399. tname = util::stripIter(parmnameFirst, parmnameLast);
  400. }
  401. } else {
  402. first = parmnameLast+1;
  403. tname = util::stripIter(parmnameFirst, parmnameLast);
  404. tvalue = util::stripIter(first, last);
  405. }
  406. if(last != end) {
  407. ++last;
  408. }
  409. if(!tname.empty()) {
  410. name.swap(tname);
  411. value.swap(tvalue);
  412. return std::make_pair(last, true);
  413. }
  414. first = last;
  415. }
  416. return std::make_pair(end, false);
  417. }
  418. template<typename T>
  419. SharedHandle<T> copy(const SharedHandle<T>& a)
  420. {
  421. return SharedHandle<T>(new T(*a.get()));
  422. }
  423. // This is a bit different from cookie_helper::domainMatch(). If
  424. // hostname is numeric host, then returns true if domain == hostname.
  425. // That is if domain starts with ".", then returns true if domain is a
  426. // suffix of hostname. If domain does not start with ".", then
  427. // returns true if domain == hostname. Otherwise returns true.
  428. // For example,
  429. //
  430. // * noProxyDomainMatch("aria2.sf.net", ".sf.net") returns true.
  431. // * noProxyDomainMatch("sf.net", ".sf.net") returns false.
  432. bool noProxyDomainMatch(const std::string& hostname, const std::string& domain);
  433. } // namespace util
  434. } // namespace aria2
  435. #endif // D_UTIL_H