Add fsync option.
[platform/upstream/cryptsetup.git] / src / crypt_reencrypt.c
1 /*
2  * crypt_reencrypt - crypt utility for offline reencryption
3  *
4  * Copyright (C) 2012 Milan Broz All rights reserved.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * version 2 as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19
20 #define _LARGEFILE64_SOURCE
21 #define _FILE_OFFSET_BITS 64
22 #define SECTOR_SIZE 512
23
24 #include <string.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <stdint.h>
28 #include <stdarg.h>
29 #include <inttypes.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <sys/stat.h>
33 #include <sys/ioctl.h>
34 #include <sys/time.h>
35 #include <linux/fs.h>
36 #include <fcntl.h>
37 #include <signal.h>
38 #include <popt.h>
39
40 #include "cryptsetup.h"
41
42 static int opt_verbose = 0;
43 static int opt_debug = 0;
44 static const char *opt_cipher = NULL;
45 static const char *opt_hash = NULL;
46 static const char *opt_key_file = NULL;
47 static long opt_keyfile_size = 0;
48 static long opt_keyfile_offset = 0;
49 static int opt_iteration_time = 1000;
50 static int opt_batch_mode = 0;
51 static int opt_version_mode = 0;
52 static int opt_random = 0;
53 static int opt_urandom = 0;
54 static int opt_bsize = 4;
55 static int opt_directio = 0;
56 static int opt_fsync = 0;
57 static int opt_write_log = 0;
58 static int opt_tries = 3;
59 static int opt_key_slot = CRYPT_ANY_SLOT;
60
61 static const char **action_argv;
62
63 static volatile int quit = 0;
64
65 #define MAX_SLOT 8
66 struct reenc_ctx {
67         char *device;
68         char *device_uuid;
69         uint64_t device_size;
70         uint64_t device_offset;
71         uint64_t device_shift;
72
73         int in_progress:1;
74         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
75
76         char header_file_org[PATH_MAX];
77         char header_file_new[PATH_MAX];
78         char log_file[PATH_MAX];
79
80         char crypt_path_org[PATH_MAX];
81         char crypt_path_new[PATH_MAX];
82         int log_fd;
83         char *log_buf;
84
85         struct {
86                 char *password;
87                 size_t passwordLen;
88         } p[MAX_SLOT];
89         int keyslot;
90
91         struct timeval start_time, end_time;
92         uint64_t restart_bytes;
93 };
94
95 char MAGIC[]   = {'L','U','K','S', 0xba, 0xbe};
96 char NOMAGIC[] = {'L','U','K','S', 0xde, 0xad};
97 int  MAGIC_L = 6;
98
99 typedef enum {
100         MAKE_UNUSABLE,
101         MAKE_USABLE,
102         CHECK_UNUSABLE
103 } header_magic;
104
105 __attribute__((format(printf, 5, 6)))
106 static void clogger(struct crypt_device *cd, int level, const char *file,
107                    int line, const char *format, ...)
108 {
109         va_list argp;
110         char *target = NULL;
111
112         va_start(argp, format);
113
114         if (vasprintf(&target, format, argp) > 0) {
115                 if (level >= 0) {
116                         crypt_log(cd, level, target);
117                 } else if (opt_debug)
118                         printf("# %s\n", target);
119         }
120
121         va_end(argp);
122         free(target);
123 }
124
125 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
126 {
127         switch(level) {
128
129         case CRYPT_LOG_NORMAL:
130                 fputs(msg, stdout);
131                 break;
132         case CRYPT_LOG_VERBOSE:
133                 if (opt_verbose)
134                         fputs(msg, stdout);
135                 break;
136         case CRYPT_LOG_ERROR:
137                 fputs(msg, stderr);
138                 break;
139         case CRYPT_LOG_DEBUG:
140                 if (opt_debug)
141                         printf("# %s\n", msg);
142                 break;
143         default:
144                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
145                 break;
146         }
147 }
148
149 static void _quiet_log(int level, const char *msg, void *usrptr)
150 {
151         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
152                 level = CRYPT_LOG_VERBOSE;
153         _log(level, msg, usrptr);
154 }
155
156 static void int_handler(int sig __attribute__((__unused__)))
157 {
158         quit++;
159 }
160
161 static void set_int_block(int block)
162 {
163         sigset_t signals_open;
164
165         sigemptyset(&signals_open);
166         sigaddset(&signals_open, SIGINT);
167         sigaddset(&signals_open, SIGTERM);
168         sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
169 }
170
171 static void set_int_handler(void)
172 {
173         struct sigaction sigaction_open;
174
175         memset(&sigaction_open, 0, sizeof(struct sigaction));
176         sigaction_open.sa_handler = int_handler;
177         sigaction(SIGINT, &sigaction_open, 0);
178         sigaction(SIGTERM, &sigaction_open, 0);
179         set_int_block(0);
180 }
181
182 /* The difference in seconds between two times in "timeval" format. */
183 static double time_diff(struct timeval start, struct timeval end)
184 {
185         return (end.tv_sec - start.tv_sec)
186                 + (end.tv_usec - start.tv_usec) / 1E6;
187 }
188
189 static int alignment(int fd)
190 {
191         int alignment;
192
193         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
194         if (alignment < 0)
195                 alignment = 4096;
196         return alignment;
197 }
198
199 static int device_magic(struct reenc_ctx *rc, header_magic set_magic)
200 {
201         char *buf = NULL;
202         int r, devfd;
203         ssize_t s;
204
205         devfd = open(rc->device, O_RDWR | O_DIRECT);
206         if (devfd == -1)
207                 return errno == EBUSY ? -EBUSY : -EINVAL;
208
209         if (posix_memalign((void *)&buf, alignment(devfd), SECTOR_SIZE)) {
210                 log_err(_("Allocation of aligned memory failed.\n"));
211                 r = -ENOMEM;
212                 goto out;
213         }
214
215         s = read(devfd, buf, SECTOR_SIZE);
216         if (s < 0 || s != SECTOR_SIZE) {
217                 log_err(_("Cannot read device %s.\n"), rc->device);
218                 close(devfd);
219                 return -EIO;
220         }
221
222         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L)) {
223                 log_verbose(_("Marking LUKS device %s unusable.\n"), rc->device);
224                 memcpy(buf, NOMAGIC, MAGIC_L);
225                 r = 0;
226
227         } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L)) {
228                 log_verbose(_("Marking LUKS device %s usable.\n"), rc->device);
229                 memcpy(buf, MAGIC, MAGIC_L);
230                 r = 0;
231         } else if (set_magic == CHECK_UNUSABLE) {
232                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
233                 if (!r)
234                         rc->device_uuid = strndup(&buf[0xa8], 40);
235                 goto out;
236         } else
237                 r = -EINVAL;
238
239         if (!r) {
240                 if (lseek(devfd, 0, SEEK_SET) == -1)
241                         goto out;
242                 s = write(devfd, buf, SECTOR_SIZE);
243                 if (s < 0 || s != SECTOR_SIZE) {
244                         log_err(_("Cannot write device %s.\n"), rc->device);
245                         r = -EIO;
246                 }
247         } else
248                 log_dbg("LUKS signature check failed for %s.", rc->device);
249 out:
250         if (buf)
251                 memset(buf, 0, SECTOR_SIZE);
252         free(buf);
253         close(devfd);
254         return r;
255 }
256
257 static int create_empty_header(const char *new_file, const char *old_file)
258 {
259         struct stat st;
260         ssize_t size;
261         int fd, r = 0;
262         char *buf;
263
264         if (stat(old_file, &st) == -1 ||
265                  (st.st_mode & S_IFMT) != S_IFREG ||
266                  (st.st_size > 16 * 1024 * 1024))
267                 return -EINVAL;
268         size = st.st_size;
269
270         log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
271
272         if (!(buf = malloc(size)))
273                 return -ENOMEM;
274         memset(buf, 0, size);
275
276         fd = creat(new_file, S_IRUSR|S_IWUSR);
277         if(fd == -1) {
278                 free(buf);
279                 return -EINVAL;
280         }
281
282         if (write(fd, buf, size) < size)
283                 r = -EIO;
284
285         close(fd);
286         free(buf);
287         return r;
288 }
289
290 static int write_log(struct reenc_ctx *rc)
291 {
292         ssize_t r;
293
294         memset(rc->log_buf, 0, SECTOR_SIZE);
295         snprintf(rc->log_buf, SECTOR_SIZE, "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
296                 "version = %d\nUUID = %s\ndirection = %d\n"
297                 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
298                 1, rc->device_uuid, rc->reencrypt_direction,
299                 rc->device_offset, rc->device_shift);
300
301         lseek(rc->log_fd, 0, SEEK_SET);
302         r = write(rc->log_fd, rc->log_buf, SECTOR_SIZE);
303         if (r < 0 || r != SECTOR_SIZE) {
304                 log_err(_("Cannot write reencryption log file.\n"));
305                 return -EIO;
306         }
307
308         return 0;
309 }
310
311 static int parse_line_log(struct reenc_ctx *rc, const char *line)
312 {
313         uint64_t u64;
314         int i;
315         char s[64];
316
317         /* whole line is comment */
318         if (*line == '#')
319                 return 0;
320
321         if (sscanf(line, "version = %d", &i) == 1) {
322                 if (i != 1) {
323                         log_dbg("Log: Unexpected version = %i", i);
324                         return -EINVAL;
325                 }
326         } else if (sscanf(line, "UUID = %40s", s) == 1) {
327                 if (!rc->device_uuid || strcmp(rc->device_uuid, s)) {
328                         log_dbg("Log: Unexpected UUID %s", s);
329                         return -EINVAL;
330                 }
331         } else if (sscanf(line, "direction = %d", &i) == 1) {
332                 log_dbg("Log: direction = %i", i);
333                 rc->reencrypt_direction = i;
334         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
335                 log_dbg("Log: offset = %" PRIu64, u64);
336                 rc->device_offset = u64;
337         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
338                 log_dbg("Log: shift = %" PRIu64, u64);
339                 rc->device_shift = u64;
340         } else
341                 return -EINVAL;
342
343         return 0;
344 }
345
346 static int parse_log(struct reenc_ctx *rc)
347 {
348         char *start, *end;
349         ssize_t s;
350
351         s = read(rc->log_fd, rc->log_buf, SECTOR_SIZE);
352         if (s == -1) {
353                 log_err(_("Cannot read reencryption log file.\n"));
354                 return -EIO;
355         }
356
357         rc->log_buf[SECTOR_SIZE - 1] = '\0';
358         start = rc->log_buf;
359         do {
360                 end = strchr(start, '\n');
361                 if (end) {
362                         *end++ = '\0';
363                         if (parse_line_log(rc, start)) {
364                                 log_err("Wrong log format.\n");
365                                 return -EINVAL;
366                         }
367                 }
368
369                 start = end;
370         } while (start);
371
372         return 0;
373 }
374
375 static void close_log(struct reenc_ctx *rc)
376 {
377         log_dbg("Closing LUKS reencryption log file %s.", rc->log_file);
378         if (rc->log_fd != -1)
379                 close(rc->log_fd);
380         free(rc->log_buf);
381         rc->log_buf = NULL;
382 }
383
384 static int open_log(struct reenc_ctx *rc)
385 {
386         int flags, create_new;
387         struct stat st;
388
389         if (!stat(rc->log_file, &st))
390                 create_new = 0;
391         else if (errno == ENOENT)
392                 create_new = 1;
393         else
394                 return -EINVAL;
395
396         if (create_new) {
397                 log_dbg("Creating LUKS reencryption log file %s.", rc->log_file);
398                 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
399                 rc->log_fd = open(rc->log_file, flags, S_IRUSR|S_IWUSR);
400                 if (rc->log_fd == -1)
401                         return -EINVAL;
402         } else {
403                 log_dbg("Log file %s exists, restarting.", rc->log_file);
404                 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
405                 rc->log_fd = open(rc->log_file, flags);
406                 if (rc->log_fd == -1)
407                         return -EINVAL;
408                 rc->in_progress = 1;
409         }
410
411         if (posix_memalign((void *)&rc->log_buf, alignment(rc->log_fd), SECTOR_SIZE)) {
412                 log_err(_("Allocation of aligned memory failed.\n"));
413                 close_log(rc);
414                 return -ENOMEM;
415         }
416
417         if (create_new && write_log(rc) < 0) {
418                 close_log(rc);
419                 return -EIO;
420         }
421
422         /* Be sure it is correct format */
423         return parse_log(rc);
424 }
425
426 static int activate_luks_headers(struct reenc_ctx *rc)
427 {
428         struct crypt_device *cd = NULL, *cd_new = NULL;
429         int r;
430
431         log_dbg("Activating LUKS devices from headers.");
432
433         if ((r = crypt_init(&cd, rc->header_file_org)) ||
434             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
435             (r = crypt_set_data_device(cd, rc->device)))
436                 goto out;
437
438         if ((r = crypt_activate_by_passphrase(cd, rc->header_file_org,
439                 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
440                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
441                 goto out;
442
443         if ((r = crypt_init(&cd_new, rc->header_file_new)) ||
444             (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
445             (r = crypt_set_data_device(cd_new, rc->device)))
446                 goto out;
447
448         if ((r = crypt_activate_by_passphrase(cd_new, rc->header_file_new,
449                 opt_key_slot, rc->p[rc->keyslot].password, rc->p[rc->keyslot].passwordLen,
450                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
451                 goto out;
452         r = 0;
453 out:
454         crypt_free(cd);
455         crypt_free(cd_new);
456         if (r < 0)
457                 log_err(_("Activation of temporary devices failed.\n"));
458         return r;
459 }
460
461 static int backup_luks_headers(struct reenc_ctx *rc)
462 {
463         struct crypt_device *cd = NULL, *cd_new = NULL;
464         struct crypt_params_luks1 params = {0};
465         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
466         int i, r;
467
468         log_dbg("Creating LUKS header backup for device %s.", rc->device);
469
470         if ((r = crypt_init(&cd, rc->device)) ||
471             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
472                 goto out;
473
474         crypt_set_confirm_callback(cd, NULL, NULL);
475         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rc->header_file_org)))
476                 goto out;
477         log_verbose(_("LUKS header backup of device %s created.\n"), rc->device);
478
479         if ((r = create_empty_header(rc->header_file_new, rc->header_file_org)))
480                 goto out;
481
482         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
483         params.data_alignment = crypt_get_data_offset(cd);
484         params.data_device = rc->device;
485
486         if ((r = crypt_init(&cd_new, rc->header_file_new)))
487                 goto out;
488
489         if (opt_random)
490                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
491         else if (opt_urandom)
492                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
493
494         if (opt_iteration_time)
495                 crypt_set_iteration_time(cd_new, opt_iteration_time);
496
497         if (opt_cipher) {
498                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
499                 if (r < 0) {
500                         log_err(_("No known cipher specification pattern detected.\n"));
501                         goto out;
502                 }
503         }
504
505         if ((r = crypt_format(cd_new, CRYPT_LUKS1,
506                         opt_cipher ? cipher : crypt_get_cipher(cd),
507                         opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
508                         crypt_get_uuid(cd),
509                         NULL, crypt_get_volume_key_size(cd), &params)))
510                 goto out;
511         log_verbose(_("New LUKS header for device %s created.\n"), rc->device);
512
513         for (i = 0; i < MAX_SLOT; i++) {
514                 if (!rc->p[i].password)
515                         continue;
516                 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
517                         NULL, 0, rc->p[i].password, rc->p[i].passwordLen)) < 0)
518                         goto out;
519                 log_verbose(_("Activated keyslot %i.\n"), r);
520                 r = 0;
521         }
522 out:
523         crypt_free(cd);
524         crypt_free(cd_new);
525         if (r)
526                 log_err(_("Creation of LUKS backup headers failed.\n"));
527         return r;
528 }
529
530 static void remove_headers(struct reenc_ctx *rc)
531 {
532         struct crypt_device *cd = NULL;
533
534         log_dbg("Removing headers.");
535
536         if (crypt_init(&cd, NULL))
537                 return;
538         crypt_set_log_callback(cd, _quiet_log, NULL);
539         (void)crypt_deactivate(cd, rc->header_file_org);
540         (void)crypt_deactivate(cd, rc->header_file_new);
541         crypt_free(cd);
542 }
543
544 static int restore_luks_header(struct reenc_ctx *rc)
545 {
546         struct crypt_device *cd = NULL;
547         int r;
548
549         log_dbg("Restoring header for %s from %s.", rc->device, rc->header_file_new);
550
551         r = crypt_init(&cd, rc->device);
552         if (r == 0) {
553                 crypt_set_confirm_callback(cd, NULL, NULL);
554                 r = crypt_header_restore(cd, CRYPT_LUKS1, rc->header_file_new);
555         }
556
557         crypt_free(cd);
558         if (r)
559                 log_err(_("Cannot restore LUKS header on device %s.\n"), rc->device);
560         else
561                 log_verbose(_("LUKS header on device %s restored.\n"), rc->device);
562         return r;
563 }
564
565 static void print_progress(struct reenc_ctx *rc, uint64_t bytes, int final)
566 {
567         uint64_t mbytes = (bytes - rc->restart_bytes) / 1024 / 1024;
568         struct timeval now_time;
569         double tdiff;
570
571         gettimeofday(&now_time, NULL);
572         if (!final && time_diff(rc->end_time, now_time) < 0.5)
573                 return;
574
575         rc->end_time = now_time;
576
577         if (opt_batch_mode)
578                 return;
579
580         tdiff = time_diff(rc->start_time, rc->end_time);
581         if (!tdiff)
582                 return;
583
584         /* vt100 code clear line */
585         log_err("\33[2K\r");
586         log_err(_("Progress: %5.1f%%, time elapsed %4.0f seconds, "
587                 "%4llu MiB written, speed %5.1f MiB/s%s"),
588                 (double)bytes / rc->device_size * 100,
589                 time_diff(rc->start_time, rc->end_time),
590                 (unsigned long long)mbytes, (double)(mbytes) / tdiff,
591                 final ? "\n" :"");
592 }
593
594 static int copy_data_forward(struct reenc_ctx *rc, int fd_old, int fd_new,
595                              size_t block_size, void *buf, uint64_t *bytes)
596 {
597         ssize_t s1, s2;
598
599         log_dbg("Reencrypting in forward direction.");
600
601         if (lseek64(fd_old, rc->device_offset, SEEK_SET) < 0 ||
602             lseek64(fd_new, rc->device_offset, SEEK_SET) < 0) {
603                 log_err(_("Cannot seek to device offset.\n"));
604                 return -EIO;
605         }
606
607         rc->restart_bytes = *bytes = rc->device_offset;
608
609         if (write_log(rc) < 0)
610                 return -EIO;
611
612         while (!quit && rc->device_offset < rc->device_size) {
613                 s1 = read(fd_old, buf, block_size);
614                 if (s1 < 0 || ((size_t)s1 != block_size &&
615                     (rc->device_offset + s1) != rc->device_size)) {
616                         log_dbg("Read error, expecting %d, got %d.",
617                                 (int)block_size, (int)s1);
618                         return -EIO;
619                 }
620
621                 s2 = write(fd_new, buf, s1);
622                 if (s2 < 0) {
623                         log_dbg("Write error, expecting %d, got %d.",
624                                 (int)block_size, (int)s2);
625                         return -EIO;
626                 }
627
628                 rc->device_offset += s1;
629                 if (opt_write_log && write_log(rc) < 0)
630                         return -EIO;
631
632                 if (opt_fsync && fsync(fd_new) < 0) {
633                         log_dbg("Write error, fsync.");
634                         return -EIO;
635                 }
636
637                 *bytes += (uint64_t)s2;
638                 print_progress(rc, *bytes, 0);
639         }
640
641         return quit ? -EAGAIN : 0;
642 }
643
644 static int copy_data_backward(struct reenc_ctx *rc, int fd_old, int fd_new,
645                               size_t block_size, void *buf, uint64_t *bytes)
646 {
647         ssize_t s1, s2, working_block;
648         off64_t working_offset;
649
650         log_dbg("Reencrypting in backward direction.");
651
652         if (!rc->in_progress) {
653                 rc->device_offset = rc->device_size;
654                 rc->restart_bytes = 0;
655                 *bytes = 0;
656         } else {
657                 rc->restart_bytes = rc->device_size - rc->device_offset;
658                 *bytes = rc->restart_bytes;
659         }
660
661         if (write_log(rc) < 0)
662                 return -EIO;
663
664         while (!quit && rc->device_offset) {
665                 if (rc->device_offset < block_size) {
666                         working_offset = 0;
667                         working_block = rc->device_offset;
668                 } else {
669                         working_offset = rc->device_offset - block_size;
670                         working_block = block_size;
671                 }
672
673                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
674                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
675                         log_err(_("Cannot seek to device offset.\n"));
676                         return -EIO;
677                 }
678
679                 s1 = read(fd_old, buf, working_block);
680                 if (s1 < 0 || (s1 != working_block)) {
681                         log_dbg("Read error, expecting %d, got %d.",
682                                 (int)block_size, (int)s1);
683                         return -EIO;
684                 }
685
686                 s2 = write(fd_new, buf, working_block);
687                 if (s2 < 0) {
688                         log_dbg("Write error, expecting %d, got %d.",
689                                 (int)block_size, (int)s2);
690                         return -EIO;
691                 }
692
693                 rc->device_offset -= s1;
694                 if (opt_write_log && write_log(rc) < 0)
695                         return -EIO;
696
697                 if (opt_fsync && fsync(fd_new) < 0) {
698                         log_dbg("Write error, fsync.");
699                         return -EIO;
700                 }
701
702                 *bytes += (uint64_t)s2;
703                 print_progress(rc, *bytes, 0);
704         }
705
706         return quit ? -EAGAIN : 0;
707 }
708
709 static int copy_data(struct reenc_ctx *rc)
710 {
711         size_t block_size = opt_bsize * 1024 * 1024;
712         int fd_old = -1, fd_new = -1;
713         int r = -EINVAL;
714         void *buf = NULL;
715         uint64_t bytes = 0;
716
717         log_dbg("Data copy preparation.");
718
719         fd_old = open(rc->crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
720         if (fd_old == -1) {
721                 log_err(_("Cannot open temporary LUKS header file.\n"));
722                 goto out;
723         }
724
725         fd_new = open(rc->crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
726         if (fd_new == -1) {
727                 log_err(_("Cannot open temporary LUKS header file.\n"));
728                 goto out;
729         }
730
731         /* Check size */
732         if (ioctl(fd_old, BLKGETSIZE64, &rc->device_size) < 0) {
733                 log_err(_("Cannot get device size.\n"));
734                 goto out;
735         }
736
737         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
738                 log_err(_("Allocation of aligned memory failed.\n"));
739                 r = -ENOMEM;
740                 goto out;
741         }
742
743         set_int_handler();
744         gettimeofday(&rc->start_time, NULL);
745
746         if (rc->reencrypt_direction == FORWARD)
747                 r = copy_data_forward(rc, fd_old, fd_new, block_size, buf, &bytes);
748         else
749                 r = copy_data_backward(rc, fd_old, fd_new, block_size, buf, &bytes);
750
751         set_int_block(1);
752         print_progress(rc, bytes, 1);
753
754         if (r == -EAGAIN)
755                  log_err(_("Interrupted by a signal.\n"));
756         else if (r < 0)
757                 log_err(_("IO error during reencryption.\n"));
758
759         (void)write_log(rc);
760 out:
761         if (fd_old != -1)
762                 close(fd_old);
763         if (fd_new != -1)
764                 close(fd_new);
765         free(buf);
766         return r;
767 }
768
769 static int initialize_uuid(struct reenc_ctx *rc)
770 {
771         struct crypt_device *cd = NULL;
772         int r;
773
774         log_dbg("Initialising UUID.");
775
776         /* Try to load LUKS from device */
777         if ((r = crypt_init(&cd, rc->device)))
778                 return r;
779         crypt_set_log_callback(cd, _quiet_log, NULL);
780         r = crypt_load(cd, CRYPT_LUKS1, NULL);
781         if (!r)
782                 rc->device_uuid = strdup(crypt_get_uuid(cd));
783         else
784                 /* Reencryption already in progress - magic header? */
785                 r = device_magic(rc, CHECK_UNUSABLE);
786
787         crypt_free(cd);
788         return r;
789 }
790
791 static int init_passphrase1(struct reenc_ctx *rc, struct crypt_device *cd,
792                             const char *msg, int slot_check)
793 {
794         int r = -EINVAL, slot, retry_count;
795
796         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
797
798         retry_count = opt_tries ?: 1;
799         while (retry_count--) {
800                 r = crypt_get_key(msg, &rc->p[slot].password,
801                         &rc->p[slot].passwordLen,
802                         0, 0, NULL /*opt_key_file*/,
803                         0, 0, cd);
804                 if (r < 0)
805                         return r;
806
807                 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
808                         rc->p[slot].password, rc->p[slot].passwordLen, 0);
809
810                 if (r < 0) {
811                         crypt_safe_free(rc->p[slot].password);
812                         rc->p[slot].password = NULL;
813                         rc->p[slot].passwordLen = 0;
814                 }
815                 if (r < 0 && r != -EPERM)
816                         return r;
817                 if (r >= 0) {
818                         rc->keyslot = slot;
819                         break;
820                 }
821                 log_err(_("No key available with this passphrase.\n"));
822         }
823         return r;
824 }
825
826 static int init_keyfile(struct reenc_ctx *rc, struct crypt_device *cd, int slot_check)
827 {
828         int r, slot;
829
830         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
831         r = crypt_get_key(NULL, &rc->p[slot].password, &rc->p[slot].passwordLen,
832                 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
833         if (r < 0)
834                 return r;
835
836         r = crypt_activate_by_passphrase(cd, NULL, slot_check,
837                 rc->p[slot].password, rc->p[slot].passwordLen, 0);
838
839         /*
840          * Allow keyslot only if it is last slot or if user explicitly
841          * specify whch slot to use (IOW others will be disabled).
842          */
843         if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
844             crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
845                 log_err(_("Key file can be used only with --key-slot or with "
846                           "exactly one key slot active.\n"));
847                 r = -EINVAL;
848         }
849
850         if (r < 0) {
851                 crypt_safe_free(rc->p[slot].password);
852                 rc->p[slot].password = NULL;
853                 rc->p[slot].passwordLen = 0;
854                 if (r == -EPERM)
855                         log_err(_("No key available with this passphrase.\n"));
856                 return r;
857         } else
858                 rc->keyslot = slot;
859
860         return r;
861 }
862
863 static int initialize_passphrase(struct reenc_ctx *rc, const char *device)
864 {
865         struct crypt_device *cd = NULL;
866         crypt_keyslot_info ki;
867         char msg[256];
868         int i, r;
869
870         log_dbg("Passhrases initialization.");
871
872         if ((r = crypt_init(&cd, device)) ||
873             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
874             (r = crypt_set_data_device(cd, rc->device))) {
875                 crypt_free(cd);
876                 return r;
877         }
878
879         if (opt_key_file) {
880                 r = init_keyfile(rc, cd, opt_key_slot);
881         } else if (rc->in_progress) {
882                 r = init_passphrase1(rc, cd, _("Enter any LUKS passphrase: "), CRYPT_ANY_SLOT);
883         } else for (i = 0; i < MAX_SLOT; i++) {
884                 ki = crypt_keyslot_status(cd, i);
885                 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
886                         continue;
887
888                 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u: "), i);
889                 r = init_passphrase1(rc, cd, msg, i);
890                 if (r < 0)
891                         break;
892         }
893
894         crypt_free(cd);
895         return r > 0 ? 0 : r;
896 }
897
898 static int initialize_context(struct reenc_ctx *rc, const char *device)
899 {
900         log_dbg("Initialising reencryption context.");
901
902         rc->log_fd =-1;
903
904         if (!(rc->device = strndup(device, PATH_MAX)))
905                 return -ENOMEM;
906
907         if (initialize_uuid(rc)) {
908                 log_err(_("Device %s is not a valid LUKS device.\n"), device);
909                 return -EINVAL;
910         }
911
912         /* Prepare device names */
913         if (snprintf(rc->log_file, PATH_MAX,
914                      "LUKS-%s.log", rc->device_uuid) < 0)
915                 return -ENOMEM;
916         if (snprintf(rc->header_file_org, PATH_MAX,
917                      "LUKS-%s.org", rc->device_uuid) < 0)
918                 return -ENOMEM;
919         if (snprintf(rc->header_file_new, PATH_MAX,
920                      "LUKS-%s.new", rc->device_uuid) < 0)
921                 return -ENOMEM;
922
923         /* Paths to encrypted devices */
924         if (snprintf(rc->crypt_path_org, PATH_MAX,
925                      "%s/%s", crypt_get_dir(), rc->header_file_org) < 0)
926                 return -ENOMEM;
927         if (snprintf(rc->crypt_path_new, PATH_MAX,
928                      "%s/%s", crypt_get_dir(), rc->header_file_new) < 0)
929                 return -ENOMEM;
930
931         remove_headers(rc);
932
933         if (open_log(rc) < 0) {
934                 log_err(_("Cannot open reencryption log file.\n"));
935                 return -EINVAL;
936         }
937
938         if (!rc->in_progress) {
939                 if (1 /*opt_new */)
940                         rc->reencrypt_direction = FORWARD;
941                 else {
942                         rc->reencrypt_direction = BACKWARD;
943                         rc->device_offset = (uint64_t)~0;
944                 }
945         }
946
947         return 0;
948 }
949
950 static void destroy_context(struct reenc_ctx *rc)
951 {
952         int i;
953
954         log_dbg("Destroying reencryption context.");
955
956         close_log(rc);
957         remove_headers(rc);
958
959         if ((rc->reencrypt_direction == FORWARD &&
960              rc->device_offset == rc->device_size) ||
961              rc->device_offset == 0) {
962                 unlink(rc->log_file);
963                 unlink(rc->header_file_org);
964                 unlink(rc->header_file_new);
965         }
966
967         for (i = 0; i < MAX_SLOT; i++)
968                 crypt_safe_free(rc->p[i].password);
969
970         free(rc->device);
971         free(rc->device_uuid);
972 }
973
974 static int run_reencrypt(const char *device)
975 {
976         int r = -EINVAL;
977         struct reenc_ctx rc = {};
978
979         if (initialize_context(&rc, device))
980                 goto out;
981
982         log_dbg("Running reencryption.");
983
984         if (!rc.in_progress) {
985                 if ((r = initialize_passphrase(&rc, rc.device)) ||
986                     (r = backup_luks_headers(&rc)) ||
987                     (r = device_magic(&rc, MAKE_UNUSABLE)))
988                         goto out;
989         } else {
990                 if ((r = initialize_passphrase(&rc, rc.header_file_new)))
991                         goto out;
992         }
993
994         if ((r = activate_luks_headers(&rc)))
995                 goto out;
996
997         if ((r = copy_data(&rc)))
998                 goto out;
999
1000         r = restore_luks_header(&rc);
1001 out:
1002         destroy_context(&rc);
1003         return r;
1004 }
1005
1006 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
1007                                              int exitcode, const char *error,
1008                                              const char *more)
1009 {
1010         poptPrintUsage(popt_context, stderr, 0);
1011         if (error)
1012                 log_err("%s: %s\n", more, error);
1013         poptFreeContext(popt_context);
1014         exit(exitcode);
1015 }
1016
1017 static void help(poptContext popt_context,
1018                  enum poptCallbackReason reason __attribute__((unused)),
1019                  struct poptOption *key,
1020                  const char *arg __attribute__((unused)),
1021                  void *data __attribute__((unused)))
1022 {
1023         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
1024 }
1025
1026 static void _dbg_version_and_cmd(int argc, const char **argv)
1027 {
1028         int i;
1029
1030         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
1031         for (i = 0; i < argc; i++) {
1032                 if (i)
1033                         log_std(" ");
1034                 log_std("%s", argv[i]);
1035         }
1036         log_std("\"\n");
1037 }
1038
1039 int main(int argc, const char **argv)
1040 {
1041         static struct poptOption popt_help_options[] = {
1042                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
1043                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
1044                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
1045                 POPT_TABLEEND
1046         };
1047         static struct poptOption popt_options[] = {
1048                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
1049                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
1050                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
1051                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
1052                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MiB") },
1053                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
1054                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
1055                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
1056                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
1057                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
1058                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
1059                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1060                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1061                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accesing devices."), NULL },
1062                 { "use-fsync",         '\0', POPT_ARG_NONE, &opt_fsync,                 0, N_("Use fsync after each block."), NULL },
1063                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block."), NULL },
1064                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Use only this slot (others will be disabled)."), NULL },
1065                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1066                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1067                 POPT_TABLEEND
1068         };
1069         poptContext popt_context;
1070         int r;
1071
1072         crypt_set_log_callback(NULL, _log, NULL);
1073
1074         set_int_block(1);
1075
1076         setlocale(LC_ALL, "");
1077         bindtextdomain(PACKAGE, LOCALEDIR);
1078         textdomain(PACKAGE);
1079
1080         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1081         poptSetOtherOptionHelp(popt_context,
1082                                N_("[OPTION...] <device>]"));
1083
1084         while((r = poptGetNextOpt(popt_context)) > 0) {
1085                 if (r < 0)
1086                         break;
1087         }
1088
1089         if (r < -1)
1090                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1091                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1092         if (opt_version_mode) {
1093                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1094                 poptFreeContext(popt_context);
1095                 exit(EXIT_SUCCESS);
1096         }
1097
1098         if (!opt_batch_mode)
1099                 log_err(_("WARNING: this is experimental code, it can completely break your data.\n"));
1100
1101         action_argv = poptGetArgs(popt_context);
1102         if(!action_argv)
1103                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1104                       poptGetInvocationName(popt_context));
1105
1106         if (opt_random && opt_urandom)
1107                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1108                       poptGetInvocationName(popt_context));
1109
1110         if (opt_bsize < 1 || opt_bsize > 64)
1111                 usage(popt_context, EXIT_FAILURE,
1112                       _("Only values between 1MiB and 64 MiB allowed for reencryption block size."),
1113                       poptGetInvocationName(popt_context));
1114
1115         if (opt_debug) {
1116                 opt_verbose = 1;
1117                 crypt_set_debug_level(-1);
1118                 _dbg_version_and_cmd(argc, argv);
1119         }
1120
1121         r = run_reencrypt(action_argv[0]);
1122
1123         poptFreeContext(popt_context);
1124
1125         /* Translate exit code to simple codes */
1126         switch (r) {
1127         case 0:         r = EXIT_SUCCESS; break;
1128         case -EEXIST:
1129         case -EBUSY:    r = 5; break;
1130         case -ENOTBLK:
1131         case -ENODEV:   r = 4; break;
1132         case -ENOMEM:   r = 3; break;
1133         case -EPERM:    r = 2; break;
1134         case -EAGAIN:
1135         case -EINVAL:
1136         case -ENOENT:
1137         case -ENOSYS:
1138         default:        r = EXIT_FAILURE;
1139         }
1140         return r;
1141 }