/
CryptoManager.h
419 lines (350 loc) · 9.93 KB
/
CryptoManager.h
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
/*
* PROGRAM: JRD access method
* MODULE: CryptoManager.h
* 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): ______________________________________.
*
*
*/
#ifndef JRD_CRYPTO_MANAGER
#define JRD_CRYPTO_MANAGER
#include "../common/classes/alloc.h"
#include "../common/classes/fb_atomic.h"
#include "../common/classes/SyncObject.h"
#include "../common/classes/fb_string.h"
#include "../common/classes/objects_array.h"
#include "../common/classes/condition.h"
#include "../common/classes/MetaName.h"
#include "../common/ThreadStart.h"
#include "../jrd/ods.h"
#include "../jrd/status.h"
#include "firebird/Interface.h"
// forward
class Config;
namespace Ods {
struct pag;
}
namespace Firebird {
class ClumpletReader;
}
namespace Jrd {
class Database;
class Attachment;
class jrd_file;
class BufferDesc;
class thread_db;
class Lock;
class PageSpace;
//
// This very specific locking class makes it possible to perform traditional read/write locks,
// but in addition it can on special request perform some predefined action or (in a case when
// >=1 read lock is taken) set barrier for new locks (new locks will not be granted) and
// at the moment when last existing lock is released execute that predefined action in context
// of a thread, releasing last lock.
//
// In our case special request is done from AST handler - and therefore called ast.
// Read locks are done when performing IO+crypt activity - and called ioBegin/ioEnd.
// Write locks are done when some exclusive activity like changing crypt state is
// needed - they are full locks and called lockBegin/lockEnd.
//
class BarSync
{
public:
class IBar
{
public:
virtual void doOnTakenWriteSync(Jrd::thread_db* tdbb) = 0;
virtual void doOnAst(Jrd::thread_db* tdbb) = 0;
};
BarSync(IBar* i)
: callback(i), counter(0), lockMode(0), flagWriteLock(false)
{ }
class IoGuard
{
public:
IoGuard(Jrd::thread_db* p_tdbb, BarSync& p_bs)
: tdbb(p_tdbb), bs(p_bs)
{
bs.ioBegin(tdbb);
}
~IoGuard()
{
bs.ioEnd(tdbb);
}
private:
Jrd::thread_db* tdbb;
BarSync& bs;
};
class LockGuard
{
public:
LockGuard(Jrd::thread_db* p_tdbb, BarSync& p_bs)
: tdbb(p_tdbb), bs(p_bs), flagLocked(false)
{ }
void lock()
{
fb_assert(!flagLocked);
if (!flagLocked)
{
bs.lockBegin(tdbb);
flagLocked = true;
}
}
~LockGuard()
{
if (flagLocked)
{
bs.lockEnd(tdbb);
}
}
private:
Jrd::thread_db* tdbb;
BarSync& bs;
bool flagLocked;
};
void ioBegin(Jrd::thread_db* tdbb)
{
Firebird::MutexLockGuard g(mutex, FB_FUNCTION);
if (counter < 0)
{
if (!(flagWriteLock && (thread == getThreadId())))
{
if ((counter % BIG_VALUE == 0) && (!flagWriteLock))
{
if (lockMode)
{
// Someone is waiting for write lock
lockCond.notifyOne();
barCond.wait(mutex);
}
else
{
// Ast done
callWriteLockHandler(tdbb);
counter = 0;
}
}
else
barCond.wait(mutex);
}
}
++counter;
}
void ioEnd(Jrd::thread_db* tdbb)
{
Firebird::MutexLockGuard g(mutex, FB_FUNCTION);
if (--counter < 0 && counter % BIG_VALUE == 0)
{
if (!(flagWriteLock && (thread == getThreadId())))
{
if (lockMode)
lockCond.notifyOne();
else
{
callWriteLockHandler(tdbb);
finishWriteLock();
}
}
}
}
void ast(Jrd::thread_db* tdbb)
{
Firebird::MutexLockGuard g(mutex, FB_FUNCTION);
if (counter >= 0)
{
counter -= BIG_VALUE;
}
callback->doOnAst(tdbb);
}
void lockBegin(Jrd::thread_db* tdbb)
{
Firebird::MutexLockGuard g(mutex, FB_FUNCTION);
if ((counter -= BIG_VALUE) != -BIG_VALUE)
{
++lockMode;
try
{
lockCond.wait(mutex);
}
catch (const Firebird::Exception&)
{
--lockMode;
throw;
}
--lockMode;
}
thread = getThreadId();
flagWriteLock = true;
}
void lockEnd(Jrd::thread_db* tdbb)
{
Firebird::MutexLockGuard g(mutex, FB_FUNCTION);
flagWriteLock = false;
finishWriteLock();
}
private:
void callWriteLockHandler(Jrd::thread_db* tdbb)
{
thread = getThreadId();
flagWriteLock = true;
callback->doOnTakenWriteSync(tdbb);
flagWriteLock = false;
}
void finishWriteLock()
{
if ((counter += BIG_VALUE) == 0)
barCond.notifyAll();
else
lockCond.notifyOne();
}
Firebird::Condition barCond, lockCond;
Firebird::Mutex mutex;
IBar* callback;
ThreadId thread;
int counter;
int lockMode;
bool flagWriteLock;
static const int BIG_VALUE = 1000000;
};
class CryptoManager FB_FINAL : public Firebird::PermanentStorage, public BarSync::IBar
{
public:
explicit CryptoManager(thread_db* tdbb);
~CryptoManager();
void shutdown(thread_db* tdbb);
void prepareChangeCryptState(thread_db* tdbb, const Firebird::MetaName& plugName,
const Firebird::MetaName& key);
void changeCryptState(thread_db* tdbb, const Firebird::string& plugName);
void attach(thread_db* tdbb, Attachment* att);
void detach(thread_db* tdbb, Attachment* att);
void startCryptThread(thread_db* tdbb);
void terminateCryptThread(thread_db* tdbb);
void stopThreadUsing(thread_db* tdbb, Attachment* att);
class IOCallback
{
public:
virtual bool callback(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page) = 0;
};
bool read(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page, IOCallback* io);
bool write(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page, IOCallback* io);
void cryptThread();
ULONG getCurrentPage() const;
UCHAR getCurrentState() const;
private:
enum IoResult {SUCCESS_ALL, FAILED_CRYPT, FAILED_IO};
IoResult internalRead(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page, IOCallback* io);
IoResult internalWrite(thread_db* tdbb, FbStatusVector* sv, Ods::pag* page, IOCallback* io);
class Buffer
{
public:
operator Ods::pag*()
{
return reinterpret_cast<Ods::pag*>(FB_ALIGN(buf, PAGE_ALIGNMENT));
}
Ods::pag* operator->()
{
return reinterpret_cast<Ods::pag*>(FB_ALIGN(buf, PAGE_ALIGNMENT));
}
private:
char buf[MAX_PAGE_SIZE + PAGE_ALIGNMENT - 1];
};
class HolderAttachments
{
public:
explicit HolderAttachments(Firebird::MemoryPool& p);
~HolderAttachments();
void registerAttachment(Attachment* att);
bool unregisterAttachment(Attachment* att);
void setPlugin(Firebird::IKeyHolderPlugin* kh);
Firebird::IKeyHolderPlugin* getPlugin() const
{
return keyHolder;
}
bool operator==(Firebird::IKeyHolderPlugin* kh) const;
private:
Firebird::IKeyHolderPlugin* keyHolder;
Firebird::HalfStaticArray<Attachment*, 32> attachments;
};
class KeyHolderPlugins
{
public:
explicit KeyHolderPlugins(Firebird::MemoryPool& p)
: knownHolders(p)
{ }
void attach(Attachment* att, Config* config);
void detach(Attachment* att);
void init(Firebird::IDbCryptPlugin* crypt, const char* keyName);
private:
Firebird::Mutex holdersMutex;
Firebird::ObjectsArray<HolderAttachments> knownHolders;
};
static int blockingAstChangeCryptState(void*);
void blockingAstChangeCryptState();
// IBar's pure virtual functions are implemented here
void doOnTakenWriteSync(thread_db* tdbb);
void doOnAst(thread_db* tdbb);
void loadPlugin(const char* pluginName);
ULONG getLastPage(thread_db* tdbb);
void writeDbHeader(thread_db* tdbb, ULONG runpage);
void calcValidation(Firebird::string& valid);
void lockAndReadHeader(thread_db* tdbb, unsigned flags = 0);
static const unsigned CRYPT_HDR_INIT = 0x01;
static const unsigned CRYPT_HDR_NOWAIT = 0x02;
void addClumplet(Firebird::string& value, Firebird::ClumpletReader& block, UCHAR tag);
void calcDigitalSignature(Firebird::string& signature, const class Header& hdr);
void digitalySignDatabase(class CchHdr& hdr);
void checkDigitalSignature(const class Header& hdr);
BarSync sync;
Firebird::MetaName keyName;
ULONG currentPage;
Firebird::Mutex pluginLoadMtx, cryptThreadMtx;
KeyHolderPlugins keyHolderPlugins;
Thread::Handle cryptThreadId;
Firebird::IDbCryptPlugin* cryptPlugin;
Database& dbb;
Lock* stateLock;
Lock* threadLock;
Attachment* cryptAtt;
// This counter works only in a case when database encryption is changed.
// Traditional processing of AST can not be used for crypto manager.
// The problem is with taking state lock after AST.
// That should be done before next IO operation to guarantee database
// consistency, but IO operation may be requested from another AST
// (database cache blocking) when 'wait for a lock' operations are
// prohibited. I.e. we can't proceed with normal IO without a lock
// but at the same time can't take it.
// The solution is to use crypt versions counter in a lock (incremented
// by one each time one issues ALTER DATABASE ENCRYPT/DECRYPT), read
// it when lock can't be taken, store in slowIO variable, perform IO
// and compare stored value with current lock data. In case when values
// differ encryption status of database was changed during IO operation
// and such operation should be repeated. When data in lock does not
// change during IO that means that crypt rules remained the same even
// without state lock taken by us and therefore result of IO operation
// is correct. As soon as non-waiting attempt to take state lock succeeds
// slowIO mode is off (slowIO counter becomes zero) and we return to
// normal operation.
SINT64 slowIO;
bool crypt, process, down, run;
};
} // namespace Jrd
#endif // JRD_CRYPTO_MANAGER