util.cc 37 KB

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