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