VeraCrypt
aboutsummaryrefslogtreecommitdiff
path: root/src/Format/InPlace.c
blob: b2f1b386e9bedb940a2fdf99dae4212098f61cad (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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
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
.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 */
/*
 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.
*/

#define FUSE_USE_VERSION  25
#include <errno.h>
#include <fcntl.h>
#include <fuse.h>
#include <iostream>
#include <signal.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <sys/wait.h>

#include "FuseService.h"
#include "Platform/FileStream.h"
#include "Platform/MemoryStream.h"
#include "Platform/Serializable.h"
#include "Platform/SystemLog.h"
#include "Platform/Unix/Pipe.h"
#include "Platform/Unix/Poller.h"
#include "Volume/EncryptionThreadPool.h"
#include "Core/Core.h"

namespace VeraCrypt
{
	static int fuse_service_access (const char *path, int mask)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return 0;
	}

	static void *fuse_service_init ()
	{
		try
		{
			// Termination signals are handled by a separate process to allow clean dismount on shutdown
			struct sigaction action;
			Memory::Zero (&action, sizeof (action));
			action.sa_handler = SIG_IGN;

			sigaction (SIGINT, &action, nullptr);
			sigaction (SIGQUIT, &action, nullptr);
			sigaction (SIGTERM, &action, nullptr);

			if (!EncryptionThreadPool::IsRunning())
				EncryptionThreadPool::Start();
		}
		catch (exception &e)
		{
			SystemLog::WriteException (e);
		}
		catch (...)
		{
			SystemLog::WriteException (UnknownException (SRC_POS));
		}

		return nullptr;
	}

	static void fuse_service_destroy (void *userdata)
	{
		try
		{
			FuseService::Dismount();
		}
		catch (exception &e)
		{
			SystemLog::WriteException (e);
		}
		catch (...)
		{
			SystemLog::WriteException (UnknownException (SRC_POS));
		}
	}

	static int fuse_service_getattr (const char *path, struct stat *statData)
	{
		try
		{
			Memory::Zero (statData, sizeof(*statData));

			statData->st_uid = FuseService::GetUserId();
			statData->st_gid = FuseService::GetGroupId();
			statData->st_atime = time (NULL);
			statData->st_ctime = time (NULL);
			statData->st_mtime = time (NULL);

			if (strcmp (path, "/") == 0)
			{
				statData->st_mode = S_IFDIR | 0500;
				statData->st_nlink = 2;
			}
			else
			{
				if (!FuseService::CheckAccessRights())
					return -EACCES;

				if (strcmp (path, FuseService::GetVolumeImagePath()) == 0)
				{
					statData->st_mode = S_IFREG | 0600;
					statData->st_nlink = 1;
					statData->st_size = FuseService::GetVolumeSize();
				}
				else if (strcmp (path, FuseService::GetControlPath()) == 0)
				{
					statData->st_mode = S_IFREG | 0600;
					statData->st_nlink = 1;
					statData->st_size = FuseService::GetVolumeInfo()->Size();
				}
				else
				{
					return -ENOENT;
				}
			}
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return 0;
	}

	static int fuse_service_opendir (const char *path, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, "/") != 0)
				return -ENOENT;
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return 0;
	}

	static int fuse_service_open (const char *path, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, FuseService::GetVolumeImagePath()) == 0)
				return 0;

			if (strcmp (path, FuseService::GetControlPath()) == 0)
			{
				fi->direct_io = 1;
				return 0;
			}
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}
		return -ENOENT;
	}

	static int fuse_service_read (const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, FuseService::GetVolumeImagePath()) == 0)
			{
				try
				{
					// Test for read beyond the end of the volume
					if ((uint64) offset + size > FuseService::GetVolumeSize())
						size = FuseService::GetVolumeSize() - offset;

					size_t sectorSize = FuseService::GetVolumeSectorSize();
					if (size % sectorSize != 0 || offset % sectorSize != 0)
					{
						// Support for non-sector-aligned read operations is required by some loop device tools
						// which may analyze the volume image before attaching it as a device

						uint64 alignedOffset = offset - (offset % sectorSize);
						uint64 alignedSize = size + (offset % sectorSize);

						if (alignedSize % sectorSize != 0)
							alignedSize += sectorSize - (alignedSize % sectorSize);

						SecureBuffer alignedBuffer (alignedSize);

						FuseService::ReadVolumeSectors (alignedBuffer, alignedOffset);
						BufferPtr ((byte *) buf, size).CopyFrom (alignedBuffer.GetRange (offset % sectorSize, size));
					}
					else
					{
						FuseService::ReadVolumeSectors (BufferPtr ((byte *) buf, size), offset);
					}
				}
				catch (MissingVolumeData)
				{
					return 0;
				}

				return size;
			}

			if (strcmp (path, FuseService::GetControlPath()) == 0)
			{
				shared_ptr <Buffer> infoBuf = FuseService::GetVolumeInfo();
				BufferPtr outBuf ((byte *)buf, size);

				if (offset >= (off_t) infoBuf->Size())
					return 0;

				if (offset + size > infoBuf->Size())
					size = infoBuf->Size () - offset;

				outBuf.CopyFrom (infoBuf->GetRange (offset, size));
				return size;
			}
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return -ENOENT;
	}

	static int fuse_service_readdir (const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, "/") != 0)
				return -ENOENT;

			filler (buf, ".", NULL, 0);
			filler (buf, "..", NULL, 0);
			filler (buf, FuseService::GetVolumeImagePath() + 1, NULL, 0);
			filler (buf, FuseService::GetControlPath() + 1, NULL, 0);
		}
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return 0;
	}

	static int fuse_service_write (const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
	{
		try
		{
			if (!FuseService::CheckAccessRights())
				return -EACCES;

			if (strcmp (path, FuseService::GetVolumeImagePath()) == 0)
			{
				FuseService::WriteVolumeSectors (BufferPtr ((byte *) buf, size), offset);
				return size;
			}

			if (strcmp (path, FuseService::GetControlPath()) == 0)
			{
				if (FuseService::AuxDeviceInfoReceived())
					return -EACCES;

				FuseService::ReceiveAuxDeviceInfo (ConstBufferPtr ((const byte *)buf, size));
				return size;
			}
		}
#ifdef TC_FREEBSD
		// FreeBSD apparently retries failed write operations forever, which may lead to a system crash.
		catch (VolumeReadOnly&)
		{
			return size;
		}
		catch (VolumeProtected&)
		{
			return size;
		}
#endif
		catch (...)
		{
			return FuseService::ExceptionToErrorCode();
		}

		return -ENOENT;
	}

	bool FuseService::CheckAccessRights ()
	{
		return fuse_get_context()->uid == 0 || fuse_get_context()->uid == UserId;
	}

	void FuseService::CloseMountedVolume ()
	{
		if (MountedVolume)
		{
			// This process will exit before the use count of MountedVolume reaches zero
			if (MountedVolume->GetFile().use_count() > 1)
				MountedVolume->GetFile()->Close();

			if (MountedVolume.use_count() > 1)
				delete MountedVolume.get();

			MountedVolume.reset();
		}
	}

	void FuseService::Dismount ()
	{
		CloseMountedVolume();

		if (EncryptionThreadPool::IsRunning())
			EncryptionThreadPool::Stop();
	}

	int FuseService::ExceptionToErrorCode ()
	{
		try
		{
			throw;
		}
		catch (std::bad_alloc)
		{
			return -ENOMEM;
		}
		catch (ParameterIncorrect &e)
		{
			SystemLog::WriteException (e);
			return -EINVAL;
		}
		catch (VolumeProtected&)
		{
			return -EPERM;
		}
		catch (VolumeReadOnly&)
		{
			return -EPERM;
		}
		catch (SystemException &e)
		{
			SystemLog::WriteException (e);
			return -static_cast <int> (e.GetErrorCode());
		}
		catch (std::exception &e)
		{
			SystemLog::WriteException (e);
			return -EINTR;
		}
		catch (...)
		{
			SystemLog::WriteException (UnknownException (SRC_POS));
			return -EINTR;
		}
	}

	shared_ptr <Buffer> FuseService::GetVolumeInfo ()
	{
		shared_ptr <Stream> stream (new MemoryStream);

		{
			ScopeLock lock (OpenVolumeInfoMutex);

			OpenVolumeInfo.Set (*MountedVolume);
			OpenVolumeInfo.SlotNumber = SlotNumber;

			OpenVolumeInfo.Serialize (stream);
		}

		ConstBufferPtr infoBuf = dynamic_cast <MemoryStream&> (*stream);
		shared_ptr <Buffer> outBuf (new Buffer (infoBuf.Size()));
		outBuf->CopyFrom (infoBuf);

		return outBuf;
	}

	const char *FuseService::GetVolumeImagePath ()
	{
#ifdef TC_MACOSX
		return "/volume.dmg";
#else
		return "/volume";
#endif
	}

	uint64 FuseService::GetVolumeSize ()
	{
		if (!MountedVolume)
			throw NotInitialized (SRC_POS);

		return MountedVolume->GetSize();
	}

	void FuseService::Mount (shared_ptr <Volume> openVolume, VolumeSlotNumber slotNumber, const string &fuseMountPoint)
	{
		list <string> args;
		args.push_back (FuseService::GetDeviceType());
		args.push_back (fuseMountPoint);

#ifdef TC_MACOSX
		args.push_back ("-o");
		args.push_back ("noping_diskarb");
		args.push_back ("-o");
		args.push_back ("nobrowse");

		if (getuid() == 0 || geteuid() == 0)
#endif
		{
			args.push_back ("-o");
			args.push_back ("allow_other");
		}

		ExecFunctor execFunctor (openVolume, slotNumber);
		Process::Execute ("fuse", args, -1, &execFunctor);

		for (int t = 0; true; t++)
		{
			try
			{
				if (FilesystemPath (fuseMountPoint + FuseService::GetControlPath()).GetType() == FilesystemPathType::File)
					break;
			}
			catch (...)
			{
				if (t > 50)
					throw;

				Thread::Sleep (100);
			}
		}
	}

	void FuseService::ReadVolumeSectors (const BufferPtr &buffer, uint64 byteOffset)
	{
		if (!MountedVolume)
			throw NotInitialized (SRC_POS);

		MountedVolume->ReadSectors (buffer, byteOffset);
	}

	void FuseService::ReceiveAuxDeviceInfo (const ConstBufferPtr &buffer)
	{
		shared_ptr <Stream> stream (new MemoryStream (buffer));
		Serializer sr (stream);

		ScopeLock lock (OpenVolumeInfoMutex);
		OpenVolumeInfo.VirtualDevice = sr.DeserializeString ("VirtualDevice");
		OpenVolumeInfo.LoopDevice = sr.DeserializeString ("LoopDevice");
	}

	void FuseService::SendAuxDeviceInfo (const DirectoryPath &fuseMountPoint, const DevicePath &virtualDevice, const DevicePath &loopDevice)
	{
		File fuseServiceControl;
		fuseServiceControl.Open (string (fuseMountPoint) + GetControlPath(), File::OpenWrite);

		shared_ptr <Stream> stream (new MemoryStream);
		Serializer sr (stream);

		sr.Serialize ("VirtualDevice", string (virtualDevice));
		sr.Serialize ("LoopDevice", string (loopDevice));
		fuseServiceControl.Write (dynamic_cast <MemoryStream&> (*stream));
	}

	void FuseService::WriteVolumeSectors (const ConstBufferPtr &buffer, uint64 byteOffset)
	{
		if (!MountedVolume)
			throw NotInitialized (SRC_POS);

		MountedVolume->WriteSectors (buffer, byteOffset);
	}

	void FuseService::OnSignal (int signal)
	{
		try
		{
			shared_ptr <VolumeInfo> volume = Core->GetMountedVolume (SlotNumber);

			if (volume)
				Core->DismountVolume (volume, true);
		}
		catch (...) { }

		_exit (0);
	}

	void FuseService::ExecFunctor::operator() (int argc, char *argv[])
	{
		struct timeval tv;
		gettimeofday (&tv, NULL);
		FuseService::OpenVolumeInfo.SerialInstanceNumber = (uint64)tv.tv_sec * 1000000ULL + tv.tv_usec;

		FuseService::MountedVolume = MountedVolume;
		FuseService::SlotNumber = SlotNumber;

		FuseService::UserId = getuid();
		FuseService::GroupId = getgid();

		if (getenv ("SUDO_UID"))
		{
			try
			{
				string s (getenv ("SUDO_UID"));
				FuseService::UserId = static_cast <uid_t.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 */
/*
 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.
*/


/* In this file, _WIN32_WINNT is defined as 0x0600 to make filesystem shrink available (Vista
or later). _WIN32_WINNT cannot be defined as 0x0600 for the entire user-space projects
because it breaks the main font app when the app is running on XP (likely an MS bug).
IMPORTANT: Due to this issue, functions in this file must not directly interact with GUI. */
#define TC_LOCAL_WIN32_WINNT_OVERRIDE	 1
#if (_WIN32_WINNT < 0x0600)
#	undef _WIN32_WINNT
#	define _WIN32_WINNT 0x0600
#endif


#include <stdlib.h>
#include <string.h>
#include <string>
#include <intsafe.h>

#include "Tcdefs.h"
#include "Platform/Finally.h"

#include "Common.h"
#include "Crc.h"
#include "Dlgcode.h"
#include "Language.h"
#include "Tcformat.h"
#include "Volumes.h"

#include "InPlace.h"

#include <Strsafe.h>

using namespace std;
using namespace VeraCrypt;

#if TC_VOLUME_DATA_OFFSET != 131072
#	error TC_VOLUME_DATA_OFFSET != 131072
#endif

#if TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512
#	error TC_VOLUME_HEADER_EFFECTIVE_SIZE != 512
#endif

#if TC_TOTAL_VOLUME_HEADERS_SIZE != 262144
#	error TC_TOTAL_VOLUME_HEADERS_SIZE != 262144
#endif

#define TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE	(2048 * BYTES_PER_KB)
#define TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE		(2 * TC_MAX_VOLUME_SECTOR_SIZE)
#define TC_NTFS_CONCEAL_CONSTANT	0xFF
#define TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL	(64 * BYTES_PER_MB)
#define TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE			(TC_TOTAL_VOLUME_HEADERS_SIZE + TC_MIN_NTFS_FS_SIZE * 2)


// If the returned value is greater than 0, it is the desired volume size in NTFS sectors (not in bytes)
// after shrinking has been performed. If there's any error, returns -1.
static __int64 NewFileSysSizeAfterShrink (HANDLE dev, const wchar_t *devicePath, int64 *totalClusterCount, DWORD *bytesPerCluster, BOOL silent)
{
	NTFS_VOLUME_DATA_BUFFER ntfsVolData;
	DWORD nBytesReturned;
	__int64 fileSysSize, desiredNbrSectors;

	// Filesystem size and sector size

	if (!DeviceIoControl (dev,
		FSCTL_GET_NTFS_VOLUME_DATA,
		NULL,
		0,
		(LPVOID) &ntfsVolData,
		sizeof (ntfsVolData),
		&nBytesReturned,
		NULL))
	{
		if (!silent)
			handleWin32Error (MainDlg, SRC_POS);

		return -1;
	}

	if (	(ntfsVolData.NumberSectors.QuadPart <= 0)
		||	(ntfsVolData.NumberSectors.QuadPart > (INT64_MAX / (__int64) ntfsVolData.BytesPerSector)) // overflow test
		)
	{
		SetLastError (ERROR_INTERNAL_ERROR);
		if (!silent)
			handleWin32Error (MainDlg, SRC_POS);

		return -1;
	}

	fileSysSize = ntfsVolData.NumberSectors.QuadPart * ntfsVolData.BytesPerSector;

	desiredNbrSectors = (fileSysSize - TC_TOTAL_VOLUME_HEADERS_SIZE) / ntfsVolData.BytesPerSector;

	if (desiredNbrSectors <= 0)
		return -1;

	if (totalClusterCount)
		*totalClusterCount = ntfsVolData.TotalClusters.QuadPart;
	if (bytesPerCluster)
		*bytesPerCluster = ntfsVolData.BytesPerCluster;

	return desiredNbrSectors;
}


BOOL CheckRequirementsForNonSysInPlaceEnc (HWND hwndDlg, const wchar_t *devicePath, BOOL silent)
{
	NTFS_VOLUME_DATA_BUFFER ntfsVolData;
	DWORD nBytesReturned;
	HANDLE dev;
	WCHAR szFileSysName [256];
	WCHAR devPath [MAX_PATH];
	WCHAR dosDev [TC_MAX_PATH] = {0};
	WCHAR devName [MAX_PATH] = {0};
	int driveLetterNo = -1;
	WCHAR szRootPath[4] = {0, L':', L'\\', 0};
	__int64 deviceSize;
	int partitionNumber = -1, driveNumber = -1;


	/* ---------- Checks that do not require admin rights ----------- */


	/* Operating system */

	if (CurrentOSMajor < 6)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "OS_NOT_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);

		return FALSE;
	}


	/* Volume type (must be a partition or a dynamic volume) */

	if (swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1
		&& swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
	{
		if (!silent)
			Error ("INPLACE_ENC_INVALID_PATH", hwndDlg);

		return FALSE;
	}

	if (partitionNumber == 0)
	{
		if (!silent)
			Warning ("RAW_DEV_NOT_SUPPORTED_FOR_INPLACE_ENC", hwndDlg);

		return FALSE;
	}


	/* Admin rights */

	if (!IsAdmin())
	{
		// We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
		// status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.

		if (!silent)
			Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg);
	}


	/* ---------- Checks that may require admin rights ----------- */


	/* Access to the partition */

	StringCbCopyW (devPath, sizeof(devPath), devicePath);

	driveLetterNo = GetDiskDeviceDriveLetter (devPath);

	if (driveLetterNo >= 0)
		szRootPath[0] = (wchar_t) driveLetterNo + L'A';

	if (FakeDosNameForDevice (devicePath, dosDev, sizeof(dosDev), devName, sizeof(devName),FALSE) != 0)
	{
		if (!silent)
		{
			handleWin32Error (hwndDlg, SRC_POS);
			Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
		}
		return FALSE;
	}

	dev = OpenPartitionVolume (hwndDlg, devName,
		FALSE,	// Do not require exclusive access
		TRUE,	// Require shared access (must be TRUE; otherwise, volume properties will not be possible to obtain)
		FALSE,	// Do not ask the user to confirm shared access (if exclusive fails)
		FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
		silent);	// Silent mode

	if (dev == INVALID_HANDLE_VALUE)
		return FALSE;


	/* File system type */

	GetVolumeInformation (szRootPath, NULL, 0, NULL, NULL, NULL, szFileSysName, ARRAYSIZE (szFileSysName));

	if (wcsncmp (szFileSysName, L"NTFS", 4))
	{
		// The previous filesystem type detection method failed (or it's not NTFS) -- try an alternative method

		if (!DeviceIoControl (dev,
			FSCTL_GET_NTFS_VOLUME_DATA,
			NULL,
			0,
			(LPVOID) &ntfsVolData,
			sizeof (ntfsVolData),
			&nBytesReturned,
			NULL))
		{
			if (!silent)
			{
				// The filesystem is not NTFS or the filesystem type could not be determined (or the NTFS filesystem
				// is dismounted).

				if (IsDeviceMounted (devName))
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "ONLY_NTFS_SUPPORTED_FOR_NONSYS_INPLACE_ENC", FALSE);
				else
					Warning ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg);
			}

			CloseHandle (dev);
			return FALSE;
		}
	}


	/* Attempt to determine whether the filesystem can be safely shrunk */

	if (NewFileSysSizeAfterShrink (dev, devicePath, NULL, NULL, silent) == -1)
	{
		// Cannot determine whether shrinking is required
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	/* Partition size */

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		if (!silent)
			Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);

		CloseHandle (dev);
		return FALSE;
	}

	if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
	{
		// The partition is too small
		if (!silent)
		{
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", FALSE);
		}

		CloseHandle (dev);
		return FALSE;
	}


	/* Free space on the filesystem */

	if (!DeviceIoControl (dev,
		FSCTL_GET_NTFS_VOLUME_DATA,
		NULL,
		0,
		(LPVOID) &ntfsVolData,
		sizeof (ntfsVolData),
		&nBytesReturned,
		NULL))
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", TRUE);

		CloseHandle (dev);
		return FALSE;
	}

	if (ntfsVolData.FreeClusters.QuadPart * ntfsVolData.BytesPerCluster < TC_TOTAL_VOLUME_HEADERS_SIZE)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "NOT_ENOUGH_FREE_FILESYS_SPACE_FOR_SHRINK", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	/* Filesystem sector size */

	if (ntfsVolData.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE
		|| ntfsVolData.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0)
	{
		if (!silent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "SECTOR_SIZE_UNSUPPORTED", TRUE);

		CloseHandle (dev);
		return FALSE;
	}


	CloseHandle (dev);
	return TRUE;
}

