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