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