rred.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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), Debug(false) {};
  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. #ifdef _POSIX_MAPPED_FILES
  227. struct EdCommand {
  228. size_t data_start;
  229. size_t data_end;
  230. size_t data_lines;
  231. size_t first_line;
  232. size_t last_line;
  233. char type;
  234. };
  235. #define IOV_COUNT 1024 /* Don't really want IOV_MAX since it can be arbitrarily large */
  236. #endif
  237. /*}}}*/
  238. RredMethod::State RredMethod::patchMMap(FileFd &Patch, FileFd &From, /*{{{*/
  239. FileFd &out_file, Hashes *hash) const {
  240. #ifdef _POSIX_MAPPED_FILES
  241. MMap ed_cmds(MMap::ReadOnly);
  242. if (Patch.gzFd() != NULL) {
  243. unsigned long mapSize = Patch.Size();
  244. DynamicMMap* dyn = new DynamicMMap(0, mapSize, 0);
  245. if (dyn->validData() == false) {
  246. delete dyn;
  247. return MMAP_FAILED;
  248. }
  249. dyn->AddSize(mapSize);
  250. gzread(Patch.gzFd(), dyn->Data(), mapSize);
  251. ed_cmds = *dyn;
  252. } else
  253. ed_cmds = MMap(Patch, MMap::ReadOnly);
  254. MMap in_file(From, MMap::ReadOnly);
  255. if (ed_cmds.Size() == 0 || in_file.Size() == 0)
  256. return MMAP_FAILED;
  257. EdCommand* commands = 0;
  258. size_t command_count = 0;
  259. size_t command_alloc = 0;
  260. const char* begin = (char*) ed_cmds.Data();
  261. const char* end = begin;
  262. const char* ed_end = (char*) ed_cmds.Data() + ed_cmds.Size();
  263. const char* input = (char*) in_file.Data();
  264. const char* input_end = (char*) in_file.Data() + in_file.Size();
  265. size_t i;
  266. /* 1. Parse entire script. It is executed in reverse order, so we cather it
  267. * in the `commands' buffer first
  268. */
  269. for(;;) {
  270. EdCommand cmd;
  271. cmd.data_start = 0;
  272. cmd.data_end = 0;
  273. while(begin != ed_end && *begin == '\n')
  274. ++begin;
  275. while(end != ed_end && *end != '\n')
  276. ++end;
  277. if(end == ed_end && begin == end)
  278. break;
  279. /* Determine command range */
  280. const char* tmp = begin;
  281. for(;;) {
  282. /* atoll is safe despite lacking NUL-termination; we know there's an
  283. * alphabetic character at end[-1]
  284. */
  285. if(tmp == end) {
  286. cmd.first_line = atol(begin);
  287. cmd.last_line = cmd.first_line;
  288. break;
  289. }
  290. if(*tmp == ',') {
  291. cmd.first_line = atol(begin);
  292. cmd.last_line = atol(tmp + 1);
  293. break;
  294. }
  295. ++tmp;
  296. }
  297. // which command to execute on this line(s)?
  298. switch (end[-1]) {
  299. case MODE_CHANGED:
  300. if (Debug == true)
  301. std::clog << "Change from line " << cmd.first_line << " to " << cmd.last_line << std::endl;
  302. break;
  303. case MODE_ADDED:
  304. if (Debug == true)
  305. std::clog << "Insert after line " << cmd.first_line << std::endl;
  306. break;
  307. case MODE_DELETED:
  308. if (Debug == true)
  309. std::clog << "Delete from line " << cmd.first_line << " to " << cmd.last_line << std::endl;
  310. break;
  311. default:
  312. _error->Error("rred: Unknown ed command '%c'. Abort.", end[-1]);
  313. free(commands);
  314. return ED_PARSER;
  315. }
  316. cmd.type = end[-1];
  317. /* Determine the size of the inserted text, so we don't have to scan this
  318. * text again later.
  319. */
  320. begin = end + 1;
  321. end = begin;
  322. cmd.data_lines = 0;
  323. if(cmd.type == MODE_ADDED || cmd.type == MODE_CHANGED) {
  324. cmd.data_start = begin - (char*) ed_cmds.Data();
  325. while(end != ed_end) {
  326. if(*end == '\n') {
  327. if(end[-1] == '.' && end[-2] == '\n')
  328. break;
  329. ++cmd.data_lines;
  330. }
  331. ++end;
  332. }
  333. cmd.data_end = end - (char*) ed_cmds.Data() - 1;
  334. begin = end + 1;
  335. end = begin;
  336. }
  337. if(command_count == command_alloc) {
  338. command_alloc = (command_alloc + 64) * 3 / 2;
  339. commands = (EdCommand*) realloc(commands, command_alloc * sizeof(EdCommand));
  340. }
  341. commands[command_count++] = cmd;
  342. }
  343. struct iovec* iov = new struct iovec[IOV_COUNT];
  344. size_t iov_size = 0;
  345. size_t amount, remaining;
  346. size_t line = 1;
  347. EdCommand* cmd;
  348. /* 2. Execute script. We gather writes in a `struct iov' array, and flush
  349. * using writev to minimize the number of system calls. Data is read
  350. * directly from the memory mappings of the input file and the script.
  351. */
  352. for(i = command_count; i-- > 0; ) {
  353. cmd = &commands[i];
  354. if(cmd->type == MODE_ADDED)
  355. amount = cmd->first_line + 1;
  356. else
  357. amount = cmd->first_line;
  358. if(line < amount) {
  359. begin = input;
  360. while(line != amount) {
  361. input = (const char*) memchr(input, '\n', input_end - input);
  362. if(!input)
  363. break;
  364. ++line;
  365. ++input;
  366. }
  367. iov[iov_size].iov_base = (void*) begin;
  368. iov[iov_size].iov_len = input - begin;
  369. hash->Add((const unsigned char*) begin, input - begin);
  370. if(++iov_size == IOV_COUNT) {
  371. writev(out_file.Fd(), iov, IOV_COUNT);
  372. iov_size = 0;
  373. }
  374. }
  375. if(cmd->type == MODE_DELETED || cmd->type == MODE_CHANGED) {
  376. remaining = (cmd->last_line - cmd->first_line) + 1;
  377. line += remaining;
  378. while(remaining) {
  379. input = (const char*) memchr(input, '\n', input_end - input);
  380. if(!input)
  381. break;
  382. --remaining;
  383. ++input;
  384. }
  385. }
  386. if(cmd->type == MODE_CHANGED || cmd->type == MODE_ADDED) {
  387. if(cmd->data_end != cmd->data_start) {
  388. iov[iov_size].iov_base = (void*) ((char*)ed_cmds.Data() + cmd->data_start);
  389. iov[iov_size].iov_len = cmd->data_end - cmd->data_start;
  390. hash->Add((const unsigned char*) ((char*)ed_cmds.Data() + cmd->data_start),
  391. iov[iov_size].iov_len);
  392. if(++iov_size == IOV_COUNT) {
  393. writev(out_file.Fd(), iov, IOV_COUNT);
  394. iov_size = 0;
  395. }
  396. }
  397. }
  398. }
  399. if(input != input_end) {
  400. iov[iov_size].iov_base = (void*) input;
  401. iov[iov_size].iov_len = input_end - input;
  402. hash->Add((const unsigned char*) input, input_end - input);
  403. ++iov_size;
  404. }
  405. if(iov_size) {
  406. writev(out_file.Fd(), iov, iov_size);
  407. iov_size = 0;
  408. }
  409. for(i = 0; i < iov_size; i += IOV_COUNT) {
  410. if(iov_size - i < IOV_COUNT)
  411. writev(out_file.Fd(), iov + i, iov_size - i);
  412. else
  413. writev(out_file.Fd(), iov + i, IOV_COUNT);
  414. }
  415. delete [] iov;
  416. free(commands);
  417. return ED_OK;
  418. #else
  419. return MMAP_FAILED;
  420. #endif
  421. }
  422. /*}}}*/
  423. bool RredMethod::Fetch(FetchItem *Itm) /*{{{*/
  424. {
  425. Debug = _config->FindB("Debug::pkgAcquire::RRed", false);
  426. URI Get = Itm->Uri;
  427. string Path = Get.Host + Get.Path; // To account for relative paths
  428. FetchResult Res;
  429. Res.Filename = Itm->DestFile;
  430. if (Itm->Uri.empty() == true) {
  431. Path = Itm->DestFile;
  432. Itm->DestFile.append(".result");
  433. } else
  434. URIStart(Res);
  435. if (Debug == true)
  436. std::clog << "Patching " << Path << " with " << Path
  437. << ".ed and putting result into " << Itm->DestFile << std::endl;
  438. // Open the source and destination files (the d'tor of FileFd will do
  439. // the cleanup/closing of the fds)
  440. FileFd From(Path,FileFd::ReadOnly);
  441. FileFd Patch(Path+".ed",FileFd::ReadOnlyGzip);
  442. FileFd To(Itm->DestFile,FileFd::WriteAtomic);
  443. To.EraseOnFailure();
  444. if (_error->PendingError() == true)
  445. return false;
  446. Hashes Hash;
  447. // now do the actual patching
  448. State const result = patchMMap(Patch, From, To, &Hash);
  449. if (result == MMAP_FAILED) {
  450. // retry with patchFile
  451. Patch.Seek(0);
  452. From.Seek(0);
  453. To.Open(Itm->DestFile,FileFd::WriteAtomic);
  454. if (_error->PendingError() == true)
  455. return false;
  456. if (patchFile(Patch, From, To, &Hash) != ED_OK) {
  457. return _error->WarningE("rred", _("Could not patch %s with mmap and with file operation usage - the patch seems to be corrupt."), Path.c_str());
  458. } else if (Debug == true) {
  459. std::clog << "rred: finished file patching of " << Path << " after mmap failed." << std::endl;
  460. }
  461. } else if (result != ED_OK) {
  462. return _error->Errno("rred", _("Could not patch %s with mmap (but no mmap specific fail) - the patch seems to be corrupt."), Path.c_str());
  463. } else if (Debug == true) {
  464. std::clog << "rred: finished mmap patching of " << Path << std::endl;
  465. }
  466. // write out the result
  467. From.Close();
  468. Patch.Close();
  469. To.Close();
  470. /* Transfer the modification times from the patch file
  471. to be able to see in which state the file should be
  472. and use the access time from the "old" file */
  473. struct stat BufBase, BufPatch;
  474. if (stat(Path.c_str(),&BufBase) != 0 ||
  475. stat(string(Path+".ed").c_str(),&BufPatch) != 0)
  476. return _error->Errno("stat",_("Failed to stat"));
  477. struct utimbuf TimeBuf;
  478. TimeBuf.actime = BufBase.st_atime;
  479. TimeBuf.modtime = BufPatch.st_mtime;
  480. if (utime(Itm->DestFile.c_str(),&TimeBuf) != 0)
  481. return _error->Errno("utime",_("Failed to set modification time"));
  482. if (stat(Itm->DestFile.c_str(),&BufBase) != 0)
  483. return _error->Errno("stat",_("Failed to stat"));
  484. // return done
  485. Res.LastModified = BufBase.st_mtime;
  486. Res.Size = BufBase.st_size;
  487. Res.TakeHashes(Hash);
  488. URIDone(Res);
  489. return true;
  490. }
  491. /*}}}*/
  492. /** \brief Wrapper class for testing rred */ /*{{{*/
  493. class TestRredMethod : public RredMethod {
  494. public:
  495. /** \brief Run rred in debug test mode
  496. *
  497. * This method can be used to run the rred method outside
  498. * of the "normal" acquire environment for easier testing.
  499. *
  500. * \param base basename of all files involved in this rred test
  501. */
  502. bool Run(char const *base) {
  503. _config->CndSet("Debug::pkgAcquire::RRed", "true");
  504. FetchItem *test = new FetchItem;
  505. test->DestFile = base;
  506. return Fetch(test);
  507. }
  508. };
  509. /*}}}*/
  510. /** \brief Starter for the rred method (or its test method) {{{
  511. *
  512. * Used without parameters is the normal behavior for methods for
  513. * the APT acquire system. While this works great for the acquire system
  514. * it is very hard to test the method and therefore the method also
  515. * accepts one parameter which will switch it directly to debug test mode:
  516. * The test mode expects that if "Testfile" is given as parameter
  517. * the file "Testfile" should be ed-style patched with "Testfile.ed"
  518. * and will write the result to "Testfile.result".
  519. */
  520. int main(int argc, char *argv[]) {
  521. if (argc <= 1) {
  522. RredMethod Mth;
  523. return Mth.Run();
  524. } else {
  525. TestRredMethod Mth;
  526. bool result = Mth.Run(argv[1]);
  527. _error->DumpErrors();
  528. return result;
  529. }
  530. }
  531. /*}}}*/