/* gzwrite.c -- zlib functions for writing gzip files * Copyright (C) 2004-2017 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h */ #include "gzguts.h" /* Local functions */ local int gz_init OF((gz_statep)); local int gz_comp OF((gz_statep, int)); local int gz_zero OF((gz_statep, z_off64_t)); local z_size_t gz_write OF((gz_statep, voidpc, z_size_t)); /* Initialize state for writing a gzip file. Mark initialization by setting state->size to non-zero. Return -1 on a memory allocation failure, or 0 on success. */ local int gz_init(state) gz_statep state; { int ret; z_streamp strm = &(state->strm); /* allocate input buffer (double size for gzprintf) */ state->in = (unsigned char *)malloc(state->want << 1); if (state->in == NULL) { gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* only need output buffer and deflate state if compressing */ if (!state->direct) { /* allocate output buffer */ state->out = (unsigned char *)malloc(state->want); if (state->out == NULL) { free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } /* allocate deflate memory, set up for gzip compression */ strm->zalloc = Z_NULL; strm->zfree = Z_NULL; strm->opaque = Z_NULL; ret = deflateInit2(strm, state->level, Z_DEFLATED, MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy); if (ret != Z_OK) { free(state->out); free(state->in); gz_error(state, Z_MEM_ERROR, "out of memory"); return -1; } strm->next_in = NULL; } /* mark state as initialized */ state->size = state->want; /* initialize write buffer if compressing */ if (!state->direct) { strm->avail_out = state->size; strm->next_out = state->out; state->x.next = strm->next_out; } return 0; } /* Compress whatever is at avail_in and next_in and write to the output file. Return -1 if there is an error writing to the output file or if gz_init() fails to allocate memory, otherwise 0. flush is assumed to be a valid deflate() flush value. If flush is Z_FINISH, then the deflate() state is reset to start a new gzip stream. If gz->direct is true, then simply write to the output file without compressing, and ignore flush. */ local int gz_comp(state, flush) gz_statep state; int flush; { int ret, writ; unsigned have, put, max = ((unsigned)-1 >> 2) + 1; z_streamp strm = &(state->strm); /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return -1; /* write directly if requested */ if (state->direct) { while (strm->avail_in) { put = strm->avail_in > max ? max : strm->avail_in; writ = write(state->fd, strm->next_in, put); if (writ < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } strm->avail_in -= (unsigned)writ; strm->next_in += writ; } return 0; } /* run deflate() on provided input until it produces no more output */ ret = Z_OK; do { /* write out current buffer contents if full, or if flushing, but if doing Z_FINISH then don't write until we get to Z_STREAM_END */ if (strm->avail_out == 0 || (flush != Z_NO_FLUSH && (flush != Z_FINISH || ret == Z_STREAM_END))) { while (strm->next_out > state->x.next) { put = strm->next_out - state->x.next > (int)max ? max : (unsigned)(strm->next_out - state->x.next); writ = write(state->fd, state->x.next, put); if (writ < 0) { gz_error(state, Z_ERRNO, zstrerror()); return -1; } state->x.next += writ; } if (strm->avail_out == 0) { strm->avail_out = state->size; strm->next_out = state->out; state->x.next = state->out; } } /* compress */ have = strm->avail_out; ret = deflate(strm, flush); if (ret == Z_STREAM_ERROR) { gz_error(state, Z_STREAM_ERROR, "internal error: deflate stream corrupt"); return -1; } have -= strm->avail_out; } while (have); /* if that completed a deflate stream, allow another to start */ if (flush == Z_FINISH) deflateReset(strm); /* all done, no errors */ return 0; } /* Compress len zeros to output. Return -1 on a write error or memory allocation failure by gz_comp(), or 0 on success. */ local int gz_zero(state, len) gz_statep state; z_off64_t len; { int first; unsigned n; z_streamp strm = &(state->strm); /* consume whatever's left in the input buffer */ if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return -1; /* compress len zeros (len guaranteed > 0) */ first = 1; while (len) { n = GT_OFF(state->size) || (z_off64_t)state->size > len ? (unsigned)len : state->size; if (first) { memset(state->in, 0, n); first = 0; } strm->avail_in = n; strm->next_in = state->in; state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return -1; len -= n; } return 0; } /* Write len bytes from buf to file. Return the number of bytes written. If the returned value is less than len, then there was an error. */ local z_size_t gz_write(state, buf, len) gz_statep state; voidpc buf; z_size_t len; { z_size_t put = len; /* if len is zero, avoid unnecessary operations */ if (len == 0) return 0; /* allocate memory if this is the first time through */ if (state->size == 0 && gz_init(state) == -1) return 0; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return 0; } /* for small len, copy to input buffer, otherwise compress directly */ if (len < state->size) { /* copy to input buffer, compress when full */ do { unsigned have, copy; if (state->strm.avail_in == 0) state->strm.next_in = state->in; have = (unsigned)((state->strm.next_in + state->strm.avail_in) - state->in); copy = state->size - have; if (copy > len) copy = len; memcpy(state->in + have, buf, copy); state->strm.avail_in += copy; state->x.pos += copy; buf = (const char *)buf + copy; len -= copy; if (len && gz_comp(state, Z_NO_FLUSH) == -1) return 0; } while (len); } else { /* consume whatever's left in the input buffer */ if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1) return 0; /* directly compress user buffer to file */ state->strm.next_in = (z_const Bytef *)buf; do { unsigned n = (unsigned)-1; if (n > len) n = len; state->strm.avail_in = n; state->x.pos += n; if (gz_comp(state, Z_NO_FLUSH) == -1) return 0; len -= n; } while (len); } /* input was all buffered or compressed */ return put; } /* -- see zlib.h -- */ int ZEXPORT gzwrite(file, buf, len) gzFile file; voidpc buf; unsigned len; { gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* since an int is returned, make sure len fits in one, otherwise return with an error (this avoids a flaw in the interface) */ if ((int)len < 0) { gz_error(state, Z_DATA_ERROR, "requested length does not fit in int"); return 0; } /* write len bytes from buf (the return value will fit in an int) */ return (int)gz_write(state, buf, len); } /* -- see zlib.h -- */ z_size_t ZEXPORT gzfwrite(buf, size, nitems, file) voidpc buf; z_size_t size; z_size_t nitems; gzFile file; { z_size_t len; gz_statep state; /* get internal structure */ if (file == NULL) return 0; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return 0; /* compute bytes to read -- error on overflow */ len = nitems * size; if (size && len / size != nitems) { gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t"); return 0; } /* write len bytes to buf, return the number of full items written */ return len ? gz_write(state, buf, len) / size : 0; } /* -- see zlib.h -- */ int ZEXPORT gzputc(file, c) gzFile file; int c; { unsigned have; unsigned char buf[1]; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return -1; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return -1; } /* try writing to input buffer for speed (state->size == 0 if buffer not initialized) */ if (state->size) { if (strm->avail_in == 0) strm->next_in = state->in; have = (unsigned)((strm->next_in + strm->avail_in) - state->in); if (have < state->size) { state->in[have] = (unsigned char)c; strm->avail_in++; state->x.pos++; return c & 0xff; } } /* no room in buffer or not initialized, use gz_write() */ buf[0] = (unsigned char)c; if (gz_write(state, buf, 1) != 1) return -1; return c & 0xff; } /* -- see zlib.h -- */ int ZEXPORT gzputs(file, str) gzFile file; const char *str; { int ret; z_size_t len; gz_statep state; /* get internal structure */ if (file == NULL) return -1; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return -1; /* write string */ len = strlen(str); ret = gz_write(state, str, len); return ret == 0 && len != 0 ? -1 : ret; } #if defined(STDC) || defined(Z_HAVE_STDARG_H) #include /* -- see zlib.h -- */ int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va) { int len; unsigned left; char *next; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return state->err; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* do the printf() into the input buffer, put length in len -- the input buffer is double-sized just for this function, so there is guaranteed to be state->size bytes available after the current contents */ if (strm->avail_in == 0) strm->next_in = state->in; next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in); next[state->size - 1] = 0; #ifdef NO_vsnprintf # ifdef HAS_vsprintf_void (void)vsprintf(next, format, va); for (len = 0; len < state->size; len++) if (next[len] == 0) break; # else len = vsprintf(next, format, va); # endif #else # ifdef HAS_vsnprintf_void (void)vsnprintf(next, state->size, format, va); len = strlen(next); # else len = vsnprintf(next, state->size, format, va); # endif #endif /* check that printf() results fit in buffer */ if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0) return 0; /* update buffer and position, compress first half if past that */ strm->avail_in += (unsigned)len; state->x.pos += len; if (strm->avail_in >= state->size) { left = strm->avail_in - state->size; strm->avail_in = state->size; if (gz_comp(state, Z_NO_FLUSH) == -1) return state->err; memcpy(state->in, state->in + state->size, left); strm->next_in = state->in; strm->avail_in = left; } return len; } int ZEXPORTVA gzprintf(gzFile file, const char *format, ...) { va_list va; int ret; va_start(va, format); ret = gzvprintf(file, format, va); va_end(va); return ret; } #else /* !STDC && !Z_HAVE_STDARG_H */ /* -- see zlib.h -- */ int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) gzFile file; const char *format; int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; { unsigned len, left; char *next; gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that can really pass pointer in ints */ if (sizeof(int) != sizeof(void *)) return Z_STREAM_ERROR; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* make sure we have some buffer space */ if (state->size == 0 && gz_init(state) == -1) return state->error; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->error; } /* do the printf() into the input buffer, put length in len -- the input buffer is double-sized just for this function, so there is guaranteed to be state->size bytes available after the current contents */ if (strm->avail_in == 0) strm->next_in = state->in; next = (char *)(strm->next_in + strm->avail_in); next[state->size - 1] = 0; #ifdef NO_snprintf # ifdef HAS_sprintf_void sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); for (len = 0; len < size; len++) if (next[len] == 0) break; # else len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #else # ifdef HAS_snprintf_void snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); len = strlen(next); # else len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); # endif #endif /* check that printf() results fit in buffer */ if (len == 0 || len >= state->size || next[state->size - 1] != 0) return 0; /* update buffer and position, compress first half if past that */ strm->avail_in += len; state->x.pos += len; if (strm->avail_in >= state->size) { left = strm->avail_in - state->size; strm->avail_in = state->size; if (gz_comp(state, Z_NO_FLUSH) == -1) return state->err; memcpy(state->in, state->in + state->size, left); strm->next_in = state->in; strm->avail_in = left; } return (int)len; } #endif /* -- see zlib.h -- */ int ZEXPORT gzflush(file, flush) gzFile file; int flush; { gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* check flush parameter */ if (flush < 0 || flush > Z_FINISH) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* compress remaining data with requested flush */ (void)gz_comp(state, flush); return state->err; } /* -- see zlib.h -- */ int ZEXPORT gzsetparams(file, level, strategy) gzFile file; int level; int strategy; { gz_statep state; z_streamp strm; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; strm = &(state->strm); /* check that we're writing and that there's no error */ if (state->mode != GZ_WRITE || state->err != Z_OK) return Z_STREAM_ERROR; /* if no change is requested, then do nothing */ if (level == state->level && strategy == state->strategy) return Z_OK; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) return state->err; } /* change compression parameters for subsequent input */ if (state->size) { /* flush previous input with previous parameters before changing */ if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1) return state->err; deflateParams(strm, level, strategy); } state->level = level; state->strategy = strategy; return Z_OK; } /* -- see zlib.h -- */ int ZEXPORT gzclose_w(file) gzFile file; { int ret = Z_OK; gz_statep state; /* get internal structure */ if (file == NULL) return Z_STREAM_ERROR; state = (gz_statep)file; /* check that we're writing */ if (state->mode != GZ_WRITE) return Z_STREAM_ERROR; /* check for seek request */ if (state->seek) { state->seek = 0; if (gz_zero(state, state->skip) == -1) ret = state->err; } /* flush, free memory, and close file */ if (gz_comp(state, Z_FINISH) == -1) ret = state->err; if (state->size) { if (!state->direct) { (void)deflateEnd(&(state->strm)); free(state->out); } free(state->in); } gz_error(state, Z_OK, NULL); free(state->path); if (close(state->fd) == -1) ret = Z_ERRNO; free(state); return ret; } id='n469' href='#n469'>469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 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 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753
/*
 Derived from source code of TrueCrypt 7.1a, which is
 Copyright (c) 2008-2012 TrueCrypt Developers Association and which is governed
 by the TrueCrypt License 3.0.

 Modifications and additions to the original source code (contained in this file) 
 and all other portions of this file are Copyright (c) 2013-2015 IDRIX
 and are governed by the Apache License 2.0 the full text of which is
 contained in the file License.txt included in VeraCrypt binary and source
 code distribution packages.
*/