BOOL CheckRequirementsForNonSysInPlaceDec (HWND hwndDlg, const wchar_t *devicePath, BOOL silent)
{
	int partitionNumber = -1, driveNumber = -1;

	/* ---------- Checks that do not require admin rights ----------- */

	/* Volume type (must be a partition or a dynamic volume) */
	if ((swscanf (devicePath, L"\\Device\\HarddiskVolume%d", &partitionNumber) != 1
		&& swscanf (devicePath, L"\\Device\\Harddisk%d\\Partition%d", &driveNumber, &partitionNumber) != 2)
		|| partitionNumber == 0)
	{
		if (!silent)
			Error ("INPLACE_ENC_INVALID_PATH", hwndDlg);

		return FALSE;
	}


	/* Admin rights */
	if (!IsAdmin())
	{
		// We rely on the wizard process to call us only when the whole wizard process has been elevated (so UAC
		// status can be ignored). In case the IsAdmin() detection somehow fails, we allow the user to continue.

		if (!silent)
			Warning ("ADMIN_PRIVILEGES_WARN_DEVICES", hwndDlg);
	}


	/* ---------- Checks that may require admin rights ----------- */

	// [Currently none]

	return TRUE;
}


int EncryptPartitionInPlaceBegin (volatile FORMAT_VOL_PARAMETERS *volParams, volatile HANDLE *outHandle, WipeAlgorithmId wipeAlgorithm)
{
	SHRINK_VOLUME_INFORMATION shrinkVolInfo;
	signed __int64 sizeToShrinkTo;
	int nStatus = ERR_SUCCESS;
	PCRYPTO_INFO cryptoInfo = NULL;
	PCRYPTO_INFO cryptoInfo2 = NULL;
	HANDLE dev = INVALID_HANDLE_VALUE;
	DWORD dwError;
	char *header;
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	int driveLetter = -1;
	WCHAR deviceName[MAX_PATH];
	uint64 dataAreaSize;
	__int64 deviceSize;
	LARGE_INTEGER offset;
	DWORD dwResult;
	HWND hwndDlg = volParams->hwndDlg;

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);


	if (!CheckRequirementsForNonSysInPlaceEnc (hwndDlg, volParams->volumePath, FALSE))
		return ERR_DONT_REPORT;


	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	deviceSize = GetDeviceSize (volParams->volumePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_PARAMETER_INCORRECT;
		goto closing_seq;
	}

	if (deviceSize < TC_NONSYS_INPLACE_ENC_MIN_VOL_SIZE)
	{
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "PARTITION_TOO_SMALL_FOR_NONSYS_INPLACE_ENC", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	dataAreaSize = GetVolumeDataAreaSize (volParams->hiddenVol, deviceSize);

	StringCchCopyW (deviceName, ARRAYSIZE(deviceName), volParams->volumePath);

	driveLetter = GetDiskDeviceDriveLetter (deviceName);


	if (FakeDosNameForDevice (volParams->volumePath, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (IsDeviceMounted (devName))
	{
		dev = OpenPartitionVolume (hwndDlg, devName,
			FALSE,	// Do not require exclusive access (must be FALSE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
			TRUE,	// Require shared access (must be TRUE; otherwise, it will not be possible to dismount the volume or obtain its properties and FSCTL_ALLOW_EXTENDED_DASD_IO will fail too)
			FALSE,	// Do not ask the user to confirm shared access (if exclusive fails)
			FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
			FALSE);	// Non-silent mode

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}
	}
	else
	{
		// The volume is not mounted so we can't work with the filesystem.
		Error ("ONLY_MOUNTED_VOL_SUPPORTED_FOR_NONSYS_INPLACE_ENC", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}


	/* Gain "raw" access to the partition (the NTFS driver guards hidden sectors). */

	if (!DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL))
	{
		handleWin32Error (MainDlg, SRC_POS);
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	/* Shrink the filesystem */

	int64 totalClusterCount;
	DWORD bytesPerCluster;

	sizeToShrinkTo = NewFileSysSizeAfterShrink (dev, volParams->volumePath, &totalClusterCount, &bytesPerCluster, FALSE);

	if (sizeToShrinkTo == -1)
	{
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_RESIZING);

	memset (&shrinkVolInfo, 0, sizeof (shrinkVolInfo));

	shrinkVolInfo.ShrinkRequestType = ShrinkPrepare;
	shrinkVolInfo.NewNumberOfSectors = sizeToShrinkTo;

	if (!DeviceIoControl (dev,
		FSCTL_SHRINK_VOLUME,
		(LPVOID) &shrinkVolInfo,
		sizeof (shrinkVolInfo),
		NULL,
		0,
		&dwResult,
		NULL))
	{
		handleWin32Error (hwndDlg, SRC_POS);
		ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	BOOL clustersMovedBeforeVolumeEnd = FALSE;

	while (true)
	{
		shrinkVolInfo.ShrinkRequestType = ShrinkCommit;
		shrinkVolInfo.NewNumberOfSectors = 0;

		if (!DeviceIoControl (dev, FSCTL_SHRINK_VOLUME, &shrinkVolInfo, sizeof (shrinkVolInfo), NULL, 0, &dwResult, NULL))
		{
			// If there are any occupied clusters beyond the new desired end of the volume, the call fails with
			// ERROR_ACCESS_DENIED (STATUS_ALREADY_COMMITTED).
			if (GetLastError () == ERROR_ACCESS_DENIED)
			{
				if (!clustersMovedBeforeVolumeEnd)
				{
					if (MoveClustersBeforeThreshold (dev, deviceName, totalClusterCount - (bytesPerCluster > TC_TOTAL_VOLUME_HEADERS_SIZE ? 1 : TC_TOTAL_VOLUME_HEADERS_SIZE / bytesPerCluster)))
					{
						clustersMovedBeforeVolumeEnd = TRUE;
						continue;
					}

					handleWin32Error (hwndDlg, SRC_POS);
				}
			}
			else
				handleWin32Error (hwndDlg, SRC_POS);

			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "CANNOT_RESIZE_FILESYS", TRUE);
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}

		break;
	}

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PREPARING);


	/* Gain exclusive access to the volume */

	nStatus = DismountFileSystem (hwndDlg, dev,
		driveLetter,
		TRUE,
		TRUE,
		FALSE);

	if (nStatus != ERR_SUCCESS)
	{
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	/* Create header backup on the partition. Until the volume is fully encrypted, the backup header will provide
	us with the master key, encrypted range, and other data for pause/resume operations. We cannot create the
	primary header until the entire partition is encrypted (because we encrypt backwards and the primary header
	area is occuppied by data until the very end of the process). */

	// Prepare the backup header
	for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++)
	{
		PCRYPTO_INFO dummyInfo = NULL;

		nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
			header,
			volParams->ea,
			FIRST_MODE_OF_OPERATION_ID,
			volParams->password,
			volParams->pkcs5,
			volParams->pim,
			wipePass == 0 ? NULL : (char *) cryptoInfo->master_keydata,
			&cryptoInfo,
			dataAreaSize,
			0,
			TC_VOLUME_DATA_OFFSET + dataAreaSize,	// Start of the encrypted area = the first byte of the backup heeader (encrypting from the end)
			0,	// No data is encrypted yet
			0,
			volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
			volParams->sectorSize,
			wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

		if (nStatus != 0)
			goto closing_seq;

		offset.QuadPart = TC_VOLUME_DATA_OFFSET + dataAreaSize;

		if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Write the backup header to the partition
		if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Fill the reserved sectors of the backup header area with random data
		nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, cryptoInfo, dataAreaSize, FALSE, TRUE);

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;

		// write fake hidden volume header to protect against attacks that use statistical entropy
		// analysis to detect presence of hidden volumes
		nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
			header,
			volParams->ea,
			FIRST_MODE_OF_OPERATION_ID,
			NULL,
			0,
			0,
			NULL,
			&dummyInfo,
			dataAreaSize,
			dataAreaSize,
			TC_VOLUME_DATA_OFFSET + dataAreaSize,	// Start of the encrypted area = the first byte of the backup heeader (encrypting from the end)
			dataAreaSize,	// No data is encrypted yet
			0,
			volParams->headerFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
			volParams->sectorSize,
			wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;

		crypto_close (dummyInfo);

		offset.QuadPart += TC_HIDDEN_VOLUME_HEADER_OFFSET;

		if (!SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		// Write the fake hidden backup header to the partition
		if (!WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

	}


	/* Now we will try to decrypt the backup header to verify it has been correctly written. */

	nStatus = OpenBackupHeader (dev, volParams->volumePath, volParams->password, volParams->pkcs5, volParams->pim, &cryptoInfo2, NULL, deviceSize);

	if (nStatus != ERR_SUCCESS
		|| cryptoInfo->EncryptedAreaStart.Value != cryptoInfo2->EncryptedAreaStart.Value
		|| cryptoInfo2->EncryptedAreaStart.Value == 0)
	{
		if (nStatus == ERR_SUCCESS)
			nStatus = ERR_PARAMETER_INCORRECT;

		goto closing_seq;
	}

	// The backup header is valid so we know we should be able to safely resume in-place encryption
	// of this partition even if the system/app crashes.



	/* Conceal the NTFS filesystem (by performing an easy-to-undo modification). This will prevent Windows
	and apps from interfering with the volume until it has been fully encrypted. */

	nStatus = ConcealNTFS (dev);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;



	// /* If a drive letter is assigned to the device, remove it (so that users do not try to open it, which
	//would cause Windows to ask them if they want to format the volume and other dangerous things). */

	//if (driveLetter >= 0)
	//{
	//	char rootPath[] = { driveLetter + 'A', ':', '\\', 0 };

	//	// Try to remove the assigned drive letter
	//	if (DeleteVolumeMountPoint (rootPath))
	//		driveLetter = -1;
	//}



	/* Update config files and app data */

	// In the config file, increase the number of partitions where in-place encryption is in progress

	SaveNonSysInPlaceEncSettings (1, wipeAlgorithm, FALSE);


	// Add the wizard to the system startup sequence if appropriate

	if (!IsNonInstallMode ())
		ManageStartupSeqWiz (FALSE, L"/prinplace");


	nStatus = ERR_SUCCESS;


closing_seq:

	dwError = GetLastError();

	if (cryptoInfo != NULL)
	{
		crypto_close (cryptoInfo);
		cryptoInfo = NULL;
	}

	if (cryptoInfo2 != NULL)
	{
		crypto_close (cryptoInfo2);
		cryptoInfo2 = NULL;
	}

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	if (dosDev[0])
		RemoveFakeDosName (volParams->volumePath, dosDev);

	*outHandle = dev;

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


int EncryptPartitionInPlaceResume (HANDLE dev,
								   volatile FORMAT_VOL_PARAMETERS *volParams,
								   WipeAlgorithmId wipeAlgorithm,
								   volatile BOOL *bTryToCorrectReadErrors)
{
	PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL, tmpCryptoInfo = NULL;
	UINT64_STRUCT unitNo;
	char *buf = NULL, *header = NULL;
	byte *wipeBuffer = NULL;
	byte wipeRandChars [TC_WIPE_RAND_CHAR_COUNT];
	byte wipeRandCharsUpdate [TC_WIPE_RAND_CHAR_COUNT];
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	WCHAR deviceName[MAX_PATH];
	int nStatus = ERR_SUCCESS;
	__int64 deviceSize;
	uint64 remainingBytes, lastHeaderUpdateDistance = 0, zeroedSectorCount = 0;
	uint32 workChunkSize;
	DWORD dwError, dwResult;
	BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE;
	LARGE_INTEGER offset;
	int sectorSize;
	int i;
	DWORD n;
	WCHAR *devicePath = volParams->volumePath;
	Password *password = volParams->password;
	int pkcs5_prf = volParams->pkcs5;
	int pim = volParams->pim;
	DISK_GEOMETRY driveGeometry;
	HWND hwndDlg = volParams->hwndDlg;


	bInPlaceEncNonSysResumed = TRUE;

	buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
	if (!buf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	if (wipeAlgorithm != TC_WIPE_NONE)
	{
		wipeBuffer = (byte *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
		if (!wipeBuffer)
		{
			nStatus = ERR_OUTOFMEMORY;
			goto closing_seq;
		}
	}

	headerCryptoInfo = crypto_open();

	if (headerCryptoInfo == NULL)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (dev == INVALID_HANDLE_VALUE)
	{
		StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath);

		if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev),devName, sizeof(devName),FALSE) != 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		dev = OpenPartitionVolume (hwndDlg, devName,
			FALSE,	// Do not require exclusive access
			FALSE,	// Do not require shared access
			TRUE,	// Ask the user to confirm shared access (if exclusive fails)
			FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
			FALSE);	// Non-silent mode

		if (dev == INVALID_HANDLE_VALUE)
		{
			nStatus = ERR_DONT_REPORT;
			goto closing_seq;
		}
	}

	// This should never be needed, but is still performed for extra safety (without checking the result)
	DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL);


	if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	sectorSize = driveGeometry.BytesPerSector;


	nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;



    remainingBytes = masterCryptoInfo->VolumeSize.Value - masterCryptoInfo->EncryptedAreaLength.Value;

	lastHeaderUpdateDistance = 0;


	ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_ENCRYPTING);

	bFirstNonSysInPlaceEncResumeDone = TRUE;


	/* The in-place encryption core */

	while (remainingBytes > 0)
	{
		workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);

		if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			nStatus = ERR_PARAMETER_INCORRECT;
			goto closing_seq;
		}

		unitNo.Value = (remainingBytes - workChunkSize + TC_VOLUME_DATA_OFFSET) / ENCRYPTION_DATA_UNIT_SIZE;


		// Read the plaintext into RAM

