e86b6260957d18ac3ac0662ae1ed655474d70459
[platform/upstream/cryptsetup.git] / src / cryptsetup.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <stdint.h>
5 #include <stdarg.h>
6 #include <inttypes.h>
7 #include <errno.h>
8 #include <unistd.h>
9 #include <fcntl.h>
10 #include <assert.h>
11
12 #include <libcryptsetup.h>
13 #include <popt.h>
14
15 #include "../config.h"
16
17 #include "cryptsetup.h"
18
19 static int opt_verbose = 0;
20 static int opt_debug = 0;
21 static char *opt_cipher = NULL;
22 static char *opt_hash = NULL;
23 static int opt_verify_passphrase = 0;
24 static char *opt_key_file = NULL;
25 static char *opt_master_key_file = NULL;
26 static char *opt_header_backup_file = NULL;
27 static char *opt_uuid = NULL;
28 static unsigned int opt_key_size = 0;
29 static int opt_key_slot = CRYPT_ANY_SLOT;
30 static uint64_t opt_size = 0;
31 static uint64_t opt_offset = 0;
32 static uint64_t opt_skip = 0;
33 static int opt_readonly = 0;
34 static int opt_iteration_time = 1000;
35 static int opt_batch_mode = 0;
36 static int opt_version_mode = 0;
37 static int opt_timeout = 0;
38 static int opt_tries = 3;
39 static int opt_align_payload = 0;
40 static int opt_non_exclusive = 0;
41 static int opt_random = 0;
42 static int opt_urandom = 0;
43
44 static const char **action_argv;
45 static int action_argc;
46
47 static int action_create(int arg);
48 static int action_remove(int arg);
49 static int action_resize(int arg);
50 static int action_status(int arg);
51 static int action_luksFormat(int arg);
52 static int action_luksOpen(int arg);
53 static int action_luksAddKey(int arg);
54 static int action_luksDelKey(int arg);
55 static int action_luksKillSlot(int arg);
56 static int action_luksRemoveKey(int arg);
57 static int action_isLuks(int arg);
58 static int action_luksUUID(int arg);
59 static int action_luksDump(int arg);
60 static int action_luksSuspend(int arg);
61 static int action_luksResume(int arg);
62 static int action_luksBackup(int arg);
63 static int action_luksRestore(int arg);
64
65 static struct action_type {
66         const char *type;
67         int (*handler)(int);
68         int arg;
69         int required_action_argc;
70         int required_memlock;
71         const char *arg_desc;
72         const char *desc;
73 } action_types[] = {
74         { "create",     action_create,          0, 2, 1, N_("<name> <device>"),N_("create device") },
75         { "remove",     action_remove,          0, 1, 1, N_("<name>"), N_("remove device") },
76         { "resize",     action_resize,          0, 1, 1, N_("<name>"), N_("resize active device") },
77         { "status",     action_status,          0, 1, 0, N_("<name>"), N_("show device status") },
78         { "luksFormat", action_luksFormat,      0, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
79         { "luksOpen",   action_luksOpen,        0, 2, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
80         { "luksAddKey", action_luksAddKey,      0, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
81         { "luksRemoveKey",action_luksRemoveKey, 0, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
82         { "luksKillSlot",  action_luksKillSlot, 0, 2, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
83         { "luksUUID",   action_luksUUID,        0, 1, 0, N_("<device>"), N_("print UUID of LUKS device") },
84         { "isLuks",     action_isLuks,          0, 1, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
85         { "luksClose",  action_remove,          0, 1, 1, N_("<name>"), N_("remove LUKS mapping") },
86         { "luksDump",   action_luksDump,        0, 1, 0, N_("<device>"), N_("dump LUKS partition information") },
87         { "luksSuspend",action_luksSuspend,     0, 1, 1, N_("<device>"), N_("Suspend LUKS device and wipe key (all IOs are frozen).") },
88         { "luksResume", action_luksResume,      0, 1, 1, N_("<device>"), N_("Resume suspended LUKS device.") },
89         { "luksHeaderBackup",action_luksBackup, 0, 1, 1, N_("<device>"), N_("Backup LUKS device header and keyslots") },
90         { "luksHeaderRestore",action_luksRestore,0,1, 1, N_("<device>"), N_("Restore LUKS device header and keyslots") },
91         { "luksDelKey", action_luksDelKey,      0, 2, 1, N_("<device> <key slot>"), N_("identical to luksKillSlot - DEPRECATED - see man page") },
92         { "reload",     action_create,          1, 2, 1, N_("<name> <device>"), N_("modify active device - DEPRECATED - see man page") },
93         { NULL, NULL, 0, 0, 0, NULL, NULL }
94 };
95
96 static void clogger(struct crypt_device *cd, int level, const char *file,
97                    int line, const char *format, ...)
98 {
99         va_list argp;
100         char *target = NULL;
101
102         va_start(argp, format);
103
104         if (vasprintf(&target, format, argp) > 0) {
105                 if (level >= 0) {
106                         crypt_log(cd, level, target);
107 #ifdef CRYPT_DEBUG
108                 } else if (opt_debug)
109                         printf("# %s:%d %s\n", file ?: "?", line, target);
110 #else
111                 } else if (opt_debug)
112                         printf("# %s\n", target);
113 #endif
114         }
115
116         va_end(argp);
117         free(target);
118 }
119
120 /* Interface Callbacks */
121 static int yesDialog(char *msg)
122 {
123         char *answer = NULL;
124         size_t size = 0;
125         int r = 1;
126
127         if(isatty(0) && !opt_batch_mode) {
128                 log_std("\nWARNING!\n========\n");
129                 log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
130                 if(getline(&answer, &size, stdin) == -1) {
131                         perror("getline");
132                         free(answer);
133                         return 0;
134                 }
135                 if(strcmp(answer, "YES\n"))
136                         r = 0;
137                 free(answer);
138         }
139
140         return r;
141 }
142
143 static void cmdLineLog(int level, char *msg) {
144         switch(level) {
145
146         case CRYPT_LOG_NORMAL:
147                 fputs(msg, stdout);
148                 break;
149         case CRYPT_LOG_VERBOSE:
150                 if (opt_verbose)
151                         fputs(msg, stdout);
152                 break;
153         case CRYPT_LOG_ERROR:
154                 fputs(msg, stderr);
155                 break;
156         default:
157                 fprintf(stderr, "Internal error on logging class for msg: %s", msg);
158                 break;
159         }
160 }
161
162 static struct interface_callbacks cmd_icb = {
163         .yesDialog = yesDialog,
164         .log = cmdLineLog,
165 };
166
167 static void _log(int level, const char *msg, void *usrptr)
168 {
169         cmdLineLog(level, (char *)msg);
170 }
171
172 static int _yesDialog(const char *msg, void *usrptr)
173 {
174         return yesDialog((char*)msg);
175 }
176
177 /* End ICBs */
178
179 static void show_status(int errcode)
180 {
181         char error[256], *error_;
182
183         if(!opt_verbose)
184                 return;
185
186         if(!errcode) {
187                 log_std(_("Command successful.\n"));
188                 return;
189         }
190
191         crypt_get_error(error, sizeof(error));
192
193         if (!error[0]) {
194                 error_ = strerror_r(-errcode, error, sizeof(error));
195                 if (error_ != error) {
196                         strncpy(error, error_, sizeof(error));
197                         error[sizeof(error) - 1] = '\0';
198                 }
199         }
200
201         log_err(_("Command failed with code %i"), -errcode);
202         if (*error)
203                 log_err(": %s\n", error);
204         else
205                 log_err(".\n");
206 }
207
208 static int action_create(int reload)
209 {
210         struct crypt_options options = {
211                 .name = action_argv[0],
212                 .device = action_argv[1],
213                 .cipher = opt_cipher ? opt_cipher : DEFAULT_CIPHER(PLAIN),
214                 .hash = opt_hash ?: DEFAULT_PLAIN_HASH,
215                 .key_file = opt_key_file,
216                 .key_size = (opt_key_size ?: DEFAULT_PLAIN_KEYBITS) / 8,
217                 .key_slot = opt_key_slot,
218                 .flags = 0,
219                 .size = opt_size,
220                 .offset = opt_offset,
221                 .skip = opt_skip,
222                 .timeout = opt_timeout,
223                 .tries = opt_tries,
224                 .icb = &cmd_icb,
225         };
226         int r;
227
228         if(reload) 
229                 log_err(_("The reload action is deprecated. Please use \"dmsetup reload\" in case you really need this functionality.\nWARNING: do not use reload to touch LUKS devices. If that is the case, hit Ctrl-C now.\n"));
230
231         if (options.hash && strcmp(options.hash, "plain") == 0)
232                 options.hash = NULL;
233         if (opt_verify_passphrase)
234                 options.flags |= CRYPT_FLAG_VERIFY;
235         if (opt_readonly)
236                 options.flags |= CRYPT_FLAG_READONLY;
237
238         if (reload)
239                 r = crypt_update_device(&options);
240         else
241                 r = crypt_create_device(&options);
242
243         return r;
244 }
245
246 static int action_remove(int arg)
247 {
248         struct crypt_options options = {
249                 .name = action_argv[0],
250                 .icb = &cmd_icb,
251         };
252
253         return crypt_remove_device(&options);
254 }
255
256 static int action_resize(int arg)
257 {
258         struct crypt_options options = {
259                 .name = action_argv[0],
260                 .size = opt_size,
261                 .icb = &cmd_icb,
262         };
263
264         return crypt_resize_device(&options);
265 }
266
267 static int action_status(int arg)
268 {
269         struct crypt_options options = {
270                 .name = action_argv[0],
271                 .icb = &cmd_icb,
272         };
273         int r;
274
275         r = crypt_query_device(&options);
276         if (r < 0)
277                 return r;
278
279         if (r == 0) {
280                 /* inactive */
281                 log_std("%s/%s is inactive.\n", crypt_get_dir(), options.name);
282                 r = 1;
283         } else {
284                 /* active */
285                 log_std("%s/%s is active:\n", crypt_get_dir(), options.name);
286                 log_std("  cipher:  %s\n", options.cipher);
287                 log_std("  keysize: %d bits\n", options.key_size * 8);
288                 log_std("  device:  %s\n", options.device ?: "");
289                 log_std("  offset:  %" PRIu64 " sectors\n", options.offset);
290                 log_std("  size:    %" PRIu64 " sectors\n", options.size);
291                 if (options.skip)
292                         log_std("  skipped: %" PRIu64 " sectors\n", options.skip);
293                 log_std("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
294                                            ? "readonly" : "read/write");
295                 crypt_put_options(&options);
296                 r = 0;
297         }
298         return r;
299 }
300
301 static int _read_mk(const char *file, char **key, int keysize)
302 {
303         int fd;
304
305         *key = crypt_safe_alloc(keysize);
306         if (!*key)
307                 return -ENOMEM;
308
309         fd = open(file, O_RDONLY);
310         if (fd == -1) {
311                 log_err("Cannot read keyfile %s.\n", file);
312                 return -EINVAL;
313         }
314         if ((read(fd, *key, keysize) != keysize)) {
315                 log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
316                 close(fd);
317                 crypt_safe_free(*key);
318                 return -EINVAL;
319         }
320         close(fd);
321         return 0;
322 }
323
324 static int action_luksFormat(int arg)
325 {
326         int r = -EINVAL, keysize;
327         char *msg = NULL, *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
328         const char *key_file = NULL;
329         char *password = NULL;
330         unsigned int passwordLen;
331         struct crypt_device *cd = NULL;
332         struct crypt_params_luks1 params = {
333                 .hash = opt_hash ?: DEFAULT_LUKS1_HASH,
334                 .data_alignment = opt_align_payload,
335         };
336
337         /* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
338         if (opt_offset || opt_skip) {
339                 log_err("Options --offset and --skip are not supported for luksFormat.\n");
340                 r = -EINVAL;
341                 goto out;;
342         }
343
344         if (action_argc > 1) {
345                 key_file = action_argv[1];
346                 if (opt_key_file)
347                         log_err(_("Option --key-file takes precedence over specified key file argument.\n"));
348         } else
349                 key_file = opt_key_file;
350
351         if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
352                 log_err(_("memory allocation error in action_luksFormat"));
353                 r = -ENOMEM;
354                 goto out;
355         }
356         r = yesDialog(msg);
357         free(msg);
358
359         if (!r) {
360                 r = -EINVAL;
361                 goto out;
362         }
363
364         r = crypt_parse_name_and_mode(opt_cipher ?: DEFAULT_CIPHER(LUKS1),
365                                       cipher, cipher_mode);
366         if (r < 0) {
367                 log_err("No known cipher specification pattern detected.\n");
368                 goto out;
369         }
370
371         if ((r = crypt_init(&cd, action_argv[0])))
372                 goto out;
373
374         crypt_set_log_callback(cd, _log, NULL);
375
376         keysize = (opt_key_size ?: DEFAULT_LUKS1_KEYBITS) / 8;
377
378         crypt_set_password_verify(cd, 1);
379         crypt_set_timeout(cd, opt_timeout);
380         if (opt_iteration_time)
381                 crypt_set_iterarion_time(cd, opt_iteration_time);
382
383         if (opt_random)
384                 crypt_set_rng_type(cd, CRYPT_RNG_RANDOM);
385         else if (opt_urandom)
386                 crypt_set_rng_type(cd, CRYPT_RNG_URANDOM);
387
388         if (opt_master_key_file) {
389                 r = _read_mk(opt_master_key_file, &key, keysize);
390                 if (r < 0)
391                         goto out;
392
393                 r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
394                                  opt_uuid, key, keysize, &params);
395                 if (r < 0)
396                         goto out;
397
398                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
399                                                     key, keysize, NULL, 0);
400         } else {
401                 crypt_get_key(_("Enter LUKS passphrase: "),
402                               &password, &passwordLen, 0,
403                               key_file, opt_timeout,
404                               opt_batch_mode ? 0 : 1, /* always verify */
405                               cd);
406
407                 if(!password) {
408                         r = -EINVAL;
409                         goto out;
410                 }
411
412                 r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode,
413                                  opt_uuid, NULL, keysize, &params);
414                 if (r < 0)
415                         goto out;
416
417                 /* Add keyslot using internally stored volume key generated during format */
418                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
419                                                     NULL, 0, password, passwordLen);
420         }
421 out:
422         crypt_free(cd);
423         crypt_safe_free(key);
424         crypt_safe_free(password);
425
426         return (r < 0) ? r : 0;
427 }
428
429 static int action_luksOpen(int arg)
430 {
431         struct crypt_device *cd = NULL;
432         uint32_t flags = 0;
433         int r;
434
435         if ((r = crypt_init(&cd, action_argv[0])))
436                 goto out;
437
438         crypt_set_log_callback(cd, _log, NULL);
439
440         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
441                 goto out;
442
443         crypt_set_timeout(cd, opt_timeout);
444         crypt_set_password_retry(cd, opt_tries);
445
446         if (opt_iteration_time)
447                 crypt_set_iterarion_time(cd, opt_iteration_time);
448         if (opt_readonly)
449                 flags |= CRYPT_ACTIVATE_READONLY;
450
451         if (opt_non_exclusive)
452                 log_err(_("Obsolete option --non-exclusive is ignored.\n"));
453
454         if (opt_key_file) {
455                 crypt_set_password_retry(cd, 1);
456                 /* limit bytes read from keyfile using opt_key_size*/
457                 r = crypt_activate_by_keyfile(cd, action_argv[1],
458                         CRYPT_ANY_SLOT, opt_key_file, opt_key_size / 8,
459                         flags);
460         } else
461                 r = crypt_activate_by_passphrase(cd, action_argv[1],
462                         CRYPT_ANY_SLOT, NULL, 0, flags);
463 out:
464         crypt_free(cd);
465         return (r < 0) ? r : 0;
466 }
467
468 /* FIXME: keyslot operation needs better get_key() implementation. Use old API for now */
469 static int action_luksDelKey(int arg)
470 {
471         log_err("luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
472         return action_luksKillSlot(arg);
473 }
474
475 static int action_luksKillSlot(int arg)
476 {
477         struct crypt_options options = {
478                 .device = action_argv[0],
479                 .key_slot = atoi(action_argv[1]),
480                 .key_file = opt_key_file,
481                 .timeout = opt_timeout,
482                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
483                 .icb = &cmd_icb,
484         };
485
486         return crypt_luksKillSlot(&options);
487 }
488
489 static int action_luksRemoveKey(int arg)
490 {
491         struct crypt_options options = {
492                 .device = action_argv[0],
493                 .new_key_file = action_argc>1?action_argv[1]:NULL,
494                 .key_file = opt_key_file,
495                 .timeout = opt_timeout,
496                 .flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
497                 .icb = &cmd_icb,
498         };
499
500         return crypt_luksRemoveKey(&options);
501 }
502
503 static int action_luksAddKey(int arg)
504 {
505         int r = -EINVAL, keysize = 0;
506         char *key = NULL;
507         const char *opt_new_key_file = (action_argc > 1 ? action_argv[1] : NULL);
508         struct crypt_device *cd = NULL;
509
510         if ((r = crypt_init(&cd, action_argv[0])))
511                 goto out;
512
513         crypt_set_log_callback(cd, _log, NULL);
514         crypt_set_confirm_callback(cd, _yesDialog, NULL);
515
516         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
517                 goto out;
518
519         keysize = crypt_get_volume_key_size(cd);
520         crypt_set_password_verify(cd, opt_verify_passphrase ? 1 : 0);
521         crypt_set_timeout(cd, opt_timeout);
522         if (opt_iteration_time)
523                 crypt_set_iterarion_time(cd, opt_iteration_time);
524
525         if (opt_master_key_file) {
526                 if (_read_mk(opt_master_key_file, &key, keysize) < 0)
527                         goto out;
528
529                 r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot,
530                                                     key, keysize, NULL, 0);
531         } else if (opt_key_file || opt_new_key_file) {
532                 r = crypt_keyslot_add_by_keyfile(cd, opt_key_slot,
533                                                  opt_key_file, 0,
534                                                  opt_new_key_file, 0);
535         } else {
536                 r = crypt_keyslot_add_by_passphrase(cd, opt_key_slot,
537                                                     NULL, 0, NULL, 0);
538         }
539 out:
540         crypt_free(cd);
541         crypt_safe_free(key);
542
543         return (r < 0) ? r : 0;
544 }
545
546 static int action_isLuks(int arg)
547 {
548         struct crypt_options options = {
549                 .device = action_argv[0],
550                 .icb = &cmd_icb,
551         };
552
553         return crypt_isLuks(&options);
554 }
555
556 static int action_luksUUID(int arg)
557 {
558         struct crypt_device *cd = NULL;
559         const char *existing_uuid = NULL;
560         int r;
561
562         if ((r = crypt_init(&cd, action_argv[0])))
563                 goto out;
564
565         crypt_set_log_callback(cd, _log, NULL);
566         crypt_set_confirm_callback(cd, _yesDialog, NULL);
567
568         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
569                 goto out;
570
571         if (opt_uuid)
572                 r = crypt_set_uuid(cd, opt_uuid);
573         else {
574                 existing_uuid = crypt_get_uuid(cd);
575                 log_std("%s\n", existing_uuid ?: "");
576                 r = existing_uuid ? 0 : 1;
577         }
578 out:
579         crypt_free(cd);
580         return r;
581
582 }
583
584 static int action_luksDump(int arg)
585 {
586         struct crypt_options options = {
587                 .device = action_argv[0],
588                 .icb = &cmd_icb,
589         };
590
591         return crypt_luksDump(&options);
592 }
593
594 static int action_luksSuspend(int arg)
595 {
596         struct crypt_device *cd = NULL;
597         int r;
598
599         r = crypt_init_by_name(&cd, action_argv[0]);
600         if (!r)
601                 r = crypt_suspend(cd, action_argv[0]);
602
603         crypt_free(cd);
604         return r;
605 }
606
607 static int action_luksResume(int arg)
608 {
609         struct crypt_device *cd = NULL;
610         int r;
611
612         if ((r = crypt_init_by_name(&cd, action_argv[0])))
613                 goto out;
614
615         if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
616                 goto out;
617
618         if (opt_key_file)
619                 r = crypt_resume_by_keyfile(cd, action_argv[0], CRYPT_ANY_SLOT,
620                                             opt_key_file, opt_key_size / 8);
621         else
622                 r = crypt_resume_by_passphrase(cd, action_argv[0], CRYPT_ANY_SLOT,
623                                                NULL, 0);
624 out:
625         crypt_free(cd);
626         return r;
627 }
628
629 static int action_luksBackup(int arg)
630 {
631         struct crypt_device *cd = NULL;
632         int r;
633
634         if (!opt_header_backup_file) {
635                 log_err(_("Option --header-backup-file is required.\n"));
636                 return -EINVAL;
637         }
638
639         if ((r = crypt_init(&cd, action_argv[0])))
640                 goto out;
641
642         crypt_set_log_callback(cd, _log, NULL);
643         crypt_set_confirm_callback(cd, _yesDialog, NULL);
644
645         r = crypt_header_backup(cd, CRYPT_LUKS1, opt_header_backup_file);
646 out:
647         crypt_free(cd);
648         return r;
649 }
650
651 static int action_luksRestore(int arg)
652 {
653         struct crypt_device *cd = NULL;
654         int r = 0;
655
656         if (!opt_header_backup_file) {
657                 log_err(_("Option --header-backup-file is required.\n"));
658                 return -EINVAL;
659         }
660
661         if ((r = crypt_init(&cd, action_argv[0])))
662                 goto out;
663
664         crypt_set_log_callback(cd, _log, NULL);
665         crypt_set_confirm_callback(cd, _yesDialog, NULL);
666         r = crypt_header_restore(cd, CRYPT_LUKS1, opt_header_backup_file);
667 out:
668         crypt_free(cd);
669         return r;
670 }
671
672 static void usage(poptContext popt_context, int exitcode,
673                   const char *error, const char *more)
674 {
675         poptPrintUsage(popt_context, stderr, 0);
676         if (error)
677                 log_err("%s: %s\n", more, error);
678         exit(exitcode);
679 }
680
681 static void help(poptContext popt_context, enum poptCallbackReason reason,
682                  struct poptOption *key, const char * arg, void *data)
683 {
684         if (key->shortName == '?') {
685                 struct action_type *action;
686
687                 log_std("%s\n",PACKAGE_STRING);
688
689                 poptPrintHelp(popt_context, stdout, 0);
690
691                 log_std(_("\n"
692                          "<action> is one of:\n"));
693
694                 for(action = action_types; action->type; action++)
695                         log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
696                 
697                 log_std(_("\n"
698                          "<name> is the device to create under %s\n"
699                          "<device> is the encrypted device\n"
700                          "<key slot> is the LUKS key slot number to modify\n"
701                          "<key file> optional key file for the new key for luksAddKey action\n"),
702                         crypt_get_dir());
703
704                 log_std(_("\nDefault compiled-in device cipher parameters:\n"
705                          "\tplain: %s, Key: %d bits, Password hashing: %s\n"
706                          "\tLUKS1: %s, Key: %d bits, LUKS header hashing: %s, RNG: %s\n"),
707                          DEFAULT_CIPHER(PLAIN), DEFAULT_PLAIN_KEYBITS, DEFAULT_PLAIN_HASH,
708                          DEFAULT_CIPHER(LUKS1), DEFAULT_LUKS1_KEYBITS, DEFAULT_LUKS1_HASH,
709                          DEFAULT_RNG);
710                 exit(0);
711         } else
712                 usage(popt_context, 0, NULL, NULL);
713 }
714
715 void set_debug_level(int level);
716
717 static void _dbg_version_and_cmd(int argc, char **argv)
718 {
719         int i;
720
721         log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
722         for (i = 0; i < argc; i++) {
723                 if (i)
724                         log_std(" ");
725                 log_std(argv[i]);
726         }
727         log_std("\"\n");
728 }
729
730 static int run_action(struct action_type *action)
731 {
732         int r;
733
734         if (action->required_memlock)
735                 crypt_memory_lock(NULL, 1);
736
737         r = action->handler(action->arg);
738
739         if (action->required_memlock)
740                 crypt_memory_lock(NULL, 0);
741
742         show_status(r);
743
744         return r;
745 }
746
747 int main(int argc, char **argv)
748 {
749         static char *popt_tmp;
750         static struct poptOption popt_help_options[] = {
751                 { NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
752                 { "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
753                 { "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
754                 POPT_TABLEEND
755         };
756         static struct poptOption popt_options[] = {
757                 { NULL,                '\0', POPT_ARG_INCLUDE_TABLE, popt_help_options, 0, N_("Help options:"), NULL },
758                 { "verbose",           'v',  POPT_ARG_NONE, &opt_verbose,               0, N_("Shows more detailed error messages"), NULL },
759                 { "debug",             '\0', POPT_ARG_NONE, &opt_debug,                 0, N_("Show debug messages"), NULL },
760                 { "cipher",            'c',  POPT_ARG_STRING, &opt_cipher,              0, N_("The cipher used to encrypt the disk (see /proc/crypto)"), NULL },
761                 { "hash",              'h',  POPT_ARG_STRING, &opt_hash,                0, N_("The hash used to create the encryption key from the passphrase"), NULL },
762                 { "verify-passphrase", 'y',  POPT_ARG_NONE, &opt_verify_passphrase,     0, N_("Verifies the passphrase by asking for it twice"), NULL },
763                 { "key-file",          'd',  POPT_ARG_STRING, &opt_key_file,            0, N_("Read the key from a file (can be /dev/random)"), NULL },
764                 { "master-key-file",  '\0',  POPT_ARG_STRING, &opt_master_key_file,     0, N_("Read the volume (master) key from file."), NULL },
765                 { "key-size",          's',  POPT_ARG_INT, &opt_key_size,               0, N_("The size of the encryption key"), N_("BITS") },
766                 { "key-slot",          'S',  POPT_ARG_INT, &opt_key_slot,               0, N_("Slot number for new key (default is first free)"), NULL },
767                 { "size",              'b',  POPT_ARG_STRING, &popt_tmp,                1, N_("The size of the device"), N_("SECTORS") },
768                 { "offset",            'o',  POPT_ARG_STRING, &popt_tmp,                2, N_("The start offset in the backend device"), N_("SECTORS") },
769                 { "skip",              'p',  POPT_ARG_STRING, &popt_tmp,                3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
770                 { "readonly",          'r',  POPT_ARG_NONE, &opt_readonly,              0, N_("Create a readonly mapping"), NULL },
771                 { "iter-time",         'i',  POPT_ARG_INT, &opt_iteration_time,         0, N_("PBKDF2 iteration time for LUKS (in ms)"), N_("msecs") },
772                 { "batch-mode",        'q',  POPT_ARG_NONE, &opt_batch_mode,            0, N_("Do not ask for confirmation"), NULL },
773                 { "version",           '\0', POPT_ARG_NONE, &opt_version_mode,          0, N_("Print package version"), NULL },
774                 { "timeout",           't',  POPT_ARG_INT, &opt_timeout,                0, N_("Timeout for interactive passphrase prompt (in seconds)"), N_("secs") },
775                 { "tries",             'T',  POPT_ARG_INT, &opt_tries,                  0, N_("How often the input of the passphrase can be retried"), NULL },
776                 { "align-payload",     '\0', POPT_ARG_INT, &opt_align_payload,          0, N_("Align payload at <n> sector boundaries - for luksFormat"), N_("SECTORS") },
777                 { "non-exclusive",     '\0', POPT_ARG_NONE, &opt_non_exclusive,         0, N_("(Obsoleted, see man page.)"), NULL },
778                 { "header-backup-file",'\0', POPT_ARG_STRING, &opt_header_backup_file,  0, N_("File with LUKS header and keyslots backup."), NULL },
779                 { "use-random",        '\0', POPT_ARG_NONE, &opt_random,                0, N_("Use /dev/random for generating volume key."), NULL },
780                 { "use-urandom",       '\0', POPT_ARG_NONE, &opt_urandom,               0, N_("Use /dev/urandom for generating volume key."), NULL },
781                 { "uuid",              '\0',  POPT_ARG_STRING, &opt_uuid,               0, N_("UUID for device to use."), NULL },
782                 POPT_TABLEEND
783         };
784         poptContext popt_context;
785         struct action_type *action;
786         char *aname;
787         int r;
788         const char *null_action_argv[] = {NULL};
789
790         crypt_set_log_callback(NULL, _log, NULL);
791
792         setlocale(LC_ALL, "");
793         bindtextdomain(PACKAGE, LOCALEDIR);
794         textdomain(PACKAGE);
795
796         popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
797                                       popt_options, 0);
798         poptSetOtherOptionHelp(popt_context,
799                                N_("[OPTION...] <action> <action-specific>]"));
800
801         while((r = poptGetNextOpt(popt_context)) > 0) {
802                 unsigned long long ull_value;
803                 char *endp;
804
805                 ull_value = strtoull(popt_tmp, &endp, 0);
806                 if (*endp || !*popt_tmp)
807                         r = POPT_ERROR_BADNUMBER;
808
809                 switch(r) {
810                         case 1:
811                                 opt_size = ull_value;
812                                 break;
813                         case 2:
814                                 opt_offset = ull_value;
815                                 break;
816                         case 3:
817                                 opt_skip = ull_value;
818                                 break;
819                 }
820
821                 if (r < 0)
822                         break;
823         }
824
825         if (r < -1)
826                 usage(popt_context, 1, poptStrerror(r),
827                       poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
828         if (opt_version_mode) {
829                 log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
830                 exit(0);
831         }
832
833         if (opt_key_size % 8)
834                 usage(popt_context, 1,
835                       _("Key size must be a multiple of 8 bits"),
836                       poptGetInvocationName(popt_context));
837
838         /* FIXME: use per format define here */
839         if (opt_key_slot != CRYPT_ANY_SLOT &&
840            (opt_key_slot < 0 || opt_key_slot > 8)) {
841                 usage(popt_context, 1, _("Key slot is invalid."),
842                       poptGetInvocationName(popt_context));
843         }
844
845         if (!(aname = (char *)poptGetArg(popt_context)))
846                 usage(popt_context, 1, _("Argument <action> missing."),
847                       poptGetInvocationName(popt_context));
848         for(action = action_types; action->type; action++)
849                 if (strcmp(action->type, aname) == 0)
850                         break;
851         if (!action->type)
852                 usage(popt_context, 1, _("Unknown action."),
853                       poptGetInvocationName(popt_context));
854
855         if (opt_random && opt_urandom)
856                 usage(popt_context, 1, _("Only one of --use-[u]random options is allowed."),
857                       poptGetInvocationName(popt_context));
858         if ((opt_random || opt_urandom) && strcmp(aname, "luksFormat"))
859                 usage(popt_context, 1, _("Option --use-[u]random is allowed only for luksFormat."),
860                       poptGetInvocationName(popt_context));
861
862         if (opt_uuid && strcmp(aname, "luksFormat") && strcmp(aname, "luksUUID"))
863                 usage(popt_context, 1, _("Option --uuid is allowed only for luksFormat and luksUUID."),
864                       poptGetInvocationName(popt_context));
865
866         action_argc = 0;
867         action_argv = poptGetArgs(popt_context);
868         /* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
869         if(!action_argv) 
870                 action_argv = null_action_argv;
871
872         /* Count args, somewhat unnice, change? */
873         while(action_argv[action_argc] != NULL)
874                 action_argc++;
875
876         if(action_argc < action->required_action_argc) {
877                 char buf[128];
878                 snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
879                 usage(popt_context, 1, buf,
880                       poptGetInvocationName(popt_context));
881         }
882
883         if (opt_debug) {
884                 opt_verbose = 1;
885                 crypt_set_debug_level(-1);
886                 _dbg_version_and_cmd(argc, argv);
887         }
888
889         return run_action(action);
890 }