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