inplace_enc_read:

		offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Read error

			DWORD dwTmpErr = GetLastError ();

			if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel)
			{
				// Physical defect or data corruption

				if (!*bTryToCorrectReadErrors)
				{
					*bTryToCorrectReadErrors = (AskWarnYesNo ("ENABLE_BAD_SECTOR_ZEROING", hwndDlg) == IDYES);
				}

				if (*bTryToCorrectReadErrors)
				{
					// Try to correct the read errors physically

					offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize - TC_VOLUME_DATA_OFFSET;

					nStatus = ZeroUnreadableSectors (dev, offset, workChunkSize, sectorSize, &zeroedSectorCount);

					if (nStatus != ERR_SUCCESS)
					{
						// Due to write errors, we can't correct the read errors
						nStatus = ERR_OS_ERROR;
						goto closing_seq;
					}

					goto inplace_enc_read;
				}
			}

			SetLastError (dwTmpErr);		// Preserve the original error code

			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (remainingBytes - workChunkSize < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE)
		{
			// We reached the inital portion of the filesystem, which we had concealed (in order to prevent
			// Windows from interfering with the volume). Now we need to undo that modification.

			for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE - (remainingBytes - workChunkSize); i++)
				buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
		}


		// Encrypt the plaintext in RAM

		EncryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);


		// If enabled, wipe the area to which we will write the ciphertext

		if (wipeAlgorithm != TC_WIPE_NONE)
		{
			byte wipePass;
			int wipePassCount = GetWipePassCount (wipeAlgorithm);

			if (wipePassCount <= 0)
			{
				SetLastError (ERROR_INVALID_PARAMETER);
				nStatus = ERR_PARAMETER_INCORRECT;
				goto closing_seq;
			}

			offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;

			for (wipePass = 1; wipePass <= wipePassCount; ++wipePass)
			{
				if (!WipeBuffer (wipeAlgorithm, wipeRandChars, wipePass, wipeBuffer, workChunkSize))
				{
					ULONG i;
					for (i = 0; i < workChunkSize; ++i)
					{
						wipeBuffer[i] = buf[i] + wipePass;
					}

					EncryptDataUnits (wipeBuffer, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
					memcpy (wipeRandCharsUpdate, wipeBuffer, sizeof (wipeRandCharsUpdate));
				}

				if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
					|| WriteFile (dev, wipeBuffer, workChunkSize, &n, NULL) == 0)
				{
					// Write error
					dwError = GetLastError();

					// Undo failed write operation
					if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
					{
						DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
						WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
					}

					SetLastError (dwError);
					nStatus = ERR_OS_ERROR;
					goto closing_seq;
				}
			}

			memcpy (wipeRandChars, wipeRandCharsUpdate, sizeof (wipeRandCharsUpdate));
		}


		// Write the ciphertext

		offset.QuadPart = masterCryptoInfo->EncryptedAreaStart.Value - workChunkSize;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Write error
			dwError = GetLastError();

			// Undo failed write operation
			if (workChunkSize > TC_VOLUME_DATA_OFFSET && SetFilePointerEx (dev, offset, NULL, FILE_BEGIN))
			{
				DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);
				WriteFile (dev, buf + TC_VOLUME_DATA_OFFSET, workChunkSize - TC_VOLUME_DATA_OFFSET, &n, NULL);
			}

			SetLastError (dwError);
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}


		masterCryptoInfo->EncryptedAreaStart.Value -= workChunkSize;
		masterCryptoInfo->EncryptedAreaLength.Value += workChunkSize;

		remainingBytes -= workChunkSize;
		lastHeaderUpdateDistance += workChunkSize;

		bEncryptedAreaSizeChanged = TRUE;

		if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL)
		{
			nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			lastHeaderUpdateDistance = 0;
		}

		ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

		if (bVolTransformThreadCancel)
		{
			bPause = TRUE;
			break;
		}
	}

	nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);


	if (nStatus != ERR_SUCCESS)
		goto closing_seq;


	if (!bPause)
	{
		/* The data area has been fully encrypted; create and write the primary volume header */

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING);

		for (int wipePass = 0; wipePass < (wipeAlgorithm == TC_WIPE_NONE ? 1 : PRAND_HEADER_WIPE_PASSES); wipePass++)
		{
			PCRYPTO_INFO dummyInfo = NULL;

			nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				header,
				headerCryptoInfo->ea,
				headerCryptoInfo->mode,
				password,
				masterCryptoInfo->pkcs5,
				pim,
				(char *) masterCryptoInfo->master_keydata,
				&tmpCryptoInfo,
				masterCryptoInfo->VolumeSize.Value,
				0,
				masterCryptoInfo->EncryptedAreaStart.Value,
				masterCryptoInfo->EncryptedAreaLength.Value,
				masterCryptoInfo->RequiredProgramVersion,
				masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
				masterCryptoInfo->SectorSize,
				wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;


			offset.QuadPart = TC_VOLUME_HEADER_OFFSET;

			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
				|| !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

			// Fill the reserved sectors of the header area with random data
			nStatus = WriteRandomDataToReservedHeaderAreas (hwndDlg, dev, headerCryptoInfo, masterCryptoInfo->VolumeSize.Value, TRUE, FALSE);

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			// write fake hidden volume header to protect against attacks that use statistical entropy
			// analysis to detect presence of hidden volumes
			nStatus = CreateVolumeHeaderInMemory (hwndDlg, FALSE,
				header,
				headerCryptoInfo->ea,
				headerCryptoInfo->mode,
				NULL,
				0,
				0,
				NULL,
				&dummyInfo,
				masterCryptoInfo->VolumeSize.Value,
				masterCryptoInfo->VolumeSize.Value,
				masterCryptoInfo->EncryptedAreaStart.Value,
				masterCryptoInfo->EncryptedAreaLength.Value,
				masterCryptoInfo->RequiredProgramVersion,
				masterCryptoInfo->HeaderFlags | TC_HEADER_FLAG_NONSYS_INPLACE_ENC,
				masterCryptoInfo->SectorSize,
				wipeAlgorithm == TC_WIPE_NONE ? FALSE : (wipePass < PRAND_HEADER_WIPE_PASSES - 1));

			if (nStatus != ERR_SUCCESS)
				goto closing_seq;

			crypto_close (dummyInfo);

			offset.QuadPart += TC_HIDDEN_VOLUME_HEADER_OFFSET;

			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
				|| !WriteEffectiveVolumeHeader (TRUE, dev, (byte *) header))
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}

		// Update the configuration files

		SaveNonSysInPlaceEncSettings (-1, wipeAlgorithm, FALSE);



		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED);

		nStatus = ERR_SUCCESS;
	}
	else
	{
		// The process has been paused by the user or aborted by the wizard (e.g. on app exit)

		nStatus = ERR_USER_ABORT;

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
	}


