cryptsetup.c 20.8 KB
Newer Older
1 2 3 4 5 6 7
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <errno.h>
#include <unistd.h>
8
#include <fcntl.h>
9 10 11 12 13 14 15 16 17
#include <assert.h>

#include <libcryptsetup.h>
#include <popt.h>

#include "../config.h"

#include "cryptsetup.h"

18 19
static int opt_verbose = 0;
static int opt_debug = 0;
20
static char *opt_cipher = NULL;
21
static char *opt_hash = NULL;
22 23
static int opt_verify_passphrase = 0;
static char *opt_key_file = NULL;
24
static char *opt_master_key_file = NULL;
25
static unsigned int opt_key_size = 0;
26
static int opt_key_slot = CRYPT_ANY_SLOT;
27 28 29 30 31 32 33 34 35 36
static uint64_t opt_size = 0;
static uint64_t opt_offset = 0;
static uint64_t opt_skip = 0;
static int opt_readonly = 0;
static int opt_iteration_time = 1000;
static int opt_batch_mode = 0;
static int opt_version_mode = 0;
static int opt_timeout = 0;
static int opt_tries = 3;
static int opt_align_payload = 0;
37
static int opt_non_exclusive = 0;
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

static const char **action_argv;
static int action_argc;

static int action_create(int arg);
static int action_remove(int arg);
static int action_resize(int arg);
static int action_status(int arg);
static int action_luksFormat(int arg);
static int action_luksOpen(int arg);
static int action_luksAddKey(int arg);
static int action_luksDelKey(int arg);
static int action_luksKillSlot(int arg);
static int action_luksRemoveKey(int arg);
static int action_isLuks(int arg);
static int action_luksUUID(int arg);
static int action_luksDump(int arg);

static struct action_type {
	const char *type;
58
	int (*handler)(int);
59 60
	int arg;
	int required_action_argc;
61 62 63
	int required_dm_backend;
	int required_memlock;
	int show_status;
64 65 66
	const char *arg_desc;
	const char *desc;
} action_types[] = {
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
	{ "create",	action_create,		0, 2, 1, 1, 1, N_("<name> <device>"),N_("create device") },
	{ "remove",	action_remove,		0, 1, 1, 0, 1, N_("<name>"), N_("remove device") },
	{ "resize",	action_resize,		0, 1, 1, 1, 1, N_("<name>"), N_("resize active device") },
	{ "status",	action_status,		0, 1, 1, 0, 1, N_("<name>"), N_("show device status") },
	{ "luksFormat", action_luksFormat,	0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("formats a LUKS device") },
	{ "luksOpen",	action_luksOpen,	0, 2, 1, 1, 1, N_("<device> <name> "), N_("open LUKS device as mapping <name>") },
	{ "luksAddKey",	action_luksAddKey,	0, 1, 1, 1, 1, N_("<device> [<new key file>]"), N_("add key to LUKS device") },
	{ "luksRemoveKey",action_luksRemoveKey,	0, 1, 1, 1, 1, N_("<device> [<key file>]"), N_("removes supplied key or key file from LUKS device") },
	{ "luksKillSlot",  action_luksKillSlot, 0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("wipes key with number <key slot> from LUKS device") },
	{ "luksUUID",	action_luksUUID,	0, 1, 0, 0, 1, N_("<device>"), N_("print UUID of LUKS device") },
	{ "isLuks",	action_isLuks,		0, 1, 0, 0, 0, N_("<device>"), N_("tests <device> for LUKS partition header") },
	{ "luksClose",	action_remove,		0, 1, 1, 0, 1, N_("<name>"), N_("remove LUKS mapping") },
	{ "luksDump",	action_luksDump,	0, 1, 0, 0, 1, N_("<device>"), N_("dump LUKS partition information") },
	{ "luksDelKey", action_luksDelKey,	0, 2, 1, 1, 1, N_("<device> <key slot>"), N_("identical to luksKillSlot - DEPRECATED - see man page") },
	{ "reload",	action_create,		1, 2, 1, 1, 1, N_("<name> <device>"), N_("modify active device - DEPRECATED - see man page") },
	{ NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL }
83 84 85 86 87
};

