VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Main/TextUserInterface.cpp
blob: 61b8b8a6166e9a54aac4196006bd902cfb7f61fa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>VeraCrypt - Free Open source disk encryption with strong security for the Paranoid</title>
<meta name="description" content="VeraCrypt is free open-source disk encryption software for Windows, Mac OS X and Linux. In case an attacker forces you to reveal the password, VeraCrypt provides plausible deniability. In contrast to file encryption, data encryption performed by VeraCrypt is real-time (on-the-fly), automatic, transparent, needs very little memory, and does not involve temporary unencrypted files."/>
<meta name="keywords" content="encryption, security"/>
<link href="styles.css" rel="stylesheet" type="text/css" />
</head>
<body>

<div>                      
<a href="https://www.veracrypt.fr/en/Home.html"><img src="VeraCrypt128x128.png" alt="VeraCrypt"/></a>
</div>

<div id="menu">
	<ul>
	  <li><a href="Home.html">Home</a></li>
	  <li><a href="/code/">Source Code</a></li>
	  <li><a href="Downloads.html">Downloads</a></li>
	  <li><a class="active" href="Documentation.html">Documentation</a></li>
	  <li><a href="Donation.html">Donate</a></li>
	  <li><a href="https://sourceforge.net/p/veracrypt/discussion/" target="_blank">Forums</a></li>
	</ul>
</div>

<div>
<p>
<a href="Documentation.html">Documentation</a>           
<img src="arrow_right.gif" alt=">>" style="margin-top: 5px">
<a href="Technical%20Details.html">Technical Details</a>
<img src="arrow_right.gif" alt=">>" style="margin-top: 5px">
<a href="Random%20Number%20Generator.html">Random Number Generator</a>
</p></div>

<div class="wikidoc">
<h1>Random Number Generator</h1>
<p>The VeraCrypt random number generator (RNG) is used to generate the master encryption key, the secondary key (XTS mode), salt, and keyfiles. It creates a pool of random values in RAM (memory). The pool, which is 320 bytes long, is filled with data from the
 following sources:</p>
<ul>
<li>Mouse movements </li><li>Keystrokes </li><li><em>Mac OS X and Linux</em>: Values generated by the built-in RNG (both <em>/dev/random</em> and<em>/dev/urandom</em>)
</li><li><em>MS Windows only</em>: MS Windows CryptoAPI (collected regularly at 500-ms interval)
</li><li><em>MS Windows only</em>: Network interface statistics (NETAPI32) </li><li><em>MS Windows only</em>: Various Win32 handles, time variables, and counters (collected regularly at 500-ms interval)
</li></ul>
<p>Before a value obtained from any of the above-mentioned sources is written to the pool, it is divided into individual bytes (e.g., a 32-bit number is divided into four bytes). These bytes are then individually written to the pool with the modulo 2<sup>8</sup>
 addition operation (not by replacing the old values in the pool) at the position of the pool cursor. After a byte is written, the pool cursor position is advanced by one byte. When the cursor reaches the end of the pool, its position is set to the beginning
 of the pool. After every 16<sup>th</sup> byte written to the pool, the pool mixing function is automatically applied to the entire pool (see below).</p>
<h2>Pool Mixing Function</h2>
<p>The purpose of this function is to perform diffusion [2]. Diffusion spreads the influence of individual &ldquo;raw&rdquo; input bits over as much of the pool state as possible, which also hides statistical relationships. After every 16<sup>th</sup> byte
 written to the pool, this function is applied to the entire pool.</p>
<p>Description of the pool mixing function:</p>
<ol>
<li>Let <em>R</em> be the randomness pool. </li><li>Let <em>H</em> be the hash function selected by the user (SHA-512, RIPEMD-160, or Whirlpool).
</li><li><em>l</em> = byte size of the output of the hash function <em>H</em> (i.e., if
<em>H</em> is RIPEMD-160, then <em>l</em> = 20; if <em>H</em> is SHA-512, <em>l</em> = 64)
</li><li><em>z</em> = byte size of the randomness pool <em>R </em>(320 bytes) </li><li><em>q</em> = <em>z</em> / <em>l</em> &ndash; 1 (e.g., if <em>H</em> is Whirlpool, then
<em>q</em> = 4) </li><li>Ris divided intol-byte blocksB0...Bq.
<p>For 0 &le; i &le; q (i.e., for each block B) the following steps are performed:</p>
<ol type="a">
<li><em>M = H</em> (<em>B</em>0 || <em>B</em>1 || ... || <em>B</em>q) [i.e., the randomness pool is hashed using the hash function H, which produces a hash M]
</li><li>Bi = Bi ^ M </li></ol>
</li><li><em>R = B</em>0 || <em>B</em>1 || ... || <em>B</em>q </li></ol>
<p>For example, if <em>q</em> = 1, the randomness pool would be mixed as follows:</p>
<ol>
<li>(<em>B</em>0 || <em>B</em>1) = <em>R</em> </li><li><em>B</em>0 = <em>B</em>0 ^ <em>H</em>(<em>B</em>0 || <em>B</em>1) </li><li><em>B</em>1 = <em>B</em>1 ^ <em>H</em>(<em>B</em>0 || <em>B</em>1) </li><li><em>R</em> = <em>B</em>0 || <em>B</em>1 </li></ol>
<h2>Generated Values</h2>
<p>The content of the RNG pool is never directly exported (even when VeraCrypt instructs the RNG to generate and export a value). Thus, even if the attacker obtains a value generated by the RNG, it is infeasible for him to determine or predict (using the obtained
 value) any other values generated by the RNG during the session (it is infeasible to determine the content of the pool from a value generated by the RNG).</p>
<p>The RNG ensures this by performing the following steps whenever VeraCrypt instructs it to generate and export a value:</p>
<ol>
<li>Data obtained from the sources listed above is added to the pool as described above.
</li><li>The requested number of bytes is copied from the pool to the output buffer (the copying starts from the position of the pool cursor; when the end of the pool is reached, the copying continues from the beginning of the pool; if the requested number of bytes
 is greater than the size of the pool, no value is generated and an error is returned).