closing_seq:

	dwError = GetLastError();

	if (bEncryptedAreaSizeChanged
		&& dev != INVALID_HANDLE_VALUE
		&& masterCryptoInfo != NULL
		&& headerCryptoInfo != NULL
		&& deviceSize > 0)
	{
		// Execution of the core loop may have been interrupted due to an error or user action without updating the header
		FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
	}

	if (masterCryptoInfo != NULL)
	{
		crypto_close (masterCryptoInfo);
		masterCryptoInfo = NULL;
	}

	if (headerCryptoInfo != NULL)
	{
		crypto_close (headerCryptoInfo);
		headerCryptoInfo = NULL;
	}

	if (tmpCryptoInfo != NULL)
	{
		crypto_close (tmpCryptoInfo);
		tmpCryptoInfo = NULL;
	}

	if (dosDev[0])
		RemoveFakeDosName (devicePath, dosDev);

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (buf != NULL)
		TCfree (buf);

	if (header != NULL)
	{
		burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
		VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
		TCfree (header);
	}

	if (wipeBuffer != NULL)
		TCfree (wipeBuffer);

	if (zeroedSectorCount > 0)
	{
		wchar_t msg[30000] = {0};
		wchar_t sizeStr[500] = {0};

		GetSizeString (zeroedSectorCount * sectorSize, sizeStr, sizeof(sizeStr));

		StringCbPrintfW (msg, sizeof(msg),
			GetString ("ZEROED_BAD_SECTOR_COUNT"),
			zeroedSectorCount,
			sizeStr);

		WarningDirect (msg, hwndDlg);
	}

	if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
		SetLastError (dwError);

	return nStatus;
}