/* Interface Callbacks */
static int yesDialog(char *msg)
{
88 89 90 91
	char *answer = NULL;
	size_t size = 0;
	int r = 1;

92
	if(isatty(0) && !opt_batch_mode) {
93 94
		log_std("\nWARNING!\n========\n");
		log_std("%s\n\nAre you sure? (Type uppercase yes): ", msg);
95 96 97
		if(getline(&answer, &size, stdin) == -1) {
			perror("getline");
			free(answer);
98
			return 0;
99 100 101
		}
		if(strcmp(answer, "YES\n"))
			r = 0;
102
		free(answer);
103 104
	}

105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
	return r;
}

static void cmdLineLog(int class, char *msg) {
    switch(class) {

    case CRYPT_LOG_NORMAL:
            fputs(msg, stdout);
            break;
    case CRYPT_LOG_ERROR:
            fputs(msg, stderr);
            break;
    default:
            fprintf(stderr, "Internal error on logging class for msg: %s", msg);
            break;
    }
}

static struct interface_callbacks cmd_icb = {
        .yesDialog = yesDialog,
        .log = cmdLineLog,
};

/* End ICBs */

static void show_status(int errcode)
{
	char error[256];

134 135 136
	if(!errcode && opt_verbose) {
		log_std(_("Command successful.\n"));
		return;
137 138 139
	}

	crypt_get_error(error, sizeof(error));
140

141 142 143 144 145 146 147 148
	if (!opt_verbose) {
		char *error_ = strerror_r(errcode, error, sizeof(error));
		if (error_ != error) {
			strncpy(error, error_, sizeof(error));
			error[sizeof error - 1] = '\0';
		}
	}

149
	log_err(_("Command failed"));
150
	if (*error)
151
		log_err(": %s\n", error);
152
	else
153
		log_err(".\n");
154 155 156 157 158 159 160 161 162
	return;
}

static int action_create(int reload)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.device = action_argv[1],
		.cipher = opt_cipher?opt_cipher:DEFAULT_CIPHER,
163
		.hash = opt_hash ?: DEFAULT_HASH,
164 165 166 167 168 169 170 171 172 173 174 175 176 177
		.key_file = opt_key_file,
		.key_size = ((opt_key_size)?opt_key_size:DEFAULT_KEY_SIZE)/8,
		.key_slot = opt_key_slot,
		.flags = 0,
		.size = opt_size,
		.offset = opt_offset,
		.skip = opt_skip,
		.timeout = opt_timeout,
		.tries = opt_tries,
		.icb = &cmd_icb,
	};
	int r;

        if(reload) 
178
                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"));
179 180 181 182 183 184 185 186 187 188 189 190

	if (options.hash && strcmp(options.hash, "plain") == 0)
		options.hash = NULL;
	if (opt_verify_passphrase)
		options.flags |= CRYPT_FLAG_VERIFY;
	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;

	if (reload)
		r = crypt_update_device(&options);
	else
		r = crypt_create_device(&options);
191

192 193 194 195 196 197 198 199 200 201
	return r;
}

static int action_remove(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.icb = &cmd_icb,
	};

202
	return crypt_remove_device(&options);
203 204 205 206 207 208 209 210 211 212
}

static int action_resize(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.size = opt_size,
		.icb = &cmd_icb,
	};

213
	return crypt_resize_device(&options);
214 215 216 217 218 219 220 221 222 223 224
}

static int action_status(int arg)
{
	struct crypt_options options = {
		.name = action_argv[0],
		.icb = &cmd_icb,
	};
	int r;

	r = crypt_query_device(&options);
225 226 227 228
	if (r < 0)
		return r;

	if (r == 0) {
229
		/* inactive */
230
		log_std("%s/%s is inactive.\n", crypt_get_dir(), options.name);
231 232 233
		r = 1;
	} else {
		/* active */
234 235 236 237 238 239
		log_std("%s/%s is active:\n", crypt_get_dir(), options.name);
		log_std("  cipher:  %s\n", options.cipher);
		log_std("  keysize: %d bits\n", options.key_size * 8);
		log_std("  device:  %s\n", options.device);
		log_std("  offset:  %" PRIu64 " sectors\n", options.offset);
		log_std("  size:    %" PRIu64 " sectors\n", options.size);
240
		if (options.skip)
241 242
			log_std("  skipped: %" PRIu64 " sectors\n", options.skip);
		log_std("  mode:    %s\n", (options.flags & CRYPT_FLAG_READONLY)
243 244 245 246 247 248 249
		                           ? "readonly" : "read/write");
		crypt_put_options(&options);
		r = 0;
	}
	return r;
}

