rred.cc 16 KB

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