int DecryptPartitionInPlace (volatile FORMAT_VOL_PARAMETERS *volParams, volatile BOOL *DiscardUnreadableEncryptedSectors)
{
	HANDLE dev = INVALID_HANDLE_VALUE;
	PCRYPTO_INFO masterCryptoInfo = NULL, headerCryptoInfo = NULL;
	UINT64_STRUCT unitNo;
	char *buf = NULL;
	byte *tmpSectorBuf = NULL;
	WCHAR dosDev[TC_MAX_PATH] = {0};
	WCHAR devName[MAX_PATH] = {0};
	WCHAR deviceName[MAX_PATH];
	int nStatus = ERR_SUCCESS;
	__int64 deviceSize;
	uint64 remainingBytes, workChunkStartByteOffset, lastHeaderUpdateDistance = 0, skippedBadSectorCount = 0;
	uint32 workChunkSize;
	DWORD dwError, dwResult;
	BOOL bPause = FALSE, bEncryptedAreaSizeChanged = FALSE;
	LARGE_INTEGER offset;
	int sectorSize;
	int i;
	DWORD n;
	WCHAR *devicePath = volParams->volumePath;
	Password *password = volParams->password;
	HWND hwndDlg = volParams->hwndDlg;
	int pkcs5_prf = volParams->pkcs5;
	int pim = volParams->pim;
	DISK_GEOMETRY driveGeometry;


	buf = (char *) TCalloc (TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);
	if (!buf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	headerCryptoInfo = crypto_open();

	if (headerCryptoInfo == NULL)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}

	deviceSize = GetDeviceSize (devicePath);
	if (deviceSize < 0)
	{
		// Cannot determine the size of the partition
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	// The wizard should have dismounted the TC volume if it was mounted, but for extra safety we will check this again.
	if (IsMountedVolume (devicePath))
	{
		int driveLetter = GetMountedVolumeDriveNo (devicePath);

		if (driveLetter == -1
			|| !UnmountVolume (hwndDlg, driveLetter, TRUE))
		{
			handleWin32Error (hwndDlg, SRC_POS);
			AbortProcess ("CANT_DISMOUNT_VOLUME");
		}
	}


	StringCchCopyW (deviceName, ARRAYSIZE(deviceName), devicePath);

	if (FakeDosNameForDevice (deviceName, dosDev, sizeof(dosDev), devName, sizeof(devName), FALSE) != 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	dev = OpenPartitionVolume (hwndDlg, devName,
		TRUE,	// Require exclusive access
		FALSE,	// Do not require shared access
		TRUE,	// Ask the user to confirm shared access (if exclusive fails)
		FALSE,	// Do not append alternative instructions how to encrypt the data (to applicable error messages)
		FALSE);	// Non-silent mode

	if (dev == INVALID_HANDLE_VALUE)
	{
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}



	// This should never be needed, but is still performed for extra safety (without checking the result)
	DeviceIoControl (dev,
		FSCTL_ALLOW_EXTENDED_DASD_IO,
		NULL,
		0,
		NULL,
		0,
		&dwResult,
		NULL);


	if (!DeviceIoControl (dev, IOCTL_DISK_GET_DRIVE_GEOMETRY, NULL, 0, &driveGeometry, sizeof (driveGeometry), &dwResult, NULL))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}

	if (	(driveGeometry.BytesPerSector == 0)
		||	(driveGeometry.BytesPerSector > TC_MAX_VOLUME_SECTOR_SIZE)
		|| (driveGeometry.BytesPerSector % ENCRYPTION_DATA_UNIT_SIZE != 0)
		)
	{
		Error ("SECTOR_SIZE_UNSUPPORTED", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	sectorSize = driveGeometry.BytesPerSector;


	tmpSectorBuf = (byte *) TCalloc (sectorSize);
	if (!tmpSectorBuf)
	{
		nStatus = ERR_OUTOFMEMORY;
		goto closing_seq;
	}


	nStatus = OpenBackupHeader (dev, devicePath, password, pkcs5_prf, pim, &masterCryptoInfo, headerCryptoInfo, deviceSize);

	if (nStatus != ERR_SUCCESS)
		goto closing_seq;


	if (masterCryptoInfo->LegacyVolume)
	{
		Error ("NONSYS_INPLACE_DECRYPTION_BAD_VOL_FORMAT", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	if (masterCryptoInfo->hiddenVolume)
	{
		Error ("NONSYS_INPLACE_DECRYPTION_CANT_DECRYPT_HID_VOL", hwndDlg);
		nStatus = ERR_DONT_REPORT;
		goto closing_seq;
	}

	if (!bInPlaceEncNonSysResumed
		&& masterCryptoInfo->VolumeSize.Value == masterCryptoInfo->EncryptedAreaLength.Value)
	{
		/* Decryption started (not resumed) */

		if ((masterCryptoInfo->HeaderFlags & TC_HEADER_FLAG_NONSYS_INPLACE_ENC) == 0)
		{
			// The volume has not been encrypted in-place so it may contain a hidden volume.
			// Ask the user to confirm it does not.

			char *tmpStr[] = {0,
				"CONFIRM_VOL_CONTAINS_NO_HIDDEN_VOL",
				"VOL_CONTAINS_NO_HIDDEN_VOL",
				"VOL_CONTAINS_A_HIDDEN_VOL",
				0};

			switch (AskMultiChoice ((void **) tmpStr, FALSE, hwndDlg))
			{
			case 1:
				// NOP
				break;
			case 2:
			default:
				// Cancel
				nStatus = ERR_DONT_REPORT;
				goto closing_seq;
			}
		}

		// Update config files and app data

		// In the config file, increase the number of partitions where in-place decryption is in progress
		SaveNonSysInPlaceEncSettings (1, TC_WIPE_NONE, TRUE);

		// Add the wizard to the system startup sequence if appropriate
		if (!IsNonInstallMode ())
			ManageStartupSeqWiz (FALSE, L"/prinplace");
	}



	bInPlaceEncNonSysResumed = TRUE;
	bFirstNonSysInPlaceEncResumeDone = TRUE;


	remainingBytes = masterCryptoInfo->EncryptedAreaLength.Value;

	lastHeaderUpdateDistance = 0;


	ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

	SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_DECRYPTING);



	/* The in-place decryption core */

	while (remainingBytes > 0)
	{
		workChunkSize = (uint32) min (remainingBytes, TC_MAX_NONSYS_INPLACE_ENC_WORK_CHUNK_SIZE);

		if (workChunkSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			nStatus = ERR_PARAMETER_INCORRECT;
			goto closing_seq;
		}

		workChunkStartByteOffset = masterCryptoInfo->EncryptedAreaStart.Value;

		unitNo.Value = workChunkStartByteOffset / ENCRYPTION_DATA_UNIT_SIZE;


		// Read the ciphertext into RAM

		offset.QuadPart = workChunkStartByteOffset;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (ReadFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Read error

			DWORD dwTmpErr = GetLastError ();

			if (IsDiskReadError (dwTmpErr) && !bVolTransformThreadCancel)
			{
				// Physical defect or data corruption

				if (!*DiscardUnreadableEncryptedSectors)
				{
					*DiscardUnreadableEncryptedSectors = (AskWarnYesNo ("DISCARD_UNREADABLE_ENCRYPTED_SECTORS", hwndDlg) == IDYES);
				}

				if (*DiscardUnreadableEncryptedSectors)
				{
					// Read the work chunk again, but this time each sector individually and skiping each bad sector

					LARGE_INTEGER tmpSectorOffset;
					uint64 tmpSectorCount;
					uint64 tmpBufOffset = 0;
					DWORD tmpNbrReadBytes = 0;

					tmpSectorOffset.QuadPart = offset.QuadPart;

					for (tmpSectorCount = workChunkSize / sectorSize; tmpSectorCount > 0; --tmpSectorCount)
					{
						if (SetFilePointerEx (dev, tmpSectorOffset, NULL, FILE_BEGIN) == 0)
						{
							nStatus = ERR_OS_ERROR;
							goto closing_seq;
						}

						if (ReadFile (dev, tmpSectorBuf, sectorSize, &tmpNbrReadBytes, NULL) == 0
							|| tmpNbrReadBytes != (DWORD) sectorSize)
						{
							// Read error

							// Clear the buffer so the content of each unreadable sector is replaced with decrypted all-zero blocks (producing pseudorandom data)
							memset (tmpSectorBuf, 0, sectorSize);

							skippedBadSectorCount++;
						}

						memcpy (buf + tmpBufOffset, tmpSectorBuf, sectorSize);

						tmpSectorOffset.QuadPart += sectorSize;
						tmpBufOffset += sectorSize;
					}
				}
				else
				{
					SetLastError (dwTmpErr);		// Preserve the original error code

					nStatus = ERR_OS_ERROR;
					goto closing_seq;
				}
			}
			else
			{
				SetLastError (dwTmpErr);		// Preserve the original error code

				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}

		// Decrypt the ciphertext in RAM

		DecryptDataUnits ((byte *) buf, &unitNo, workChunkSize / ENCRYPTION_DATA_UNIT_SIZE, masterCryptoInfo);



		// Conceal initial portion of the filesystem

		if (workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE)
		{
			// We are decrypting the initial TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE bytes of the filesystem. We will
			// conceal this portion to prevent Windows and applications from interfering with the volume.

			for (i = 0; i < min (TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET + workChunkSize); i++)
				buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;
		}


		// Write the plaintext

		offset.QuadPart = workChunkStartByteOffset - TC_VOLUME_DATA_OFFSET;

		if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		{
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}

		if (WriteFile (dev, buf, workChunkSize, &n, NULL) == 0)
		{
			// Write error
			nStatus = ERR_OS_ERROR;
			goto closing_seq;
		}


		masterCryptoInfo->EncryptedAreaStart.Value += workChunkSize;
		masterCryptoInfo->EncryptedAreaLength.Value -= workChunkSize;

		remainingBytes -= workChunkSize;
		lastHeaderUpdateDistance += workChunkSize;

		bEncryptedAreaSizeChanged = TRUE;

		if (lastHeaderUpdateDistance >= TC_NONSYS_INPLACE_ENC_HEADER_UPDATE_INTERVAL)
		{
			nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);

			if (nStatus != ERR_SUCCESS)
			{
				// Possible write error
				goto closing_seq;
			}

			lastHeaderUpdateDistance = 0;
		}

		ExportProgressStats (masterCryptoInfo->EncryptedAreaLength.Value, masterCryptoInfo->VolumeSize.Value);

		if (bVolTransformThreadCancel)
		{
			bPause = TRUE;
			break;
		}
	}

	nStatus = FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);


	if (nStatus != ERR_SUCCESS)
	{
		// Possible write error
		goto closing_seq;
	}


	if (!bPause)
	{
		/* Volume has been fully decrypted. */


		// Prevent attempts to update volume header during the closing sequence
		bEncryptedAreaSizeChanged = FALSE;


		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINALIZING);



		/* Undo concealing of the filesystem */

		nStatus = ConcealNTFS (dev);

		if (nStatus != ERR_SUCCESS)
			goto closing_seq;



		/* Ovewrite the backup header and the remaining ciphertext with all-zero blocks (the primary header was overwritten with the decrypted data). */

		memset (tmpSectorBuf, 0, sectorSize);

		for (offset.QuadPart = masterCryptoInfo->VolumeSize.Value;
			offset.QuadPart <= deviceSize - sectorSize;
			offset.QuadPart += sectorSize)
		{
			if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

			if (WriteFile (dev, tmpSectorBuf, sectorSize, &n, NULL) == 0)
			{
				// Write error
				dwError = GetLastError();

				SetLastError (dwError);
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
		}



		/* Update the configuration files */

		SaveNonSysInPlaceEncSettings (-1, TC_WIPE_NONE, TRUE);



		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_FINISHED);

		nStatus = ERR_SUCCESS;

	}
	else
	{
		// The process has been paused by the user or aborted by the wizard (e.g. on app exit)

		nStatus = ERR_USER_ABORT;

		SetNonSysInplaceEncUIStatus (NONSYS_INPLACE_ENC_STATUS_PAUSED);
	}

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}


closing_seq:

	dwError = GetLastError();

	if (bEncryptedAreaSizeChanged
		&& dev != INVALID_HANDLE_VALUE
		&& masterCryptoInfo != NULL
		&& headerCryptoInfo != NULL
		&& deviceSize > 0)
	{
		// Execution of the core loop may have been interrupted due to an error or user action without updating the header
		FastVolumeHeaderUpdate (dev, headerCryptoInfo, masterCryptoInfo, deviceSize);
	}

	if (dev != INVALID_HANDLE_VALUE)
	{
		CloseHandle (dev);
		dev = INVALID_HANDLE_VALUE;
	}

	if (masterCryptoInfo != NULL)
	{
		crypto_close (masterCryptoInfo);
		masterCryptoInfo = NULL;
	}

	if (headerCryptoInfo != NULL)
	{
		crypto_close (headerCryptoInfo);
		headerCryptoInfo = NULL;
	}

	if (dosDev[0])
		RemoveFakeDosName (devicePath, dosDev);

	if (buf != NULL)
	{
		TCfree (buf);
		buf = NULL;
	}

	if (tmpSectorBuf != NULL)
	{
		TCfree (tmpSectorBuf);
		tmpSectorBuf = NULL;
	}

	if (skippedBadSectorCount > 0)
	{
		wchar_t msg[30000] = {0};
		wchar_t sizeStr[500] = {0};

		GetSizeString (skippedBadSectorCount * sectorSize, sizeStr, sizeof(sizeStr));

		StringCbPrintfW (msg, sizeof(msg),
			GetString ("SKIPPED_BAD_SECTOR_COUNT"),
			skippedBadSectorCount,
			sizeStr);

		WarningDirect (msg, hwndDlg);
	}

	if (nStatus != ERR_SUCCESS && nStatus != ERR_USER_ABORT)
		SetLastError (dwError);

	return nStatus;
}

int FastVolumeHeaderUpdate (HANDLE dev, CRYPTO_INFO *headerCryptoInfo, CRYPTO_INFO *masterCryptoInfo, __int64 deviceSize)
{
	LARGE_INTEGER offset;
	DWORD n;
	int nStatus = ERR_SUCCESS;
	byte *header;
	DWORD dwError;
	uint32 headerCrc32;
	byte *fieldPos;

	header = (byte *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);

	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);


	fieldPos = (byte *) header + TC_HEADER_OFFSET_ENCRYPTED_AREA_START;

	offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !ReadEffectiveVolumeHeader (TRUE, dev, header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	DecryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo);

	if (GetHeaderField32 (header, TC_HEADER_OFFSET_MAGIC) != 0x56455241)
	{
		nStatus = ERR_PARAMETER_INCORRECT;
		goto closing_seq;
	}

	mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaStart.Value));
	mputInt64 (fieldPos, (masterCryptoInfo->EncryptedAreaLength.Value));

	// We need to ensure the TC_HEADER_FLAG_NONSYS_INPLACE_ENC flag bit is set, because if volumes created by TC-format
	// were decrypted in place, it would be possible to mount them partially encrypted and it wouldn't be possible
	// to resume interrupted decryption after the wizard exits.
	masterCryptoInfo->HeaderFlags |= TC_HEADER_FLAG_NONSYS_INPLACE_ENC;
	fieldPos = (byte *) header + TC_HEADER_OFFSET_FLAGS;
	mputLong (fieldPos, (masterCryptoInfo->HeaderFlags));


	headerCrc32 = GetCrc32 (header + TC_HEADER_OFFSET_MAGIC, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC);
	fieldPos = (byte *) header + TC_HEADER_OFFSET_HEADER_CRC;
	mputLong (fieldPos, headerCrc32);

	EncryptBuffer (header + HEADER_ENCRYPTED_DATA_OFFSET, HEADER_ENCRYPTED_DATA_SIZE, headerCryptoInfo);


	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !WriteEffectiveVolumeHeader (TRUE, dev, header))
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