250
static int _action_luksFormat_generateMK()
251 252
{
	struct crypt_options options = {
253
		.key_size = (opt_key_size ?: DEFAULT_LUKS_KEY_SIZE) / 8,
254 255
		.key_slot = opt_key_slot,
		.device = action_argv[0],
256
		.cipher = opt_cipher ?: DEFAULT_LUKS_CIPHER,
257
		.hash = opt_hash ?: DEFAULT_LUKS_HASH,
258 259 260 261 262 263 264
		.new_key_file = action_argc > 1 ? action_argv[1] : NULL,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE :  0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
		.align_payload = opt_align_payload,
		.icb = &cmd_icb,
	};
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335

	return crypt_luksFormat(&options);
}

static int _read_mk(const char *file, char **key, int keysize)
{
	int fd;

	*key = malloc(keysize);
	if (!*key)
		return -ENOMEM;

	fd = open(file, O_RDONLY);
	if (fd == -1) {
		log_err("Cannot read keyfile %s.\n", file);
		return -EINVAL;
	}
	if ((read(fd, *key, keysize) != keysize)) {
		log_err("Cannot read %d bytes from keyfile %s.\n", keysize, file);
		close(fd);
		memset(*key, 0, keysize);
		free(*key);
		return -EINVAL;
	}
	close(fd);
	return 0;
}

static int _action_luksFormat_useMK()
{
	int r = -EINVAL, keysize;
	char *key = NULL, cipher [MAX_CIPHER_LEN], cipher_mode[MAX_CIPHER_LEN];
	struct crypt_device *cd = NULL;
	struct crypt_params_luks1 params = {
		.hash = opt_hash ?: DEFAULT_LUKS_HASH,
		.data_alignment = opt_align_payload,
	};

	if (parse_into_name_and_mode(opt_cipher ?: DEFAULT_LUKS_CIPHER, cipher, cipher_mode)) {
		log_err("No known cipher specification pattern detected.\n");
		return -EINVAL;
	}

	keysize = (opt_key_size ?: DEFAULT_LUKS_KEY_SIZE) / 8;
	if (_read_mk(opt_master_key_file, &key, keysize) < 0)
		return -EINVAL;

	if ((r = crypt_init(&cd, action_argv[0])))
		goto out;

	crypt_set_password_verify(cd, 1);
	crypt_set_timeout(cd, opt_timeout);
	if (opt_iteration_time)
		crypt_set_iterarion_time(cd, opt_iteration_time);

	if ((r = crypt_format(cd, CRYPT_LUKS1, cipher, cipher_mode, NULL, key, keysize, &params)))
		goto out;

	r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot, key, keysize, NULL, 0);
out:

	crypt_free(cd);
	if (key) {
		memset(key, 0, keysize);
		free(key);
	}
	return r;
}

static int action_luksFormat(int arg)
{
336 337
	int r = 0; char *msg = NULL;

338 339
	/* Avoid overwriting possibly wrong part of device than user requested by rejecting these options */
	if (opt_offset || opt_skip) {
340
		log_err("Options --offset and --skip are not supported for luksFormat.\n"); 
341 342 343
		return -EINVAL;
	}

344 345
	if(asprintf(&msg, _("This will overwrite data on %s irrevocably."), action_argv[0]) == -1) {
		log_err(_("memory allocation error in action_luksFormat"));
346
		return -ENOMEM;
347
	}
348 349 350 351 352 353
	r = yesDialog(msg);
	free(msg);

	if (!r)
		return -EINVAL;

354 355 356 357
	if (opt_master_key_file)
		return _action_luksFormat_useMK();
	else
		return _action_luksFormat_generateMK();
358 359 360 361 362 363 364 365
}

static int action_luksOpen(int arg)
{
	struct crypt_options options = {
		.name = action_argv[1],
		.device = action_argv[0],
		.key_file = opt_key_file,
366
		.key_size = opt_key_file ? (opt_key_size / 8) : 0, /* limit bytes read from keyfile */
367
		.timeout = opt_timeout,
368
		.tries = opt_key_file ? 1 : opt_tries, /* verify is usefull only for tty */
369 370 371 372 373
		.icb = &cmd_icb,
	};

	if (opt_readonly)
		options.flags |= CRYPT_FLAG_READONLY;
374 375
	if (opt_non_exclusive)
		options.flags |= CRYPT_FLAG_NON_EXCLUSIVE_ACCESS;
376
	return crypt_luksOpen(&options);
377 378 379 380
}

