Change log manipulation, print log always.
[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 #define _LARGEFILE64_SOURCE
21 #define _FILE_OFFSET_BITS 64
22
23 #include <string.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <stdint.h>
27 #include <stdarg.h>
28 #include <inttypes.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <sys/stat.h>
32 #include <sys/ioctl.h>
33 #include <sys/time.h>
34 #include <linux/fs.h>
35 #include <fcntl.h>
36 #include <limits.h>
37 #include <signal.h>
38 #include <libcryptsetup.h>
39 #include <popt.h>
40
41 #include "cryptsetup.h"
42
43 static int opt_verbose = 0;
44 static int opt_debug = 0;
45 static const char *opt_cipher = NULL;
46 static const char *opt_hash = NULL;
47 static const char *opt_key_file = NULL;
48 static long opt_keyfile_size = 0;
49 static long opt_keyfile_offset = 0;
50 static int opt_iteration_time = 1000;
51 static int opt_batch_mode = 0;
52 static int opt_version_mode = 0;
53 static int opt_random = 0;
54 static int opt_urandom = 0;
55 static int opt_bsize = 4;
56 static int opt_directio = 0;
57 static int opt_write_log = 0;
58 static int opt_tries = 3;
59 static int opt_key_slot = CRYPT_ANY_SLOT;
60
61 static const char **action_argv;
62
63 static volatile int quit = 0;
64
65 #define MAX_SLOT 8
66 struct {
67         char *device;
68         char *device_uuid;
69         uint64_t device_size;
70         uint64_t device_offset;
71         uint64_t device_shift;
72
73         int in_progress:1;
74         enum { FORWARD = 0, BACKWARD = 1 } reencrypt_direction;
75
76         char header_file_org[PATH_MAX];
77         char header_file_new[PATH_MAX];
78         char log_file[PATH_MAX];
79
80         char crypt_path_org[PATH_MAX];
81         char crypt_path_new[PATH_MAX];
82         int log_fd;
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 restart_bytes;
92 } rnc;
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 } header_magic;
103
104 __attribute__((format(printf, 5, 6)))
105 static void clogger(struct crypt_device *cd, int level, const char *file,
106                    int line, const char *format, ...)
107 {
108         va_list argp;
109         char *target = NULL;
110
111         va_start(argp, format);
112
113         if (vasprintf(&target, format, argp) > 0) {
114                 if (level >= 0) {
115                         crypt_log(cd, level, target);
116                 } else if (opt_debug)
117                         printf("# %s\n", target);
118         }
119
120         va_end(argp);
121         free(target);
122 }
123
124 static void _log(int level, const char *msg, void *usrptr __attribute__((unused)))
125 {
126         switch(level) {
127
128         case CRYPT_LOG_NORMAL:
129                 fputs(msg, stdout);
130                 break;
131         case CRYPT_LOG_VERBOSE:
132                 if (opt_verbose)
133                         fputs(msg, stdout);
134                 break;
135         case CRYPT_LOG_ERROR:
136                 fputs(msg, stderr);
137                 break;
138         case CRYPT_LOG_DEBUG:
139                 if (opt_debug)
140                         printf("# %s\n", msg);
141                 break;
142         default:
143                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
144                 break;
145         }
146 }
147
148 static void _quiet_log(int level, const char *msg, void *usrptr)
149 {
150         if (!opt_verbose && (level == CRYPT_LOG_ERROR || level == CRYPT_LOG_NORMAL))
151                 level = CRYPT_LOG_VERBOSE;
152         _log(level, msg, usrptr);
153 }
154
155 static void int_handler(int sig __attribute__((__unused__)))
156 {
157         quit++;
158 }
159
160 static void set_int_block(int block)
161 {
162         sigset_t signals_open;
163
164         sigemptyset(&signals_open);
165         sigaddset(&signals_open, SIGINT);
166         sigaddset(&signals_open, SIGTERM);
167         sigprocmask(block ? SIG_SETMASK : SIG_UNBLOCK, &signals_open, NULL);
168 }
169
170 static void set_int_handler(void)
171 {
172         struct sigaction sigaction_open;
173
174         memset(&sigaction_open, 0, sizeof(struct sigaction));
175         sigaction_open.sa_handler = int_handler;
176         sigaction(SIGINT, &sigaction_open, 0);
177         sigaction(SIGTERM, &sigaction_open, 0);
178         set_int_block(0);
179 }
180
181 /* The difference in seconds between two times in "timeval" format. */
182 double time_diff(struct timeval start, struct timeval end)
183 {
184         return (end.tv_sec - start.tv_sec)
185                 + (end.tv_usec - start.tv_usec) / 1E6;
186 }
187
188 static int alignment(int fd)
189 {
190         int alignment;
191
192         alignment = fpathconf(fd, _PC_REC_XFER_ALIGN);
193         if (alignment < 0)
194                 alignment = 4096;
195         return alignment;
196 }
197
198 static int device_magic(header_magic set_magic)
199 {
200         char *buf = NULL;
201         size_t block_size = 512;
202         int r, devfd;
203         ssize_t s;
204
205         devfd = open(rnc.device, O_RDWR | O_DIRECT);
206         if (devfd == -1)
207                 return errno == EBUSY ? -EBUSY : -EINVAL;
208
209         if (posix_memalign((void *)&buf, alignment(devfd), block_size)) {
210                 r = -ENOMEM;
211                 goto out;
212         }
213
214         s = read(devfd, buf, block_size);
215         if (s < 0 || s != block_size) {
216                 log_verbose(_("Cannot read device %s.\n"), rnc.device);
217                 close(devfd);
218                 return -EIO;
219         }
220
221         if (set_magic == MAKE_UNUSABLE && !memcmp(buf, MAGIC, MAGIC_L)) {
222                 log_dbg("Marking LUKS device %s unusable.", rnc.device);
223                 memcpy(buf, NOMAGIC, MAGIC_L);
224                 r = 0;
225
226         } else if (set_magic == MAKE_USABLE && !memcmp(buf, NOMAGIC, MAGIC_L)) {
227                 log_dbg("Marking LUKS device %s usable.", rnc.device);
228                 memcpy(buf, MAGIC, MAGIC_L);
229                 r = 0;
230         } else if (set_magic == CHECK_UNUSABLE) {
231                 r = memcmp(buf, NOMAGIC, MAGIC_L) ? -EINVAL : 0;
232                 if (!r)
233                         rnc.device_uuid = strndup(&buf[0xa8], 40);
234                 goto out;
235         } else
236                 r = -EINVAL;
237
238         if (!r) {
239                 if (lseek(devfd, 0, SEEK_SET) == -1)
240                         goto out;
241                 s = write(devfd, buf, block_size);
242                 if (s < 0 || s != block_size) {
243                         log_verbose(_("Cannot write device %s.\n"), rnc.device);
244                         r = -EIO;
245                 }
246         } else
247                 log_dbg("LUKS signature check failed for %s.", rnc.device);
248 out:
249         if (buf)
250                 memset(buf, 0, block_size);
251         free(buf);
252         close(devfd);
253         return r;
254 }
255
256 static int create_empty_header(const char *new_file, const char *old_file)
257 {
258         struct stat st;
259         size_t size;
260         int fd, r = 0;
261         char *buf;
262
263         if (stat(old_file, &st) == -1 || (st.st_mode & S_IFMT) != S_IFREG)
264                 return -EINVAL;
265         size = st.st_size;
266
267         log_dbg("Creating empty file %s of size %lu.", new_file, (unsigned long)size);
268
269         if (!(buf = malloc(size)))
270                 return -ENOMEM;
271         memset(buf, 0, size);
272
273         fd = creat(new_file, S_IRUSR|S_IWUSR);
274         if(fd == -1) {
275                 free(buf);
276                 return -EINVAL;
277         }
278
279         if (write(fd, buf, size) < size)
280                 r = -EIO;
281
282         close(fd);
283         free(buf);
284         return r;
285 }
286
287 static int write_log(void)
288 {
289         static char buf[512];
290         ssize_t r;
291
292         //log_dbg("Updating LUKS reencryption log offset %" PRIu64 ".", offset);
293         memset(buf, 0, sizeof(buf));
294         snprintf(buf, sizeof(buf), "# LUKS reencryption log, DO NOT EDIT OR DELETE.\n"
295                 "version = %d\nUUID = %s\ndirection = %d\n"
296                 "offset = %" PRIu64 "\nshift = %" PRIu64 "\n# EOF\n",
297                 1, rnc.device_uuid, rnc.reencrypt_direction,
298                 rnc.device_offset, rnc.device_shift);
299
300         lseek(rnc.log_fd, 0, SEEK_SET);
301         r = write(rnc.log_fd, buf, sizeof(buf));
302         if (r < 0 || r != sizeof(buf)) {
303                 log_err(_("Cannot write reencryption log file.\n"));
304                 return -EIO;
305         }
306
307         return 0;
308 }
309
310 static int parse_line_log(const char *line)
311 {
312         uint64_t u64;
313         int i;
314         char s[64];
315
316         /* comment */
317         if (*line == '#')
318                 return 0;
319
320         if (sscanf(line, "version = %d", &i) == 1) {
321                 if (i != 1) {
322                         log_dbg("Log: Unexpected version = %i", i);
323                         return -EINVAL;
324                 }
325         } else if (sscanf(line, "UUID = %40s", s) == 1) {
326                 if (!rnc.device_uuid || strcmp(rnc.device_uuid, s)) {
327                         log_dbg("Log: Unexpected UUID %s", s);
328                         return -EINVAL;
329                 }
330         } else if (sscanf(line, "direction = %d", &i) == 1) {
331                 log_dbg("Log: direction = %i", i);
332                 rnc.reencrypt_direction = i;
333         } else if (sscanf(line, "offset = %" PRIu64, &u64) == 1) {
334                 log_dbg("Log: offset = %" PRIu64, u64);
335                 rnc.device_offset = u64;
336         } else if (sscanf(line, "shift = %" PRIu64, &u64) == 1) {
337                 log_dbg("Log: shift = %" PRIu64, u64);
338                 rnc.device_shift = u64;
339         } else
340                 return -EINVAL;
341
342         return 0;
343 }
344
345 static int parse_log(void)
346 {
347         static char buf[512];
348         char *start, *end;
349         ssize_t s;
350
351         s = read(rnc.log_fd, buf, sizeof(buf));
352         if (s == -1)
353                 return -EIO;
354
355         buf[511] = '\0';
356         start = buf;
357         do {
358                 end = strchr(start, '\n');
359                 if (end) {
360                         *end++ = '\0';
361                         if (parse_line_log(start)) {
362                                 log_err("Wrong log format.\n");
363                                 return -EINVAL;
364                         }
365                 }
366
367                 start = end;
368         } while (start);
369
370         return 0;
371 }
372
373 static int open_log(void)
374 {
375         int flags;
376         struct stat st;
377
378         if(stat(rnc.log_file, &st) < 0) {
379                 log_dbg("Creating LUKS reencryption log file %s.", rnc.log_file);
380                 flags = opt_directio ? O_RDWR|O_CREAT|O_DIRECT : O_RDWR|O_CREAT;
381                 rnc.log_fd = open(rnc.log_file, flags, S_IRUSR|S_IWUSR);
382                 if (rnc.log_fd == -1)
383                         return -EINVAL;
384                 if (write_log() < 0)
385                         return -EIO;
386         } else {
387                 log_dbg("Log file %s exists, restarting.", rnc.log_file);
388                 flags = opt_directio ? O_RDWR|O_DIRECT : O_RDWR;
389                 rnc.log_fd = open(rnc.log_file, flags);
390                 if (rnc.log_fd == -1)
391                         return -EINVAL;
392                 rnc.in_progress = 1;
393         }
394
395         /* Be sure it is correct format */
396         return parse_log();
397 }
398
399 static void close_log(void)
400 {
401         log_dbg("Closing LUKS reencryption log file %s.", rnc.log_file);
402         if (rnc.log_fd != -1)
403                 close(rnc.log_fd);
404 }
405
406 static int activate_luks_headers(void)
407 {
408         struct crypt_device *cd = NULL, *cd_new = NULL;
409         int r;
410
411         log_dbg("Activating LUKS devices from headers.");
412
413         if ((r = crypt_init(&cd, rnc.header_file_org)) ||
414             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
415             (r = crypt_set_data_device(cd, rnc.device)))
416                 goto out;
417
418         if ((r = crypt_activate_by_passphrase(cd, rnc.header_file_org,
419                 opt_key_slot, rnc.p[rnc.keyslot].password, rnc.p[rnc.keyslot].passwordLen,
420                 CRYPT_ACTIVATE_READONLY|CRYPT_ACTIVATE_PRIVATE)) < 0)
421                 goto out;
422
423         if ((r = crypt_init(&cd_new, rnc.header_file_new)) ||
424             (r = crypt_load(cd_new, CRYPT_LUKS1, NULL)) ||
425             (r = crypt_set_data_device(cd_new, rnc.device)))
426                 goto out;
427
428         if ((r = crypt_activate_by_passphrase(cd_new, rnc.header_file_new,
429                 opt_key_slot, rnc.p[rnc.keyslot].password, rnc.p[rnc.keyslot].passwordLen,
430                 CRYPT_ACTIVATE_SHARED|CRYPT_ACTIVATE_PRIVATE)) < 0)
431                 goto out;
432         r = 0;
433 out:
434         crypt_free(cd);
435         crypt_free(cd_new);
436         if (r < 0)
437                 log_err("Activation of devices failed.\n");
438         return r;
439 }
440
441 static int backup_luks_headers(void)
442 {
443         struct crypt_device *cd = NULL, *cd_new = NULL;
444         struct crypt_params_luks1 params = {0};
445         char cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
446         int i, r;
447
448         log_dbg("Creating LUKS header backup for device %s.", rnc.device);
449         if ((r = crypt_init(&cd, rnc.device)) ||
450             (r = crypt_load(cd, CRYPT_LUKS1, NULL)))
451                 goto out;
452
453         crypt_set_confirm_callback(cd, NULL, NULL);
454         if ((r = crypt_header_backup(cd, CRYPT_LUKS1, rnc.header_file_org)))
455                 goto out;
456
457         if ((r = create_empty_header(rnc.header_file_new, rnc.header_file_org)))
458                 goto out;
459
460         params.hash = opt_hash ?: DEFAULT_LUKS1_HASH;
461         params.data_alignment = crypt_get_data_offset(cd);
462         params.data_device = rnc.device;
463
464         if ((r = crypt_init(&cd_new, rnc.header_file_new)))
465                 goto out;
466
467         if (opt_random)
468                 crypt_set_rng_type(cd_new, CRYPT_RNG_RANDOM);
469         else if (opt_urandom)
470                 crypt_set_rng_type(cd_new, CRYPT_RNG_URANDOM);
471
472         if (opt_iteration_time)
473                 crypt_set_iteration_time(cd_new, opt_iteration_time);
474
475         if (opt_cipher) {
476                 r = crypt_parse_name_and_mode(opt_cipher, cipher, NULL, cipher_mode);
477                 if (r < 0) {
478                         log_err(_("No known cipher specification pattern detected.\n"));
479                         goto out;
480                 }
481         }
482
483         if ((r = crypt_format(cd_new, CRYPT_LUKS1,
484                         opt_cipher ? cipher : crypt_get_cipher(cd),
485                         opt_cipher ? cipher_mode : crypt_get_cipher_mode(cd),
486                         crypt_get_uuid(cd),
487                         NULL, crypt_get_volume_key_size(cd), &params)))
488                 goto out;
489
490         for (i = 0; i < MAX_SLOT; i++) {
491                 if (!rnc.p[i].password)
492                         continue;
493                 if ((r = crypt_keyslot_add_by_volume_key(cd_new, i,
494                         NULL, 0, rnc.p[i].password, rnc.p[i].passwordLen)) < 0)
495                         goto out;
496                 r = 0;
497         }
498
499 out:
500         crypt_free(cd);
501         crypt_free(cd_new);
502         return r;
503 }
504
505 static void remove_headers(void)
506 {
507         struct crypt_device *cd = NULL;
508
509         log_dbg("Removing headers.");
510
511         if (crypt_init(&cd, NULL))
512                 return;
513         crypt_set_log_callback(cd, _quiet_log, NULL);
514         (void)crypt_deactivate(cd, rnc.header_file_org);
515         (void)crypt_deactivate(cd, rnc.header_file_new);
516         crypt_free(cd);
517 }
518
519 static int restore_luks_header(const char *backup)
520 {
521         struct crypt_device *cd = NULL;
522         int r;
523
524         log_dbg("Restoring header for %s.", backup);
525
526         r = crypt_init(&cd, rnc.device);
527
528         if (r == 0) {
529                 crypt_set_confirm_callback(cd, NULL, NULL);
530                 r = crypt_header_restore(cd, CRYPT_LUKS1, backup);
531         }
532
533         crypt_free(cd);
534         return r;
535 }
536
537 void print_progress(uint64_t bytes, int final)
538 {
539         uint64_t mbytes = (bytes - rnc.restart_bytes) / 1024 / 1024;
540         struct timeval now_time;
541         double tdiff;
542
543         gettimeofday(&now_time, NULL);
544         if (!final && time_diff(rnc.end_time, now_time) < 0.5)
545                 return;
546
547         rnc.end_time = now_time;
548
549         if (opt_batch_mode)
550                 return;
551
552         tdiff = time_diff(rnc.start_time, rnc.end_time);
553         if (!tdiff)
554                 return;
555
556         log_err("\33[2K\rProgress: %5.1f%%, time elapsed %3.1f seconds, %4"
557                 PRIu64 " MB written, speed %5.1f MB/s%s",
558                 (double)bytes / rnc.device_size * 100,
559                 time_diff(rnc.start_time, rnc.end_time),
560                 mbytes, (double)(mbytes) / tdiff,
561                 final ? "\n" :"");
562 }
563
564 static int copy_data_forward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
565 {
566         ssize_t s1, s2;
567
568         log_dbg("Reencrypting forward.");
569
570         if (lseek64(fd_old, rnc.device_offset, SEEK_SET) < 0 ||
571             lseek64(fd_new, rnc.device_offset, SEEK_SET) < 0) {
572                 log_err("Cannot seek to device offset.\n");
573                 return -EIO;
574         }
575
576         rnc.restart_bytes = *bytes = rnc.device_offset;
577
578         if (write_log() < 0)
579                 return -EIO;
580
581         while (!quit && rnc.device_offset < rnc.device_size) {
582                 s1 = read(fd_old, buf, block_size);
583                 if (s1 < 0 || (s1 != block_size && (rnc.device_offset + s1) != rnc.device_size)) {
584                         log_err("Read error, expecting %d, got %d.\n", (int)block_size, (int)s1);
585                         return -EIO;
586                 }
587                 s2 = write(fd_new, buf, s1);
588                 if (s2 < 0) {
589                         log_err("Write error, expecting %d, got %d.\n", (int)block_size, (int)s2);
590                         return -EIO;
591                 }
592                 rnc.device_offset += s1;
593                 if (opt_write_log && write_log() < 0)
594                         return -EIO;
595
596                 *bytes += (uint64_t)s2;
597                 print_progress(*bytes, 0);
598         }
599
600         return quit ? -EAGAIN : 0;
601 }
602
603 static int copy_data_backward(int fd_old, int fd_new, size_t block_size, void *buf, uint64_t *bytes)
604 {
605         ssize_t s1, s2, working_block;
606         off64_t working_offset;
607
608         log_dbg("Reencrypting backward.");
609
610         if (!rnc.in_progress) {
611                 rnc.device_offset = rnc.device_size;
612                 rnc.restart_bytes = 0;
613                 *bytes = 0;
614         } else {
615                 rnc.restart_bytes = rnc.device_size - rnc.device_offset;
616                 *bytes = rnc.restart_bytes;
617         }
618
619         if (write_log() < 0)
620                 return -EIO;
621
622         while (!quit && rnc.device_offset) {
623                 if (rnc.device_offset < block_size) {
624                         working_offset = 0;
625                         working_block = rnc.device_offset;
626                 } else {
627                         working_offset = rnc.device_offset - block_size;
628                         working_block = block_size;
629                 }
630
631                 if (lseek64(fd_old, working_offset, SEEK_SET) < 0 ||
632                     lseek64(fd_new, working_offset, SEEK_SET) < 0) {
633                         log_err("Cannot seek to device offset.\n");
634                         return -EIO;
635                 }
636
637                 s1 = read(fd_old, buf, working_block);
638                 if (s1 < 0 || (s1 != working_block)) {
639                         log_err("Read error, expecting %d, got %d.\n", (int)block_size, (int)s1);
640                         return -EIO;
641                 }
642                 s2 = write(fd_new, buf, working_block);
643                 if (s2 < 0) {
644                         log_err("Write error, expecting %d, got %d.\n", (int)block_size, (int)s2);
645                         return -EIO;
646                 }
647                 rnc.device_offset -= s1;
648                 if (opt_write_log && write_log() < 0)
649                         return -EIO;
650
651                 *bytes += (uint64_t)s2;
652                 print_progress(*bytes, 0);
653         }
654
655         return quit ? -EAGAIN : 0;
656 }
657
658 static int copy_data(void)
659 {
660         size_t block_size = opt_bsize * 1024 * 1024;
661         int fd_old = -1, fd_new = -1;
662         int r = -EINVAL;
663         void *buf = NULL;
664         uint64_t bytes = 0;
665
666         log_dbg("Data copy preparation.");
667
668         fd_old = open(rnc.crypt_path_org, O_RDONLY | (opt_directio ? O_DIRECT : 0));
669         if (fd_old == -1)
670                 goto out;
671
672         fd_new = open(rnc.crypt_path_new, O_WRONLY | (opt_directio ? O_DIRECT : 0));
673         if (fd_new == -1)
674                 goto out;
675
676         /* Check size */
677         if (ioctl(fd_old, BLKGETSIZE64, &rnc.device_size) < 0)
678                 goto out;
679
680         if (posix_memalign((void *)&buf, alignment(fd_new), block_size)) {
681                 r = -ENOMEM;
682                 goto out;
683         }
684
685         set_int_handler();
686
687         gettimeofday(&rnc.start_time, NULL);
688
689         if (rnc.reencrypt_direction == FORWARD)
690                 r = copy_data_forward(fd_old, fd_new, block_size, buf, &bytes);
691         else
692                 r = copy_data_backward(fd_old, fd_new, block_size, buf, &bytes);
693
694         set_int_block(1);
695         print_progress(bytes, 1);
696
697         if (r == -EAGAIN)
698                  log_err(_("Interrupted by a signal.\n"));
699         else if (r < 0)
700                 log_err("ERROR during reencryption.\n");
701
702         (void)write_log();
703 out:
704         if (fd_old != -1)
705                 close(fd_old);
706         if (fd_new != -1)
707                 close(fd_new);
708         free(buf);
709         return r;
710 }
711
712 static int initialize_uuid(void)
713 {
714         struct crypt_device *cd = NULL;
715         int r;
716
717         log_dbg("Initialising UUID.");
718
719         /* Try to load LUKS from device */
720         if ((r = crypt_init(&cd, rnc.device)))
721                 return r;
722         crypt_set_log_callback(cd, _quiet_log, NULL);
723         r = crypt_load(cd, CRYPT_LUKS1, NULL);
724         if (!r)
725                 rnc.device_uuid = strdup(crypt_get_uuid(cd));
726         else
727                 /* Reencryption already in progress - magic header? */
728                 r = device_magic(CHECK_UNUSABLE);
729
730         crypt_free(cd);
731         return r;
732 }
733
734 static int init_passphrase1(struct crypt_device *cd, const char *msg, int slot_check)
735 {
736         int r = -EINVAL, slot, retry_count;
737
738         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
739
740         retry_count = opt_tries ?: 1;
741         while (retry_count--) {
742                 r = crypt_get_key(msg, &rnc.p[slot].password,
743                         &rnc.p[slot].passwordLen,
744                         0, 0, NULL /*opt_key_file*/,
745                         0, 0, cd);
746                 if (r < 0)
747                         return r;
748
749                 r = crypt_activate_by_passphrase(cd, NULL, slot_check,
750                         rnc.p[slot].password, rnc.p[slot].passwordLen, 0);
751
752                 if (r < 0) {
753                         crypt_safe_free(rnc.p[slot].password);
754                         rnc.p[slot].password = NULL;
755                         rnc.p[slot].passwordLen = 0;
756                 }
757                 if (r < 0 && r != -EPERM)
758                         return r;
759                 if (r >= 0) {
760                         rnc.keyslot = slot;
761                         break;
762                 }
763                 log_err(_("No key available with this passphrase.\n"));
764         }
765         return r;
766 }
767
768 static int init_keyfile(struct crypt_device *cd, int slot_check)
769 {
770         int r, slot;
771
772         slot = (slot_check == CRYPT_ANY_SLOT) ? 0 : slot_check;
773         r = crypt_get_key(NULL, &rnc.p[slot].password, &rnc.p[slot].passwordLen,
774                 opt_keyfile_offset, opt_keyfile_size, opt_key_file, 0, 0, cd);
775         if (r < 0)
776                 return r;
777
778         r = crypt_activate_by_passphrase(cd, NULL, slot_check,
779                 rnc.p[slot].password, rnc.p[slot].passwordLen, 0);
780
781         /*
782          * Allow keyslot only if it is last slot or if user explicitly
783          * specify whch slot to use (IOW others will be disabled).
784          */
785         if (r >= 0 && opt_key_slot == CRYPT_ANY_SLOT &&
786             crypt_keyslot_status(cd, r) != CRYPT_SLOT_ACTIVE_LAST) {
787                 log_err(_("Key file can be used only with --key-slot or with "
788                           "exactly one key slot active.\n"));
789                 r = -EINVAL;
790         }
791
792         if (r < 0) {
793                 crypt_safe_free(rnc.p[slot].password);
794                 rnc.p[slot].password = NULL;
795                 rnc.p[slot].passwordLen = 0;
796                 if (r == -EPERM)
797                         log_err(_("No key available with this passphrase.\n"));
798                 return r;
799         } else
800                 rnc.keyslot = slot;
801
802         return r;
803 }
804
805 static int initialize_passphrase(const char *device)
806 {
807         struct crypt_device *cd = NULL;
808         crypt_keyslot_info ki;
809         char msg[256];
810         int i, r;
811
812         log_dbg("Passhrases initialization.");
813
814         if ((r = crypt_init(&cd, device)) ||
815             (r = crypt_load(cd, CRYPT_LUKS1, NULL)) ||
816             (r = crypt_set_data_device(cd, rnc.device))) {
817                 crypt_free(cd);
818                 return r;
819         }
820
821         if (opt_key_file) {
822                 r = init_keyfile(cd, opt_key_slot);
823         } else if (rnc.in_progress) {
824                 r = init_passphrase1(cd, _("Enter any LUKS passphrase: "), CRYPT_ANY_SLOT);
825         } else for (i = 0; i < MAX_SLOT; i++) {
826                 ki = crypt_keyslot_status(cd, i);
827                 if (ki != CRYPT_SLOT_ACTIVE && ki != CRYPT_SLOT_ACTIVE_LAST)
828                         continue;
829
830                 snprintf(msg, sizeof(msg), _("Enter LUKS passphrase for key slot %u): "), i);
831                 r = init_passphrase1(cd, msg, i);
832                 if (r < 0)
833                         break;
834         }
835
836         crypt_free(cd);
837         return r > 0 ? 0 : r;
838 }
839
840 static int initialize_context(const char *device)
841 {
842         log_dbg("Initialising reencryption context.");
843
844         rnc.log_fd =-1;
845
846         if (!(rnc.device = strndup(device, PATH_MAX)))
847                 return -ENOMEM;
848
849         if (initialize_uuid()) {
850                 log_err("No header found on device.\n");
851                 return -EINVAL;
852         }
853
854         /* Prepare device names */
855         if (snprintf(rnc.log_file, PATH_MAX,
856                      "LUKS-%s.log", rnc.device_uuid) < 0)
857                 return -ENOMEM;
858         if (snprintf(rnc.header_file_org, PATH_MAX,
859                      "LUKS-%s.org", rnc.device_uuid) < 0)
860                 return -ENOMEM;
861         if (snprintf(rnc.header_file_new, PATH_MAX,
862                      "LUKS-%s.new", rnc.device_uuid) < 0)
863                 return -ENOMEM;
864
865         /* Paths to encrypted devices */
866         if (snprintf(rnc.crypt_path_org, PATH_MAX,
867                      "%s/%s", crypt_get_dir(), rnc.header_file_org) < 0)
868                 return -ENOMEM;
869         if (snprintf(rnc.crypt_path_new, PATH_MAX,
870                      "%s/%s", crypt_get_dir(), rnc.header_file_new) < 0)
871                 return -ENOMEM;
872
873         remove_headers();
874
875         if (open_log() < 0) {
876                 log_err(_("Cannot open reencryption log file.\n"));
877                 return -EINVAL;
878         }
879
880         if (!rnc.in_progress) {
881                 if (1 /*opt_new */)
882                         rnc.reencrypt_direction = FORWARD;
883                 else {
884                         rnc.reencrypt_direction = BACKWARD;
885                         rnc.device_offset = (uint64_t)~0;
886                 }
887         }
888
889         return 0;
890 }
891
892 static void destroy_context(void)
893 {
894         int i;
895
896         log_dbg("Destroying reencryption context.");
897
898         close_log();
899         remove_headers();
900
901         if ((rnc.reencrypt_direction == FORWARD &&
902              rnc.device_offset == rnc.device_size) ||
903              rnc.device_offset == 0) {
904                 unlink(rnc.log_file);
905                 unlink(rnc.header_file_org);
906                 unlink(rnc.header_file_new);
907         }
908
909         for (i = 0; i < MAX_SLOT; i++)
910                 crypt_safe_free(rnc.p[i].password);
911
912         free(rnc.device);
913         free(rnc.device_uuid);
914 }
915
916 int run_reencrypt(const char *device)
917 {
918         int r = -EINVAL;
919         if (initialize_context(device))
920                 goto out;
921
922         log_dbg("Running reencryption.");
923
924         if (!rnc.in_progress) {
925                 if ((r = initialize_passphrase(rnc.device)) ||
926                     (r = backup_luks_headers()) ||
927                     (r = device_magic(MAKE_UNUSABLE)))
928                         goto out;
929         } else {
930                 if ((r = initialize_passphrase(rnc.header_file_new)))
931                         goto out;
932         }
933
934         if ((r = activate_luks_headers()))
935                 goto out;
936
937         if ((r = copy_data()))
938                 goto out;
939
940         r = restore_luks_header(rnc.header_file_new);
941 out:
942         destroy_context();
943         return r;
944 }
945
946 static __attribute__ ((noreturn)) void usage(poptContext popt_context,
947                                              int exitcode, const char *error,
948                                              const char *more)
949 {
950         poptPrintUsage(popt_context, stderr, 0);
951         if (error)
952                 log_err("%s: %s\n", more, error);
953         poptFreeContext(popt_context);
954         exit(exitcode);
955 }
956
957 static void help(poptContext popt_context,
958                  enum poptCallbackReason reason __attribute__((unused)),
959                  struct poptOption *key,
960                  const char *arg __attribute__((unused)),
961                  void *data __attribute__((unused)))
962 {
963         usage(popt_context, EXIT_SUCCESS, NULL, NULL);
964 }
965
966 static void _dbg_version_and_cmd(int argc, const char **argv)
967 {
968         int i;
969
970         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
971         for (i = 0; i < argc; i++) {
972                 if (i)
973                         log_std(" ");
974                 log_std("%s", argv[i]);
975         }
976         log_std("\"\n");
977 }
978
979 int main(int argc, const char **argv)
980 {
981         static struct poptOption popt_help_options[] = {
982                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
983                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
984                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
985                 POPT_TABLEEND
986         };
987         static struct poptOption popt_options[] = {
988                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
989                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
990                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
991                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
992                 { "block-size",        'B',  POPT_ARG_INT, &opt_bsize,                  0, N_("Reencryption block size"), N_("MB") },
993                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
994                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
995                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file."), NULL },
996                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
997                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
998                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
999                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
1000                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
1001                 { "use-directio",      '\0', POPT_ARG_NONE, &opt_directio,              0, N_("Use direct-io when accesing devices."), NULL },
1002                 { "write-log",         '\0', POPT_ARG_NONE, &opt_write_log,             0, N_("Update log file after every block."), NULL },
1003                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Use only this slot (others will be disabled)."), NULL },
1004                 { "keyfile-offset",   '\0',  POPT_ARG_LONG, &opt_keyfile_offset,        0, N_("Number of bytes to skip in keyfile"), N_("bytes") },
1005                 { "keyfile-size",      'l',  POPT_ARG_LONG, &opt_keyfile_size,          0, N_("Limits the read from keyfile"), N_("bytes") },
1006                 POPT_TABLEEND
1007         };
1008         poptContext popt_context;
1009         int r;
1010
1011         crypt_set_log_callback(NULL, _log, NULL);
1012         log_err("WARNING: this is experimental code, it can completely break your data.\n");
1013
1014         set_int_block(1);
1015
1016         setlocale(LC_ALL, "");
1017         bindtextdomain(PACKAGE, LOCALEDIR);
1018         textdomain(PACKAGE);
1019
1020         popt_context = poptGetContext(PACKAGE, argc, argv, popt_options, 0);
1021         poptSetOtherOptionHelp(popt_context,
1022                                N_("[OPTION...] <device>]"));
1023
1024         while((r = poptGetNextOpt(popt_context)) > 0) {
1025                 if (r < 0)
1026                         break;
1027         }
1028
1029         if (r < -1)
1030                 usage(popt_context, EXIT_FAILURE, poptStrerror(r),
1031                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
1032         if (opt_version_mode) {
1033                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
1034                 poptFreeContext(popt_context);
1035                 exit(EXIT_SUCCESS);
1036         }
1037
1038         action_argv = poptGetArgs(popt_context);
1039         if(!action_argv)
1040                 usage(popt_context, EXIT_FAILURE, _("Argument required."),
1041                       poptGetInvocationName(popt_context));
1042
1043         if (opt_random && opt_urandom)
1044                 usage(popt_context, EXIT_FAILURE, _("Only one of --use-[u]random options is allowed."),
1045                       poptGetInvocationName(popt_context));
1046
1047         if (opt_debug) {
1048                 opt_verbose = 1;
1049                 crypt_set_debug_level(-1);
1050                 _dbg_version_and_cmd(argc, argv);
1051         }
1052
1053         r = run_reencrypt(action_argv[0]);
1054
1055         poptFreeContext(popt_context);
1056
1057         /* Translate exit code to simple codes */
1058         switch (r) {
1059         case 0:         r = EXIT_SUCCESS; break;
1060         case -EEXIST:
1061         case -EBUSY:    r = 5; break;
1062         case -ENOTBLK:
1063         case -ENODEV:   r = 4; break;
1064         case -ENOMEM:   r = 3; break;
1065         case -EPERM:    r = 2; break;
1066         case -EAGAIN:
1067         case -EINVAL:
1068         case -ENOENT:
1069         case -ENOSYS:
1070         default:        r = EXIT_FAILURE;
1071         }
1072         return r;
1073 }