closing_seq:

	dwError = GetLastError();

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static HANDLE OpenPartitionVolume (HWND hwndDlg, const wchar_t *devName,
							 BOOL bExclusiveRequired,
							 BOOL bSharedRequired,
							 BOOL bSharedRequiresConfirmation,
							 BOOL bShowAlternativeSteps,
							 BOOL bSilent)
{
	HANDLE dev = INVALID_HANDLE_VALUE;
	int retryCount = 0;

	if (bExclusiveRequired)
		bSharedRequired = FALSE;

	if (bExclusiveRequired || !bSharedRequired)
	{
		// Exclusive access
		// Note that when exclusive access is denied, it is worth retrying (usually succeeds after a few tries).
		while (dev == INVALID_HANDLE_VALUE && retryCount++ < EXCL_ACCESS_MAX_AUTO_RETRIES)
		{
			dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);

			if (retryCount > 1)
				Sleep (EXCL_ACCESS_AUTO_RETRY_DELAY);
		}
	}

	if (dev == INVALID_HANDLE_VALUE)
	{
		if (bExclusiveRequired)
		{
			if (!bSilent)
			{
				handleWin32Error (hwndDlg, SRC_POS);

				if (bShowAlternativeSteps)
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
				else
					Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
			}
			return INVALID_HANDLE_VALUE;
		}

		// Shared mode
		dev = CreateFile (devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_WRITE_THROUGH, NULL);
		if (dev != INVALID_HANDLE_VALUE)
		{
			if (bSharedRequiresConfirmation
				&& !bSilent
				&& AskWarnNoYes ("DEVICE_IN_USE_INPLACE_ENC", hwndDlg) == IDNO)
			{
				CloseHandle (dev);
				return INVALID_HANDLE_VALUE;
			}
		}
		else
		{
			if (!bSilent)
			{
				handleWin32Error (MainDlg, SRC_POS);

				if (bShowAlternativeSteps)
					ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL_ALT", TRUE);
				else
					Error ("INPLACE_ENC_CANT_ACCESS_OR_GET_INFO_ON_VOL", hwndDlg);
			}
			return INVALID_HANDLE_VALUE;
		}
	}

	return dev;
}