static int action_luksDelKey(int arg)
{
381 382
	log_err("luksDelKey is a deprecated action name.\nPlease use luksKillSlot.\n"); 
	return action_luksKillSlot(arg);
383 384 385 386 387 388 389 390 391 392 393 394 395
}

static int action_luksKillSlot(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.key_slot = atoi(action_argv[1]),
		.key_file = opt_key_file,
		.timeout = opt_timeout,
		.flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
		.icb = &cmd_icb,
	};

396
	return crypt_luksKillSlot(&options);
397 398 399 400 401 402 403 404 405 406 407 408 409
}

static int action_luksRemoveKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.new_key_file = action_argc>1?action_argv[1]:NULL,
		.key_file = opt_key_file,
		.timeout = opt_timeout,
		.flags = !opt_batch_mode?CRYPT_FLAG_VERIFY_ON_DELKEY : 0,
		.icb = &cmd_icb,
	};

410
	return crypt_luksRemoveKey(&options);
411 412
}

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
static int _action_luksAddKey_useMK()
{
	int r = -EINVAL, keysize;
	char *key = NULL;
	struct crypt_device *cd = NULL;

	if ((r = crypt_init(&cd, action_argv[0])))
		goto out;

	if ((r = crypt_load(cd, CRYPT_LUKS1, NULL)))
		goto out;

	keysize = crypt_get_volume_key_size(cd);
	crypt_set_password_verify(cd, 1);
	crypt_set_timeout(cd, opt_timeout);
	if (opt_iteration_time)
		crypt_set_iterarion_time(cd, opt_iteration_time);

	if (_read_mk(opt_master_key_file, &key, keysize) < 0)
		goto out;

	r = crypt_keyslot_add_by_volume_key(cd, opt_key_slot, key, keysize, NULL, 0);
out:
	crypt_free(cd);
	if (key) {
		memset(key, 0, keysize);
		free(key);
	}
	return r;
}

444 445 446 447 448 449 450 451 452 453 454 455 456
static int action_luksAddKey(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.new_key_file = action_argc>1?action_argv[1]:NULL,
		.key_file = opt_key_file,
		.key_slot = opt_key_slot,
		.flags = opt_verify_passphrase ? CRYPT_FLAG_VERIFY : (!opt_batch_mode?CRYPT_FLAG_VERIFY_IF_POSSIBLE : 0),
		.iteration_time = opt_iteration_time,
		.timeout = opt_timeout,
		.icb = &cmd_icb,
	};

457 458 459 460
	if (opt_master_key_file)
		return _action_luksAddKey_useMK();
	else
		return crypt_luksAddKey(&options);
461 462 463 464 465 466 467 468
}

static int action_isLuks(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};
469

470 471 472 473 474 475 476 477 478 479
	return crypt_isLuks(&options);
}

static int action_luksUUID(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};

480
	return crypt_luksUUID(&options);
481 482 483 484 485 486 487 488 489
}

static int action_luksDump(int arg)
{
	struct crypt_options options = {
		.device = action_argv[0],
		.icb = &cmd_icb,
	};

490
	return crypt_luksDump(&options);
491 492 493 494 495 496 497
}

static void usage(poptContext popt_context, int exitcode,
                  const char *error, const char *more)
{
	poptPrintUsage(popt_context, stderr, 0);
	if (error)
498
		log_err("%s: %s\n", more, error);
499 500 501 502 503 504 505 506 507
	exit(exitcode);
}

static void help(poptContext popt_context, enum poptCallbackReason reason,
                 struct poptOption *key, const char * arg, void *data)
{
	if (key->shortName == '?') {
		struct action_type *action;

508
		log_std("%s\n",PACKAGE_STRING);
509 510 511

		poptPrintHelp(popt_context, stdout, 0);

512
		log_std(_("\n"
513 514 515
			 "<action> is one of:\n"));

		for(action = action_types; action->type; action++)
516
			log_std("\t%s %s - %s\n", action->type, _(action->arg_desc), _(action->desc));
517
		
518
		log_std(_("\n"
519 520 521 522 523 524 525 526
			 "<name> is the device to create under %s\n"
			 "<device> is the encrypted device\n"
			 "<key slot> is the LUKS key slot number to modify\n"
			 "<key file> optional key file for the new key for luksAddKey action\n"),
			crypt_get_dir());
		exit(0);
	} else
		usage(popt_context, 0, NULL, NULL);
527 528
}