#include "System.h"
#include <wx/cmdline.h>
#include <wx/tokenzr.h>
#include "Core/Core.h"
#include "Application.h"
#include "CommandLineInterface.h"
#include "LanguageStrings.h"
#include "UserInterfaceException.h"

namespace VeraCrypt
{
	CommandLineInterface::CommandLineInterface (int argc, wchar_t** argv, UserInterfaceType::Enum interfaceType) :
		ArgCommand (CommandId::None),
		ArgFilesystem (VolumeCreationOptions::FilesystemType::Unknown),
		ArgNewPim (-1),
		ArgNoHiddenVolumeProtection (false),
		ArgPim (-1),
		ArgSize (0),
		ArgVolumeType (VolumeType::Unknown),
		ArgTrueCryptMode (false),
		StartBackgroundTask (false)
	{
		wxCmdLineParser parser;
		parser.SetCmdLine (argc, argv);

		parser.SetSwitchChars (L"-");

		parser.AddOption (L"",  L"auto-mount",			_("Auto mount device-hosted/favorite volumes"));
		parser.AddSwitch (L"",  L"backup-headers",		_("Backup volume headers"));
		parser.AddSwitch (L"",  L"background-task",		_("Start Background Task"));
#ifdef TC_WINDOWS
		parser.AddSwitch (L"",  L"cache",				_("Cache passwords and keyfiles"));
#endif
		parser.AddSwitch (L"C", L"change",				_("Change password or keyfiles"));
		parser.AddSwitch (L"c", L"create",				_("Create new volume"));
		parser.AddSwitch (L"",	L"create-keyfile",		_("Create new keyfile"));
		parser.AddSwitch (L"",	L"delete-token-keyfiles", _("Delete security token keyfiles"));
		parser.AddSwitch (L"d", L"dismount",			_("Dismount volume"));
		parser.AddSwitch (L"",	L"display-password",	_("Display password while typing"));
		parser.AddOption (L"",	L"encryption",			_("Encryption algorithm"));
		parser.AddSwitch (L"",	L"explore",				_("Open explorer window for mounted volume"));
		parser.AddSwitch (L"",	L"export-token-keyfile",_("Export keyfile from security token"));
		parser.AddOption (L"",	L"filesystem",			_("Filesystem type"));
		parser.AddSwitch (L"f", L"force",				_("Force mount/dismount/overwrite"));
#if !defined(TC_WINDOWS) && !defined(TC_MACOSX)
		parser.AddOption (L"",	L"fs-options",			_("Filesystem mount options"));
#endif
		parser.AddOption (L"",	L"hash",				_("Hash algorithm"));
		parser.AddSwitch (L"h", L"help",				_("Display detailed command line help"), wxCMD_LINE_OPTION_HELP);
		parser.AddSwitch (L"",	L"import-token-keyfiles", _("Import keyfiles to security token"));
		parser.AddOption (L"k", L"keyfiles",			_("Keyfiles"));
		parser.AddSwitch (L"l", L"list",				_("List mounted volumes"));
		parser.AddSwitch (L"",	L"list-token-keyfiles",	_("List security token keyfiles"));
		parser.AddSwitch (L"",	L"load-preferences",	_("Load user preferences"));
		parser.AddSwitch (L"",	L"mount",				_("Mount volume interactively"));
		parser.AddOption (L"m", L"mount-options",		_("VeraCrypt volume mount options"));
		parser.AddOption (L"",	L"new-hash",			_("New hash algorithm"));
		parser.AddOption (L"",	L"new-keyfiles",		_("New keyfiles"));
		parser.AddOption (L"",	L"new-password",		_("New password"));
		parser.AddOption (L"",	L"new-pim",				_("New PIM"));
		parser.AddSwitch (L"",	L"non-interactive",		_("Do not interact with user"));
		parser.AddSwitch (L"",  L"stdin",				_("Read password from standard input"));
		parser.AddOption (L"p", L"password",			_("Password"));
		parser.AddOption (L"",  L"pim",					_("PIM"));
		parser.AddOption (L"",	L"protect-hidden",		_("Protect hidden volume"));
		parser.AddOption (L"",	L"protection-hash",		_("Hash algorithm for protected hidden volume"));
		parser.AddOption (L"",	L"protection-keyfiles",	_("Keyfiles for protected hidden volume"));
		parser.AddOption (L"",	L"protection-password",	_("Password for protected hidden volume"));
		parser.AddOption (L"",	L"protection-pim",		_("PIM for protected hidden volume"));
		parser.AddOption (L"",	L"random-source",		_("Use file as source of random data"));
		parser.AddSwitch (L"",  L"restore-headers",		_("Restore volume headers"));
		parser.AddSwitch (L"",	L"save-preferences",	_("Save user preferences"));
		parser.AddSwitch (L"",	L"quick",				_("Enable quick format"));
		parser.AddOption (L"",	L"size",				_("Size in bytes"));
		parser.AddOption (L"",	L"slot",				_("Volume slot number"));
		parser.AddSwitch (L"tc",L"truecrypt",			_("Enable TrueCrypt mode. Should be put first to avoid issues."));
		parser.AddSwitch (L"",	L"test",				_("Test internal algorithms"));
		parser.AddSwitch (L"t", L"text",				_("Use text user interface"));
		parser.AddOption (L"",	L"token-lib",			_("Security token library"));
		parser.AddSwitch (L"v", L"verbose",				_("Enable verbose output"));
		parser.AddSwitch (L"",	L"version",				_("Display version information"));
		parser.AddSwitch (L"",	L"volume-properties",	_("Display volume properties"));
		parser.AddOption (L"",	L"volume-type",			_("Volume type"));
		parser.AddParam (								_("Volume path"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);
		parser.AddParam (								_("Mount point"), wxCMD_LINE_VAL_STRING, wxCMD_LINE_PARAM_OPTIONAL);

		wxString str;
		bool param1IsVolume = false;
		bool param1IsMountedVolumeSpec = false;
		bool param1IsMountPoint = false;
		bool param1IsFile = false;

		if (parser.Parse () > 0)
			throw_err (_("Incorrect command line specified."));
		
		if (parser.Found (L"help"))
		{
			ArgCommand = CommandId::Help;
			return;
		}

		if (parser.Found (L"text") && interfaceType != UserInterfaceType::Text)
		{
			wstring msg = wstring (_("Option -t or --text must be specified as the first argument."));
			wcerr << msg << endl;
			throw_err (msg);
		}

		if (parser.Found (L"version"))
		{
			ArgCommand = CommandId::DisplayVersion;
			return;
		}

		// Preferences
		if (parser.Found (L"load-preferences"))
		{
			// Load preferences first to allow command line options to override them
			Preferences.Load();
			ArgMountOptions = Preferences.DefaultMountOptions;
		}

		// Commands
		if (parser.Found (L"auto-mount", &str))
		{
			CheckCommandSingle();

			wxStringTokenizer tokenizer (str, L",");
			while (tokenizer.HasMoreTokens())
			{
				wxString token = tokenizer.GetNextToken();

				if (token == L"devices")
				{
					if (ArgCommand == CommandId::AutoMountFavorites)
						ArgCommand = CommandId::AutoMountDevicesFavorites;
					else
						ArgCommand = CommandId::AutoMountDevices;

					param1IsMountPoint = true;
				}
				else if (token == L"favorites")
				{
					if (ArgCommand == CommandId::AutoMountDevices)
						ArgCommand = CommandId::AutoMountDevicesFavorites;
					else
						ArgCommand = CommandId::AutoMountFavorites;
				}
				else
				{
					throw_err (LangString["UNKNOWN_OPTION"] + L": " + token);
				}
			}
		}

		if (parser.Found (L"backup-headers"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::BackupHeaders;
			param1IsVolume = true;
		}

		if (parser.Found (L"change"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::ChangePassword;
			param1IsVolume = true;
		}

		if (parser.Found (L"create"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::CreateVolume;
			param1IsVolume = true;
		}

		if (parser.Found (L"create-keyfile"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::CreateKeyfile;
			param1IsFile = true;
		}
			
		if (parser.Found (L"delete-token-keyfiles"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::DeleteSecurityTokenKeyfiles;
		}

		if (parser.Found (L"dismount"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::DismountVolumes;
			param1IsMountedVolumeSpec = true;
		}
		
		if (parser.Found (L"export-token-keyfile"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::ExportSecurityTokenKeyfile;
		}

		if (parser.Found (L"import-token-keyfiles"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::ImportSecurityTokenKeyfiles;
		}

		if (parser.Found (L"list"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::ListVolumes;
			param1IsMountedVolumeSpec = true;
		}

		if (parser.Found (L"list-token-keyfiles"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::ListSecurityTokenKeyfiles;
		}

		if (parser.Found (L"mount"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::MountVolume;
			param1IsVolume = true;
		}

		if (parser.Found (L"save-preferences"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::SavePreferences;
		}

		if (parser.Found (L"test"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::Test;
		}

		if (parser.Found (L"volume-properties"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::DisplayVolumeProperties;
			param1IsMountedVolumeSpec = true;
		}

		// Options
		if (parser.Found (L"background-task"))
			StartBackgroundTask = true;

#ifdef TC_WINDOWS
		if (parser.Found (L"cache"))
			ArgMountOptions.CachePassword = true;
#endif
		ArgDisplayPassword = parser.Found (L"display-password");

		if (parser.Found (L"encryption", &str))
		{
			ArgEncryptionAlgorithm.reset();

			foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithm::GetAvailableAlgorithms())
			{
				if (!ea->IsDeprecated() && wxString (ea->GetName()).IsSameAs (str, false))
					ArgEncryptionAlgorithm = ea;
			}

			if (!ArgEncryptionAlgorithm)
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		if (parser.Found (L"explore"))
			Preferences.OpenExplorerWindowAfterMount = true;

		if (parser.Found (L"filesystem", &str))
		{
			if (str.IsSameAs (L"none", false))
			{
				ArgMountOptions.NoFilesystem = true;
				ArgFilesystem = VolumeCreationOptions::FilesystemType::None;
			}
			else
			{
				ArgMountOptions.FilesystemType = wstring (str);
				
				if (str.IsSameAs (L"FAT", false))
					ArgFilesystem = VolumeCreationOptions::FilesystemType::FAT;
				else
					ArgFilesystem = VolumeCreationOptions::FilesystemType::None;
			}
		}

		ArgForce = parser.Found (L"force");
		
		ArgTrueCryptMode = parser.Found (L"truecrypt");

#if !defined(TC_WINDOWS) && !defined(TC_MACOSX)
		if (parser.Found (L"fs-options", &str))
			ArgMountOptions.FilesystemOptions = str;
#endif

		if (parser.Found (L"hash", &str))
		{
			ArgHash.reset();

			foreach (shared_ptr <Hash> hash, Hash::GetAvailableAlgorithms())
			{
				wxString hashName (hash->GetName());
				wxString hashAltName (hash->GetAltName());
				if (hashName.IsSameAs (str, false) || hashAltName.IsSameAs (str, false))
					ArgHash = hash;
			}

			if (!ArgHash)
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		if (parser.Found (L"new-hash", &str))
		{
			ArgNewHash.reset();

			foreach (shared_ptr <Hash> hash, Hash::GetAvailableAlgorithms())
			{
				wxString hashName (hash->GetName());
				wxString hashAltName (hash->GetAltName());
				if (hashName.IsSameAs (str, false) || hashAltName.IsSameAs (str, false))
					ArgNewHash = hash;
			}

			if (!ArgNewHash)
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		if (parser.Found (L"keyfiles", &str))
			ArgKeyfiles = ToKeyfileList (str);

		if (parser.Found (L"mount-options", &str))
		{
			wxStringTokenizer tokenizer (str, L",");
			while (tokenizer.HasMoreTokens())
			{
				wxString token = tokenizer.GetNextToken();

				if (token == L"headerbak")
					ArgMountOptions.UseBackupHeaders = true;
				else if (token == L"nokernelcrypto")
					ArgMountOptions.NoKernelCrypto = true;
				else if (token == L"readonly" || token == L"ro")
					ArgMountOptions.Protection = VolumeProtection::ReadOnly;
				else if (token == L"system")
					ArgMountOptions.PartitionInSystemEncryptionScope = true;
				else if (token == L"timestamp" || token == L"ts")
					ArgMountOptions.PreserveTimestamps = false;
#ifdef TC_WINDOWS
				else if (token == L"removable" || token == L"rm")
					ArgMountOptions.Removable = true;
#endif
				else
					throw_err (LangString["UNKNOWN_OPTION"] + L": " + token);
			}
		}

		if (parser.Found (L"new-keyfiles", &str))
			ArgNewKeyfiles = ToKeyfileList (str);

		if (parser.Found (L"new-password", &str))
			ArgNewPassword = ToUTF8Password (str);
		
		if (parser.Found (L"new-pim", &str))
		{
			try
			{
				ArgNewPim = StringConverter::ToInt32 (wstring (str));
			}
			catch (...)
			{
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			}

			if (ArgNewPim < 0)
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			else if (ArgNewPim > 0 && ArgTrueCryptMode)
				throw_err (LangString["PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE"]);
		}
		
		if (parser.Found (L"non-interactive"))
		{
			if (interfaceType != UserInterfaceType::Text)
				throw_err (L"--non-interactive is supported only in text mode");

			Preferences.NonInteractive = true;
		}

		if (parser.Found (L"stdin"))
		{
			if (!Preferences.NonInteractive)
				throw_err (L"--stdin is supported only in non-interactive mode");

			Preferences.UseStandardInput = true;
		}

		if (parser.Found (L"password", &str))
		{
			if (Preferences.UseStandardInput)
				throw_err (L"--password cannot be used with --stdin");
			ArgPassword = ToUTF8Password (str);
		}

		if (parser.Found (L"pim", &str))
		{
			try
			{
				ArgPim = StringConverter::ToInt32 (wstring (str));
			}
			catch (...)
			{
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			}

			if (ArgPim < 0)
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			else if (ArgPim > 0 && ArgTrueCryptMode)
				throw_err (LangString["PIM_NOT_SUPPORTED_FOR_TRUECRYPT_MODE"]);
		}

		if (parser.Found (L"protect-hidden", &str))
		{
			if (str == L"yes")
			{
				if (ArgMountOptions.Protection != VolumeProtection::ReadOnly)
					ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
			}
			else if (str == L"no")
				ArgNoHiddenVolumeProtection = true;
			else
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		if (parser.Found (L"protection-keyfiles", &str))
		{
			ArgMountOptions.ProtectionKeyfiles = ToKeyfileList (str);
			ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
		}
		
		if (parser.Found (L"protection-password", &str))
		{
			ArgMountOptions.ProtectionPassword = ToUTF8Password (str);
			ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
		}
		
		if (parser.Found (L"protection-pim", &str))
		{
			int pim = -1;
			try
			{
				pim = StringConverter::ToInt32 (wstring (str));
				if (pim < 0)
					throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			}
			catch (...)
			{
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			}
			ArgMountOptions.ProtectionPim = pim;
			ArgMountOptions.Protection = VolumeProtection::HiddenVolumeReadOnly;
		}

		if (parser.Found (L"protection-hash", &str))
		{
			bool bHashFound = false;
			foreach (shared_ptr <Hash> hash, Hash::GetAvailableAlgorithms())
			{
				wxString hashName (hash->GetName());
				wxString hashAltName (hash->GetAltName());
				if (hashName.IsSameAs (str, false) || hashAltName.IsSameAs (str, false))
				{
					bHashFound = true;
					ArgMountOptions.ProtectionKdf = Pkcs5Kdf::GetAlgorithm (*hash, ArgTrueCryptMode);
				}
			}

			if (!bHashFound)
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		ArgQuick = parser.Found (L"quick");

		if (parser.Found (L"random-source", &str))
			ArgRandomSourcePath = FilesystemPath (str.wc_str());

		if (parser.Found (L"restore-headers"))
		{
			CheckCommandSingle();
			ArgCommand = CommandId::RestoreHeaders;
			param1IsVolume = true;
		}

		if (parser.Found (L"slot", &str))
		{
			unsigned long number;
			if (!str.ToULong (&number) || number < Core->GetFirstSlotNumber() || number > Core->GetLastSlotNumber())
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);

			ArgMountOptions.SlotNumber = number;

			if (param1IsMountedVolumeSpec)
			{
				shared_ptr <VolumeInfo> volume = Core->GetMountedVolume (number);
				if (!volume)
					throw_err (_("No such volume is mounted."));

				ArgVolumes.push_back (volume);
				param1IsMountedVolumeSpec = false;
			}
		}

		if (parser.Found (L"size", &str))
		{
			try
			{
				ArgSize = StringConverter::ToUInt64 (wstring (str));
			}
			catch (...)
			{
				throw_err (LangString["PARAMETER_INCORRECT"] + L": " + str);
			}
		}

		if (parser.Found (L"token-lib", &str))
			Preferences.SecurityTokenModule = wstring (str);

		if (parser.Found (L"verbose"))
			Preferences.Verbose = true;

		if (parser.Found (L"volume-type", &str))
		{
			if (str.IsSameAs (L"normal", false))
				ArgVolumeType = VolumeType::Normal;
			else if (str.IsSameAs (L"hidden", false))
				ArgVolumeType = VolumeType::Hidden;
			else
				throw_err (LangString["UNKNOWN_OPTION"] + L": " + str);
		}

		// Parameters
		if (parser.GetParamCount() > 0)
		{
			// in case of GUI interface, we load the preference when only 
			// specifying volume path without any option/switch
			if (Application::GetUserInterfaceType() != UserInterfaceType::Text)
			{
				// check if only parameters were specified in the command line
				// (e.g. when associating .hc extension in mimetype with /usr/bin/veracrypt)
				bool onlyParametersPresent = (parser.GetParamCount() == (size_t) (argc - 1));

				if (onlyParametersPresent)
				{
					// no options/switches, so we load prefences now
					Preferences.Load();
					ArgMountOptions = Preferences.DefaultMountOptions;
				}
			}

			if (ArgCommand == CommandId::None)
			{
				ArgCommand = CommandId::MountVolume;
				param1IsVolume = true;
			}

			if (param1IsVolume)
			{
				wxFileName volPath (parser.GetParam (0));
				
#ifdef TC_WINDOWS
				if (!parser.GetParam (0).StartsWith (L"\\Device\\"))
#endif
					volPath.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);

				ArgVolumePath.reset (new VolumePath (wstring (volPath.GetFullPath())));
			}

			if (param1IsMountPoint || parser.GetParamCount() >= 2)
			{
				wstring s (parser.GetParam (param1IsMountPoint ? 0 : 1));

				if (s.empty())
					ArgMountOptions.NoFilesystem = true;

				wxFileName mountPoint (wstring (Directory::AppendSeparator (s)));
				mountPoint.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
				ArgMountPoint.reset (new DirectoryPath (wstring (mountPoint.GetPath())));
			}

			if (param1IsFile)
			{
				ArgFilePath.reset (new FilePath (parser.GetParam (0).wc_str()));
			}
		}

		if (param1IsMountedVolumeSpec)
			ArgVolumes = GetMountedVolumes (parser.GetParamCount() > 0 ? parser.GetParam (0) : wxString());

		if (ArgCommand == CommandId::None && Application::GetUserInterfaceType() == UserInterfaceType::Text)
			parser.Usage();
	}

	CommandLineInterface::~CommandLineInterface ()
	{
	}

	void CommandLineInterface::CheckCommandSingle () const
	{
		if (ArgCommand != CommandId::None)
			throw_err (_("Only a single command can be specified at a time."));
	}

	shared_ptr <KeyfileList> CommandLineInterface::ToKeyfileList (const wxString &arg) const
	{
		wxStringTokenizer tokenizer (arg, L",", wxTOKEN_RET_EMPTY_ALL);

		// Handle escaped separator
		wxArrayString arr;
		bool prevEmpty = false;
		while (tokenizer.HasMoreTokens())
		{
			wxString token = tokenizer.GetNextToken();

			if (prevEmpty && token.empty() && tokenizer.HasMoreTokens())
			{
				token = tokenizer.GetNextToken();
				if (!token.empty())
				{
					arr.Add (token);
					prevEmpty = true;
					continue;
				}
			}
			
			if (token.empty() && !tokenizer.HasMoreTokens())
				break;

			if (prevEmpty || token.empty())
			{
				if (arr.Count() < 1)
				{
					arr.Add (L"");
					continue;
				}
				arr.Last() += token.empty() ? L"," : token.wc_str();
			}
			else
				arr.Add (token);

			prevEmpty = token.empty();
		}

		make_shared_auto (KeyfileList, keyfileList);
		for (size_t i = 0; i < arr.GetCount(); i++)
		{
			if (!arr[i].empty())
				keyfileList->push_back (make_shared <Keyfile> (wstring (arr[i])));
		}

		return keyfileList;
	}

	VolumeInfoList CommandLineInterface::GetMountedVolumes (const wxString &mountedVolumeSpec) const
	{
		VolumeInfoList volumes = Core->GetMountedVolumes ();
		VolumeInfoList filteredVolumes;

		wxFileName pathFilter;
		if (!mountedVolumeSpec.empty())
		{
			pathFilter = mountedVolumeSpec;
			pathFilter.Normalize (wxPATH_NORM_ABSOLUTE | wxPATH_NORM_DOTS);
		}
		else
			return volumes;

		foreach (shared_ptr <VolumeInfo> volume, volumes)
		{
			if (mountedVolumeSpec.empty())
			{
				filteredVolumes.push_back (volume);
			}
			else if (wxString (wstring(volume->Path)) == pathFilter.GetFullPath())
			{
				filteredVolumes.push_back (volume);
			}
			else if (wxString (wstring(volume->MountPoint)) == pathFilter.GetFullPath()
				|| (wxString (wstring(volume->MountPoint)) + wxFileName::GetPathSeparator()) == pathFilter.GetFullPath())
			{
				filteredVolumes.push_back (volume);
			}
		}
		
		if (!mountedVolumeSpec.IsEmpty() && filteredVolumes.size() < 1)
			throw_err (_("No such volume is mounted."));

		return filteredVolumes;
	}

	shared_ptr<VolumePassword> ToUTF8Password (const wchar_t* str, size_t charCount)
	{
		if (charCount > 0)
		{
			shared_ptr<SecureBuffer> utf8Buffer = ToUTF8Buffer (str, charCount);
			return shared_ptr<VolumePassword>(new VolumePassword (*utf8Buffer));
		}
		else
			return shared_ptr<VolumePassword>(new VolumePassword ());
	}

	shared_ptr<SecureBuffer> ToUTF8Buffer (const wchar_t* str, size_t charCount)
	{
		if (charCount == (size_t) -1)
			charCount = wcslen (str);

		if (charCount > 0)
		{
			wxMBConvUTF8 utf8;
			size_t ulen = utf8.FromWChar (NULL, 0, str, charCount);
			if (wxCONV_FAILED == ulen)
				throw PasswordUTF8Invalid (SRC_POS);
			SecureBuffer passwordBuf(ulen);
			ulen = utf8.FromWChar ((char*) (byte*) passwordBuf, ulen, str, charCount);
			if (wxCONV_FAILED == ulen)
				throw PasswordUTF8Invalid (SRC_POS);
			if (ulen > VolumePassword::MaxSize)
				throw PasswordUTF8TooLong (SRC_POS);

			ConstBufferPtr utf8Buffer ((byte*) passwordBuf, ulen);
			return shared_ptr<SecureBuffer>(new SecureBuffer (utf8Buffer));
		}
		else
			return shared_ptr<SecureBuffer>(new SecureBuffer ());
	}

	auto_ptr <CommandLineInterface> CmdLine;
}