static int DismountFileSystem (HWND hwndDlg, HANDLE dev,
					int driveLetter,
					BOOL bForcedAllowed,
					BOOL bForcedRequiresConfirmation,
					BOOL bSilent)
{
	int attempt;
	BOOL bResult;
	DWORD dwResult;

	CloseVolumeExplorerWindows (MainDlg, driveLetter);

	attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;

	while (!(bResult = DeviceIoControl (dev, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
		&& attempt > 0)
	{
		Sleep (UNMOUNT_AUTO_RETRY_DELAY);
		attempt--;
	}

	if (!bResult)
	{
		if (!bForcedAllowed)
		{
			if (!bSilent)
				ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);

			return ERR_DONT_REPORT;
		}

		if (bForcedRequiresConfirmation
			&& !bSilent
			&& AskWarnYesNo ("VOL_LOCK_FAILED_OFFER_FORCED_DISMOUNT", hwndDlg) == IDNO)
		{
			return ERR_DONT_REPORT;
		}
	}

	// Dismount the volume

	attempt = UNMOUNT_MAX_AUTO_RETRIES * 10;

	while (!(bResult = DeviceIoControl (dev, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &dwResult, NULL))
		&& attempt > 0)
	{
		Sleep (UNMOUNT_AUTO_RETRY_DELAY);
		attempt--;
	}

	if (!bResult)
	{
		if (!bSilent)
			ShowInPlaceEncErrMsgWAltSteps (hwndDlg, "INPLACE_ENC_CANT_LOCK_OR_DISMOUNT_FILESYS", TRUE);

		return ERR_DONT_REPORT;
	}

	return ERR_SUCCESS;
}


// Easy-to-undo modification applied to conceal the NTFS filesystem (to prevent Windows and apps from
// interfering with it until the volume has been fully encrypted). Note that this function will precisely
// undo any modifications it made to the filesystem automatically if an error occurs when writing (including
// physical drive defects).
static int ConcealNTFS (HANDLE dev)
{
	char buf [TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE];
	DWORD nbrBytesProcessed, nbrBytesProcessed2;
	int i;
	LARGE_INTEGER offset;
	DWORD dwError;

	offset.QuadPart = 0;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		return ERR_OS_ERROR;

	if (ReadFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
		return ERR_OS_ERROR;

	for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
		buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;

	offset.QuadPart = 0;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0)
		return ERR_OS_ERROR;

	if (WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed, NULL) == 0)
	{
		// One or more of the sectors is/are probably damaged and cause write errors.
		// We must undo the modifications we made.

		dwError = GetLastError();

		for (i = 0; i < TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE; i++)
			buf[i] ^= TC_NTFS_CONCEAL_CONSTANT;

		offset.QuadPart = 0;

		do
		{
			Sleep (1);
		}
		while (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
			|| WriteFile (dev, buf, TC_INITIAL_NTFS_CONCEAL_PORTION_SIZE, &nbrBytesProcessed2, NULL) == 0);

		SetLastError (dwError);

		return ERR_OS_ERROR;
	}

	return ERR_SUCCESS;
}


void ShowInPlaceEncErrMsgWAltSteps (HWND hwndDlg, char *iniStrId, BOOL bErr)
{
	wchar_t msg[30000];

	StringCbCopyW (msg, sizeof(msg), GetString (iniStrId));

	StringCbCatW (msg, sizeof(msg), L"\n\n\n");
	StringCbCatW (msg, sizeof(msg), GetString ("INPLACE_ENC_ALTERNATIVE_STEPS"));

	if (bErr)
		ErrorDirect (msg, hwndDlg);
	else
		WarningDirect (msg, hwndDlg);
}


static void ExportProgressStats (__int64 bytesDone, __int64 totalSize)
{
	NonSysInplaceEncBytesDone = bytesDone;
	NonSysInplaceEncTotalSize = totalSize;
}


void SetNonSysInplaceEncUIStatus (int nonSysInplaceEncStatus)
{
	NonSysInplaceEncStatus = nonSysInplaceEncStatus;
}