529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
void set_debug_level(int level);

static void _dbg_version_and_cmd(int argc, char **argv)
{
	int i;

	log_std("# %s %s processing \"", PACKAGE_NAME, PACKAGE_VERSION);
	for (i = 0; i < argc; i++) {
		if (i)
			log_std(" ");
		log_std(argv[i]);
	}
	log_std("\"\n");
}

544 545 546 547 548
static int run_action(struct action_type *action)
{
	int r;

	if (dm_init(NULL, action->required_dm_backend) < 1) {
549
		log_err("Cannot communicate with device-mapper. Is dm_mod kernel module loaded?\n");
550 551 552 553
		return -ENOSYS;
	}

	if (action->required_memlock)
554
		crypt_memory_lock(NULL, 1);
555 556 557 558

	r = action->handler(action->arg);

	if (action->required_memlock)
559
		crypt_memory_lock(NULL, 0);
560 561 562 563 564 565 566 567 568

	if (action->required_dm_backend)
		dm_exit();

	if (r < 0 && (opt_verbose || action->show_status))
		show_status(-r);

	return r;
}
569 570 571 572 573 574 575 576 577 578 579 580 581

int main(int argc, char **argv)
{
	static char *popt_tmp;
	static struct poptOption popt_help_options[] = {
		{ NULL,    '\0', POPT_ARG_CALLBACK, help, 0, NULL,                         NULL },
		{ "help",  '?',  POPT_ARG_NONE,     NULL, 0, N_("Show this help message"), NULL },
		{ "usage", '\0', POPT_ARG_NONE,     NULL, 0, N_("Display brief usage"),    NULL },
		POPT_TABLEEND
	};
	static struct poptOption popt_options[] = {
		{ NULL,                '\0', POPT_ARG_INCLUDE_TABLE,                      popt_help_options,      0, N_("Help options:"),                                                   NULL },
		{ "verbose",           'v',  POPT_ARG_NONE,                               &opt_verbose,           0, N_("Shows more detailed error messages"),                              NULL },
582
		{ "debug",             '\0', POPT_ARG_NONE,                               &opt_debug,             0, N_("Show debug messsgages"),                                           NULL },
583 584 585 586
		{ "cipher",            'c',  POPT_ARG_STRING | POPT_ARGFLAG_SHOW_DEFAULT, &opt_cipher,            0, N_("The cipher used to encrypt the disk (see /proc/crypto)"),          NULL },
		{ "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 },
		{ "verify-passphrase", 'y',  POPT_ARG_NONE,                               &opt_verify_passphrase, 0, N_("Verifies the passphrase by asking for it twice"),                  NULL },
		{ "key-file",          'd',  POPT_ARG_STRING,                             &opt_key_file,          0, N_("Read the key from a file (can be /dev/random)"),                   NULL },
587
		{ "master-key-file",  '\0',  POPT_ARG_STRING,                             &opt_master_key_file,   0, N_("Read the volume (master) key from file."),                         NULL },
588 589 590 591 592 593 594 595 596
		{ "key-size",          's',  POPT_ARG_INT    | POPT_ARGFLAG_SHOW_DEFAULT, &opt_key_size,          0, N_("The size of the encryption key"),                                  N_("BITS") },
		{ "key-slot",          'S',  POPT_ARG_INT,                                &opt_key_slot,          0, N_("Slot number for new key (default is first free)"),      NULL },
		{ "size",              'b',  POPT_ARG_STRING,                             &popt_tmp,              1, N_("The size of the device"),                                          N_("SECTORS") },
		{ "offset",            'o',  POPT_ARG_STRING,                             &popt_tmp,              2, N_("The start offset in the backend device"),                          N_("SECTORS") },
		{ "skip",              'p',  POPT_ARG_STRING,                             &popt_tmp,              3, N_("How many sectors of the encrypted data to skip at the beginning"), N_("SECTORS") },
		{ "readonly",          'r',  POPT_ARG_NONE,                               &opt_readonly,          0, N_("Create a readonly mapping"),                                       NULL },
		{ "iter-time",         'i',  POPT_ARG_INT,                                &opt_iteration_time,    0, N_("PBKDF2 iteration time for LUKS (in ms)"),
		  N_("msecs") },
		{ "batch-mode",        'q',  POPT_ARG_NONE,                               &opt_batch_mode,        0, N_("Do not ask for confirmation"),                                     NULL },
597
		{ "version",        '\0',  POPT_ARG_NONE,                                 &opt_version_mode,        0, N_("Print package version"),                                     NULL },
598 599 600 601
		{ "timeout",           't',  POPT_ARG_INT,                                &opt_timeout,           0, N_("Timeout for interactive passphrase prompt (in seconds)"),          N_("secs") },
		{ "tries",             'T',  POPT_ARG_INT,                                &opt_tries,             0, N_("How often the input of the passphrase canbe retried"),            NULL },
		{ "align-payload",     '\0',  POPT_ARG_INT,                               &opt_align_payload,     0, N_("Align payload at <n> sector boundaries - for luksFormat"),         N_("SECTORS") },
		{ "non-exclusive",     '\0',  POPT_ARG_NONE,                              &opt_non_exclusive,     0, N_("Allows non-exclusive access for luksOpen, WARNING see manpage."),        NULL },
602 603 604 605 606 607 608 609
		POPT_TABLEEND
	};
	poptContext popt_context;
	struct action_type *action;
	char *aname;
	int r;
	const char *null_action_argv[] = {NULL};

610 611
	set_default_log(cmdLineLog);

612
	setlocale(LC_ALL, "");
613 614
	bindtextdomain(PACKAGE, LOCALEDIR);
	textdomain(PACKAGE);
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648

	popt_context = poptGetContext(PACKAGE, argc, (const char **)argv,
	                              popt_options, 0);
	poptSetOtherOptionHelp(popt_context,
	                       N_("[OPTION...] <action> <action-specific>]"));

	while((r = poptGetNextOpt(popt_context)) > 0) {
		unsigned long long ull_value;
		char *endp;

		ull_value = strtoull(popt_tmp, &endp, 0);
		if (*endp || !*popt_tmp)
			r = POPT_ERROR_BADNUMBER;

		switch(r) {
			case 1:
				opt_size = ull_value;
				break;
			case 2:
				opt_offset = ull_value;
				break;
			case 3:
				opt_skip = ull_value;
				break;
		}

		if (r < 0)
			break;
	}

	if (r < -1)
		usage(popt_context, 1, poptStrerror(r),
		      poptBadOption(popt_context, POPT_BADOPTION_NOALIAS));
	if (opt_version_mode) {
649
		log_std("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
650 651
		exit(0);
	}
652

653 654 655 656
	if (opt_key_size % 8)
		usage(popt_context, 1,
		      _("Key size must be a multiple of 8 bits"),
		      poptGetInvocationName(popt_context));
657

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
	if (!(aname = (char *)poptGetArg(popt_context)))
		usage(popt_context, 1, _("Argument <action> missing."),
		      poptGetInvocationName(popt_context));
	for(action = action_types; action->type; action++)
		if (strcmp(action->type, aname) == 0)
			break;
	if (!action->type)
		usage(popt_context, 1, _("Unknown action."),
		      poptGetInvocationName(popt_context));

	action_argc = 0;
	action_argv = poptGetArgs(popt_context);
	/* Make return values of poptGetArgs more consistent in case of remaining argc = 0 */
	if(!action_argv) 
		action_argv = null_action_argv;
673

674 675 676 677 678 679 680 681 682
	/* Count args, somewhat unnice, change? */
	while(action_argv[action_argc] != NULL)
		action_argc++;

	if(action_argc < action->required_action_argc) {
		char buf[128];
		snprintf(buf, 128,_("%s: requires %s as arguments"), action->type, action->arg_desc);
		usage(popt_context, 1, buf,
		      poptGetInvocationName(popt_context));
683
	}
684

685 686 687 688 689 690
	if (opt_debug) {
		opt_verbose = 1;
		crypt_set_debug_level(-1);
		_dbg_version_and_cmd(argc, argv);
	}

691 692
	return run_action(action);
}