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