BOOL SaveNonSysInPlaceEncSettings (int delta, WipeAlgorithmId newWipeAlgorithm, BOOL bDecrypt)
{
	int count;
	char str[32];
	WipeAlgorithmId savedWipeAlgorithm = TC_WIPE_NONE;

	if (delta == 0)
		return TRUE;

	count = LoadNonSysInPlaceEncSettings (&savedWipeAlgorithm) + delta;

	if (count < 1)
	{
		RemoveNonSysInPlaceEncNotifications();
		return TRUE;
	}
	else if (!bDecrypt)
	{
		if (newWipeAlgorithm != TC_WIPE_NONE)
		{
			StringCbPrintfA (str, sizeof(str), "%d", (int) newWipeAlgorithm);

			SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE), (DWORD) strlen(str), FALSE, FALSE);
		}
		else if (FileExists (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE)))
		{
			_wremove (GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC_WIPE));
		}
	}

	StringCbPrintfA (str, sizeof(str), "%d", count);

	return SaveBufferToFile (str, GetConfigPath (TC_APPD_FILENAME_NONSYS_INPLACE_ENC), (DWORD) strlen(str), FALSE, FALSE);
}


// Repairs damaged sectors (i.e. those with read errors) by zeroing them.
// Note that this operating fails if there are any write errors.
int ZeroUnreadableSectors (HANDLE dev, LARGE_INTEGER startOffset, int64 size, int sectorSize, uint64 *zeroedSectorCount)
{
	int nStatus;
	DWORD n;
	int64 sectorCount;
	LARGE_INTEGER workOffset;
	byte *sectorBuffer = NULL;
	DWORD dwError;

	workOffset.QuadPart = startOffset.QuadPart;

	sectorBuffer = (byte *) TCalloc (sectorSize);

	if (!sectorBuffer)
		return ERR_OUTOFMEMORY;

	if (SetFilePointerEx (dev, startOffset, NULL, FILE_BEGIN) == 0)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	for (sectorCount = size / sectorSize; sectorCount > 0; --sectorCount)
	{
		if (ReadFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
		{
			memset (sectorBuffer, 0, sectorSize);

			if (SetFilePointerEx (dev, workOffset, NULL, FILE_BEGIN) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}

			if (WriteFile (dev, sectorBuffer, sectorSize, &n, NULL) == 0)
			{
				nStatus = ERR_OS_ERROR;
				goto closing_seq;
			}
			++(*zeroedSectorCount);
		}

		workOffset.QuadPart += n;
	}

	nStatus = ERR_SUCCESS;

closing_seq:

	dwError = GetLastError();

	if (sectorBuffer != NULL)
		TCfree (sectorBuffer);

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static int OpenBackupHeader (HANDLE dev, const wchar_t *devicePath, Password *password, int pkcs5, int pim, PCRYPTO_INFO *retMasterCryptoInfo, CRYPTO_INFO *headerCryptoInfo, __int64 deviceSize)
{
	LARGE_INTEGER offset;
	DWORD n;
	int nStatus = ERR_SUCCESS;
	char *header;
	DWORD dwError;

	header = (char *) TCalloc (TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	if (!header)
		return ERR_OUTOFMEMORY;

	VirtualLock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);



	offset.QuadPart = deviceSize - TC_VOLUME_HEADER_GROUP_SIZE;

	if (SetFilePointerEx (dev, offset, NULL, FILE_BEGIN) == 0
		|| !ReadEffectiveVolumeHeader (TRUE, dev, (byte *) header, &n) || n < TC_VOLUME_HEADER_EFFECTIVE_SIZE)
	{
		nStatus = ERR_OS_ERROR;
		goto closing_seq;
	}


	nStatus = ReadVolumeHeader (FALSE, header, password, pkcs5, pim, FALSE, retMasterCryptoInfo, headerCryptoInfo);
	if (nStatus != ERR_SUCCESS)
		goto closing_seq;


closing_seq:

	dwError = GetLastError();

	burn (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	VirtualUnlock (header, TC_VOLUME_HEADER_EFFECTIVE_SIZE);
	TCfree (header);

	dwError = GetLastError();

	if (nStatus != ERR_SUCCESS)
		SetLastError (dwError);

	return nStatus;
}


static BOOL GetFreeClusterBeforeThreshold (HANDLE volumeHandle, int64 *freeCluster, int64 clusterThreshold)
{
	const int bitmapSize = 65536;
	byte bitmapBuffer[bitmapSize + sizeof (VOLUME_BITMAP_BUFFER)];
	VOLUME_BITMAP_BUFFER *bitmap = (VOLUME_BITMAP_BUFFER *) bitmapBuffer;
	STARTING_LCN_INPUT_BUFFER startLcn;
	startLcn.StartingLcn.QuadPart = 0;

	DWORD bytesReturned;
	while (DeviceIoControl (volumeHandle, FSCTL_GET_VOLUME_BITMAP, &startLcn, sizeof (startLcn), &bitmapBuffer, sizeof (bitmapBuffer), &bytesReturned, NULL)
		|| GetLastError() == ERROR_MORE_DATA)
	{
		for (int64 bitmapIndex = 0; bitmapIndex < min (bitmapSize, (bitmap->BitmapSize.QuadPart / 8)); ++bitmapIndex)
		{
			if (bitmap->StartingLcn.QuadPart + bitmapIndex * 8 >= clusterThreshold)
				goto err;

			if (bitmap->Buffer[bitmapIndex] != 0xff)
			{
				for (int bit = 0; bit < 8; ++bit)
				{
					if ((bitmap->Buffer[bitmapIndex] & (1 << bit)) == 0)
					{
						*freeCluster = bitmap->StartingLcn.QuadPart + bitmapIndex * 8 + bit;

						if (*freeCluster >= clusterThreshold)
							goto err;

						return TRUE;
					}
				}
			}
		}

		startLcn.StartingLcn.QuadPart += min (bitmapSize * 8, bitmap->BitmapSize.QuadPart);
	}

err:
	SetLastError (ERROR_DISK_FULL);
	return FALSE;
}


static BOOL MoveClustersBeforeThresholdInDir (HANDLE volumeHandle, const wstring &directory, int64 clusterThreshold)
{
	WIN32_FIND_DATAW findData;

	HANDLE findHandle = FindFirstFileW (((directory.size() <= 3 ? L"" : L"\\\\?\\") + directory + L"\\*").c_str(), &findData);
	if (findHandle == INVALID_HANDLE_VALUE)
		return TRUE;	// Error ignored

	finally_do_arg (HANDLE, findHandle, { FindClose (finally_arg); });

	// Find all files and directories
	do
	{
		if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
		{
			wstring subDir = findData.cFileName;

			if (subDir == L"." || subDir == L"..")
				continue;

			if (!MoveClustersBeforeThresholdInDir (volumeHandle, directory + L"\\" + subDir, clusterThreshold))
				return FALSE;
		}

		DWORD access = FILE_READ_ATTRIBUTES;

		if (findData.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED)
			access = FILE_READ_DATA;

		HANDLE fsObject = CreateFileW ((directory + L"\\" + findData.cFileName).c_str(), access, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
		if (fsObject == INVALID_HANDLE_VALUE)
			continue;

		finally_do_arg (HANDLE, fsObject, { CloseHandle (finally_arg); });

		STARTING_VCN_INPUT_BUFFER startVcn;
		startVcn.StartingVcn.QuadPart = 0;
		RETRIEVAL_POINTERS_BUFFER retPointers;
		DWORD bytesReturned;

		// Find clusters allocated beyond the threshold
		while (DeviceIoControl (fsObject, FSCTL_GET_RETRIEVAL_POINTERS, &startVcn, sizeof (startVcn), &retPointers, sizeof (retPointers), &bytesReturned, NULL)
			|| GetLastError() == ERROR_MORE_DATA)
		{
			if (retPointers.ExtentCount == 0)
				break;

			if (retPointers.Extents[0].Lcn.QuadPart != -1)
			{
				int64 extentStartCluster = retPointers.Extents[0].Lcn.QuadPart;
				int64 extentLen = retPointers.Extents[0].NextVcn.QuadPart - retPointers.StartingVcn.QuadPart;
				int64 extentEndCluster = extentStartCluster + extentLen - 1;

				if (extentEndCluster >= clusterThreshold)
				{
					// Move clusters before the threshold
					for (int64 movedCluster = max (extentStartCluster, clusterThreshold); movedCluster <= extentEndCluster; ++movedCluster)
					{
						for (int retry = 0; ; ++retry)
						{
							MOVE_FILE_DATA moveData;

							if (GetFreeClusterBeforeThreshold (volumeHandle, &moveData.StartingLcn.QuadPart, clusterThreshold))
							{
								moveData.FileHandle = fsObject;
								moveData.StartingVcn.QuadPart = movedCluster - extentStartCluster + retPointers.StartingVcn.QuadPart;
								moveData.ClusterCount = 1;

								if (DeviceIoControl (volumeHandle, FSCTL_MOVE_FILE, &moveData, sizeof (moveData), NULL, 0, &bytesReturned, NULL))
									break;
							}

							if (retry > 600)
								return FALSE;

							// There are possible race conditions as we work on a live filesystem
							Sleep (100);
						}
					}
				}
			}

			startVcn.StartingVcn = retPointers.Extents[0].NextVcn;
		}

	} while (FindNextFileW (findHandle, &findData));

	return TRUE;
}


BOOL MoveClustersBeforeThreshold (HANDLE volumeHandle, PWSTR volumeDevicePath, int64 clusterThreshold)
{
	int drive = GetDiskDeviceDriveLetter (volumeDevicePath);
	if (drive == -1)
	{
		SetLastError (ERROR_INVALID_PARAMETER);
		return FALSE;
	}

	wstring volumeRoot = L"X:";
	volumeRoot[0] = L'A' + (wchar_t) drive;

	return MoveClustersBeforeThresholdInDir (volumeHandle, volumeRoot, clusterThreshold);
}