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