rred.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. // Includes /*{{{*/
  2. #include <config.h>
  3. #include <apt-pkg/fileutl.h>
  4. #include <apt-pkg/mmap.h>
  5. #include <apt-pkg/error.h>
  6. #include <apt-pkg/acquire-method.h>
  7. #include <apt-pkg/strutl.h>
  8. #include <apt-pkg/hashes.h>
  9. #include <apt-pkg/configuration.h>
  10. #include <sys/stat.h>
  11. #include <sys/uio.h>
  12. #include <unistd.h>
  13. #include <utime.h>
  14. #include <stdio.h>
  15. #include <errno.h>
  16. #include <zlib.h>
  17. #include <apti18n.h>
  18. /*}}}*/
  19. /** \brief RredMethod - ed-style incremential patch method {{{
  20. *
  21. * This method implements a patch functionality similar to "patch --ed" that is
  22. * used by the "tiffany" incremental packages download stuff. It differs from
  23. * "ed" insofar that it is way more restricted (and therefore secure).
  24. * The currently supported ed commands are "<em>c</em>hange", "<em>a</em>dd" and
  25. * "<em>d</em>elete" (diff doesn't output any other).
  26. * Additionally the records must be reverse sorted by line number and
  27. * may not overlap (diff *seems* to produce this kind of output).
  28. * */
  29. class RredMethod : public pkgAcqMethod {
  30. bool Debug;
  31. // the size of this doesn't really matter (except for performance)
  32. const static int BUF_SIZE = 1024;
  33. // the supported ed commands
  34. enum Mode {MODE_CHANGED='c', MODE_DELETED='d', MODE_ADDED='a'};
  35. // return values
  36. enum State {ED_OK, ED_ORDERING, ED_PARSER, ED_FAILURE, MMAP_FAILED};
  37. State applyFile(gzFile &ed_cmds, FILE *in_file, FILE *out_file,
  38. unsigned long &line, char *buffer, Hashes *hash) const;
  39. void ignoreLineInFile(FILE *fin, char *buffer) const;
  40. void ignoreLineInFile(gzFile &fin, char *buffer) const;
  41. void copyLinesFromFileToFile(FILE *fin, FILE *fout, unsigned int lines,
  42. Hashes *hash, char *buffer) const;
  43. void copyLinesFromFileToFile(gzFile &fin, FILE *fout, unsigned int lines,
  44. Hashes *hash, char *buffer) const;
  45. State patchFile(FileFd &Patch, FileFd &From, FileFd &out_file, Hashes *hash) const;
  46. State patchMMap(FileFd &Patch, FileFd &From, FileFd &out_file, Hashes *hash) const;
  47. protected:
  48. // the methods main method
  49. virtual bool Fetch(FetchItem *Itm);
  50. public:
  51. RredMethod() : pkgAcqMethod("1.1",SingleInstance | SendConfig), Debug(false) {};
  52. };
  53. /*}}}*/
  54. /** \brief applyFile - in reverse order with a tail recursion {{{
  55. *
  56. * As it is expected that the commands are in reversed order in the patch file
  57. * we check in the first half if the command is valid, but doesn't execute it
  58. * and move a step deeper. After reaching the end of the file we apply the
  59. * patches in the correct order: last found command first.
  60. *
  61. * \param ed_cmds patch file to apply
  62. * \param in_file base file we want to patch
  63. * \param out_file file to write the patched result to
  64. * \param line of command operation
  65. * \param buffer internal used read/write buffer
  66. * \param hash the created file for correctness
  67. * \return the success State of the ed command executor
  68. */
  69. RredMethod::State RredMethod::applyFile(gzFile &ed_cmds, FILE *in_file, FILE *out_file,
  70. unsigned long &line, char *buffer, Hashes *hash) const {
  71. // get the current command and parse it
  72. if (gzgets(ed_cmds, buffer, BUF_SIZE) == NULL) {
  73. if (Debug == true)
  74. std::clog << "rred: encounter end of file - we can start patching now." << std::endl;
  75. line = 0;
  76. return ED_OK;
  77. }
  78. // parse in the effected linenumbers
  79. char* idx;
  80. errno=0;
  81. unsigned long const startline = strtol(buffer, &idx, 10);
  82. if (errno == ERANGE || errno == EINVAL) {
  83. _error->Errno("rred", "startline is an invalid number");
  84. return ED_PARSER;
  85. }
  86. if (startline > line) {
  87. _error->Error("rred: The start line (%lu) of the next command is higher than the last line (%lu). This is not allowed.", startline, line);
  88. return ED_ORDERING;
  89. }
  90. unsigned long stopline;
  91. if (*idx == ',') {
  92. idx++;
  93. errno=0;
  94. stopline = strtol(idx, &idx, 10);
  95. if (errno == ERANGE || errno == EINVAL) {
  96. _error->Errno("rred", "stopline is an invalid number");
  97. return ED_PARSER;
  98. }
  99. }
  100. else {
  101. stopline = startline;
  102. }
  103. line = startline;
  104. // which command to execute on this line(s)?
  105. switch (*idx) {
  106. case MODE_CHANGED:
  107. if (Debug == true)
  108. std::clog << "Change from line " << startline << " to " << stopline << std::endl;
  109. break;
  110. case MODE_ADDED:
  111. if (Debug == true)
  112. std::clog << "Insert after line " << startline << std::endl;
  113. break;
  114. case MODE_DELETED:
  115. if (Debug == true)
  116. std::clog << "Delete from line " << startline << " to " << stopline << std::endl;
  117. break;
  118. default:
  119. _error->Error("rred: Unknown ed command '%c'. Abort.", *idx);
  120. return ED_PARSER;
  121. }
  122. unsigned char mode = *idx;
  123. // save the current position
  124. unsigned const long pos = gztell(ed_cmds);
  125. // if this is add or change then go to the next full stop
  126. unsigned int data_length = 0;
  127. if (mode == MODE_CHANGED || mode == MODE_ADDED) {
  128. do {
  129. ignoreLineInFile(ed_cmds, buffer);
  130. data_length++;
  131. }
  132. while (strncmp(buffer, ".", 1) != 0);
  133. data_length--; // the dot should not be copied
  134. }
  135. // do the recursive call - the last command is the one we need to execute at first
  136. const State child = applyFile(ed_cmds, in_file, out_file, line, buffer, hash);
  137. if (child != ED_OK) {
  138. return child;
  139. }
  140. // change and delete are working on "line" - add is done after "line"
  141. if (mode != MODE_ADDED)
  142. line++;
  143. // first wind to the current position and copy over all unchanged lines
  144. if (line < startline) {
  145. copyLinesFromFileToFile(in_file, out_file, (startline - line), hash, buffer);
  146. line = startline;
  147. }
  148. if (mode != MODE_ADDED)
  149. line--;
  150. // include data from ed script
  151. if (mode == MODE_CHANGED || mode == MODE_ADDED) {
  152. gzseek(ed_cmds, pos, SEEK_SET);
  153. copyLinesFromFileToFile(ed_cmds, out_file, data_length, hash, buffer);
  154. }
  155. // ignore the corresponding number of lines from input
  156. if (mode == MODE_CHANGED || mode == MODE_DELETED) {
  157. while (line < stopline) {
  158. ignoreLineInFile(in_file, buffer);
  159. line++;
  160. }
  161. }
  162. return ED_OK;
  163. }
  164. /*}}}*/
  165. void RredMethod::copyLinesFromFileToFile(FILE *fin, FILE *fout, unsigned int lines,/*{{{*/
  166. Hashes *hash, char *buffer) const {
  167. while (0 < lines--) {
  168. do {
  169. fgets(buffer, BUF_SIZE, fin);
  170. size_t const written = fwrite(buffer, 1, strlen(buffer), fout);
  171. hash->Add((unsigned char*)buffer, written);
  172. } while (strlen(buffer) == (BUF_SIZE - 1) &&
  173. buffer[BUF_SIZE - 2] != '\n');
  174. }
  175. }
  176. /*}}}*/
  177. void RredMethod::copyLinesFromFileToFile(gzFile &fin, FILE *fout, unsigned int lines,/*{{{*/
  178. Hashes *hash, char *buffer) const {
  179. while (0 < lines--) {
  180. do {
  181. gzgets(fin, buffer, BUF_SIZE);
  182. size_t const written = fwrite(buffer, 1, strlen(buffer), fout);
  183. hash->Add((unsigned char*)buffer, written);
  184. } while (strlen(buffer) == (BUF_SIZE - 1) &&
  185. buffer[BUF_SIZE - 2] != '\n');
  186. }
  187. }
  188. /*}}}*/
  189. void RredMethod::ignoreLineInFile(FILE *fin, char *buffer) const { /*{{{*/
  190. fgets(buffer, BUF_SIZE, fin);
  191. while (strlen(buffer) == (BUF_SIZE - 1) &&
  192. buffer[BUF_SIZE - 2] != '\n') {
  193. fgets(buffer, BUF_SIZE, fin);
  194. buffer[0] = ' ';
  195. }
  196. }
  197. /*}}}*/
  198. void RredMethod::ignoreLineInFile(gzFile &fin, char *buffer) const { /*{{{*/
  199. gzgets(fin, buffer, BUF_SIZE);
  200. while (strlen(buffer) == (BUF_SIZE - 1) &&
  201. buffer[BUF_SIZE - 2] != '\n') {
  202. gzgets(fin, buffer, BUF_SIZE);
  203. buffer[0] = ' ';
  204. }
  205. }
  206. /*}}}*/
  207. RredMethod::State RredMethod::patchFile(FileFd &Patch, FileFd &From, /*{{{*/
  208. FileFd &out_file, Hashes *hash) const {
  209. char buffer[BUF_SIZE];
  210. FILE* fFrom = fdopen(From.Fd(), "r");
  211. gzFile fPatch = Patch.gzFd();
  212. FILE* fTo = fdopen(out_file.Fd(), "w");
  213. /* we do a tail recursion to read the commands in the right order */
  214. unsigned long line = -1; // assign highest possible value
  215. State const result = applyFile(fPatch, fFrom, fTo, line, buffer, hash);
  216. /* read the rest from infile */
  217. if (result == ED_OK) {
  218. while (fgets(buffer, BUF_SIZE, fFrom) != NULL) {
  219. size_t const written = fwrite(buffer, 1, strlen(buffer), fTo);
  220. hash->Add((unsigned char*)buffer, written);
  221. }
  222. fflush(fTo);
  223. }
  224. return result;
  225. }
  226. /*}}}*/
  227. /* struct EdCommand {{{*/
  228. #ifdef _POSIX_MAPPED_FILES
  229. struct EdCommand {
  230. size_t data_start;
  231. size_t data_end;
  232. size_t data_lines;
  233. size_t first_line;
  234. size_t last_line;
  235. char type;
  236. };
  237. #define IOV_COUNT 1024 /* Don't really want IOV_MAX since it can be arbitrarily large */
  238. #endif
  239. /*}}}*/
  240. RredMethod::State RredMethod::patchMMap(FileFd &Patch, FileFd &From, /*{{{*/
  241. FileFd &out_file, Hashes *hash) const {
  242. #ifdef _POSIX_MAPPED_FILES
  243. MMap ed_cmds(MMap::ReadOnly);
  244. if (Patch.gzFd() != NULL) {
  245. unsigned long long mapSize = Patch.Size();
  246. DynamicMMap* dyn = new DynamicMMap(0, mapSize, 0);
  247. if (dyn->validData() == false) {
  248. delete dyn;
  249. return MMAP_FAILED;
  250. }
  251. dyn->AddSize(mapSize);
  252. gzread(Patch.gzFd(), dyn->Data(), mapSize);
  253. ed_cmds = *dyn;
  254. } else
  255. ed_cmds = MMap(Patch, MMap::ReadOnly);
  256. MMap in_file(From, MMap::ReadOnly);
  257. if (ed_cmds.Size() == 0 || in_file.Size() == 0)
  258. return MMAP_FAILED;
  259. EdCommand* commands = 0;
  260. size_t command_count = 0;
  261. size_t command_alloc = 0;
  262. const char* begin = (char*) ed_cmds.Data();
  263. const char* end = begin;
  264. const char* ed_end = (char*) ed_cmds.Data() + ed_cmds.Size();
  265. const char* input = (char*) in_file.Data();
  266. const char* input_end = (char*) in_file.Data() + in_file.Size();
  267. size_t i;
  268. /* 1. Parse entire script. It is executed in reverse order, so we cather it
  269. * in the `commands' buffer first
  270. */
  271. for(;;) {
  272. EdCommand cmd;
  273. cmd.data_start = 0;
  274. cmd.data_end = 0;
  275. while(begin != ed_end && *begin == '\n')
  276. ++begin;
  277. while(end != ed_end && *end != '\n')
  278. ++end;
  279. if(end == ed_end && begin == end)
  280. break;
  281. /* Determine command range */
  282. const char* tmp = begin;
  283. for(;;) {
  284. /* atoll is safe despite lacking NUL-termination; we know there's an
  285. * alphabetic character at end[-1]
  286. */
  287. if(tmp == end) {
  288. cmd.first_line = atol(begin);
  289. cmd.last_line = cmd.first_line;
  290. break;
  291. }
  292. if(*tmp == ',') {
  293. cmd.first_line = atol(begin);
  294. cmd.last_line = atol(tmp + 1);
  295. break;
  296. }
  297. ++tmp;
  298. }
  299. // which command to execute on this line(s)?
  300. switch (end[-1]) {
  301. case MODE_CHANGED:
  302. if (Debug == true)
  303. std::clog << "Change from line " << cmd.first_line << " to " << cmd.last_line << std::endl;
  304. break;
  305. case MODE_ADDED:
  306. if (Debug == true)
  307. std::clog << "Insert after line " << cmd.first_line << std::endl;
  308. break;
  309. case MODE_DELETED:
  310. if (Debug == true)
  311. std::clog << "Delete from line " << cmd.first_line << " to " << cmd.last_line << std::endl;
  312. break;
  313. default:
  314. _error->Error("rred: Unknown ed command '%c'. Abort.", end[-1]);
  315. free(commands);
  316. return ED_PARSER;
  317. }
  318. cmd.type = end[-1];
  319. /* Determine the size of the inserted text, so we don't have to scan this
  320. * text again later.
  321. */
  322. begin = end + 1;
  323. end = begin;
  324. cmd.data_lines = 0;
  325. if(cmd.type == MODE_ADDED || cmd.type == MODE_CHANGED) {
  326. cmd.data_start = begin - (char*) ed_cmds.Data();
  327. while(end != ed_end) {
  328. if(*end == '\n') {
  329. if(end[-1] == '.' && end[-2] == '\n')
  330. break;
  331. ++cmd.data_lines;
  332. }
  333. ++end;
  334. }
  335. cmd.data_end = end - (char*) ed_cmds.Data() - 1;
  336. begin = end + 1;
  337. end = begin;
  338. }
  339. if(command_count == command_alloc) {
  340. command_alloc = (command_alloc + 64) * 3 / 2;
  341. commands = (EdCommand*) realloc(commands, command_alloc * sizeof(EdCommand));
  342. }
  343. commands[command_count++] = cmd;
  344. }
  345. struct iovec* iov = new struct iovec[IOV_COUNT];
  346. size_t iov_size = 0;
  347. size_t amount, remaining;
  348. size_t line = 1;
  349. EdCommand* cmd;
  350. /* 2. Execute script. We gather writes in a `struct iov' array, and flush
  351. * using writev to minimize the number of system calls. Data is read
  352. * directly from the memory mappings of the input file and the script.
  353. */
  354. for(i = command_count; i-- > 0; ) {
  355. cmd = &commands[i];
  356. if(cmd->type == MODE_ADDED)
  357. amount = cmd->first_line + 1;
  358. else
  359. amount = cmd->first_line;
  360. if(line < amount) {
  361. begin = input;
  362. while(line != amount) {
  363. input = (const char*) memchr(input, '\n', input_end - input);
  364. if(!input)
  365. break;
  366. ++line;
  367. ++input;
  368. }
  369. iov[iov_size].iov_base = (void*) begin;
  370. iov[iov_size].iov_len = input - begin;
  371. hash->Add((const unsigned char*) begin, input - begin);
  372. if(++iov_size == IOV_COUNT) {
  373. writev(out_file.Fd(), iov, IOV_COUNT);
  374. iov_size = 0;
  375. }
  376. }
  377. if(cmd->type == MODE_DELETED || cmd->type == MODE_CHANGED) {
  378. remaining = (cmd->last_line - cmd->first_line) + 1;
  379. line += remaining;
  380. while(remaining) {
  381. input = (const char*) memchr(input, '\n', input_end - input);
  382. if(!input)
  383. break;
  384. --remaining;
  385. ++input;
  386. }
  387. }
  388. if(cmd->type == MODE_CHANGED || cmd->type == MODE_ADDED) {
  389. if(cmd->data_end != cmd->data_start) {
  390. iov[iov_size].iov_base = (void*) ((char*)ed_cmds.Data() + cmd->data_start);
  391. iov[iov_size].iov_len = cmd->data_end - cmd->data_start;
  392. hash->Add((const unsigned char*) ((char*)ed_cmds.Data() + cmd->data_start),
  393. iov[iov_size].iov_len);
  394. if(++iov_size == IOV_COUNT) {
  395. writev(out_file.Fd(), iov, IOV_COUNT);
  396. iov_size = 0;
  397. }
  398. }
  399. }
  400. }
  401. if(input != input_end) {
  402. iov[iov_size].iov_base = (void*) input;
  403. iov[iov_size].iov_len = input_end - input;
  404. hash->Add((const unsigned char*) input, input_end - input);
  405. ++iov_size;
  406. }
  407. if(iov_size) {
  408. writev(out_file.Fd(), iov, iov_size);
  409. iov_size = 0;
  410. }
  411. for(i = 0; i < iov_size; i += IOV_COUNT) {
  412. if(iov_size - i < IOV_COUNT)
  413. writev(out_file.Fd(), iov + i, iov_size - i);
  414. else
  415. writev(out_file.Fd(), iov + i, IOV_COUNT);
  416. }
  417. delete [] iov;
  418. free(commands);
  419. return ED_OK;
  420. #else
  421. return MMAP_FAILED;
  422. #endif
  423. }
  424. /*}}}*/
  425. bool RredMethod::Fetch(FetchItem *Itm) /*{{{*/
  426. {
  427. Debug = _config->FindB("Debug::pkgAcquire::RRed", false);
  428. URI Get = Itm->Uri;
  429. std::string Path = Get.Host + Get.Path; // To account for relative paths
  430. FetchResult Res;
  431. Res.Filename = Itm->DestFile;
  432. if (Itm->Uri.empty() == true) {
  433. Path = Itm->DestFile;
  434. Itm->DestFile.append(".result");
  435. } else
  436. URIStart(Res);
  437. if (Debug == true)
  438. std::clog << "Patching " << Path << " with " << Path
  439. << ".ed and putting result into " << Itm->DestFile << std::endl;
  440. // Open the source and destination files (the d'tor of FileFd will do
  441. // the cleanup/closing of the fds)
  442. FileFd From(Path,FileFd::ReadOnly);
  443. FileFd Patch(Path+".ed",FileFd::ReadOnlyGzip);
  444. FileFd To(Itm->DestFile,FileFd::WriteAtomic);
  445. To.EraseOnFailure();
  446. if (_error->PendingError() == true)
  447. return false;
  448. Hashes Hash;
  449. // now do the actual patching
  450. State const result = patchMMap(Patch, From, To, &Hash);
  451. if (result == MMAP_FAILED) {
  452. // retry with patchFile
  453. Patch.Seek(0);
  454. From.Seek(0);
  455. To.Open(Itm->DestFile,FileFd::WriteAtomic);
  456. if (_error->PendingError() == true)
  457. return false;
  458. if (patchFile(Patch, From, To, &Hash) != ED_OK) {
  459. return _error->WarningE("rred", _("Could not patch %s with mmap and with file operation usage - the patch seems to be corrupt."), Path.c_str());
  460. } else if (Debug == true) {
  461. std::clog << "rred: finished file patching of " << Path << " after mmap failed." << std::endl;
  462. }
  463. } else if (result != ED_OK) {
  464. return _error->Errno("rred", _("Could not patch %s with mmap (but no mmap specific fail) - the patch seems to be corrupt."), Path.c_str());
  465. } else if (Debug == true) {
  466. std::clog << "rred: finished mmap patching of " << Path << std::endl;
  467. }
  468. // write out the result
  469. From.Close();
  470. Patch.Close();
  471. To.Close();
  472. /* Transfer the modification times from the patch file
  473. to be able to see in which state the file should be
  474. and use the access time from the "old" file */
  475. struct stat BufBase, BufPatch;
  476. if (stat(Path.c_str(),&BufBase) != 0 ||
  477. stat(std::string(Path+".ed").c_str(),&BufPatch) != 0)
  478. return _error->Errno("stat",_("Failed to stat"));
  479. struct utimbuf TimeBuf;
  480. TimeBuf.actime = BufBase.st_atime;
  481. TimeBuf.modtime = BufPatch.st_mtime;
  482. if (utime(Itm->DestFile.c_str(),&TimeBuf) != 0)
  483. return _error->Errno("utime",_("Failed to set modification time"));
  484. if (stat(Itm->DestFile.c_str(),&BufBase) != 0)
  485. return _error->Errno("stat",_("Failed to stat"));
  486. // return done
  487. Res.LastModified = BufBase.st_mtime;
  488. Res.Size = BufBase.st_size;
  489. Res.TakeHashes(Hash);
  490. URIDone(Res);
  491. return true;
  492. }
  493. /*}}}*/
  494. /** \brief Wrapper class for testing rred */ /*{{{*/
  495. class TestRredMethod : public RredMethod {
  496. public:
  497. /** \brief Run rred in debug test mode
  498. *
  499. * This method can be used to run the rred method outside
  500. * of the "normal" acquire environment for easier testing.
  501. *
  502. * \param base basename of all files involved in this rred test
  503. */
  504. bool Run(char const *base) {
  505. _config->CndSet("Debug::pkgAcquire::RRed", "true");
  506. FetchItem *test = new FetchItem;
  507. test->DestFile = base;
  508. return Fetch(test);
  509. }
  510. };
  511. /*}}}*/
  512. /** \brief Starter for the rred method (or its test method) {{{
  513. *
  514. * Used without parameters is the normal behavior for methods for
  515. * the APT acquire system. While this works great for the acquire system
  516. * it is very hard to test the method and therefore the method also
  517. * accepts one parameter which will switch it directly to debug test mode:
  518. * The test mode expects that if "Testfile" is given as parameter
  519. * the file "Testfile" should be ed-style patched with "Testfile.ed"
  520. * and will write the result to "Testfile.result".
  521. */
  522. int main(int argc, char *argv[]) {
  523. if (argc <= 1) {
  524. RredMethod Mth;
  525. return Mth.Run();
  526. } else {
  527. TestRredMethod Mth;
  528. bool result = Mth.Run(argv[1]);
  529. _error->DumpErrors();
  530. return result;
  531. }
  532. }
  533. /*}}}*/