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