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