util.cc 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "util.h"
  36. #include <signal.h>
  37. #include <limits.h>
  38. #include <stdint.h>
  39. #include <cerrno>
  40. #include <cassert>
  41. #include <cstring>
  42. #include <cstdio>
  43. #include <cstdlib>
  44. #include <sstream>
  45. #include <ostream>
  46. #include <algorithm>
  47. #include <fstream>
  48. #include <iomanip>
  49. #ifndef HAVE_SLEEP
  50. # ifdef HAVE_WINSOCK_H
  51. # define WIN32_LEAN_AND_MEAN
  52. # include <windows.h>
  53. # endif // HAVE_WINSOCK_H
  54. #endif // HAVE_SLEEP
  55. #ifdef HAVE_LIBGCRYPT
  56. # include <gcrypt.h>
  57. #elif HAVE_LIBSSL
  58. # include <openssl/rand.h>
  59. # include "SimpleRandomizer.h"
  60. #endif // HAVE_LIBSSL
  61. #include "File.h"
  62. #include "message.h"
  63. #include "Randomizer.h"
  64. #include "a2netcompat.h"
  65. #include "DlAbortEx.h"
  66. #include "BitfieldMan.h"
  67. #include "DefaultDiskWriter.h"
  68. #include "FatalException.h"
  69. #include "FileEntry.h"
  70. #include "StringFormat.h"
  71. #include "A2STR.h"
  72. #include "array_fun.h"
  73. #include "a2functional.h"
  74. #include "bitfield.h"
  75. #include "DownloadHandlerConstants.h"
  76. #include "RequestGroup.h"
  77. #ifdef ENABLE_MESSAGE_DIGEST
  78. # include "MessageDigestHelper.h"
  79. #endif // ENABLE_MESSAGE_DIGEST
  80. // For libc6 which doesn't define ULLONG_MAX properly because of broken limits.h
  81. #ifndef ULLONG_MAX
  82. # define ULLONG_MAX 18446744073709551615ULL
  83. #endif // ULLONG_MAX
  84. namespace aria2 {
  85. namespace util {
  86. const std::string DEFAULT_TRIM_CHARSET("\r\n\t ");
  87. std::string trim(const std::string& src, const std::string& trimCharset)
  88. {
  89. std::string temp(src);
  90. trimSelf(temp, trimCharset);
  91. return temp;
  92. }
  93. void trimSelf(std::string& str, const std::string& trimCharset)
  94. {
  95. std::string::size_type first = str.find_first_not_of(trimCharset);
  96. if(first == std::string::npos) {
  97. str.clear();
  98. } else {
  99. std::string::size_type last = str.find_last_not_of(trimCharset)+1;
  100. str.erase(last);
  101. str.erase(0, first);
  102. }
  103. }
  104. void split(std::pair<std::string, std::string>& hp, const std::string& src, char delim)
  105. {
  106. hp.first = A2STR::NIL;
  107. hp.second = A2STR::NIL;
  108. std::string::size_type p = src.find(delim);
  109. if(p == std::string::npos) {
  110. hp.first = trim(src);
  111. hp.second = A2STR::NIL;
  112. } else {
  113. hp.first = trim(src.substr(0, p));
  114. hp.second = trim(src.substr(p+1));
  115. }
  116. }
  117. std::pair<std::string, std::string> split(const std::string& src, const std::string& delims)
  118. {
  119. std::pair<std::string, std::string> hp;
  120. hp.first = A2STR::NIL;
  121. hp.second = A2STR::NIL;
  122. std::string::size_type p = src.find_first_of(delims);
  123. if(p == std::string::npos) {
  124. hp.first = trim(src);
  125. hp.second = A2STR::NIL;
  126. } else {
  127. hp.first = trim(src.substr(0, p));
  128. hp.second = trim(src.substr(p+1));
  129. }
  130. return hp;
  131. }
  132. std::string itos(int64_t value, bool comma)
  133. {
  134. bool flag = false;
  135. std::string str;
  136. if(value < 0) {
  137. if(value == INT64_MIN) {
  138. if(comma) {
  139. str = "-9,223,372,036,854,775,808";
  140. } else {
  141. str = "-9223372036854775808";
  142. }
  143. return str;
  144. }
  145. flag = true;
  146. value = -value;
  147. }
  148. str = uitos(value, comma);
  149. if(flag) {
  150. str.insert(str.begin(), '-');
  151. }
  152. return str;
  153. }
  154. int64_t difftv(struct timeval tv1, struct timeval tv2) {
  155. if((tv1.tv_sec < tv2.tv_sec) ||
  156. ((tv1.tv_sec == tv2.tv_sec) && (tv1.tv_usec < tv2.tv_usec))) {
  157. return 0;
  158. }
  159. return ((int64_t)(tv1.tv_sec-tv2.tv_sec)*1000000+
  160. tv1.tv_usec-tv2.tv_usec);
  161. }
  162. int32_t difftvsec(struct timeval tv1, struct timeval tv2) {
  163. if(tv1.tv_sec < tv2.tv_sec) {
  164. return 0;
  165. }
  166. return tv1.tv_sec-tv2.tv_sec;
  167. }
  168. bool startsWith(const std::string& target, const std::string& part) {
  169. if(target.size() < part.size()) {
  170. return false;
  171. }
  172. if(part.empty()) {
  173. return true;
  174. }
  175. if(target.find(part) == 0) {
  176. return true;
  177. } else {
  178. return false;
  179. }
  180. }
  181. bool endsWith(const std::string& target, const std::string& part) {
  182. if(target.size() < part.size()) {
  183. return false;
  184. }
  185. if(part.empty()) {
  186. return true;
  187. }
  188. if(target.rfind(part) == target.size()-part.size()) {
  189. return true;
  190. } else {
  191. return false;
  192. }
  193. }
  194. std::string replace(const std::string& target, const std::string& oldstr, const std::string& newstr) {
  195. if(target.empty() || oldstr.empty()) {
  196. return target;
  197. }
  198. std::string result;
  199. std::string::size_type p = 0;
  200. std::string::size_type np = target.find(oldstr);
  201. while(np != std::string::npos) {
  202. result += target.substr(p, np-p);
  203. result += newstr;
  204. p = np+oldstr.size();
  205. np = target.find(oldstr, p);
  206. }
  207. result += target.substr(p);
  208. return result;
  209. }
  210. bool isAlpha(const char c)
  211. {
  212. return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
  213. }
  214. bool isDigit(const char c)
  215. {
  216. return '0' <= c && c <= '9';
  217. }
  218. bool isHexDigit(const char c)
  219. {
  220. return isDigit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
  221. }
  222. bool isHexDigit(const std::string& s)
  223. {
  224. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  225. if(!isHexDigit(*i)) {
  226. return false;
  227. }
  228. }
  229. return true;
  230. }
  231. bool inRFC3986ReservedChars(const char c)
  232. {
  233. static const char reserved[] = {
  234. ':' , '/' , '?' , '#' , '[' , ']' , '@',
  235. '!' , '$' , '&' , '\'' , '(' , ')',
  236. '*' , '+' , ',' , ';' , '=' };
  237. return std::find(vbegin(reserved), vend(reserved), c) != vend(reserved);
  238. }
  239. bool inRFC3986UnreservedChars(const char c)
  240. {
  241. static const char unreserved[] = { '-', '.', '_', '~' };
  242. return isAlpha(c) || isDigit(c) ||
  243. std::find(vbegin(unreserved), vend(unreserved), c) != vend(unreserved);
  244. }
  245. bool inRFC2978MIMECharset(const char c)
  246. {
  247. static const char chars[] = {
  248. '!', '#', '$', '%', '&',
  249. '\'', '+', '-', '^', '_',
  250. '`', '{', '}', '~'
  251. };
  252. return isAlpha(c) || isDigit(c) ||
  253. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  254. }
  255. bool inRFC2616HttpToken(const char c)
  256. {
  257. static const char chars[] = {
  258. '!', '#', '$', '%', '&', '\'', '*', '+', '-', '.',
  259. '^', '_', '`', '|', '~'
  260. };
  261. return isAlpha(c) || isDigit(c) ||
  262. std::find(vbegin(chars), vend(chars), c) != vend(chars);
  263. }
  264. std::string percentEncode(const unsigned char* target, size_t len) {
  265. std::string dest;
  266. for(size_t i = 0; i < len; ++i) {
  267. if(!inRFC3986UnreservedChars(target[i])) {
  268. dest.append(StringFormat("%%%02X", target[i]).str());
  269. } else {
  270. dest += target[i];
  271. }
  272. }
  273. return dest;
  274. }
  275. std::string percentEncode(const std::string& target)
  276. {
  277. return percentEncode(reinterpret_cast<const unsigned char*>(target.c_str()),
  278. target.size());
  279. }
  280. std::string torrentPercentEncode(const unsigned char* target, size_t len) {
  281. std::string dest;
  282. for(size_t i = 0; i < len; ++i) {
  283. if(isAlpha(target[i]) || isDigit(target[i])) {
  284. dest += target[i];
  285. } else {
  286. dest.append(StringFormat("%%%02X", target[i]).str());
  287. }
  288. }
  289. return dest;
  290. }
  291. std::string torrentPercentEncode(const std::string& target)
  292. {
  293. return torrentPercentEncode
  294. (reinterpret_cast<const unsigned char*>(target.c_str()), target.size());
  295. }
  296. std::string percentDecode(const std::string& target) {
  297. std::string result;
  298. for(std::string::const_iterator itr = target.begin(), eoi = target.end();
  299. itr != eoi; ++itr) {
  300. if(*itr == '%') {
  301. if(itr+1 != target.end() && itr+2 != target.end() &&
  302. isHexDigit(*(itr+1)) && isHexDigit(*(itr+2))) {
  303. result += parseInt(std::string(itr+1, itr+3), 16);
  304. itr += 2;
  305. } else {
  306. result += *itr;
  307. }
  308. } else {
  309. result += *itr;
  310. }
  311. }
  312. return result;
  313. }
  314. std::string toHex(const unsigned char* src, size_t len) {
  315. std::string out(len*2, '\0');
  316. std::string::iterator o = out.begin();
  317. const unsigned char* last = src+len;
  318. for(const unsigned char* i = src; i != last; ++i) {
  319. *o = (*i >> 4);
  320. *(o+1) = (*i)&0x0f;
  321. for(int j = 0; j < 2; ++j) {
  322. if(*o < 10) {
  323. *o += '0';
  324. } else {
  325. *o += 'a'-10;
  326. }
  327. ++o;
  328. }
  329. }
  330. return out;
  331. }
  332. std::string toHex(const char* src, size_t len)
  333. {
  334. return toHex(reinterpret_cast<const unsigned char*>(src), len);
  335. }
  336. std::string toHex(const std::string& src)
  337. {
  338. return toHex(reinterpret_cast<const unsigned char*>(src.c_str()), src.size());
  339. }
  340. static unsigned int hexCharToUInt(unsigned char ch)
  341. {
  342. if('a' <= ch && ch <= 'f') {
  343. ch -= 'a';
  344. ch += 10;
  345. } else if('A' <= ch && ch <= 'F') {
  346. ch -= 'A';
  347. ch += 10;
  348. } else if('0' <= ch && ch <= '9') {
  349. ch -= '0';
  350. } else {
  351. ch = 255;
  352. }
  353. return ch;
  354. }
  355. std::string fromHex(const std::string& src)
  356. {
  357. std::string dest;
  358. if(src.size()%2) {
  359. return dest;
  360. }
  361. for(size_t i = 0; i < src.size(); i += 2) {
  362. unsigned char high = hexCharToUInt(src[i]);
  363. unsigned char low = hexCharToUInt(src[i+1]);
  364. if(high == 255 || low == 255) {
  365. dest.clear();
  366. return dest;
  367. }
  368. dest += (high*16+low);
  369. }
  370. return dest;
  371. }
  372. FILE* openFile(const std::string& filename, const std::string& mode) {
  373. FILE* file = fopen(filename.c_str(), mode.c_str());
  374. return file;
  375. }
  376. bool isPowerOf(int num, int base) {
  377. if(base <= 0) { return false; }
  378. if(base == 1) { return true; }
  379. while(num%base == 0) {
  380. num /= base;
  381. if(num == 1) {
  382. return true;
  383. }
  384. }
  385. return false;
  386. }
  387. std::string secfmt(time_t sec) {
  388. std::string str;
  389. if(sec >= 3600) {
  390. str = itos(sec/3600);
  391. str += "h";
  392. sec %= 3600;
  393. }
  394. if(sec >= 60) {
  395. int min = sec/60;
  396. if(min < 10) {
  397. str += "0";
  398. }
  399. str += itos(min);
  400. str += "m";
  401. sec %= 60;
  402. }
  403. if(sec < 10) {
  404. str += "0";
  405. }
  406. str += itos(sec);
  407. str += "s";
  408. return str;
  409. }
  410. int getNum(const char* buf, int offset, size_t length) {
  411. char* temp = new char[length+1];
  412. memcpy(temp, buf+offset, length);
  413. temp[length] = '\0';
  414. int x = strtol(temp, 0, 10);
  415. delete [] temp;
  416. return x;
  417. }
  418. int32_t parseInt(const std::string& s, int32_t base)
  419. {
  420. int64_t v = parseLLInt(s, base);
  421. if(v < INT32_MIN || INT32_MAX < v) {
  422. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  423. s.c_str()).str());
  424. }
  425. return v;
  426. }
  427. uint32_t parseUInt(const std::string& s, int base)
  428. {
  429. uint64_t v = parseULLInt(s, base);
  430. if(UINT32_MAX < v) {
  431. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  432. s.c_str()).str());
  433. }
  434. return v;
  435. }
  436. bool parseUIntNoThrow(uint32_t& result, const std::string& s, int base)
  437. {
  438. std::string trimed = trim(s);
  439. if(trimed.empty()) {
  440. return false;
  441. }
  442. // We don't allow negative number.
  443. if(trimed[0] == '-') {
  444. return false;
  445. }
  446. char* stop;
  447. errno = 0;
  448. unsigned long int v = strtoul(trimed.c_str(), &stop, base);
  449. if(*stop != '\0') {
  450. return false;
  451. } else if(((v == ULONG_MAX) && (errno == ERANGE)) || (v > UINT32_MAX)) {
  452. return false;
  453. }
  454. result = v;
  455. return true;
  456. }
  457. int64_t parseLLInt(const std::string& s, int32_t base)
  458. {
  459. std::string trimed = trim(s);
  460. if(trimed.empty()) {
  461. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  462. "empty string").str());
  463. }
  464. char* stop;
  465. errno = 0;
  466. int64_t v = strtoll(trimed.c_str(), &stop, base);
  467. if(*stop != '\0') {
  468. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  469. trimed.c_str()).str());
  470. } else if(((v == INT64_MIN) || (v == INT64_MAX)) && (errno == ERANGE)) {
  471. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  472. trimed.c_str()).str());
  473. }
  474. return v;
  475. }
  476. uint64_t parseULLInt(const std::string& s, int base)
  477. {
  478. std::string trimed = trim(s);
  479. if(trimed.empty()) {
  480. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  481. "empty string").str());
  482. }
  483. // We don't allow negative number.
  484. if(trimed[0] == '-') {
  485. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  486. trimed.c_str()).str());
  487. }
  488. char* stop;
  489. errno = 0;
  490. uint64_t v = strtoull(trimed.c_str(), &stop, base);
  491. if(*stop != '\0') {
  492. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  493. trimed.c_str()).str());
  494. } else if((v == ULLONG_MAX) && (errno == ERANGE)) {
  495. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  496. trimed.c_str()).str());
  497. }
  498. return v;
  499. }
  500. IntSequence parseIntRange(const std::string& src)
  501. {
  502. IntSequence::Values values;
  503. std::string temp = src;
  504. while(temp.size()) {
  505. std::pair<std::string, std::string> p = split(temp, ",");
  506. temp = p.second;
  507. if(p.first.empty()) {
  508. continue;
  509. }
  510. if(p.first.find("-") == std::string::npos) {
  511. int32_t v = parseInt(p.first.c_str());
  512. values.push_back(IntSequence::Value(v, v+1));
  513. } else {
  514. std::pair<std::string, std::string> vp = split(p.first.c_str(), "-");
  515. if(vp.first.empty() || vp.second.empty()) {
  516. throw DL_ABORT_EX
  517. (StringFormat(MSG_INCOMPLETE_RANGE, p.first.c_str()).str());
  518. }
  519. int32_t v1 = parseInt(vp.first.c_str());
  520. int32_t v2 = parseInt(vp.second.c_str());
  521. values.push_back(IntSequence::Value(v1, v2+1));
  522. }
  523. }
  524. return values;
  525. }
  526. static void computeHeadPieces
  527. (std::vector<size_t>& indexes,
  528. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  529. size_t pieceLength,
  530. uint64_t head)
  531. {
  532. if(head == 0) {
  533. return;
  534. }
  535. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  536. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  537. if((*fi)->getLength() == 0) {
  538. continue;
  539. }
  540. size_t lastIndex =
  541. ((*fi)->getOffset()+std::min(head, (*fi)->getLength())-1)/pieceLength;
  542. for(size_t index = (*fi)->getOffset()/pieceLength;
  543. index <= lastIndex; ++index) {
  544. indexes.push_back(index);
  545. }
  546. }
  547. }
  548. static void computeTailPieces
  549. (std::vector<size_t>& indexes,
  550. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  551. size_t pieceLength,
  552. uint64_t tail)
  553. {
  554. if(tail == 0) {
  555. return;
  556. }
  557. for(std::vector<SharedHandle<FileEntry> >::const_iterator fi =
  558. fileEntries.begin(), eoi = fileEntries.end(); fi != eoi; ++fi) {
  559. if((*fi)->getLength() == 0) {
  560. continue;
  561. }
  562. uint64_t endOffset = (*fi)->getLastOffset();
  563. size_t fromIndex =
  564. (endOffset-1-(std::min(tail, (*fi)->getLength())-1))/pieceLength;
  565. for(size_t index = fromIndex; index <= (endOffset-1)/pieceLength;
  566. ++index) {
  567. indexes.push_back(index);
  568. }
  569. }
  570. }
  571. void parsePrioritizePieceRange
  572. (std::vector<size_t>& result, const std::string& src,
  573. const std::vector<SharedHandle<FileEntry> >& fileEntries,
  574. size_t pieceLength,
  575. uint64_t defaultSize)
  576. {
  577. std::vector<size_t> indexes;
  578. std::vector<std::string> parts;
  579. split(src, std::back_inserter(parts), ",", true);
  580. for(std::vector<std::string>::const_iterator i = parts.begin(),
  581. eoi = parts.end(); i != eoi; ++i) {
  582. if((*i) == "head") {
  583. computeHeadPieces(indexes, fileEntries, pieceLength, defaultSize);
  584. } else if(util::startsWith(*i, "head=")) {
  585. std::string sizestr = std::string((*i).begin()+(*i).find("=")+1,
  586. (*i).end());
  587. computeHeadPieces(indexes, fileEntries, pieceLength,
  588. std::max((int64_t)0, getRealSize(sizestr)));
  589. } else if((*i) == "tail") {
  590. computeTailPieces(indexes, fileEntries, pieceLength, defaultSize);
  591. } else if(util::startsWith(*i, "tail=")) {
  592. std::string sizestr = std::string((*i).begin()+(*i).find("=")+1,
  593. (*i).end());
  594. computeTailPieces(indexes, fileEntries, pieceLength,
  595. std::max((int64_t)0, getRealSize(sizestr)));
  596. } else {
  597. throw DL_ABORT_EX
  598. (StringFormat("Unrecognized token %s", (*i).c_str()).str());
  599. }
  600. }
  601. std::sort(indexes.begin(), indexes.end());
  602. indexes.erase(std::unique(indexes.begin(), indexes.end()), indexes.end());
  603. result.insert(result.end(), indexes.begin(), indexes.end());
  604. }
  605. // Converts ISO/IEC 8859-1 string to UTF-8 string. If there is a
  606. // character not in ISO/IEC 8859-1, returns empty string.
  607. std::string iso8859ToUtf8(const std::string& src)
  608. {
  609. std::string dest;
  610. for(std::string::const_iterator itr = src.begin(), eoi = src.end();
  611. itr != eoi; ++itr) {
  612. unsigned char c = *itr;
  613. if(0xa0 <= c) {
  614. if(c <= 0xbf) {
  615. dest += 0xc2;
  616. } else {
  617. dest += 0xc3;
  618. }
  619. dest += c&(~0x40);
  620. } else if(0x80 <= c && c <= 0x9f) {
  621. return A2STR::NIL;
  622. } else {
  623. dest += c;
  624. }
  625. }
  626. return dest;
  627. }
  628. template<typename OutputIterator>
  629. static void parseParam(OutputIterator out, const std::string& header)
  630. {
  631. for(std::string::const_iterator i = header.begin(), eoi = header.end();
  632. i != eoi;) {
  633. std::string::const_iterator paramFirst = i;
  634. std::string::const_iterator paramLast = paramFirst;
  635. for(; paramLast != eoi && *paramLast != '=' && *paramLast != ';';
  636. ++paramLast);
  637. std::string param;
  638. if(paramLast == eoi || *paramLast == ';') {
  639. // No value, parmname only
  640. param = std::string(paramFirst, paramLast);
  641. } else {
  642. for(; paramLast != eoi && *paramLast != '"' && *paramLast != ';';
  643. ++paramLast);
  644. if(paramLast != eoi && *paramLast == '"') {
  645. // quoted-string
  646. ++paramLast;
  647. for(; paramLast != eoi && *paramLast != '"'; ++paramLast);
  648. if(paramLast != eoi) {
  649. ++paramLast;
  650. }
  651. param = std::string(paramFirst, paramLast);
  652. for(; paramLast != eoi && *paramLast != ';'; ++paramLast);
  653. } else {
  654. param = std::string(paramFirst, paramLast);
  655. }
  656. }
  657. trimSelf(param);
  658. *out++ = param;
  659. if(paramLast == eoi) {
  660. break;
  661. }
  662. i = paramLast;
  663. ++i;
  664. }
  665. }
  666. std::string getContentDispositionFilename(const std::string& header)
  667. {
  668. std::string filename;
  669. std::vector<std::string> params;
  670. parseParam(std::back_inserter(params), header);
  671. for(std::vector<std::string>::const_iterator i = params.begin(),
  672. eoi = params.end(); i != eoi; ++i) {
  673. const std::string& param = *i;
  674. static const std::string keyName = "filename";
  675. if(!startsWith(toLower(param), keyName) || param.size() == keyName.size()) {
  676. continue;
  677. }
  678. std::string::const_iterator markeritr = param.begin()+keyName.size();
  679. if(*markeritr == '*') {
  680. // See RFC2231 Section4 and draft-reschke-rfc2231-in-http.
  681. // Please note that this function doesn't do charset conversion
  682. // except that if iso-8859-1 is specified, it is converted to
  683. // utf-8.
  684. ++markeritr;
  685. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  686. if(markeritr == param.end() || *markeritr != '=') {
  687. continue;
  688. }
  689. std::pair<std::string, std::string> paramPair;
  690. split(paramPair, param, '=');
  691. std::string value = paramPair.second;
  692. std::vector<std::string> extValues;
  693. split(value, std::back_inserter(extValues), "'", false, true);
  694. if(extValues.size() != 3) {
  695. continue;
  696. }
  697. bool bad = false;
  698. const std::string& charset = extValues[0];
  699. for(std::string::const_iterator j = charset.begin(), eoi = charset.end();
  700. j != eoi; ++j) {
  701. // Since we first split parameter by ', we can safely assume
  702. // that ' is not included in charset.
  703. if(!inRFC2978MIMECharset(*j)) {
  704. bad = true;
  705. break;
  706. }
  707. }
  708. if(bad) {
  709. continue;
  710. }
  711. bad = false;
  712. value = extValues[2];
  713. for(std::string::const_iterator j = value.begin(), eoi = value.end();
  714. j != eoi; ++j){
  715. if(*j == '%') {
  716. if(j+1 != value.end() && isHexDigit(*(j+1)) &&
  717. j+2 != value.end() && isHexDigit(*(j+2))) {
  718. j += 2;
  719. } else {
  720. bad = true;
  721. break;
  722. }
  723. } else {
  724. if(*j == '*' || *j == '\'' || !inRFC2616HttpToken(*j)) {
  725. bad = true;
  726. break;
  727. }
  728. }
  729. }
  730. if(bad) {
  731. continue;
  732. }
  733. value = percentDecode(value);
  734. if(toLower(extValues[0]) == "iso-8859-1") {
  735. value = iso8859ToUtf8(value);
  736. }
  737. if(!detectDirTraversal(value) &&
  738. value.find(A2STR::SLASH_C) == std::string::npos) {
  739. filename = value;
  740. }
  741. if(!filename.empty()) {
  742. break;
  743. }
  744. } else {
  745. for(; markeritr != param.end() && *markeritr == ' '; ++markeritr);
  746. if(markeritr == param.end() || *markeritr != '=') {
  747. continue;
  748. }
  749. std::pair<std::string, std::string> paramPair;
  750. split(paramPair, param, '=');
  751. std::string value = paramPair.second;
  752. if(value.empty()) {
  753. continue;
  754. }
  755. std::string::iterator filenameLast;
  756. if(*value.begin() == '\'' || *value.begin() == '"') {
  757. char qc = *value.begin();
  758. for(filenameLast = value.begin()+1;
  759. filenameLast != value.end() && *filenameLast != qc;
  760. ++filenameLast);
  761. } else {
  762. filenameLast = value.end();
  763. }
  764. static const std::string TRIMMED("\r\n\t '\"");
  765. value = percentDecode(std::string(value.begin(), filenameLast));
  766. trimSelf(value, TRIMMED);
  767. value.erase(std::remove(value.begin(), value.end(), '\\'), value.end());
  768. if(!detectDirTraversal(value) &&
  769. value.find(A2STR::SLASH_C) == std::string::npos) {
  770. filename = value;
  771. }
  772. // continue because there is a chance we can find filename*=...
  773. }
  774. }
  775. return filename;
  776. }
  777. std::string randomAlpha(size_t length, const RandomizerHandle& randomizer) {
  778. static const char *random_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  779. std::string str;
  780. for(size_t i = 0; i < length; ++i) {
  781. size_t index = randomizer->getRandomNumber(strlen(random_chars));
  782. str += random_chars[index];
  783. }
  784. return str;
  785. }
  786. std::string toUpper(const std::string& src) {
  787. std::string temp = src;
  788. std::transform(temp.begin(), temp.end(), temp.begin(), ::toupper);
  789. return temp;
  790. }
  791. std::string toLower(const std::string& src) {
  792. std::string temp = src;
  793. std::transform(temp.begin(), temp.end(), temp.begin(), ::tolower);
  794. return temp;
  795. }
  796. bool isNumericHost(const std::string& name)
  797. {
  798. struct addrinfo hints;
  799. struct addrinfo* res;
  800. memset(&hints, 0, sizeof(hints));
  801. hints.ai_family = AF_UNSPEC;
  802. hints.ai_flags = AI_NUMERICHOST;
  803. if(getaddrinfo(name.c_str(), 0, &hints, &res)) {
  804. return false;
  805. }
  806. freeaddrinfo(res);
  807. return true;
  808. }
  809. void setGlobalSignalHandler(int sig, void (*handler)(int), int flags) {
  810. #ifdef HAVE_SIGACTION
  811. struct sigaction sigact;
  812. sigact.sa_handler = handler;
  813. sigact.sa_flags = flags;
  814. sigemptyset(&sigact.sa_mask);
  815. sigaction(sig, &sigact, NULL);
  816. #else
  817. signal(sig, handler);
  818. #endif // HAVE_SIGACTION
  819. }
  820. std::string getHomeDir()
  821. {
  822. const char* p = getenv("HOME");
  823. if(p) {
  824. return p;
  825. } else {
  826. return A2STR::NIL;
  827. }
  828. }
  829. int64_t getRealSize(const std::string& sizeWithUnit)
  830. {
  831. std::string::size_type p = sizeWithUnit.find_first_of("KM");
  832. std::string size;
  833. int32_t mult = 1;
  834. if(p == std::string::npos) {
  835. size = sizeWithUnit;
  836. } else {
  837. if(sizeWithUnit[p] == 'K') {
  838. mult = 1024;
  839. } else if(sizeWithUnit[p] == 'M') {
  840. mult = 1024*1024;
  841. }
  842. size = sizeWithUnit.substr(0, p);
  843. }
  844. int64_t v = parseLLInt(size);
  845. if(v < 0) {
  846. throw DL_ABORT_EX
  847. (StringFormat("Negative value detected: %s", sizeWithUnit.c_str()).str());
  848. } else if(INT64_MAX/mult < v) {
  849. throw DL_ABORT_EX(StringFormat(MSG_STRING_INTEGER_CONVERSION_FAILURE,
  850. "overflow/underflow").str());
  851. }
  852. return v*mult;
  853. }
  854. std::string abbrevSize(int64_t size)
  855. {
  856. if(size < 1024) {
  857. return itos(size, true);
  858. }
  859. char units[] = { 'K', 'M' };
  860. size_t numUnit = sizeof(units)/sizeof(char);
  861. size_t i = 0;
  862. int r = size&0x3ff;
  863. size >>= 10;
  864. for(; i < numUnit-1 && size >= 1024; ++i) {
  865. r = size&0x3ff;
  866. size >>= 10;
  867. }
  868. std::string result = itos(size, true);
  869. result += A2STR::DOT_C;
  870. result += itos(r*10/1024);
  871. result += units[i];
  872. result += "i";
  873. return result;
  874. }
  875. void sleep(long seconds) {
  876. #ifdef HAVE_SLEEP
  877. ::sleep(seconds);
  878. #elif defined(HAVE_USLEEP)
  879. ::usleep(seconds * 1000000);
  880. #elif defined(HAVE_WINSOCK2_H)
  881. ::Sleep(seconds * 1000);
  882. #else
  883. #error no sleep function is available (nanosleep?)
  884. #endif
  885. }
  886. void usleep(long microseconds) {
  887. #ifdef HAVE_USLEEP
  888. ::usleep(microseconds);
  889. #elif defined(HAVE_WINSOCK2_H)
  890. LARGE_INTEGER current, freq, end;
  891. static enum {GET_FREQUENCY, GET_MICROSECONDS, SKIP_MICROSECONDS} state = GET_FREQUENCY;
  892. if (state == GET_FREQUENCY) {
  893. if (QueryPerformanceFrequency(&freq))
  894. state = GET_MICROSECONDS;
  895. else
  896. state = SKIP_MICROSECONDS;
  897. }
  898. long msec = microseconds / 1000;
  899. microseconds %= 1000;
  900. if (state == GET_MICROSECONDS && microseconds) {
  901. QueryPerformanceCounter(&end);
  902. end.QuadPart += (freq.QuadPart * microseconds) / 1000000;
  903. while (QueryPerformanceCounter(&current) && (current.QuadPart <= end.QuadPart))
  904. /* noop */ ;
  905. }
  906. if (msec)
  907. Sleep(msec);
  908. #else
  909. #error no usleep function is available (nanosleep?)
  910. #endif
  911. }
  912. bool isNumber(const std::string& what)
  913. {
  914. if(what.empty()) {
  915. return false;
  916. }
  917. for(std::string::const_iterator i = what.begin(), eoi = what.end();
  918. i != eoi; ++i) {
  919. if(!isDigit(*i)) {
  920. return false;
  921. }
  922. }
  923. return true;
  924. }
  925. bool isLowercase(const std::string& what)
  926. {
  927. if(what.empty()) {
  928. return false;
  929. }
  930. for(uint32_t i = 0; i < what.size(); ++i) {
  931. if(!('a' <= what[i] && what[i] <= 'z')) {
  932. return false;
  933. }
  934. }
  935. return true;
  936. }
  937. bool isUppercase(const std::string& what)
  938. {
  939. if(what.empty()) {
  940. return false;
  941. }
  942. for(uint32_t i = 0; i < what.size(); ++i) {
  943. if(!('A' <= what[i] && what[i] <= 'Z')) {
  944. return false;
  945. }
  946. }
  947. return true;
  948. }
  949. unsigned int alphaToNum(const std::string& alphabets)
  950. {
  951. if(alphabets.empty()) {
  952. return 0;
  953. }
  954. char base;
  955. if(islower(alphabets[0])) {
  956. base = 'a';
  957. } else {
  958. base = 'A';
  959. }
  960. uint64_t num = 0;
  961. for(size_t i = 0; i < alphabets.size(); ++i) {
  962. unsigned int v = alphabets[i]-base;
  963. num = num*26+v;
  964. if(num > UINT32_MAX) {
  965. return 0;
  966. }
  967. }
  968. return num;
  969. }
  970. void mkdirs(const std::string& dirpath)
  971. {
  972. File dir(dirpath);
  973. if(dir.isDir()) {
  974. // do nothing
  975. } else if(dir.exists()) {
  976. throw DL_ABORT_EX
  977. (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
  978. "File already exists.").str());
  979. } else if(!dir.mkdirs()) {
  980. throw DL_ABORT_EX
  981. (StringFormat(EX_MAKE_DIR, dir.getPath().c_str(),
  982. strerror(errno)).str());
  983. }
  984. }
  985. void convertBitfield(BitfieldMan* dest, const BitfieldMan* src)
  986. {
  987. size_t numBlock = dest->countBlock();
  988. for(size_t index = 0; index < numBlock; ++index) {
  989. if(src->isBitSetOffsetRange((uint64_t)index*dest->getBlockLength(),
  990. dest->getBlockLength())) {
  991. dest->setBit(index);
  992. }
  993. }
  994. }
  995. std::string toString(const BinaryStreamHandle& binaryStream)
  996. {
  997. std::stringstream strm;
  998. char data[2048];
  999. while(1) {
  1000. int32_t dataLength = binaryStream->readData
  1001. (reinterpret_cast<unsigned char*>(data), sizeof(data), strm.tellp());
  1002. strm.write(data, dataLength);
  1003. if(dataLength == 0) {
  1004. break;
  1005. }
  1006. }
  1007. return strm.str();
  1008. }
  1009. #ifdef HAVE_POSIX_MEMALIGN
  1010. /**
  1011. * In linux 2.6, alignment and size should be a multiple of 512.
  1012. */
  1013. void* allocateAlignedMemory(size_t alignment, size_t size)
  1014. {
  1015. void* buffer;
  1016. int res;
  1017. if((res = posix_memalign(&buffer, alignment, size)) != 0) {
  1018. throw FATAL_EXCEPTION
  1019. (StringFormat("Error in posix_memalign: %s", strerror(res)).str());
  1020. }
  1021. return buffer;
  1022. }
  1023. #endif // HAVE_POSIX_MEMALIGN
  1024. std::pair<std::string, uint16_t>
  1025. getNumericNameInfo(const struct sockaddr* sockaddr, socklen_t len)
  1026. {
  1027. char host[NI_MAXHOST];
  1028. char service[NI_MAXSERV];
  1029. int s = getnameinfo(sockaddr, len, host, NI_MAXHOST, service, NI_MAXSERV,
  1030. NI_NUMERICHOST|NI_NUMERICSERV);
  1031. if(s != 0) {
  1032. throw DL_ABORT_EX(StringFormat("Failed to get hostname and port. cause: %s",
  1033. gai_strerror(s)).str());
  1034. }
  1035. return std::pair<std::string, uint16_t>(host, atoi(service)); // TODO
  1036. }
  1037. std::string htmlEscape(const std::string& src)
  1038. {
  1039. std::string dest;
  1040. for(std::string::const_iterator i = src.begin(), eoi = src.end();
  1041. i != eoi; ++i) {
  1042. char ch = *i;
  1043. if(ch == '<') {
  1044. dest += "&lt;";
  1045. } else if(ch == '>') {
  1046. dest += "&gt;";
  1047. } else if(ch == '&') {
  1048. dest += "&amp;";
  1049. } else if(ch == '\'') {
  1050. dest += "&#39;";
  1051. } else if(ch == '"') {
  1052. dest += "&quot;";
  1053. } else {
  1054. dest += ch;
  1055. }
  1056. }
  1057. return dest;
  1058. }
  1059. std::map<size_t, std::string>::value_type
  1060. parseIndexPath(const std::string& line)
  1061. {
  1062. std::pair<std::string, std::string> p = split(line, "=");
  1063. size_t index = parseUInt(p.first);
  1064. if(p.second.empty()) {
  1065. throw DL_ABORT_EX(StringFormat("Path with index=%u is empty.",
  1066. static_cast<unsigned int>(index)).str());
  1067. }
  1068. return std::map<size_t, std::string>::value_type(index, p.second);
  1069. }
  1070. std::map<size_t, std::string> createIndexPathMap(std::istream& i)
  1071. {
  1072. std::map<size_t, std::string> indexPathMap;
  1073. std::string line;
  1074. while(getline(i, line)) {
  1075. indexPathMap.insert(indexPathMap.begin(), parseIndexPath(line));
  1076. }
  1077. return indexPathMap;
  1078. }
  1079. void generateRandomData(unsigned char* data, size_t length)
  1080. {
  1081. #ifdef HAVE_LIBGCRYPT
  1082. gcry_randomize(data, length, GCRY_STRONG_RANDOM);
  1083. #elif HAVE_LIBSSL
  1084. if(RAND_bytes(data, length) != 1) {
  1085. for(size_t i = 0; i < length; ++i) {
  1086. data[i] = SimpleRandomizer::getInstance()->getRandomNumber(UINT8_MAX+1);
  1087. }
  1088. }
  1089. #else
  1090. std::ifstream i("/dev/urandom", std::ios::binary);
  1091. i.read(reinterpret_cast<char*>(data), length);
  1092. #endif // HAVE_LIBSSL
  1093. }
  1094. bool saveAs
  1095. (const std::string& filename, const std::string& data, bool overwrite)
  1096. {
  1097. if(!overwrite && File(filename).exists()) {
  1098. return false;
  1099. }
  1100. std::string tempFilename = strconcat(filename, "__temp");
  1101. {
  1102. std::ofstream out(tempFilename.c_str(), std::ios::binary);
  1103. if(!out) {
  1104. return false;
  1105. }
  1106. out << data;
  1107. out.flush();
  1108. if(!out) {
  1109. return false;
  1110. }
  1111. }
  1112. return File(tempFilename).renameTo(filename);
  1113. }
  1114. std::string applyDir(const std::string& dir, const std::string& relPath)
  1115. {
  1116. if(dir.empty()) {
  1117. return strconcat(A2STR::DOT_C, A2STR::SLASH_C, relPath);
  1118. } else if(dir == A2STR::SLASH_C) {
  1119. return strconcat(A2STR::SLASH_C, relPath);
  1120. } else {
  1121. return strconcat(dir, A2STR::SLASH_C, relPath);
  1122. }
  1123. }
  1124. std::string fixTaintedBasename(const std::string& src)
  1125. {
  1126. return escapePath(replace(src, A2STR::SLASH_C, A2STR::UNDERSCORE_C));
  1127. }
  1128. void generateRandomKey(unsigned char* key)
  1129. {
  1130. #ifdef ENABLE_MESSAGE_DIGEST
  1131. unsigned char bytes[40];
  1132. generateRandomData(bytes, sizeof(bytes));
  1133. MessageDigestHelper::digest
  1134. (key, 20, MessageDigestContext::SHA1, bytes, sizeof(bytes));
  1135. #else // !ENABLE_MESSAGE_DIGEST
  1136. generateRandomData(key, 20);
  1137. #endif // !ENABLE_MESSAGE_DIGEST
  1138. }
  1139. // Returns true is given numeric ipv4addr is in Private Address Space.
  1140. //
  1141. // From Section.3 RFC1918
  1142. // 10.0.0.0 - 10.255.255.255 (10/8 prefix)
  1143. // 172.16.0.0 - 172.31.255.255 (172.16/12 prefix)
  1144. // 192.168.0.0 - 192.168.255.255 (192.168/16 prefix)
  1145. bool inPrivateAddress(const std::string& ipv4addr)
  1146. {
  1147. if(util::startsWith(ipv4addr, "10.") ||
  1148. util::startsWith(ipv4addr, "192.168.")) {
  1149. return true;
  1150. }
  1151. if(util::startsWith(ipv4addr, "172.")) {
  1152. for(int i = 16; i <= 31; ++i) {
  1153. if(util::startsWith(ipv4addr, "172."+util::itos(i)+".")) {
  1154. return true;
  1155. }
  1156. }
  1157. }
  1158. return false;
  1159. }
  1160. bool detectDirTraversal(const std::string& s)
  1161. {
  1162. for(std::string::const_iterator i = s.begin(), eoi = s.end(); i != eoi; ++i) {
  1163. if(0x00 <= (*i) && (*i) <= 0x1f) {
  1164. return true;
  1165. }
  1166. }
  1167. return s == A2STR::DOT_C ||
  1168. s == ".." ||
  1169. util::startsWith(s, A2STR::SLASH_C) ||
  1170. util::startsWith(s, "./") ||
  1171. util::startsWith(s, "../") ||
  1172. s.find("/../") != std::string::npos ||
  1173. s.find("/./") != std::string::npos ||
  1174. util::endsWith(s, "/") ||
  1175. util::endsWith(s, "/.") ||
  1176. util::endsWith(s, "/..");
  1177. }
  1178. namespace {
  1179. class EscapePath {
  1180. private:
  1181. char _repChar;
  1182. public:
  1183. EscapePath(const char& repChar):_repChar(repChar) {}
  1184. char operator()(const char& c) {
  1185. if(0x00 <= c && c <=0x1f) {
  1186. return _repChar;
  1187. }
  1188. #ifdef __MINGW32__
  1189. // We don't escape '/' because we use it as a path separator.
  1190. static const char WIN_INVALID_PATH_CHARS[] =
  1191. { '"', '*', ':', '<', '>', '?', '\\', '|' };
  1192. if(std::find(vbegin(WIN_INVALID_PATH_CHARS), vend(WIN_INVALID_PATH_CHARS),
  1193. c) != vend(WIN_INVALID_PATH_CHARS)) {
  1194. return _repChar;
  1195. }
  1196. #endif // __MINGW32__
  1197. return c;
  1198. }
  1199. };
  1200. }
  1201. std::string escapePath(const std::string& s)
  1202. {
  1203. std::string d = s;
  1204. std::transform(d.begin(), d.end(), d.begin(), EscapePath('_'));
  1205. return d;
  1206. }
  1207. bool getCidrPrefix(struct in_addr& in, const std::string& ip, int bits)
  1208. {
  1209. struct in_addr t;
  1210. if(inet_aton(ip.c_str(), &t) == 0) {
  1211. return false;
  1212. }
  1213. int lastindex = bits/8;
  1214. if(lastindex < 4) {
  1215. char* p = reinterpret_cast<char*>(&t.s_addr);
  1216. const char* last = p+4;
  1217. p += lastindex;
  1218. if(bits%8 != 0) {
  1219. *p &= bitfield::lastByteMask(bits);
  1220. ++p;
  1221. }
  1222. for(; p != last; ++p) {
  1223. *p &= 0;
  1224. }
  1225. }
  1226. in = t;
  1227. return true;
  1228. }
  1229. bool inSameCidrBlock(const std::string& ip1, const std::string& ip2, int bits)
  1230. {
  1231. struct in_addr in1;
  1232. struct in_addr in2;
  1233. if(!getCidrPrefix(in1, ip1, bits) || !getCidrPrefix(in2, ip2, bits)) {
  1234. return false;
  1235. }
  1236. return in1.s_addr == in2.s_addr;
  1237. }
  1238. void removeMetalinkContentTypes(const SharedHandle<RequestGroup>& group)
  1239. {
  1240. for(std::vector<std::string>::const_iterator i =
  1241. DownloadHandlerConstants::getMetalinkContentTypes().begin(),
  1242. eoi = DownloadHandlerConstants::getMetalinkContentTypes().end();
  1243. i != eoi; ++i) {
  1244. group->removeAcceptType(*i);
  1245. }
  1246. }
  1247. } // namespace util
  1248. } // namespace aria2