</li><li>The state of each bit in the pool is inverted (i.e., 0 is changed to 1, and 1 is changed to 0).
</li><li>Data obtained from some of the sources listed above is added to the pool as described above.
</li><li>The content of the pool is transformed using the pool mixing function. Note: The function uses a cryptographically secure one-way hash function selected by the user (for more information, see the section
<em>Pool Mixing Function</em> above). </li><li>The transformed content of the pool is XORed into the output buffer as follows:
<ol type="a">
<li>The output buffer write cursor is set to 0 (the first byte of the buffer). </li><li>The byte at the position of the pool cursor is read from the pool and XORed into the byte in the output buffer at the position of the output buffer write cursor.
</li><li>The pool cursor position is advanced by one byte. If the end of the pool is reached, the cursor position is set to 0 (the first byte of the pool).
</li><li>The position of the output buffer write cursor is advanced by one byte. </li><li>Steps b&ndash;d are repeated for each remaining byte of the output buffer (whose length is equal to the requested number of bytes).
</li><li>The content of the output buffer, which is the final value generated by the RNG, is exported.
</li></ol>
</li></ol>
<h2>Design Origins</h2>
<p>The design and implementation of the random number generator are based on the following works:</p>
<ul>
<li>Software Generation of Practically Strong Random Numbers by Peter Gutmann [10]
</li><li>Cryptographic Random Numbers by Carl Ellison [11] </li></ul>
<p>&nbsp;</p>
<p><a href="Keyfiles.html" style="text-align:left; color:#0080c0; text-decoration:none; font-weight:bold.html">Next Section &gt;&gt;</a></p>
</div><div class="ClearBoth"></div></body></html>
ef='#n1123'>1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680
/*
 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-2017 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"
#ifdef TC_UNIX
#include <signal.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "Platform/Unix/Process.h"
#endif

#include "Common/SecurityToken.h"
#include "Core/RandomNumberGenerator.h"
#include "Application.h"
#include "TextUserInterface.h"

namespace VeraCrypt
{
	TextUserInterface::TextUserInterface ()
	{
#ifdef TC_UNIX
		signal (SIGHUP, OnSignal);
		signal (SIGINT, OnSignal);
		signal (SIGQUIT, OnSignal);
		signal (SIGTERM, OnSignal);

		struct stat statBuf;
		if (fstat (0, &statBuf) != -1)
#endif
		{
			FInputStream.reset (new wxFFileInputStream (stdin));
			TextInputStream.reset (new wxTextInputStream (*FInputStream));
		}
	}

	TextUserInterface::~TextUserInterface ()
	{
		try
		{
			if (RandomNumberGenerator::IsRunning())
				RandomNumberGenerator::Stop();
		}
		catch (...) { }

#ifdef TC_UNIX
		signal (SIGHUP, SIG_DFL);
		signal (SIGINT, SIG_DFL);
		signal (SIGQUIT, SIG_DFL);
		signal (SIGTERM, SIG_DFL);
#endif
	}

	FilePath TextUserInterface::AskFilePath (const wxString &message) const
	{
		return AskString (!message.empty() ? message : wxString (_("Enter filename: ")));
	}

	shared_ptr <KeyfileList> TextUserInterface::AskKeyfiles (const wxString &message) const
	{
		wxString msg = _("Enter keyfile");
		if (!message.empty())
			msg = message;

		make_shared_auto (KeyfileList, keyfiles);

		wxString s;
		wxString m = msg + L" [" + _("none") + L"]: ";
		while (!(s = AskString (m)).empty())
		{
			keyfiles->push_back (make_shared <Keyfile> (wstring (s)));
			m = msg + L" [" + _("finish") + L"]: ";
		}

		return keyfiles;
	}

	shared_ptr <VolumePassword> TextUserInterface::AskPassword (const wxString &message, bool verify) const
	{
		wxString msg = LangString["ENTER_PASSWORD"] + L": ";
		if (!message.empty())
			msg = message + L": ";

		SetTerminalEcho (false);
		finally_do ({ TextUserInterface::SetTerminalEcho (true); });

		wchar_t passwordBuf[4096];
		finally_do_arg (BufferPtr, BufferPtr (reinterpret_cast <byte *> (passwordBuf), sizeof (passwordBuf)), { finally_arg.Erase(); });

		shared_ptr<VolumePassword> password;

		bool verPhase = false;
		while (true)
		{
			ShowString (verPhase ? wxString (_("Re-enter password: ")) : msg);

			wxString passwordStr;
			ReadInputStreamLine (passwordStr);

			size_t length = passwordStr.size();

			ShowString (L"\n");

			if (!verPhase && length < 1)
			{
				return shared_ptr <VolumePassword>(new VolumePassword ());
			}

			for (size_t i = 0; i < length && i < VolumePassword::MaxSize; ++i)
			{
				passwordBuf[i] = (wchar_t) passwordStr[i];
				const_cast <wchar_t *> (passwordStr.wc_str())[i] = L'X';
			}

			if (verify && verPhase)
			{
				shared_ptr <VolumePassword> verPassword = ToUTF8Password (passwordBuf, length);

				if (*password != *verPassword)
				{
					ShowInfo (_("Passwords do not match."));
					ShowString (L"\n");
					verPhase = false;
					continue;
				}
			}

			password = ToUTF8Password (passwordBuf, length);

			if (!verPhase)
			{
				if (verify)
				{
					if (password->Size() < VolumePassword::WarningSizeThreshold)
					{
						SetTerminalEcho (true);
						finally_do ({ TextUserInterface::SetTerminalEcho (false); });

						if (!AskYesNo (LangString ["PASSWORD_LENGTH_WARNING"], false, true))
						{
							ShowString (L"\n");
							continue;
						}
						ShowString (L"\n");
					}
				}
			}

			if (!verify || verPhase)
				return password;

			if (!verPhase)
				verPhase = true;
		}

		return password;
	}

	int TextUserInterface::AskPim (const wxString &message) const
	{
		int pim = -1;
		wxString msg = _("Enter new PIM: ");
		if (!message.empty())
			msg = message + L": ";
		while (pim < 0)
		{
			wstring pimStr = AskString (msg);
			if (pimStr.empty())
				pim = 0;
			else
			{
				try
				{
					pim = (int) StringConverter::ToUInt32 (pimStr);
					if (pim > MAX_PIM_VALUE)
					{
						pim = -1;
						ShowError ("PIM_TOO_BIG");
						continue;
					}
				}
				catch (...)
				{
					pim = -1;
					continue;
				}
			}
		}

		return pim;
	}

	ssize_t TextUserInterface::AskSelection (ssize_t optionCount, ssize_t defaultOption) const
	{
		while (true)
		{
			wstring selectionStr = AskString (defaultOption == -1 ? wxString (_("Select: ")) : wxString (wstring (StringFormatter (_("Select [{0}]: "), (uint32) defaultOption))));
			ssize_t selection;

			if (selectionStr.empty() && defaultOption != -1)
				return defaultOption;

			try
			{
				selection = StringConverter::ToUInt32 (selectionStr);
			}
			catch (...)
			{
				continue;
			}

			if (selection > 0 && selection <= optionCount)
				return selection;
		}
	}

	wstring TextUserInterface::AskString (const wxString &message) const
	{
		ShowString (message);
		return wstring (ReadInputStreamLine());
	}

	bool TextUserInterface::AskYesNo (const wxString &message, bool defaultYes, bool warning) const
	{
		while (true)
		{
			wxString s = AskString (StringFormatter (L"{0} (y={1}/n={2}) [{3}]: ",
				message, LangString["YES"], LangString["NO"], LangString[defaultYes ? "YES" : "NO"]));

			if (s.IsSameAs (L'n', false) || s.IsSameAs (L"no", false) || (!defaultYes && s.empty()))
				return false;

			if (s.IsSameAs (L'y', false) || s.IsSameAs (L"yes", false) || (defaultYes && s.empty()))
				return true;
		};
	}

	shared_ptr <VolumePath> TextUserInterface::AskVolumePath (const wxString &message) const
	{
		return make_shared <VolumePath> (AskString (message.empty() ? wxString (_("Enter volume path: ")) : message));
	}

	void TextUserInterface::BackupVolumeHeaders (shared_ptr <VolumePath> volumePath) const
	{
		if (!volumePath)
			volumePath = AskVolumePath();

		if (!volumePath)
			throw UserAbort (SRC_POS);

#ifdef TC_WINDOWS
		if (Core->IsVolumeMounted (*volumePath))
			throw_err (LangString["DISMOUNT_FIRST"]);
#endif

		ShowInfo ("EXTERNAL_VOL_HEADER_BAK_FIRST_INFO");

		shared_ptr <Pkcs5Kdf> kdf;
		if (CmdLine->ArgHash)
		{
			kdf = Pkcs5Kdf::GetAlgorithm (*CmdLine->ArgHash, false);
		}

		shared_ptr <Volume> normalVolume;
		shared_ptr <Volume> hiddenVolume;

		MountOptions normalVolumeMountOptions;
		MountOptions hiddenVolumeMountOptions;

		normalVolumeMountOptions.Path = volumePath;
		hiddenVolumeMountOptions.Path = volumePath;

		VolumeType::Enum volumeType = VolumeType::Normal;

		// Open both types of volumes
		while (true)
		{
			shared_ptr <Volume> volume;
			MountOptions *options = (volumeType == VolumeType::Hidden ? &hiddenVolumeMountOptions : &normalVolumeMountOptions);

			while (!volume)
			{
				ShowString (L"\n");
				options->Password = AskPassword (LangString[volumeType == VolumeType::Hidden ? "ENTER_HIDDEN_VOL_PASSWORD" : "ENTER_NORMAL_VOL_PASSWORD"]);
				options->Pim = AskPim (volumeType == VolumeType::Hidden ?_("Enter PIM for the hidden volume") : _("Enter PIM for the normal/outer volume"));
				options->Keyfiles = AskKeyfiles();

				try
				{
					volume = Core->OpenVolume (
						options->Path,
						options->PreserveTimestamps,
						options->Password,
						options->Pim,
						kdf,
						false,
						options->Keyfiles,
						options->Protection,
						options->ProtectionPassword,
						options->ProtectionPim,
						options->ProtectionKdf,
						options->ProtectionKeyfiles,
						true,
						volumeType,
						options->UseBackupHeaders
						);
				}
				catch (PasswordException &e)
				{
					bool bFailed = true;
					if (!options->UseBackupHeaders)
					{
						try
						{
							volume = Core->OpenVolume (
								options->Path,
								options->PreserveTimestamps,
								options->Password,
								options->Pim,
								kdf,
								false,
								options->Keyfiles,
								options->Protection,
								options->ProtectionPassword,
								options->ProtectionPim,
								options->ProtectionKdf,
								options->ProtectionKeyfiles,
								true,
								volumeType,
								true
								);
							
							bFailed = false;
						}
						catch (...)
						{
						}
					}
					
					if (bFailed)
						ShowInfo (e);
					else
						ShowInfo ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
				}
			}

			if (volumeType == VolumeType::Hidden)
				hiddenVolume = volume;
			else
				normalVolume = volume;

			// Ask whether a hidden volume is present
			if (volumeType == VolumeType::Normal && AskYesNo (L"\n" + LangString["DOES_VOLUME_CONTAIN_HIDDEN"]))
			{
				volumeType = VolumeType::Hidden;
				continue;
			}

			break;
		}

		if (hiddenVolume)
		{
			if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV1Normal))
				throw ParameterIncorrect (SRC_POS);

			if (typeid (*normalVolume->GetLayout()) == typeid (VolumeLayoutV2Normal) && typeid (*hiddenVolume->GetLayout()) != typeid (VolumeLayoutV2Hidden))
				throw ParameterIncorrect (SRC_POS);
		}

		// Ask user to select backup file path
		wxString confirmMsg = L"\n" + LangString["CONFIRM_VOL_HEADER_BAK"] + L"\n";

		if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true))
			return;

		ShowString (L"\n");

		FilePath filePath = AskFilePath();
		if (filePath.IsEmpty())
			throw UserAbort (SRC_POS);

		File backupFile;
		backupFile.Open (filePath, File::CreateWrite);

		RandomNumberGenerator::Start();
		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);
		UserEnrichRandomPool();

		// Re-encrypt volume header
		SecureBuffer newHeaderBuffer (normalVolume->GetLayout()->GetHeaderSize());
		Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, normalVolume->GetHeader(), normalVolumeMountOptions.Password, normalVolumeMountOptions.Pim, normalVolumeMountOptions.Keyfiles);

		backupFile.Write (newHeaderBuffer);

		if (hiddenVolume)
		{
			// Re-encrypt hidden volume header
			Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, hiddenVolume->GetHeader(), hiddenVolumeMountOptions.Password, hiddenVolumeMountOptions.Pim, hiddenVolumeMountOptions.Keyfiles);
		}
		else
		{
			// Store random data in place of hidden volume header
			shared_ptr <EncryptionAlgorithm> ea = normalVolume->GetEncryptionAlgorithm();
			Core->RandomizeEncryptionAlgorithmKey (ea);
			ea->Encrypt (newHeaderBuffer);
		}

		backupFile.Write (newHeaderBuffer);

		ShowString (L"\n");
		ShowInfo ("VOL_HEADER_BACKED_UP");
	}

	void TextUserInterface::ChangePassword (shared_ptr <VolumePath> volumePath, shared_ptr <VolumePassword> password, int pim, shared_ptr <Hash> currentHash, bool truecryptMode, shared_ptr <KeyfileList> keyfiles, shared_ptr <VolumePassword> newPassword, int newPim, shared_ptr <KeyfileList> newKeyfiles, shared_ptr <Hash> newHash) const
	{
		shared_ptr <Volume> volume;

		// Volume path
		if (!volumePath.get())
		{
			if (Preferences.NonInteractive)
				throw MissingArgument (SRC_POS);

			volumePath = AskVolumePath ();
		}

		if (volumePath->IsEmpty())
			throw UserAbort (SRC_POS);

		bool passwordInteractive = !password.get();
		bool keyfilesInteractive = !keyfiles.get();

		shared_ptr<Pkcs5Kdf> kdf;
		if (currentHash)
		{
			kdf = Pkcs5Kdf::GetAlgorithm (*currentHash, truecryptMode);
		}

		while (true)
		{
			// Current password
			if (!passwordInteractive)
			{

			}
			else if (!Preferences.NonInteractive)
			{
				password = AskPassword ();
			}

			// current PIM
			if (!truecryptMode && !Preferences.NonInteractive && (pim < 0))
			{
				pim = AskPim (_("Enter current PIM"));
			}

			// Current keyfiles
			try
			{
				if (keyfilesInteractive)
				{
					// Ask for keyfiles only if required
					try
					{
						keyfiles.reset (new KeyfileList);
						volume = Core->OpenVolume (volumePath, Preferences.DefaultMountOptions.PreserveTimestamps, password, pim, kdf, truecryptMode, keyfiles);
					}
					catch (PasswordException&)
					{
						if (!Preferences.NonInteractive)
							keyfiles = AskKeyfiles ();
					}
				}

				if (!volume.get())
					volume = Core->OpenVolume (volumePath, Preferences.DefaultMountOptions.PreserveTimestamps, password, pim, kdf, truecryptMode, keyfiles);
			}
			catch (PasswordException &e)
			{
				if (Preferences.NonInteractive || !passwordInteractive || !keyfilesInteractive)
					throw;

				ShowInfo (e);
				continue;
			}

			break;
		}

		// New password
		if (!newPassword.get() && !Preferences.NonInteractive)
			newPassword = AskPassword (_("Enter new password"), true);

		// New PIM
		if ((newPim < 0) && !Preferences.NonInteractive)
			newPim = AskPim (_("Enter new PIM"));

		// New keyfiles
		if (!newKeyfiles.get() && !Preferences.NonInteractive)
		{
			if (keyfiles.get() && keyfiles->size() > 0 && AskYesNo (_("Keep current keyfiles?"), true))
				newKeyfiles = keyfiles;
			else
				newKeyfiles = AskKeyfiles (_("Enter new keyfile"));
		}

		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);
		UserEnrichRandomPool();

		Core->ChangePassword (volume, newPassword, newPim, newKeyfiles,
			newHash ? Pkcs5Kdf::GetAlgorithm (*newHash, false) : shared_ptr <Pkcs5Kdf>());

		ShowInfo ("PASSWORD_CHANGED");
	}

	void TextUserInterface::CreateKeyfile (shared_ptr <FilePath> keyfilePath) const
	{
		FilePath path;

		RandomNumberGenerator::Start();
		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);
		UserEnrichRandomPool();

		if (keyfilePath)
		{
			Core->CreateKeyfile (*keyfilePath);
		}
		else
		{
			wstring fileName = AskFilePath();
			if (fileName.empty())
				return;

			Core->CreateKeyfile (fileName);
		}

		ShowInfo ("KEYFILE_CREATED");
	}

	void TextUserInterface::CreateVolume (shared_ptr <VolumeCreationOptions> options) const
	{
		// Volume type
		if (options->Type == VolumeType::Unknown)
		{
			if (Preferences.NonInteractive)
			{
				options->Type = VolumeType::Normal;
			}
			else
			{
				ShowString (_("Volume type:\n 1) Normal\n 2) Hidden\n"));

				switch (AskSelection (2, 1))
				{
				case 1:
					options->Type = VolumeType::Normal;
					break;

				case 2:
					options->Type = VolumeType::Hidden;
					break;
				}
			}
		}

		shared_ptr <VolumeLayout> layout;
		if (options->Type == VolumeType::Hidden)
			layout.reset (new VolumeLayoutV2Hidden);
		else
			layout.reset (new VolumeLayoutV2Normal);

		if (!Preferences.NonInteractive && options->Type == VolumeType::Hidden)
			ShowInfo (_("\nIMPORTANT: Inexperienced users should use the graphical user interface to create a hidden volume. When using the text interface, the procedure described in the command line help must be followed to create a hidden volume."));

		// Volume path
		if (options->Path.IsEmpty())
		{
			if (Preferences.NonInteractive)
				throw MissingArgument (SRC_POS);

			do
			{
				ShowString (L"\n");
				options->Path = VolumePath (*AskVolumePath());
			} while (options->Path.IsEmpty());
		}

		// Sector size
		if (options->Path.IsDevice())
			options->SectorSize = Core->GetDeviceSectorSize (options->Path);
		else
			options->SectorSize = TC_SECTOR_SIZE_FILE_HOSTED_VOLUME;

		// Volume size
		uint64 hostSize = 0;

		if (options->Type == VolumeType::Hidden)
		{
			FilesystemPath fsPath (wstring (options->Path));

			if (fsPath.IsFile())
			{
				File file;
				file.Open (fsPath);
				hostSize = file.Length();
			}
			else if (fsPath.IsDevice())
			{
				hostSize = Core->GetDeviceSize (fsPath);
			}
			else
			{
				throw_err (_("Hidden volume can be created only in an existing file or device."));
			}

			if (hostSize < TC_MIN_HIDDEN_VOLUME_HOST_SIZE)
				throw_err (StringFormatter (_("Minimum outer volume size is {0}."), SizeToString (TC_MIN_HIDDEN_VOLUME_HOST_SIZE)));
		}

		uint64 minVolumeSize = options->Type == VolumeType::Hidden ? TC_MIN_HIDDEN_VOLUME_SIZE : TC_MIN_VOLUME_SIZE;
		uint64 maxVolumeSize = options->Type == VolumeType::Hidden ? VolumeLayoutV2Normal().GetMaxDataSize (hostSize) - TC_MIN_FAT_FS_SIZE : TC_MAX_VOLUME_SIZE_GENERAL;

		if (options->Path.IsDevice() && options->Type != VolumeType::Hidden)
		{
			if (options->Size != 0)
				throw_err (_("Volume size cannot be changed for device-hosted volumes."));

			options->Size = Core->GetDeviceSize (options->Path);
		}
		else
		{
			options->Quick = false;

			uint32 sectorSizeRem = options->Size % options->SectorSize;
			if (sectorSizeRem != 0)
				options->Size += options->SectorSize - sectorSizeRem;

			while (options->Size == 0)
			{
				if (Preferences.NonInteractive)
					throw MissingArgument (SRC_POS);

				wstring sizeStr = AskString (options->Type == VolumeType::Hidden ? _("\nEnter hidden volume size (sizeK/size[M]/sizeG): ") : _("\nEnter volume size (sizeK/size[M]/sizeG): "));
				uint64 multiplier = 1024 * 1024;

				if (sizeStr.find (L"K") != string::npos)
				{
					multiplier = 1024;
					sizeStr.resize (sizeStr.size() - 1);
				}
				else if (sizeStr.find (L"M") != string::npos)
				{
					sizeStr.resize (sizeStr.size() - 1);
				}
				else if (sizeStr.find (L"G") != string::npos)
				{
					multiplier = 1024 * 1024 * 1024;
					sizeStr.resize (sizeStr.size() - 1);
				}
				else if (sizeStr.find (L"T") != string::npos)
				{
					multiplier = (uint64) 1024 * 1024 * 1024 * 1024;
					sizeStr.resize (sizeStr.size() - 1);
				}

				try
				{
					options->Size = StringConverter::ToUInt64 (sizeStr);
					options->Size *= multiplier;

					sectorSizeRem = options->Size % options->SectorSize;
					if (sectorSizeRem != 0)
						options->Size += options->SectorSize - sectorSizeRem;
				}
				catch (...)
				{
					options->Size = 0;
					continue;
				}

				if (options->Size < minVolumeSize)
				{
					ShowError (StringFormatter (_("Minimum volume size is {0}."), SizeToString (minVolumeSize)));
					options->Size = 0;
				}

				if (options->Size > maxVolumeSize)
				{
					ShowError (StringFormatter (_("Maximum volume size is {0}."), SizeToString (maxVolumeSize)));
					options->Size = 0;
				}
			}
		}

		if (options->Size < minVolumeSize || options->Size > maxVolumeSize)
			throw_err (_("Incorrect volume size"));

		if (options->Type == VolumeType::Hidden)
			options->Quick = true;

		// Encryption algorithm
		if (!options->EA)
		{
			if (Preferences.NonInteractive)
				throw MissingArgument (SRC_POS);

			ShowInfo (wxString (L"\n") + LangString["ENCRYPTION_ALGORITHM_LV"] + L":");

			vector < shared_ptr <EncryptionAlgorithm> > encryptionAlgorithms;
			foreach (shared_ptr <EncryptionAlgorithm> ea, EncryptionAlgorithm::GetAvailableAlgorithms())
			{
				if (!ea->IsDeprecated())
				{
					ShowString (StringFormatter (L" {0}) {1}\n", (uint32) encryptionAlgorithms.size() + 1, ea->GetName(true)));
					encryptionAlgorithms.push_back (ea);
				}
			}


			options->EA = encryptionAlgorithms[AskSelection (encryptionAlgorithms.size(), 1) - 1];
		}

		// Hash algorithm
		if (!options->VolumeHeaderKdf)
		{
			if (Preferences.NonInteractive)
				throw MissingArgument (SRC_POS);

			ShowInfo (_("\nHash algorithm:"));

			vector < shared_ptr <Hash> > hashes;
			foreach (shared_ptr <Hash> hash, Hash::GetAvailableAlgorithms())
			{
				if (!hash->IsDeprecated())
				{
					ShowString (StringFormatter (L" {0}) {1}\n", (uint32) hashes.size() + 1, hash->GetName()));
					hashes.push_back (hash);
				}
			}

			shared_ptr <Hash> selectedHash = hashes[AskSelection (hashes.size(), 1) - 1];
			RandomNumberGenerator::SetHash (selectedHash);
			options->VolumeHeaderKdf = Pkcs5Kdf::GetAlgorithm (*selectedHash, false);

		}

		// Filesystem
		options->FilesystemClusterSize = 0;

		if (options->Filesystem == VolumeCreationOptions::FilesystemType::Unknown)
		{
			if (Preferences.NonInteractive)
			{
				options->Filesystem = VolumeCreationOptions::FilesystemType::GetPlatformNative();
			}
			else
			{
				ShowInfo (_("\nFilesystem:"));

				vector <VolumeCreationOptions::FilesystemType::Enum> filesystems;

				ShowInfo (L" 1) " + LangString["NONE"]); filesystems.push_back (VolumeCreationOptions::FilesystemType::None);
				ShowInfo (L" 2) FAT"); filesystems.push_back (VolumeCreationOptions::FilesystemType::FAT);

#if defined (TC_LINUX)
				ShowInfo (L" 3) Linux Ext2"); filesystems.push_back (VolumeCreationOptions::FilesystemType::Ext2);
				ShowInfo (L" 4) Linux Ext3"); filesystems.push_back (VolumeCreationOptions::FilesystemType::Ext3);
				ShowInfo (L" 5) Linux Ext4"); filesystems.push_back (VolumeCreationOptions::FilesystemType::Ext4);
				ShowInfo (L" 6) NTFS");       filesystems.push_back (VolumeCreationOptions::FilesystemType::NTFS);
				ShowInfo (L" 7) exFAT");      filesystems.push_back (VolumeCreationOptions::FilesystemType::exFAT);
#elif defined (TC_MACOSX)
				ShowInfo (L" 3) Mac OS Extended"); filesystems.push_back (VolumeCreationOptions::FilesystemType::MacOsExt);
				ShowInfo (L" 4) exFAT");      filesystems.push_back (VolumeCreationOptions::FilesystemType::exFAT);
#elif defined (TC_FREEBSD) || defined (TC_SOLARIS)
				ShowInfo (L" 3) UFS"); filesystems.push_back (VolumeCreationOptions::FilesystemType::UFS);
#endif

				options->Filesystem = filesystems[AskSelection (filesystems.size(), 2) - 1];
			}
		}

		uint64 filesystemSize = layout->GetMaxDataSize (options->Size);

		if (options->Filesystem == VolumeCreationOptions::FilesystemType::FAT
			&& (filesystemSize < TC_MIN_FAT_FS_SIZE || filesystemSize > TC_MAX_FAT_SECTOR_COUNT * options->SectorSize))
		{
			throw_err (_("Specified volume size cannot be used with FAT filesystem."));
		}

		// Password
		if (!options->Password && !Preferences.NonInteractive)
		{
			ShowString (L"\n");
			options->Password = AskPassword (_("Enter password"), true);
		}

		// PIM
		if ((options->Pim < 0) && !Preferences.NonInteractive)
		{
			ShowString (L"\n");
			options->Pim = AskPim (_("Enter PIM"));
		}

		// Keyfiles
		if (!options->Keyfiles && !Preferences.NonInteractive)
		{
			ShowString (L"\n");
			options->Keyfiles = AskKeyfiles (_("Enter keyfile path"));
		}

		if ((!options->Keyfiles || options->Keyfiles->empty())
			&& (!options->Password || options->Password->IsEmpty()))
		{
			throw_err (_("Password cannot be empty when no keyfile is specified"));
		}

		// Random data
		RandomNumberGenerator::Start();
		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);
		UserEnrichRandomPool();

		ShowString (L"\n");
		wxLongLong startTime = wxGetLocalTimeMillis();

		VolumeCreator creator;
		creator.CreateVolume (options);

		bool volumeCreated = false;
		while (!volumeCreated)
		{
			VolumeCreator::ProgressInfo progress = creator.GetProgressInfo();

			wxLongLong timeDiff = wxGetLocalTimeMillis() - startTime;
			if (timeDiff.GetValue() > 0)
			{
				uint64 speed = progress.SizeDone * 1000 / timeDiff.GetValue();

				volumeCreated = !progress.CreationInProgress;

				ShowString (wxString::Format (L"\rDone: %7.3f%%  Speed: %9s  Left: %s         ",
					100.0 - double (options->Size - progress.SizeDone) / (double (options->Size) / 100.0),
					speed > 0 ? (const wchar_t*) SpeedToString (speed).c_str() : L" ",
					speed > 0 ? (const wchar_t*) TimeSpanToString ((options->Size - progress.SizeDone) / speed).c_str() : L""));
			}

			Thread::Sleep (100);
		}

		ShowString (L"\n\n");
		creator.CheckResult();

#ifdef TC_UNIX
		if (options->Filesystem != VolumeCreationOptions::FilesystemType::None
			&& options->Filesystem != VolumeCreationOptions::FilesystemType::FAT)
		{
			const char *fsFormatter = nullptr;

			switch (options->Filesystem)
			{
#if defined (TC_LINUX)
			case VolumeCreationOptions::FilesystemType::Ext2:		fsFormatter = "mkfs.ext2"; break;
			case VolumeCreationOptions::FilesystemType::Ext3:		fsFormatter = "mkfs.ext3"; break;
			case VolumeCreationOptions::FilesystemType::Ext4:		fsFormatter = "mkfs.ext4"; break;
			case VolumeCreationOptions::FilesystemType::NTFS:		fsFormatter = "mkfs.ntfs"; break;
			case VolumeCreationOptions::FilesystemType::exFAT:		fsFormatter = "mkfs.exfat"; break;
#elif defined (TC_MACOSX)
			case VolumeCreationOptions::FilesystemType::MacOsExt:	fsFormatter = "newfs_hfs"; break;
			case VolumeCreationOptions::FilesystemType::exFAT:		fsFormatter = "newfs_exfat"; break;
#elif defined (TC_FREEBSD) || defined (TC_SOLARIS)
			case VolumeCreationOptions::FilesystemType::UFS:		fsFormatter = "newfs" ; break;
#endif
			default: throw ParameterIncorrect (SRC_POS);
			}

			MountOptions mountOptions (GetPreferences().DefaultMountOptions);
			mountOptions.Path = make_shared <VolumePath> (options->Path);
			mountOptions.NoFilesystem = true;
			mountOptions.Protection = VolumeProtection::None;
			mountOptions.Password = options->Password;
			mountOptions.Pim = options->Pim;
			mountOptions.Keyfiles = options->Keyfiles;

			shared_ptr <VolumeInfo> volume = Core->MountVolume (mountOptions);
			finally_do_arg (shared_ptr <VolumeInfo>, volume, { Core->DismountVolume (finally_arg, true); });

			Thread::Sleep (2000);	// Try to prevent race conditions caused by OS

			// Temporarily take ownership of the device if the user is not an administrator
			UserId origDeviceOwner ((uid_t) -1);

			DevicePath virtualDevice = volume->VirtualDevice;
#ifdef TC_MACOSX
			string virtualDeviceStr = virtualDevice;
			if (virtualDeviceStr.find ("/dev/rdisk") != 0)
				virtualDevice = "/dev/r" + virtualDeviceStr.substr (5);
#endif
			try
			{
				File file;
				file.Open (virtualDevice, File::OpenReadWrite);
			}
			catch (...)
			{
				if (!Core->HasAdminPrivileges())
				{
					origDeviceOwner = virtualDevice.GetOwner();
					Core->SetFileOwner (virtualDevice, UserId (getuid()));
				}
			}

			finally_do_arg2 (FilesystemPath, virtualDevice, UserId, origDeviceOwner,
			{
				if (finally_arg2.SystemId != (uid_t) -1)
					Core->SetFileOwner (finally_arg, finally_arg2);
			});

			// Create filesystem
			list <string> args;

			if (options->Filesystem == VolumeCreationOptions::FilesystemType::MacOsExt && options->Size >= 10 * BYTES_PER_MB)
				args.push_back ("-J");

			// Perform a quick NTFS formatting
			if (options->Filesystem == VolumeCreationOptions::FilesystemType::NTFS)
				args.push_back ("-f");

			args.push_back (string (virtualDevice));

			Process::Execute (fsFormatter, args);
		}
#endif // TC_UNIX

		ShowInfo (options->Type == VolumeType::Hidden ? "HIDVOL_FORMAT_FINISHED_HELP" : "FORMAT_FINISHED_INFO");
	}

	void TextUserInterface::DeleteSecurityTokenKeyfiles () const
	{
		shared_ptr <KeyfileList> keyfiles = AskKeyfiles();
		if (keyfiles->empty())
			throw UserAbort();

		foreach_ref (const Keyfile &keyfile, *keyfiles)
		{
			SecurityToken::DeleteKeyfile (SecurityTokenKeyfilePath (FilePath (keyfile)));
		}
	}

	void TextUserInterface::DoShowError (const wxString &message) const
	{
		wcerr << L"Error: " << static_cast<wstring> (message) << endl;
	}

	void TextUserInterface::DoShowInfo (const wxString &message) const
	{
		wcout << static_cast<wstring> (message) << endl;
	}

	void TextUserInterface::DoShowString (const wxString &str) const
	{
		wcout << str.c_str();
	}

	void TextUserInterface::DoShowWarning (const wxString &message) const
	{
		wcerr << L"Warning: " << static_cast<wstring> (message) << endl;
	}

	void TextUserInterface::ExportSecurityTokenKeyfile () const
	{
		wstring keyfilePath = AskString (_("Enter security token keyfile path: "));

		if (keyfilePath.empty())
			throw UserAbort (SRC_POS);

		SecurityTokenKeyfile tokenKeyfile (keyfilePath);

		vector <byte> keyfileData;
		SecurityToken::GetKeyfileData (tokenKeyfile, keyfileData);

		BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());
		finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });

		FilePath exportFilePath = AskFilePath();

		if (exportFilePath.IsEmpty())
			throw UserAbort (SRC_POS);

		File keyfile;
		keyfile.Open (exportFilePath, File::CreateWrite);
		keyfile.Write (keyfileDataBuf);
	}

	shared_ptr <GetStringFunctor> TextUserInterface::GetAdminPasswordRequestHandler ()
	{
		struct AdminPasswordRequestHandler : public GetStringFunctor
		{
			AdminPasswordRequestHandler (TextUserInterface *userInterface) : UI (userInterface) { }
			virtual void operator() (string &passwordStr)
			{
				UI->ShowString (_("Enter your user password or administrator password: "));

				TextUserInterface::SetTerminalEcho (false);
				finally_do ({ TextUserInterface::SetTerminalEcho (true); });

				wstring wPassword (UI->ReadInputStreamLine());
				finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });

				UI->ShowString (L"\n");

				StringConverter::ToSingle (wPassword, passwordStr);
			}
			TextUserInterface *UI;
		};

		return shared_ptr <GetStringFunctor> (new AdminPasswordRequestHandler (this));
	}

	void TextUserInterface::ImportSecurityTokenKeyfiles () const
	{
		list <SecurityTokenInfo> tokens = SecurityToken::GetAvailableTokens();

		if (tokens.empty())
			throw_err (LangString ["NO_TOKENS_FOUND"]);

		CK_SLOT_ID slotId;

		if (tokens.size() == 1)
		{
			slotId = tokens.front().SlotId;
		}
		else
		{
			foreach (const SecurityTokenInfo &token, tokens)
			{
				wstringstream tokenLabel;
				tokenLabel << L"[" << token.SlotId << L"] " << LangString["TOKEN_SLOT_ID"].c_str() << L" " << token.SlotId << L"  " << token.Label;

				ShowInfo (tokenLabel.str());
			}

			slotId = (CK_SLOT_ID) AskSelection (tokens.back().SlotId, tokens.front().SlotId);
		}

		shared_ptr <KeyfileList> keyfiles = AskKeyfiles();
		if (keyfiles->empty())
			throw UserAbort();

		foreach_ref (const Keyfile &keyfilePath, *keyfiles)
		{
			File keyfile;
			keyfile.Open (keyfilePath, File::OpenRead, File::ShareReadWrite, File::PreserveTimestamps);

			if (keyfile.Length() > 0)
			{
				vector <byte> keyfileData (keyfile.Length());
				BufferPtr keyfileDataBuf (&keyfileData.front(), keyfileData.size());

				keyfile.ReadCompleteBuffer (keyfileDataBuf);
				finally_do_arg (BufferPtr, keyfileDataBuf, { finally_arg.Erase(); });

				SecurityToken::CreateKeyfile (slotId, keyfileData, string (FilePath (keyfilePath).ToBaseName()));
			}
			else
				throw InsufficientData (SRC_POS, FilePath (keyfilePath));
		}
	}

	void TextUserInterface::InitSecurityTokenLibrary () const
	{
		if (Preferences.SecurityTokenModule.IsEmpty())
			throw_err (LangString ["NO_PKCS11_MODULE_SPECIFIED"]);

		struct PinRequestHandler : public GetPinFunctor
		{
			PinRequestHandler (const TextUserInterface *userInterface) : UI (userInterface) { }

			virtual void operator() (string &passwordStr)
			{
                if (CmdLine->ArgTokenPin && CmdLine->ArgTokenPin->IsAllocated ())
                {
        			passwordStr.clear();
        			passwordStr.insert (0, (char*) CmdLine->ArgTokenPin->Ptr (), CmdLine->ArgTokenPin->Size());
                    return;
                }

				if (UI->GetPreferences().NonInteractive)
					throw MissingArgument (SRC_POS);

				UI->ShowString (wxString::Format (LangString["ENTER_TOKEN_PASSWORD"], StringConverter::ToWide (passwordStr).c_str()) + L" ");

				TextUserInterface::SetTerminalEcho (false);
				finally_do ({ TextUserInterface::SetTerminalEcho (true); });

				wstring wPassword (UI->ReadInputStreamLine());
				finally_do_arg (wstring *, &wPassword, { StringConverter::Erase (*finally_arg); });

				UI->ShowString (L"\n");

				StringConverter::ToSingle (wPassword, passwordStr);
			}

			virtual void notifyIncorrectPin ()
			{
				if (CmdLine->ArgTokenPin && CmdLine->ArgTokenPin->IsAllocated ())
				{
					CmdLine->ArgTokenPin->Free ();
				}
			}

			const TextUserInterface *UI;
		};

		struct WarningHandler : public SendExceptionFunctor
		{
			WarningHandler (const TextUserInterface *userInterface) : UI (userInterface) { }

			virtual void operator() (const Exception &e)
			{
				UI->ShowError (e);
			}

			const TextUserInterface *UI;
		};

		try
		{
			SecurityToken::InitLibrary (Preferences.SecurityTokenModule, auto_ptr <GetPinFunctor> (new PinRequestHandler (this)), auto_ptr <SendExceptionFunctor> (new WarningHandler (this)));
		}
		catch (Exception &e)
		{
			ShowError (e);
			throw_err (LangString ["PKCS11_MODULE_INIT_FAILED"]);
		}
	}

	void TextUserInterface::ListSecurityTokenKeyfiles () const
	{
		foreach (const SecurityTokenKeyfile &keyfile, SecurityToken::GetAvailableKeyfiles())
		{
			ShowString (wstring (SecurityTokenKeyfilePath (keyfile)));
			ShowString (L"\n");
		}
	}

	VolumeInfoList TextUserInterface::MountAllDeviceHostedVolumes (MountOptions &options) const
	{
		while (true)
		{
			if (!options.Password)
				options.Password = AskPassword();

			if (!options.TrueCryptMode && (options.Pim < 0))
				options.Pim = AskPim (_("Enter PIM"));

			if (!options.Keyfiles)
				options.Keyfiles = AskKeyfiles();

			VolumeInfoList mountedVolumes = UserInterface::MountAllDeviceHostedVolumes (options);

			if (!mountedVolumes.empty())
				return mountedVolumes;

			options.Password.reset();
			options.Pim = -1;
		}
	}

	shared_ptr <VolumeInfo> TextUserInterface::MountVolume (MountOptions &options) const
	{
		shared_ptr <VolumeInfo> volume;

		CheckRequirementsForMountingVolume();

		// Volume path
		while (!options.Path || options.Path->IsEmpty())
		{
			if (Preferences.NonInteractive)
				throw MissingArgument (SRC_POS);

			options.Path = AskVolumePath ();
		}

		if (Core->IsVolumeMounted (*options.Path))
		{
			ShowInfo (StringFormatter (LangString["VOLUME_ALREADY_MOUNTED"], wstring (*options.Path)));
			return volume;
		}

		// Mount point
		if (!options.MountPoint && !options.NoFilesystem)
			options.MountPoint.reset (new DirectoryPath (AskString (_("Enter mount directory [default]: "))));

		VolumePassword password;
		KeyfileList keyfiles;

		if ((!options.Password || options.Password->IsEmpty())
			&& (!options.Keyfiles || options.Keyfiles->empty())
			&& !Core->IsPasswordCacheEmpty())
		{
			// Cached password
			try
			{
				volume = UserInterface::MountVolume (options);
			}
			catch (PasswordException&) { }
		}

		int incorrectPasswordCount = 0;

		while (!volume)
		{
			// Password
			if (!options.Password)
			{
				options.Password = AskPassword (StringFormatter (_("Enter password for {0}"), wstring (*options.Path)));
			}

			if (!options.TrueCryptMode && (options.Pim < 0))
			{
				options.Pim = AskPim (StringFormatter (_("Enter PIM for {0}"), wstring (*options.Path)));
			}

			// Keyfiles
			if (!options.Keyfiles)
				options.Keyfiles = AskKeyfiles();

			// Hidden volume protection
			if (options.Protection == VolumeProtection::None
				&& !CmdLine->ArgNoHiddenVolumeProtection
				&& AskYesNo (_("Protect hidden volume (if any)?")))
				options.Protection = VolumeProtection::HiddenVolumeReadOnly;

			if (options.Protection == VolumeProtection::HiddenVolumeReadOnly)
			{
				if (!options.ProtectionPassword)
					options.ProtectionPassword = AskPassword (_("Enter password for hidden volume"));
				if (!options.TrueCryptMode && (options.ProtectionPim < 0))
					options.ProtectionPim = AskPim (_("Enter PIM for hidden volume"));
				if (!options.ProtectionKeyfiles)
					options.ProtectionKeyfiles = AskKeyfiles (_("Enter keyfile for hidden volume"));
			}

			try
			{
				volume = UserInterface::MountVolume (options);
			}
			catch (ProtectionPasswordIncorrect &e)
			{
				ShowInfo (e);
				options.ProtectionPassword.reset();
				options.ProtectionPim = -1;
			}
			catch (PasswordIncorrect &e)
			{
				if (++incorrectPasswordCount > 2 && !options.UseBackupHeaders)
				{
					// Try to mount the volume using the backup header
					options.UseBackupHeaders = true;

					try
					{
						volume = UserInterface::MountVolume (options);
						ShowWarning ("HEADER_DAMAGED_AUTO_USED_HEADER_BAK");
					}
					catch (...)
					{
						options.UseBackupHeaders = false;
						ShowInfo (e);
						options.Password.reset();
					}
				}
				else
				{
					ShowInfo (e);
					options.Password.reset();
				}

				ShowString (L"\n");
			}
			catch (PasswordException &e)
			{
				ShowInfo (e);
				options.Password.reset();
			}
		}

#ifdef TC_LINUX
		if (!Preferences.NonInteractive && !Preferences.DisableKernelEncryptionModeWarning
			&& volume->EncryptionModeName != L"XTS")
		{
			ShowWarning (LangString["ENCRYPTION_MODE_NOT_SUPPORTED_BY_KERNEL"]);
		}
#endif

		return volume;
	}

	bool TextUserInterface::OnInit ()
	{
		try
		{
			DefaultMessageOutput = new wxMessageOutputStderr;
			wxMessageOutput::Set (DefaultMessageOutput);

			InterfaceType = UserInterfaceType::Text;
			Init();
		}
		catch (exception &e)
		{
			ShowError (e);
			return false;
		}
		return true;
	}

	int TextUserInterface::OnRun()
	{
		try
		{
			if (ProcessCommandLine ())
			{
				Application::SetExitCode (0);
				return 0;
			}
		}
		catch (exception &e)
		{
			ShowError (e);
		}

		Application::SetExitCode (1);
		return 1;
	}

	void TextUserInterface::OnSignal (int signal)
	{
#ifdef TC_UNIX
		try
		{
			SetTerminalEcho (true);
		}
		catch (...) { }
		_exit (1);
#endif
	}

	void TextUserInterface::ReadInputStreamLine (wxString &line) const
	{
		if (!TextInputStream.get() || feof (stdin) || ferror (stdin))
			throw UserAbort (SRC_POS);

		line = TextInputStream->ReadLine();

		if (ferror (stdin) || (line.empty() && feof (stdin)))
			throw UserAbort (SRC_POS);
	}

	wxString TextUserInterface::ReadInputStreamLine () const
	{
		wxString line;
		ReadInputStreamLine (line);
		return line;
	}

	void TextUserInterface::RestoreVolumeHeaders (shared_ptr <VolumePath> volumePath) const
	{
		if (!volumePath)
			volumePath = AskVolumePath();

		if (!volumePath)
			throw UserAbort (SRC_POS);

#ifdef TC_WINDOWS
		if (Core->IsVolumeMounted (*volumePath))
			throw_err (LangString["DISMOUNT_FIRST"]);
#endif

		// Ask whether to restore internal or external backup
		bool restoreInternalBackup;
		shared_ptr <Pkcs5Kdf> kdf;
		if (CmdLine->ArgHash)
		{
			kdf = Pkcs5Kdf::GetAlgorithm (*CmdLine->ArgHash, false);
		}

		ShowInfo (LangString["HEADER_RESTORE_EXTERNAL_INTERNAL"]);
		ShowInfo (L"\n1) " + LangString["HEADER_RESTORE_INTERNAL"]);
		ShowInfo (L"2) " + LangString["HEADER_RESTORE_EXTERNAL"] + L"\n");

		switch (AskSelection (2))
		{
		case 1:
			restoreInternalBackup = true;
			break;

		case 2:
			restoreInternalBackup = false;
			break;

		default:
			throw UserAbort (SRC_POS);
		}

		/* force the display of the random enriching interface */
		RandomNumberGenerator::SetEnrichedByUserStatus (false);

		if (restoreInternalBackup)
		{
			// Restore header from the internal backup
			shared_ptr <Volume> volume;
			MountOptions options;
			options.Path = volumePath;

			while (!volume)
			{
				ShowString (L"\n");
				options.Password = AskPassword();
				options.Pim = AskPim();
				options.Keyfiles = AskKeyfiles();

				try
				{
					volume = Core->OpenVolume (
						options.Path,
						options.PreserveTimestamps,
						options.Password,
						options.Pim,
						kdf,
						false,
						options.Keyfiles,
						options.Protection,
						options.ProtectionPassword,
						options.ProtectionPim,
						options.ProtectionKdf,
						options.ProtectionKeyfiles,
						options.SharedAccessAllowed,
						VolumeType::Unknown,
						true
						);
				}
				catch (PasswordException &e)
				{
					ShowInfo (e);
				}
			}

			shared_ptr <VolumeLayout> layout = volume->GetLayout();
			if (typeid (*layout) == typeid (VolumeLayoutV1Normal))
			{
				throw_err (LangString ["VOLUME_HAS_NO_BACKUP_HEADER"]);
			}

			RandomNumberGenerator::Start();
			UserEnrichRandomPool();

			// Re-encrypt volume header
			SecureBuffer newHeaderBuffer (volume->GetLayout()->GetHeaderSize());
			Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, volume->GetHeader(), options.Password, options.Pim,  options.Keyfiles);

			// Write volume header
			int headerOffset = volume->GetLayout()->GetHeaderOffset();
			shared_ptr <File> volumeFile = volume->GetFile();

			if (headerOffset >= 0)
				volumeFile->SeekAt (headerOffset);
			else
				volumeFile->SeekEnd (headerOffset);

			volumeFile->Write (newHeaderBuffer);
		}
		else
		{
			// Restore header from an external backup

			wxString confirmMsg = L"\n\n" + LangString["CONFIRM_VOL_HEADER_RESTORE"];

			if (!AskYesNo (wxString::Format (confirmMsg, wstring (*volumePath).c_str()), true, true))
				return;

			ShowString (L"\n");

			FilePath filePath = AskFilePath();
			if (filePath.IsEmpty())
				throw UserAbort (SRC_POS);

			File backupFile;
			backupFile.Open (filePath, File::OpenRead);

			bool legacyBackup;

			// Determine the format of the backup file
			switch (backupFile.Length())
			{
			case TC_VOLUME_HEADER_GROUP_SIZE:
				legacyBackup = false;
				break;

			case TC_VOLUME_HEADER_SIZE_LEGACY * 2:
				legacyBackup = true;
				break;

			default:
				throw_err (LangString ["HEADER_BACKUP_SIZE_INCORRECT"]);
			}

			// Open the volume header stored in the backup file
			MountOptions options;

			shared_ptr <VolumeLayout> decryptedLayout;

			while (!decryptedLayout)
			{
				options.Password = AskPassword (L"\n" + LangString["ENTER_HEADER_BACKUP_PASSWORD"]);
				options.Pim = AskPim (_("Enter PIM"));
				options.Keyfiles = AskKeyfiles();

				try
				{
					// Test volume layouts
					foreach (shared_ptr <VolumeLayout> layout, VolumeLayout::GetAvailableLayouts ())
					{
						if (layout->HasDriveHeader())
							continue;

						if (!legacyBackup && (typeid (*layout) == typeid (VolumeLayoutV1Normal)))
							continue;

						if (legacyBackup && (typeid (*layout) == typeid (VolumeLayoutV2Normal) || typeid (*layout) == typeid (VolumeLayoutV2Hidden)))
							continue;

						SecureBuffer headerBuffer (layout->GetHeaderSize());
						backupFile.ReadAt (headerBuffer, layout->GetType() == VolumeType::Hidden ? layout->GetHeaderSize() : 0);

						// Decrypt header
						shared_ptr <VolumePassword> passwordKey = Keyfile::ApplyListToPassword (options.Keyfiles, options.Password);
						if (layout->GetHeader()->Decrypt (headerBuffer, *passwordKey, options.Pim, kdf, false, layout->GetSupportedKeyDerivationFunctions(false), layout->GetSupportedEncryptionAlgorithms(), layout->GetSupportedEncryptionModes()))
						{
							decryptedLayout = layout;
							break;
						}
					}

					if (!decryptedLayout)
						throw PasswordIncorrect (SRC_POS);
				}
				catch (PasswordException &e)
				{
					ShowWarning (e);
				}
			}

			File volumeFile;
			volumeFile.Open (*volumePath, File::OpenReadWrite, File::ShareNone, File::PreserveTimestamps);

			RandomNumberGenerator::Start();
			UserEnrichRandomPool();

			// Re-encrypt volume header
			SecureBuffer newHeaderBuffer (decryptedLayout->GetHeaderSize());
			Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles);

			// Write volume header
			int headerOffset = decryptedLayout->GetHeaderOffset();
			if (headerOffset >= 0)
				volumeFile.SeekAt (headerOffset);
			else
				volumeFile.SeekEnd (headerOffset);

			volumeFile.Write (newHeaderBuffer);

			if (decryptedLayout->HasBackupHeader())
			{
				// Re-encrypt backup volume header
				Core->ReEncryptVolumeHeaderWithNewSalt (newHeaderBuffer, decryptedLayout->GetHeader(), options.Password, options.Pim, options.Keyfiles);

				// Write backup volume header
				headerOffset = decryptedLayout->GetBackupHeaderOffset();
				if (headerOffset >= 0)
					volumeFile.SeekAt (headerOffset);
				else
					volumeFile.SeekEnd (headerOffset);

				volumeFile.Write (newHeaderBuffer);
			}
		}

		ShowString (L"\n");
		ShowInfo ("VOL_HEADER_RESTORED");
	}

	void TextUserInterface::SetTerminalEcho (bool enable)
	{
		if (CmdLine->ArgDisplayPassword)
			return;

#ifdef TC_UNIX
		struct termios termAttr;
		if (tcgetattr (0, &termAttr) == 0)
		{
			if (!enable)
			{
				termAttr.c_lflag &= ~ECHO;
				throw_sys_if (tcsetattr (0, TCSANOW, &termAttr) != 0);
			}
			else
			{
				termAttr.c_lflag |= ECHO;
				throw_sys_if (tcsetattr (0, TCSANOW, &termAttr) != 0);
			}
		}
#endif
	}

	void TextUserInterface::UserEnrichRandomPool () const
	{
		RandomNumberGenerator::Start();

		if (RandomNumberGenerator::IsEnrichedByUser())
			return;

		if (CmdLine->ArgHash)
			RandomNumberGenerator::SetHash (CmdLine->ArgHash);

		if (!CmdLine->ArgRandomSourcePath.IsEmpty())
		{
			SecureBuffer buffer (RandomNumberGenerator::PoolSize);
			File randSourceFile;

			randSourceFile.Open (CmdLine->ArgRandomSourcePath, File::OpenRead);

			for (size_t i = 0; i < buffer.Size(); ++i)
			{
				if (randSourceFile.Read (buffer.GetRange (i, 1)) < 1)
					break;
			}

			RandomNumberGenerator::AddToPool (buffer);
			RandomNumberGenerator::SetEnrichedByUserStatus (true);
		}
		else if (!Preferences.NonInteractive)
		{
			int randCharsRequired = RandomNumberGenerator::PoolSize;
			ShowInfo (StringFormatter (_("\nPlease type at least {0} randomly chosen characters and then press Enter:"), randCharsRequired));

			SetTerminalEcho (false);
			finally_do ({ TextUserInterface::SetTerminalEcho (true); });

			while (randCharsRequired > 0)
			{
				wstring randStr = AskString();
				RandomNumberGenerator::AddToPool (ConstBufferPtr ((byte *) randStr.c_str(), randStr.size() * sizeof (wchar_t)));

				randCharsRequired -= randStr.size();

				if (randCharsRequired > 0)
					ShowInfo (StringFormatter (_("Characters remaining: {0}"), randCharsRequired));
			}

			ShowString (L"\n");
			RandomNumberGenerator::SetEnrichedByUserStatus (true);
		}
	}

	wxMessageOutput *DefaultMessageOutput;
}