-
-
Notifications
You must be signed in to change notification settings - Fork 271
Expand file tree
/
Copy pathCryptoManager.cpp
More file actions
1444 lines (1224 loc) · 35.2 KB
/
Copy pathCryptoManager.cpp
File metadata and controls
1444 lines (1224 loc) · 35.2 KB
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* PROGRAM: JRD access method
* MODULE: CryptoManager.cpp
* DESCRIPTION: Database encryption
*
* The contents of this file are subject to the Initial
* Developer's Public License Version 1.0 (the "License");
* you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
* http://www.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl.
*
* Software distributed under the License is distributed AS IS,
* WITHOUT WARRANTY OF ANY KIND, either express or implied.
* See the License for the specific language governing rights
* and limitations under the License.
*
* The Original Code was created by Alex Peshkov
* for the Firebird Open Source RDBMS project.
*
* Copyright (c) 2012 Alex Peshkov <peshkoff at mail.ru>
* and all contributors signed below.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
*
*/
#include "firebird.h"
#include "firebird/Interface.h"
#include "gen/iberror.h"
#include "../jrd/CryptoManager.h"
#include "../common/classes/alloc.h"
#include "../jrd/Database.h"
#include "../common/ThreadStart.h"
#include "../common/StatusArg.h"
#include "../common/StatusHolder.h"
#include "../jrd/lck.h"
#include "../jrd/jrd.h"
#include "../jrd/pag.h"
#include "../jrd/nbak.h"
#include "../jrd/cch_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/pag_proto.h"
#include "../jrd/inf_pub.h"
#include "../jrd/Monitoring.h"
#include "../jrd/os/pio_proto.h"
#include "../common/isc_proto.h"
#include "../common/classes/GetPlugins.h"
#include "../common/classes/RefMutex.h"
#include "../common/classes/ClumpletWriter.h"
#include "../common/sha.h"
using namespace Firebird;
namespace {
THREAD_ENTRY_DECLARE cryptThreadStatic(THREAD_ENTRY_PARAM p)
{
Jrd::CryptoManager* cryptoManager = (Jrd::CryptoManager*) p;
cryptoManager->cryptThread();
return 0;
}
const UCHAR CRYPT_RELEASE = LCK_SR;
const UCHAR CRYPT_NORMAL = LCK_PR;
const UCHAR CRYPT_CHANGE = LCK_PW;
const UCHAR CRYPT_INIT = LCK_EX;
const int MAX_PLUGIN_NAME_LEN = 31;
}
namespace Jrd {
class Header
{
protected:
Header()
: header(NULL)
{ }
void setHeader(void* buf)
{
header = static_cast<Ods::header_page*>(buf);
}
void setHeader(Ods::header_page* newHdr)
{
header = newHdr;
}
Ods::header_page* getHeader()
{
return header;
}
public:
const Ods::header_page* operator->() const
{
return header;
}
operator const Ods::header_page*() const
{
return header;
}
// This routine is getting clumplets from header page but is not ready to handle continuation
// Fortunately, modern pages of size 4k and bigger can fit everything on one page.
void getClumplets(ClumpletWriter& writer) const
{
writer.reset(header->hdr_data, header->hdr_end - HDR_SIZE);
}
private:
Ods::header_page* header;
};
class CchHdr : public Header
{
public:
CchHdr(Jrd::thread_db* p_tdbb, USHORT lockType)
: window(Jrd::HEADER_PAGE_NUMBER),
tdbb(p_tdbb),
wrk(NULL),
buffer(*tdbb->getDefaultPool())
{
void* h = CCH_FETCH(tdbb, &window, lockType, pag_header);
if (!h)
{
ERR_punt();
}
setHeader(h);
}
Ods::header_page* write()
{
if (!wrk)
{
Ods::header_page* hdr = getHeader();
wrk = reinterpret_cast<Ods::header_page*>(buffer.getBuffer(hdr->hdr_page_size));
memcpy(wrk, hdr, hdr->hdr_page_size);
// swap headers
setHeader(wrk);
wrk = hdr;
}
return getHeader();
}
void flush()
{
if (wrk)
{
CCH_MARK_MUST_WRITE(tdbb, &window);
memcpy(wrk, getHeader(), wrk->hdr_page_size);
}
}
void setClumplets(const ClumpletWriter& writer)
{
Ods::header_page* hdr = write();
UCHAR* const to = hdr->hdr_data;
UCHAR* const end = reinterpret_cast<UCHAR*>(hdr) + hdr->hdr_page_size;
const unsigned limit = (end - to) - 1;
const unsigned length = writer.getBufferLength();
fb_assert(length <= limit);
if (length > limit)
(Arg::Gds(isc_random) << "HDR page clumplets overflow").raise();
memcpy(to, writer.getBuffer(), length);
to[length] = Ods::HDR_end;
hdr->hdr_end = HDR_SIZE + length;
}
~CchHdr()
{
CCH_RELEASE(tdbb, &window);
}
private:
Jrd::WIN window;
Jrd::thread_db* tdbb;
Ods::header_page* wrk;
Array<UCHAR> buffer;
};
class PhysHdr : public Header
{
public:
explicit PhysHdr(Jrd::thread_db* tdbb)
{
// Can't use CCH_fetch_page() here cause it will cause infinite recursion
Jrd::Database* dbb = tdbb->getDatabase();
Jrd::BufferControl* bcb = dbb->dbb_bcb;
Jrd::BufferDesc bdb(bcb);
bdb.bdb_page = Jrd::PageNumber(Jrd::DB_PAGE_SPACE, 0);
UCHAR* h = FB_NEW_POOL(*Firebird::MemoryPool::getContextPool()) UCHAR[dbb->dbb_page_size + PAGE_ALIGNMENT];
buffer.reset(h);
h = FB_ALIGN(h, PAGE_ALIGNMENT);
bdb.bdb_buffer = (Ods::pag*) h;
Jrd::FbStatusVector* const status = tdbb->tdbb_status_vector;
Ods::pag* page = bdb.bdb_buffer;
Jrd::PageSpace* pageSpace = dbb->dbb_page_manager.findPageSpace(Jrd::DB_PAGE_SPACE);
fb_assert(pageSpace);
Jrd::jrd_file* file = pageSpace->file;
const bool isTempPage = pageSpace->isTemporary();
Jrd::BackupManager::StateReadGuard::lock(tdbb, 1);
Jrd::BackupManager* bm = dbb->dbb_backup_manager;
int bak_state = bm->getState();
try
{
fb_assert(bak_state != Ods::hdr_nbak_unknown);
ULONG diff_page = 0;
if (bak_state != Ods::hdr_nbak_normal)
diff_page = bm->getPageIndex(tdbb, bdb.bdb_page.getPageNum());
if (bak_state == Ods::hdr_nbak_normal || !diff_page)
{
// Read page from disk as normal
int retryCount = 0;
while (!PIO_read(tdbb, file, &bdb, page, status))
{
if (!CCH_rollover_to_shadow(tdbb, dbb, file, false))
ERR_punt();;
if (file != pageSpace->file)
file = pageSpace->file;
else
{
if (retryCount++ == 3)
{
gds__log("IO error loop Unwind to avoid a hang");
ERR_punt();
}
}
}
}
else
{
if (!bm->readDifference(tdbb, diff_page, page))
ERR_punt();
}
setHeader(h);
}
catch(const Exception&)
{
Jrd::BackupManager::StateReadGuard::unlock(tdbb);
throw;
}
Jrd::BackupManager::StateReadGuard::unlock(tdbb);
}
private:
AutoPtr<UCHAR, ArrayDelete<UCHAR> > buffer;
};
CryptoManager::CryptoManager(thread_db* tdbb)
: PermanentStorage(*tdbb->getDatabase()->dbb_permanent),
sync(this),
keyName(getPool()),
keyHolderPlugins(getPool(), this),
hash(getPool()),
dbInfo(FB_NEW DbInfo(this)),
cryptThreadId(0),
cryptPlugin(NULL),
checkPlugin(NULL),
dbb(*tdbb->getDatabase()),
cryptAtt(NULL),
slowIO(0),
crypt(false),
process(false),
down(false),
run(false)
{
stateLock = FB_NEW_RPT(getPool(), 0)
Lock(tdbb, 0, LCK_crypt_status, this, blockingAstChangeCryptState);
threadLock = FB_NEW_RPT(getPool(), 0) Lock(tdbb, 0, LCK_crypt);
}
CryptoManager::~CryptoManager()
{
if (cryptThreadId)
Thread::waitForCompletion(cryptThreadId);
delete stateLock;
delete threadLock;
dbInfo->destroy();
}
void CryptoManager::shutdown(thread_db* tdbb)
{
terminateCryptThread(tdbb);
if (cryptPlugin)
{
PluginManagerInterfacePtr()->releasePlugin(cryptPlugin);
cryptPlugin = NULL;
}
LCK_release(tdbb, stateLock);
}
void CryptoManager::doOnTakenWriteSync(thread_db* tdbb)
{
fb_assert(stateLock);
if (stateLock->lck_physical > CRYPT_RELEASE)
return;
fb_assert(tdbb);
lockAndReadHeader(tdbb, CRYPT_HDR_NOWAIT);
}
void CryptoManager::lockAndReadHeader(thread_db* tdbb, unsigned flags)
{
if (flags & CRYPT_HDR_INIT)
{
if (LCK_lock(tdbb, stateLock, CRYPT_INIT, LCK_NO_WAIT))
{
LCK_write_data(tdbb, stateLock, 1);
if (!LCK_convert(tdbb, stateLock, CRYPT_NORMAL, LCK_NO_WAIT))
{
fb_assert(tdbb->tdbb_status_vector->getState() & IStatus::STATE_ERRORS);
ERR_punt();
}
}
else if (!LCK_lock(tdbb, stateLock, CRYPT_NORMAL, LCK_WAIT))
{
fb_assert(false);
}
}
else
{
if (!LCK_convert(tdbb, stateLock, CRYPT_NORMAL,
(flags & CRYPT_HDR_NOWAIT) ? LCK_NO_WAIT : LCK_WAIT))
{
// Failed to take state lock - switch to slow IO mode
slowIO = LCK_read_data(tdbb, stateLock);
fb_assert(slowIO);
}
else
slowIO = 0;
}
tdbb->tdbb_status_vector->init();
PhysHdr hdr(tdbb);
crypt = hdr->hdr_flags & Ods::hdr_encrypted;
process = hdr->hdr_flags & Ods::hdr_crypt_process;
if ((crypt || process) && !cryptPlugin)
{
ClumpletWriter hc(ClumpletWriter::UnTagged, hdr->hdr_page_size);
hdr.getClumplets(hc);
if (hc.find(Ods::HDR_crypt_key))
hc.getString(keyName);
else
keyName = "";
loadPlugin(hdr->hdr_crypt_plugin);
string valid;
calcValidation(valid, cryptPlugin);
if (hc.find(Ods::HDR_crypt_hash))
{
hc.getString(hash);
if (hash != valid)
(Arg::Gds(isc_bad_crypt_key) << keyName).raise();
}
else
hash = valid;
}
if (flags & CRYPT_HDR_INIT)
checkDigitalSignature(hdr);
}
void CryptoManager::loadPlugin(const char* pluginName)
{
if (cryptPlugin)
{
return;
}
MutexLockGuard guard(pluginLoadMtx, FB_FUNCTION);
if (cryptPlugin)
{
return;
}
GetPlugins<IDbCryptPlugin> cryptControl(IPluginManager::TYPE_DB_CRYPT, dbb.dbb_config, pluginName);
if (!cryptControl.hasData())
{
(Arg::Gds(isc_no_crypt_plugin) << pluginName).raise();
}
// do not assign cryptPlugin directly before key init complete
IDbCryptPlugin* p = cryptControl.plugin();
FbLocalStatus status;
p->setInfo(&status, dbInfo);
if (status->getState() & IStatus::STATE_ERRORS)
{
const ISC_STATUS* v = status->getErrors();
if (v[0] == isc_arg_gds && v[1] != isc_arg_end && v[1] != isc_interface_version_too_old)
status_exception::raise(&status);
}
keyHolderPlugins.init(p, keyName);
cryptPlugin = p;
cryptPlugin->addRef();
// May be load second instance to validate keys
if (checkPlugin)
{
PluginManagerInterfacePtr()->releasePlugin(checkPlugin);
checkPlugin = NULL;
}
if (dbb.dbb_config->getServerMode() == MODE_SUPER)
{
checkPlugin = cryptControl.makeInstance();
keyHolderPlugins.validate(checkPlugin, NULL, keyName);
}
}
void CryptoManager::prepareChangeCryptState(thread_db* tdbb, const MetaName& plugName,
const MetaName& key)
{
if (plugName.length() > MAX_PLUGIN_NAME_LEN)
{
(Arg::Gds(isc_cp_name_too_long) << Arg::Num(MAX_PLUGIN_NAME_LEN)).raise();
}
const bool newCryptState = plugName.hasData();
BackupManager::StateReadGuard::lock(tdbb, 1);
int bak_state = dbb.dbb_backup_manager->getState();
BackupManager::StateReadGuard::unlock(tdbb);
{ // window scope
CchHdr hdr(tdbb, LCK_read);
// Check header page for flags
if (hdr->hdr_flags & Ods::hdr_crypt_process)
{
(Arg::Gds(isc_cp_process_active)).raise();
}
bool headerCryptState = hdr->hdr_flags & Ods::hdr_encrypted;
if (headerCryptState == newCryptState)
{
(Arg::Gds(isc_cp_already_crypted)).raise();
}
if (bak_state != Ods::hdr_nbak_normal)
{
(Arg::Gds(isc_wish_list) << Arg::Gds(isc_random) <<
"Cannot crypt: please wait for nbackup completion").raise();
}
// Load plugin
if (newCryptState)
{
if (cryptPlugin)
{
if (!headerCryptState)
{
// unload old plugin
PluginManagerInterfacePtr()->releasePlugin(cryptPlugin);
cryptPlugin = NULL;
}
else
Arg::Gds(isc_cp_already_crypted).raise();
}
keyName = key;
loadPlugin(plugName.c_str());
}
}
}
void CryptoManager::calcValidation(string& valid, IDbCryptPlugin* plugin)
{
// crypt verifier
const char* sample = "0123456789ABCDEF";
char result[16];
FbLocalStatus sv;
plugin->encrypt(&sv, sizeof(result), sample, result);
if (sv->getState() & IStatus::STATE_ERRORS)
Arg::StatusVector(&sv).raise();
// calculate its hash
const string verifier(result, sizeof(result));
Sha1::hashBased64(valid, verifier);
}
bool CryptoManager::checkValidation(IDbCryptPlugin* plugin)
{
string valid;
calcValidation(valid, plugin);
return valid == hash;
}
void CryptoManager::changeCryptState(thread_db* tdbb, const string& plugName)
{
if (plugName.length() > 31)
{
(Arg::Gds(isc_cp_name_too_long) << Arg::Num(31)).raise();
}
const bool newCryptState = plugName.hasData();
try
{
BarSync::LockGuard writeGuard(tdbb, sync);
// header scope
CchHdr hdr(tdbb, LCK_write);
writeGuard.lock();
// Nbak's lock was taken in prepareChangeCryptState()
// If it was invalidated it's enough reason not to continue now
int bak_state = dbb.dbb_backup_manager->getState();
if (bak_state != Ods::hdr_nbak_normal)
{
(Arg::Gds(isc_wish_list) << Arg::Gds(isc_random) <<
"Cannot crypt: please wait for nbackup completion").raise();
}
// Check header page for flags
if (hdr->hdr_flags & Ods::hdr_crypt_process)
{
(Arg::Gds(isc_cp_process_active)).raise();
}
bool headerCryptState = hdr->hdr_flags & Ods::hdr_encrypted;
if (headerCryptState == newCryptState)
{
(Arg::Gds(isc_cp_already_crypted)).raise();
}
fb_assert(stateLock);
// Trigger lock on ChangeCryptState
if (!LCK_convert(tdbb, stateLock, CRYPT_CHANGE, LCK_WAIT))
{
fb_assert(tdbb->tdbb_status_vector->getState() & IStatus::STATE_ERRORS);
ERR_punt();
}
fb_utils::init_status(tdbb->tdbb_status_vector);
// Load plugin
if (newCryptState)
{
loadPlugin(plugName.c_str());
}
crypt = newCryptState;
// Write modified header page
Ods::header_page* header = hdr.write();
ClumpletWriter hc(ClumpletWriter::UnTagged, header->hdr_page_size);
hdr.getClumplets(hc);
if (crypt)
{
header->hdr_flags |= Ods::hdr_encrypted;
plugName.copyTo(header->hdr_crypt_plugin, sizeof(header->hdr_crypt_plugin));
calcValidation(hash, cryptPlugin);
hc.deleteWithTag(Ods::HDR_crypt_hash);
hc.insertString(Ods::HDR_crypt_hash, hash);
hc.deleteWithTag(Ods::HDR_crypt_key);
if (keyName.hasData())
hc.insertString(Ods::HDR_crypt_key, keyName);
}
else
header->hdr_flags &= ~Ods::hdr_encrypted;
hdr.setClumplets(hc);
// Setup hdr_crypt_page for crypt thread
header->hdr_crypt_page = 1;
header->hdr_flags |= Ods::hdr_crypt_process;
process = true;
digitalySignDatabase(hdr);
hdr.flush();
}
catch (const Exception&)
{
if (stateLock->lck_physical != CRYPT_NORMAL)
{
try
{
if (!LCK_convert(tdbb, stateLock, CRYPT_RELEASE, LCK_NO_WAIT))
fb_assert(false);
lockAndReadHeader(tdbb);
}
catch (const Exception&)
{ }
}
throw;
}
SINT64 next = LCK_read_data(tdbb, stateLock) + 1;
LCK_write_data(tdbb, stateLock, next);
if (!LCK_convert(tdbb, stateLock, CRYPT_RELEASE, LCK_NO_WAIT))
fb_assert(false);
lockAndReadHeader(tdbb);
fb_utils::init_status(tdbb->tdbb_status_vector);
startCryptThread(tdbb);
}
void CryptoManager::blockingAstChangeCryptState()
{
AsyncContextHolder tdbb(&dbb, FB_FUNCTION);
if (stateLock->lck_physical != CRYPT_CHANGE && stateLock->lck_physical != CRYPT_INIT)
{
sync.ast(tdbb);
}
}
void CryptoManager::doOnAst(thread_db* tdbb)
{
fb_assert(stateLock);
LCK_convert(tdbb, stateLock, CRYPT_RELEASE, LCK_NO_WAIT);
}
void CryptoManager::attach(thread_db* tdbb, Attachment* att)
{
keyHolderPlugins.attach(att, dbb.dbb_config);
IDbCryptPlugin* p = checkPlugin;
lockAndReadHeader(tdbb, CRYPT_HDR_INIT);
if (p && p == checkPlugin)
{
if (!keyHolderPlugins.validate(checkPlugin, att, keyName))
(Arg::Gds(isc_bad_crypt_key) << keyName).raise();
}
}
void CryptoManager::terminateCryptThread(thread_db*, bool wait)
{
down = true;
if (wait && cryptThreadId)
{
Thread::waitForCompletion(cryptThreadId);
cryptThreadId = 0;
}
}
void CryptoManager::stopThreadUsing(thread_db* tdbb, Attachment* att)
{
if (att == cryptAtt)
terminateCryptThread(tdbb);
}
void CryptoManager::startCryptThread(thread_db* tdbb)
{
// Try to take crypt mutex
// If can't take that mutex - nothing to do, cryptThread already runs in our process
MutexEnsureUnlock guard(cryptThreadMtx, FB_FUNCTION);
if (!guard.tryEnter())
return;
// Check for recursion
if (run)
return;
// Take exclusive threadLock
// If can't take that lock - nothing to do, cryptThread already runs somewhere
if (!LCK_lock(tdbb, threadLock, LCK_EX, LCK_NO_WAIT))
{
// Cleanup lock manager error
fb_utils::init_status(tdbb->tdbb_status_vector);
return;
}
bool releasingLock = false;
try
{
// Cleanup resources
terminateCryptThread(tdbb);
down = false;
// Determine current page from the header
CchHdr hdr(tdbb, LCK_read);
process = hdr->hdr_flags & Ods::hdr_crypt_process ? true : false;
if (!process)
{
releasingLock = true;
LCK_release(tdbb, threadLock);
return;
}
currentPage = hdr->hdr_crypt_page;
// Refresh encryption flag
crypt = hdr->hdr_flags & Ods::hdr_encrypted ? true : false;
// If we are going to start crypt thread, we need plugin to be loaded
loadPlugin(hdr->hdr_crypt_plugin);
releasingLock = true;
LCK_release(tdbb, threadLock);
releasingLock = false;
// ready to go
guard.leave(); // release in advance to avoid races with cryptThread()
Thread::start(cryptThreadStatic, (THREAD_ENTRY_PARAM) this, THREAD_medium, &cryptThreadId);
}
catch (const Firebird::Exception&)
{
if (!releasingLock) // avoid secondary exception in catch
{
try
{
LCK_release(tdbb, threadLock);
}
catch (const Firebird::Exception&)
{ }
}
throw;
}
}
void CryptoManager::cryptThread()
{
FbLocalStatus status_vector;
bool lckRelease = false;
try
{
// Try to take crypt mutex
// If can't take that mutex - nothing to do, cryptThread already runs in our process
MutexEnsureUnlock guard(cryptThreadMtx, FB_FUNCTION);
if (!guard.tryEnter())
{
return;
}
// Establish temp context
// Needed to take crypt thread lock
UserId user;
user.usr_user_name = "(Crypt thread)";
Jrd::Attachment* const attachment = Jrd::Attachment::create(&dbb);
RefPtr<SysStableAttachment> sAtt(FB_NEW SysStableAttachment(attachment));
attachment->setStable(sAtt);
attachment->att_filename = dbb.dbb_filename;
attachment->att_user = &user;
BackgroundContextHolder tempDbb(&dbb, attachment, &status_vector, FB_FUNCTION);
LCK_init(tempDbb, LCK_OWNER_attachment);
sAtt->initDone();
// Take exclusive threadLock
// If can't take that lock - nothing to do, cryptThread already runs somewhere
if (!LCK_lock(tempDbb, threadLock, LCK_EX, LCK_NO_WAIT))
{
Monitoring::cleanupAttachment(tempDbb);
attachment->releaseLocks(tempDbb);
LCK_fini(tempDbb, LCK_OWNER_attachment);
return;
}
try
{
// Set running flag
AutoSetRestore<bool> runFlag(&run, true);
// Establish context
// Need real attachment in order to make classic mode happy
ClumpletWriter writer(ClumpletReader::Tagged, MAX_DPB_SIZE, isc_dpb_version1);
writer.insertString(isc_dpb_user_name, "SYSDBA");
writer.insertByte(isc_dpb_no_db_triggers, TRUE);
// Avoid races with release_attachment() in jrd.cpp
MutexEnsureUnlock releaseGuard(cryptAttMutex, FB_FUNCTION);
releaseGuard.enter();
if (!down)
{
RefPtr<JAttachment> jAtt(REF_NO_INCR, dbb.dbb_provider->attachDatabase(&status_vector,
dbb.dbb_filename.c_str(), writer.getBufferLength(), writer.getBuffer()));
check(&status_vector);
MutexLockGuard attGuard(*(jAtt->getStable()->getMutex()), FB_FUNCTION);
Attachment* att = jAtt->getHandle();
if (!att)
Arg::Gds(isc_att_shutdown).raise();
att->att_flags |= ATT_crypt_thread;
releaseGuard.leave();
ThreadContextHolder tdbb(att->att_database, att, &status_vector);
tdbb->tdbb_quantum = SWEEP_QUANTUM;
DatabaseContextHolder dbHolder(tdbb);
class UseCountHolder
{
public:
explicit UseCountHolder(Attachment* a)
: att(a)
{
att->att_use_count++;
}
~UseCountHolder()
{
att->att_use_count--;
}
private:
Attachment* att;
};
UseCountHolder use_count(att);
// get ready...
AutoSetRestore<Attachment*> attSet(&cryptAtt, att);
ULONG lastPage = getLastPage(tdbb);
do
{
// Check is there some job to do
while (currentPage < lastPage)
{
// forced terminate
if (down)
{
break;
}
// scheduling
if (--tdbb->tdbb_quantum < 0)
{
JRD_reschedule(tdbb, SWEEP_QUANTUM, true);
}
// nbackup state check
BackupManager::StateReadGuard::lock(tdbb, 1);
int bak_state = tdbb->getDatabase()->dbb_backup_manager->getState();
BackupManager::StateReadGuard::unlock(tdbb);
if (bak_state != Ods::hdr_nbak_normal)
{
EngineCheckout checkout(tdbb, FB_FUNCTION);
Thread::sleep(10);
continue;
}
// writing page to disk will change it's crypt status in usual way
WIN window(DB_PAGE_SPACE, currentPage);
Ods::pag* page = CCH_FETCH(tdbb, &window, LCK_write, pag_undefined);
if (page && page->pag_type <= pag_max &&
(bool(page->pag_flags & Ods::crypted_page) != crypt) &&
Ods::pag_crypt_page[page->pag_type])
{
CCH_MARK_MUST_WRITE(tdbb, &window);
}
CCH_RELEASE_TAIL(tdbb, &window);
// sometimes save currentPage into DB header
++currentPage;
if ((currentPage & 0x3FF) == 0)
{
writeDbHeader(tdbb, currentPage);
}
}
// forced terminate
if (down)
{
break;
}
// At this moment of time all pages with number < lastpage
// are guaranteed to change crypt state. Check for added pages.
lastPage = getLastPage(tdbb);
} while (currentPage < lastPage);
// Finalize crypt
if (!down)
{
writeDbHeader(tdbb, 0);
}
}
// Release exclusive lock on StartCryptThread
lckRelease = true;
LCK_release(tempDbb, threadLock);
Monitoring::cleanupAttachment(tempDbb);
attachment->releaseLocks(tempDbb);
LCK_fini(tempDbb, LCK_OWNER_attachment);
}
catch (const Exception&)
{
try
{
if (!lckRelease)
{
// Release exclusive lock on StartCryptThread
LCK_release(tempDbb, threadLock);
Monitoring::cleanupAttachment(tempDbb);
attachment->releaseLocks(tempDbb);
LCK_fini(tempDbb, LCK_OWNER_attachment);
}
}
catch (const Exception&)
{ }
throw;
}
}
catch (const Exception& ex)
{
// Error during context creation - we can't even release lock
iscLogException("Crypt thread:", ex);
}
}
void CryptoManager::writeDbHeader(thread_db* tdbb, ULONG runpage)
{
CchHdr hdr(tdbb, LCK_write);
Ods::header_page* header = hdr.write();
header->hdr_crypt_page = runpage;
if (!runpage)
{
header->hdr_flags &= ~Ods::hdr_crypt_process;
process = false;
if (!crypt)
{
ClumpletWriter hc(ClumpletWriter::UnTagged, header->hdr_page_size);
hdr.getClumplets(hc);
hc.deleteWithTag(Ods::HDR_crypt_hash);
hc.deleteWithTag(Ods::HDR_crypt_key);
hdr.setClumplets(hc);
}
}
digitalySignDatabase(hdr);
hdr.flush();
}
bool CryptoManager::read(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page, IOCallback* io)
{
// Code calling us is not ready to process exceptions correctly
// Therefore use old (status vector based) method
try
{
// Normal case (almost always get here)
// Take shared lock on crypto manager and read data
if (!slowIO)
{
BarSync::IoGuard ioGuard(tdbb, sync);
if (!slowIO)
return internalRead(tdbb, sv, page, io) == SUCCESS_ALL;
}
// Slow IO - we need exclusive lock on crypto manager.
// That may happen only when another process changed DB encyption.
BarSync::LockGuard lockGuard(tdbb, sync);
lockGuard.lock();
for (SINT64 previous = slowIO; ; previous = slowIO)
{
switch (internalRead(tdbb, sv, page, io))
{
case SUCCESS_ALL:
if (!slowIO) // if we took a lock last time
return true; // nothing else left to do - IO complete
// An attempt to take a lock, if it fails
// we get fresh data from lock needed to validate state of encryption.
// Notice - if lock was taken that's also a kind of state
// change and first time we must proceed with one more read.
lockAndReadHeader(tdbb, CRYPT_HDR_NOWAIT);
if (slowIO == previous) // if crypt state did not change
return true; // we successfully completed IO
break;