rred.cc 17 KB

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