-
-
Notifications
You must be signed in to change notification settings - Fork 206
/
jrd.cpp
7536 lines (6365 loc) · 180 KB
/
jrd.cpp
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: jrd.cpp
* DESCRIPTION: User visible entrypoints
*
* The contents of this file are subject to the Interbase 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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, 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 Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* 2001.07.06 Sean Leyne - Code Cleanup, removed "#ifdef READONLY_DATABASE"
* conditionals, as the engine now fully supports
* readonly databases.
* 2001.07.09 Sean Leyne - Restore default setting to Force Write = "On", for
* Windows NT platform, for new database files. This was changed
* with IB 6.0 to OFF and has introduced many reported database
* corruptions.
*
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
* Claudio Valderrama C.
* Adriano dos Santos Fernandes
*
*/
#include "firebird.h"
#include "../jrd/common.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../jrd/common.h"
#include "../jrd/ThreadStart.h"
#include "../jrd/os/thd_priority.h"
#include <stdarg.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_PWD_H
#include <pwd.h>
#endif
#include <errno.h>
#include "../jrd/ibase.h"
#include "../jrd/jrd.h"
#include "../jrd/irq.h"
#include "../jrd/drq.h"
#include "../jrd/req.h"
#include "../jrd/tra.h"
#include "../jrd/blb.h"
#include "../jrd/lck.h"
#include "../jrd/nbak.h"
#include "../jrd/scl.h"
#include "../jrd/os/pio.h"
#include "../jrd/ods.h"
#include "../jrd/exe.h"
#include "../jrd/extds/ExtDS.h"
#include "../jrd/val.h"
#include "../jrd/rse.h"
#include "../jrd/fil.h"
#include "../jrd/intl.h"
#include "../jrd/sbm.h"
#include "../jrd/svc.h"
#include "../jrd/sdw.h"
#include "../jrd/lls.h"
#include "../jrd/cch.h"
#include "../intl/charsets.h"
#include "../jrd/sort.h"
#include "../jrd/PreparedStatement.h"
#include "../jrd/blb_proto.h"
#include "../jrd/cch_proto.h"
#include "../jrd/cmp_proto.h"
#include "../jrd/dbg_proto.h"
#include "../jrd/dyn_proto.h"
#include "../jrd/err_proto.h"
#include "../jrd/exe_proto.h"
#include "../jrd/ext_proto.h"
#include "../jrd/fun_proto.h"
#include "../jrd/gds_proto.h"
#include "../jrd/inf_proto.h"
#include "../jrd/ini_proto.h"
#include "../jrd/intl_proto.h"
#include "../jrd/isc_f_proto.h"
#include "../jrd/isc_proto.h"
#include "../jrd/jrd_proto.h"
#include "../jrd/lck_proto.h"
#include "../jrd/met_proto.h"
#include "../jrd/mov_proto.h"
#include "../jrd/pag_proto.h"
#include "../jrd/par_proto.h"
#include "../jrd/os/pio_proto.h"
#include "../jrd/scl_proto.h"
#include "../jrd/sdw_proto.h"
#include "../jrd/shut_proto.h"
#include "../jrd/sort_proto.h"
#include "../jrd/thread_proto.h"
#include "../jrd/tra_proto.h"
#include "../jrd/val_proto.h"
#include "../jrd/vio_proto.h"
#include "../jrd/file_params.h"
#include "../jrd/event_proto.h"
#include "../jrd/why_proto.h"
#include "../jrd/flags.h"
#include "../jrd/Database.h"
#include "../common/config/config.h"
#include "../common/config/dir_list.h"
#include "../jrd/db_alias.h"
#include "../jrd/trace/TraceManager.h"
#include "../jrd/trace/TraceObjects.h"
#include "../jrd/trace/TraceJrdHelpers.h"
#include "../jrd/IntlManager.h"
#include "../common/classes/fb_tls.h"
#include "../common/classes/ClumpletReader.h"
#include "../common/utils_proto.h"
#include "../jrd/DebugInterface.h"
#include "../dsql/dsql.h"
#include "../dsql/dsql_proto.h"
#include "../common/dllinst.h"
using namespace Jrd;
using namespace Firebird;
const SSHORT WAIT_PERIOD = -1;
#ifdef SUPPORT_RAW_DEVICES
#define unlink PIO_unlink
#endif
#ifdef DEV_BUILD
int debug;
#endif
namespace
{
// Flag engineShutdown guarantees that no new attachment is created after setting it
// and helps avoid more than 1 shutdown threads running simultaneously.
bool engineShutdown = false;
// This flag is protected with 2 mutexes. shutdownMutex is taken by each shutdown thread
// (for a relatively long time). engineEntranceMutex is taken (for a short time) when
// shutdown thread is starting shutdown and also when new attachment is created.
GlobalPtr<Mutex> shutdownMutex, engineEntranceMutex;
// This mutex is set when new Database block is created. It's global first of all to satisfy
// SS requirement - avoid 2 Database blocks for same database (file). Also guarantees no
// half-done Database block in databases linked list. Always taken before databases_mutex.
GlobalPtr<Mutex> dbInitMutex;
Database* databases = NULL;
// This mutex protects linked list of databases.
GlobalPtr<Mutex> databases_mutex;
// Holder for per-database init/fini mutex
class RefMutexUnlock
{
public:
RefMutexUnlock()
: entered(false)
{ }
explicit RefMutexUnlock(Database::ExistenceRefMutex* p)
: ref(p), entered(false)
{ }
void enter()
{
fb_assert(ref);
ref->enter();
entered = true;
}
void leave()
{
if (entered)
{
ref->leave();
entered = false;
}
}
void operator=(Database::ExistenceRefMutex* to)
{
if (ref == to)
{
return;
}
leave();
ref = to;
}
Database::ExistenceRefMutex* operator->()
{
return ref;
}
bool operator!() const
{
return !ref;
}
~RefMutexUnlock()
{
leave();
}
private:
RefPtr<Database::ExistenceRefMutex> ref;
bool entered;
};
// We have 2 more related types of mutexes in database and attachment.
// Attachment is using reference counted mutex in PublicHandle, also making it possible
// to check does object still exist after locking a mutex. This makes great use when
// checking for correctness of attachment handle in jrd8* entrypoints. Attachment mutex
// is always taken before databases_mutex (but after dbInitMutex when new attachment
// is created). Attachment mutex is never released inside engine. Database mutex (dbb_sync)
// is taken when engine starts to work with some database and released when there is no
// active job (when waiting for something) or when rescheduling. No other mutex from above
// mentioned here can be taken after dbb_sync with an exception of attachment mutex for new
// attachment. So finally the order of taking mutexes is:
// 1. dbInitMutex (in attach/create database) or attachment mutex in other calls
// 2. databases_mutex (when / if needed)
// 3. dbb_sync
// 4. only for new attachments: attachment mutex
// Any of this may be missing when not needed, but order of taking should not be changed.
class EngineStartup
{
public:
static void init()
{
IbUtil::initialize();
IntlManager::initialize();
}
static void cleanup()
{
}
};
InitMutex<EngineStartup> engineStartup;
inline void validateHandle(Service* service)
{
if (service && service->checkHandle())
return;
status_exception::raise(Arg::Gds(isc_bad_svc_handle));
}
class AttachmentHolder : public PublicHandleHolder
{
public:
AttachmentHolder(Attachment* const attachment, const char* from)
{
if (!hold(attachment, from))
Arg::Gds(isc_bad_db_handle).raise();
}
AttachmentHolder(thread_db* tdbb, Attachment* const attachment, const char* from)
{
validateHandle(tdbb, attachment, from);
}
AttachmentHolder(thread_db* tdbb, jrd_tra* const transaction, const char* from)
{
validateHandle(tdbb, transaction, from);
}
AttachmentHolder(thread_db* tdbb, jrd_req* const request, const char* from)
{
validateHandle(tdbb, request, from);
}
AttachmentHolder(thread_db* tdbb, dsql_req* const statement, const char* from)
{
validateHandle(tdbb, statement, from);
}
AttachmentHolder(thread_db* tdbb, blb* blob, const char* from)
{
validateHandle(tdbb, blob, from);
}
private:
thread_db* tdbb;
private:
inline void validateHandle(thread_db* tdbb, Attachment* const attachment, const char* from)
{
if (attachment && attachment == tdbb->getAttachment())
return;
if (attachment)
{
MutexLockGuard guard(engineEntranceMutex);
if (engineShutdown)
{
status_exception::raise(Arg::Gds(isc_att_shutdown));
}
}
if (!hold(attachment, from) || !attachment->checkHandle() || !attachment->att_database->checkHandle())
{
status_exception::raise(Arg::Gds(isc_bad_db_handle));
}
tdbb->setAttachment(attachment);
tdbb->setDatabase(attachment->att_database);
}
public:
inline void validateHandle(thread_db* tdbb, jrd_tra* const transaction, const char* from)
{
if (!transaction->checkHandle())
status_exception::raise(Arg::Gds(isc_bad_trans_handle));
validateHandle(tdbb, transaction->tra_attachment, from);
tdbb->setTransaction(transaction);
}
private:
inline void validateHandle(thread_db* tdbb, jrd_req* const request, const char* from)
{
if (!request->checkHandle())
status_exception::raise(Arg::Gds(isc_bad_req_handle));
validateHandle(tdbb, request->req_attachment, from);
}
inline void validateHandle(thread_db* tdbb, dsql_req* const statement, const char* from)
{
if (!statement->checkHandle())
status_exception::raise(Arg::Gds(isc_bad_req_handle));
validateHandle(tdbb, statement->req_dbb->dbb_attachment, from);
}
inline void validateHandle(thread_db* tdbb, blb* blob, const char* from)
{
if (!blob->checkHandle())
status_exception::raise(Arg::Gds(isc_bad_segstr_handle));
validateHandle(tdbb, blob->blb_transaction, from);
validateHandle(tdbb, blob->blb_attachment, from);
}
private:
// copying is prohibited
AttachmentHolder(const AttachmentHolder&);
AttachmentHolder& operator =(const AttachmentHolder&);
};
class DatabaseContextHolder : public Database::SyncGuard,
public Jrd::ContextPoolHolder
{
public:
explicit DatabaseContextHolder(thread_db* arg)
: Database::SyncGuard(arg->getDatabase()),
Jrd::ContextPoolHolder(arg, arg->getDatabase()->dbb_permanent),
tdbb(arg)
{
Database* dbb = tdbb->getDatabase();
++dbb->dbb_use_count;
}
~DatabaseContextHolder()
{
Database* dbb = tdbb->getDatabase();
if (dbb->checkHandle())
{
--dbb->dbb_use_count;
}
}
private:
// copying is prohibited
DatabaseContextHolder(const DatabaseContextHolder&);
DatabaseContextHolder& operator=(const DatabaseContextHolder&);
thread_db* tdbb;
};
// This holder class disables AST delivery into att for instance's lifetime
// Also it guarantees existence mutex to exist for same time
class DisableAst
{
public:
explicit DisableAst(Attachment* att)
: attExistenceMutex(att->mutex())
{
MutexLockGuard guard(attExistenceMutex->astMutex);
++(attExistenceMutex->astDisabled);
}
~DisableAst()
{
// since astDisabled is atomic, no need to lock something in dtor
--(attExistenceMutex->astDisabled);
}
private:
RefPtr<ExistenceMutex> attExistenceMutex;
};
void validateAccess(const Attachment* attachment)
{
if (!attachment->locksmith())
{
ERR_post(Arg::Gds(isc_adm_task_denied));
}
}
} // anonymous
#ifdef WIN_NT
#include <windows.h>
// these should stop a most annoying warning
#undef TEXT
#define TEXT SCHAR
#endif // WIN_NT
void Jrd::Trigger::compile(thread_db* tdbb)
{
if (!trig_request /*&& !compile_in_progress*/)
{
SET_TDBB(tdbb);
Database* dbb = tdbb->getDatabase();
Database::CheckoutLockGuard guard(dbb, dbb->dbb_meta_mutex);
if (trig_request)
{
return;
}
compile_in_progress = true;
// Allocate statement memory pool
MemoryPool* new_pool = dbb->createPool();
// Trigger request is not compiled yet. Lets do it now
USHORT par_flags = (USHORT) (flags & TRG_ignore_perm) ? csb_ignore_perm : 0;
if (type & 1)
par_flags |= csb_pre_trigger;
else
par_flags |= csb_post_trigger;
try {
Jrd::ContextPoolHolder context(tdbb, new_pool);
AutoPtr<CompilerScratch> csb(CompilerScratch::newCsb(*dbb->dbb_permanent, 5));
csb->csb_g_flags |= par_flags;
if (debugInfo.hasData())
{
DBG_parse_debug_info((USHORT) debugInfo.getCount(), debugInfo.begin(),
csb->csb_dbg_info);
}
PAR_blr(tdbb, relation, blr.begin(), (ULONG) blr.getCount(), NULL, csb, &trig_request,
(relation ? true : false), par_flags);
}
catch (const Exception&)
{
compile_in_progress = false;
if (trig_request)
{
CMP_release(tdbb, trig_request);
trig_request = NULL;
}
else {
dbb->deletePool(new_pool);
}
throw;
}
trig_request->req_trg_name = name;
if (sys_trigger)
{
trig_request->req_flags |= req_sys_trigger;
}
if (flags & TRG_ignore_perm)
{
trig_request->req_flags |= req_ignore_perm;
}
compile_in_progress = false;
}
}
void Jrd::Trigger::release(thread_db* tdbb)
{
if (blr.getCount() == 0 || !trig_request || CMP_clone_is_active(trig_request))
{
return; // FALSE;
}
CMP_release(tdbb, trig_request);
trig_request = NULL;
return; // TRUE;
}
// Option block for database parameter block
class DatabaseOptions
{
public:
USHORT dpb_wal_action;
SLONG dpb_sweep_interval;
ULONG dpb_page_buffers;
bool dpb_set_page_buffers;
ULONG dpb_buffers;
USHORT dpb_verify;
USHORT dpb_sweep;
USHORT dpb_dbkey_scope;
USHORT dpb_page_size;
bool dpb_activate_shadow;
bool dpb_delete_shadow;
bool dpb_no_garbage;
USHORT dpb_shutdown;
SSHORT dpb_shutdown_delay;
USHORT dpb_online;
bool dpb_force_write;
bool dpb_set_force_write;
bool dpb_no_reserve;
bool dpb_set_no_reserve;
SSHORT dpb_interp;
bool dpb_single_user;
bool dpb_overwrite;
bool dpb_sec_attach;
bool dpb_disable_wal;
bool dpb_gsec_attach;
SLONG dpb_connect_timeout;
SLONG dpb_dummy_packet_interval;
bool dpb_db_readonly;
bool dpb_set_db_readonly;
bool dpb_gfix_attach;
bool dpb_gstat_attach;
USHORT dpb_sql_dialect;
USHORT dpb_set_db_sql_dialect;
SLONG dpb_remote_pid;
bool dpb_no_db_triggers;
bool dpb_gbak_attach;
bool dpb_trusted_role;
bool dpb_utf8_filename;
ULONG dpb_ext_call_depth;
ULONG dpb_flags; // to OR'd with dbb_flags
// here begin compound objects
// for constructor to work properly dpb_sys_user_name
// MUST be FIRST
string dpb_sys_user_name;
string dpb_user_name;
string dpb_password;
string dpb_password_enc;
string dpb_role_name;
string dpb_journal;
string dpb_key;
string dpb_lc_ctype;
PathName dpb_working_directory;
string dpb_set_db_charset;
string dpb_network_protocol;
string dpb_remote_address;
string dpb_trusted_login;
PathName dpb_remote_process;
PathName dpb_org_filename;
public:
DatabaseOptions()
{
memset(this, 0,
reinterpret_cast<char*>(&this->dpb_sys_user_name) - reinterpret_cast<char*>(this));
}
void get(const UCHAR*, USHORT, bool&);
private:
void getPath(ClumpletReader& reader, PathName& s)
{
reader.getPath(s);
if (!dpb_utf8_filename)
ISC_systemToUtf8(s);
ISC_unescape(s);
}
void getString(ClumpletReader& reader, string& s)
{
reader.getString(s);
if (!dpb_utf8_filename)
ISC_systemToUtf8(s);
ISC_unescape(s);
}
};
/// trace manager support
class TraceFailedConnection : public TraceDatabaseConnection
{
public:
TraceFailedConnection(const char* filename, const DatabaseOptions* options) :
m_filename(filename),
m_options(options)
{}
virtual int getConnectionID() { return 0; }
virtual int getProcessID() { return m_options->dpb_remote_pid; }
virtual const char* getDatabaseName() { return m_filename; }
virtual const char* getUserName()
{
if (m_options->dpb_user_name.empty())
return m_options->dpb_trusted_login.c_str();
return m_options->dpb_user_name.c_str();
}
virtual ntrace_connection_kind_t getKind() { return connection_database; }
virtual const char* getRoleName() { return m_options->dpb_role_name.c_str(); }
virtual const char* getCharSet() { return m_options->dpb_lc_ctype.c_str(); }
virtual const char* getRemoteProtocol() { return m_options->dpb_network_protocol.c_str(); }
virtual const char* getRemoteAddress() { return m_options->dpb_remote_address.c_str(); }
virtual int getRemoteProcessID() { return m_options->dpb_remote_pid; }
virtual const char* getRemoteProcessName() { return m_options->dpb_remote_process.c_str(); }
private:
const char* m_filename;
const DatabaseOptions* m_options;
};
namespace {
const unsigned CHECK_PERSISTENT_ONLY = 1;
}
static void check_database(thread_db* tdbb, unsigned flags = 0);
static void check_monitoring(thread_db* tdbb);
static void commit(thread_db*, jrd_tra*, const bool);
static bool drop_files(const jrd_file*);
static void find_intl_charset(thread_db*, Attachment*, const DatabaseOptions*);
static jrd_tra* find_transaction(thread_db*, ISC_STATUS);
static void init_database_lock(thread_db*);
static void init_monitoring_lock(thread_db*);
static ISC_STATUS handle_error(ISC_STATUS*, ISC_STATUS);
static void run_commit_triggers(thread_db* tdbb, jrd_tra* transaction);
static void verify_request_synchronization(jrd_req*& request, SSHORT level);
static void purge_transactions(thread_db*, Attachment*, const bool);
namespace {
enum VdnResult {VDN_FAIL, VDN_OK, VDN_SECURITY};
}
static VdnResult verifyDatabaseName(const PathName&, ISC_STATUS*, bool);
static ISC_STATUS unwindAttach(const Exception& ex,
ISC_STATUS* userStatus,
thread_db* tdbb,
Attachment* attachment,
Database* dbb);
#ifdef WIN_NT
static void ExtractDriveLetter(const TEXT*, ULONG*);
#endif
static void init(thread_db*, const PathName&, const PathName&, bool, const DatabaseOptions&,
RefMutexUnlock&);
static Attachment* create_attachment(const PathName&, Database*, const DatabaseOptions&);
static void prepare(thread_db*, jrd_tra*, USHORT, const UCHAR*);
static void release_attachment(thread_db*, Attachment*);
static void detachLocksFromAttachment(Attachment*);
static void rollback(thread_db*, jrd_tra*, const bool);
static bool shutdown_database(Database*, const bool);
static void strip_quotes(string&);
static void purge_attachment(thread_db*, Attachment*, const bool);
static void getUserInfo(UserId&, const DatabaseOptions&);
static THREAD_ENTRY_DECLARE shutdown_thread(THREAD_ENTRY_PARAM);
//____________________________________________________________
//
// check whether we need to perform an autocommit;
// do it here to prevent committing every record update
// in a statement
//
static void check_autocommit(jrd_req* request, thread_db* tdbb)
{
// dimitr: we should ignore autocommit for requests
// created by EXECUTE STATEMENT
// AP: also do nothing if request is cancelled and
// transaction is already missing
if ((!request->req_transaction) || (request->req_transaction->tra_callback_count > 0))
return;
if (request->req_transaction->tra_flags & TRA_perform_autocommit)
{
if (!(tdbb->getAttachment()->att_flags & ATT_no_db_triggers) &&
!(request->req_transaction->tra_flags & TRA_prepared))
{
// run ON TRANSACTION COMMIT triggers
run_commit_triggers(tdbb, request->req_transaction);
}
request->req_transaction->tra_flags &= ~TRA_perform_autocommit;
TRA_commit(tdbb, request->req_transaction, true);
}
}
static ISC_STATUS successful_completion(ISC_STATUS* status,
ISC_STATUS return_code = FB_SUCCESS,
bool forceUseCode = false)
{
fb_assert(status);
// This assert validates whether we really have a successful status vector
fb_assert(status[0] != isc_arg_gds || status[1] == FB_SUCCESS || status[1] == return_code);
// Clear the status vector if it doesn't contain a warning
if (status[0] != isc_arg_gds || status[1] != FB_SUCCESS || status[2] != isc_arg_warning)
{
fb_utils::init_status(status);
}
return forceUseCode ? return_code : status[1];
}
const int SWEEP_INTERVAL = 20000;
const char DBL_QUOTE = '\042';
const char SINGLE_QUOTE = '\'';
#define GDS_ATTACH_DATABASE jrd8_attach_database
#define GDS_BLOB_INFO jrd8_blob_info
#define GDS_CANCEL_BLOB jrd8_cancel_blob
#define GDS_CANCEL_EVENTS jrd8_cancel_events
#define FB_CANCEL_OPERATION jrd8_cancel_operation
#define GDS_CLOSE_BLOB jrd8_close_blob
#define GDS_COMMIT jrd8_commit_transaction
#define GDS_COMMIT_RETAINING jrd8_commit_retaining
#define GDS_COMPILE jrd8_compile_request
#define GDS_CREATE_BLOB2 jrd8_create_blob2
#define GDS_CREATE_DATABASE jrd8_create_database
#define GDS_DATABASE_INFO jrd8_database_info
#define GDS_DDL jrd8_ddl
#define GDS_DETACH jrd8_detach_database
#define GDS_DROP_DATABASE jrd8_drop_database
#define GDS_GET_SEGMENT jrd8_get_segment
#define GDS_GET_SLICE jrd8_get_slice
#define GDS_OPEN_BLOB2 jrd8_open_blob2
#define GDS_PREPARE jrd8_prepare_transaction
#define GDS_PUT_SEGMENT jrd8_put_segment
#define GDS_PUT_SLICE jrd8_put_slice
#define GDS_QUE_EVENTS jrd8_que_events
#define GDS_RECONNECT jrd8_reconnect_transaction
#define GDS_RECEIVE jrd8_receive
#define GDS_RELEASE_REQUEST jrd8_release_request
#define GDS_REQUEST_INFO jrd8_request_info
#define GDS_ROLLBACK jrd8_rollback_transaction
#define GDS_ROLLBACK_RETAINING jrd8_rollback_retaining
#define GDS_SEEK_BLOB jrd8_seek_blob
#define GDS_SEND jrd8_send
#define GDS_SERVICE_ATTACH jrd8_service_attach
#define GDS_SERVICE_DETACH jrd8_service_detach
#define GDS_SERVICE_QUERY jrd8_service_query
#define GDS_SERVICE_START jrd8_service_start
#define GDS_START_AND_SEND jrd8_start_and_send
#define GDS_START jrd8_start_request
#define GDS_START_MULTIPLE jrd8_start_multiple
#define GDS_START_TRANSACTION jrd8_start_transaction
#define GDS_TRANSACT_REQUEST jrd8_transact_request
#define GDS_TRANSACTION_INFO jrd8_transaction_info
#define GDS_UNWIND jrd8_unwind_request
#define GDS_SHUTDOWN jrd8_shutdown_all
#define GDS_PING jrd8_ping_attachment
#define GDS_DSQL_ALLOCATE jrd8_allocate_statement
#define GDS_DSQL_EXECUTE jrd8_execute
#define GDS_DSQL_EXECUTE_IMMEDIATE jrd8_execute_immediate
#define GDS_DSQL_FETCH jrd8_fetch
#define GDS_DSQL_FREE jrd8_free_statement
#define GDS_DSQL_INSERT jrd8_insert
#define GDS_DSQL_PREPARE jrd8_prepare
#define GDS_DSQL_SET_CURSOR jrd8_set_cursor
#define GDS_DSQL_SQL_INFO jrd8_sql_info
#define ENTRYPOINT_NAME(func) STRINGIZE(func)
// External hook definitions
/* dimitr: just uncomment the following line to use this feature.
Requires support from the PIO modules. Only Win32 is 100% ready
for this so far. Note that the database encryption code in the
PIO layer seems to be incompatible with the SUPERSERVER_V2 code.
2003.02.09 */
//#define ISC_DATABASE_ENCRYPTION
static const char* CRYPT_IMAGE = "fbcrypt";
static const char* ENCRYPT = "encrypt";
static const char* DECRYPT = "decrypt";
static ISC_STATUS trace_error(thread_db* tdbb, const Exception& ex, ISC_STATUS* user_status, const char* func)
{
const ISC_STATUS ret = ex.stuff_exception(user_status);
Attachment* att = tdbb->getAttachment();
if (ret == isc_bad_db_handle || !att)
return ret;
if (att->att_trace_manager->needs().event_error)
{
TraceConnectionImpl conn(att);
TraceStatusVectorImpl traceStatus(user_status);
att->att_trace_manager->event_error(&conn, &traceStatus, func);
}
return ret;
}
static void trace_warning(thread_db* tdbb, ISC_STATUS* user_status, const char* func)
{
Attachment* att = tdbb->getAttachment();
if (!att)
return;
if (att->att_trace_manager->needs().event_error)
{
TraceStatusVectorImpl traceStatus(user_status);
if (traceStatus.hasWarning())
{
TraceConnectionImpl conn(att);
att->att_trace_manager->event_error(&conn, &traceStatus, func);
}
}
}
static void trace_failed_attach(TraceManager* traceManager, const char* filename,
const DatabaseOptions& options, bool create, ISC_STATUS* status)
{
// Report to Trace API that attachment has not been created
const char* origFilename = filename;
if (options.dpb_org_filename.hasData())
origFilename = options.dpb_org_filename.c_str();
TraceFailedConnection conn(origFilename, &options);
TraceStatusVectorImpl traceStatus(status);
const bool no_priv = (status[1] == isc_login || status[1] == isc_no_priv);
const char* func = create ? ENTRYPOINT_NAME(GDS_CREATE_DATABASE) :
ENTRYPOINT_NAME(GDS_ATTACH_DATABASE);
if (!traceManager)
{
TraceManager tempMgr(origFilename);
if (tempMgr.needs().event_attach)
tempMgr.event_attach(&conn, create, no_priv ? res_unauthorized : res_failed);
if (tempMgr.needs().event_error)
tempMgr.event_error(&conn, &traceStatus, func);
}
else
{
if (traceManager->needs().event_attach)
traceManager->event_attach(&conn, create, no_priv ? res_unauthorized : res_failed);
if (traceManager->needs().event_error)
traceManager->event_error(&conn, &traceStatus, func);
}
}
ISC_STATUS GDS_ATTACH_DATABASE(ISC_STATUS* user_status,
const TEXT* filename,
Attachment** handle,
SSHORT dpb_length,
const UCHAR* dpb)
{
/**************************************
*
* g d s _ $ a t t a c h _ d a t a b a s e
*
**************************************
*
* Functional description
* Attach a moldy, grungy, old database
* sullied by user data.
*
**************************************/
ThreadContextHolder tdbb(user_status);
if (*handle)
{
return handle_error(user_status, isc_bad_db_handle);
}
UserId userId;
DatabaseOptions options;
bool invalid_client_SQL_dialect = false;
PathName file_name, expanded_name;
bool is_alias = false;
MutexEnsureUnlock guardDbInit(dbInitMutex);
#ifdef REEXPAND_DBNAME
guardDbInit.enter(); // Required to correctly expand name of just created database
#endif
try
{
// Process database parameter block
options.get(dpb, dpb_length, invalid_client_SQL_dialect);
if (options.dpb_org_filename.hasData())
file_name = options.dpb_org_filename;
else
{
file_name = filename;
if (!options.dpb_utf8_filename)
ISC_systemToUtf8(file_name);
ISC_unescape(file_name);
}
ISC_utf8ToSystem(file_name);
// Resolve given alias name
is_alias = ResolveDatabaseAlias(file_name, expanded_name);
if (is_alias)
{
ISC_systemToUtf8(expanded_name);
ISC_unescape(expanded_name);
ISC_utf8ToSystem(expanded_name);
ISC_expand_filename(expanded_name, false);
}
else
{
expanded_name = filename;
if (!options.dpb_utf8_filename)
ISC_systemToUtf8(expanded_name);
ISC_unescape(expanded_name);
ISC_utf8ToSystem(expanded_name);
}
// Check to see if the database is truly local
if (ISC_check_if_remote(expanded_name, true))
{
return handle_error(user_status, isc_unavailable);
}
// Check for correct credentials supplied
getUserInfo(userId, options);
}
catch (const DelayFailedLogin& ex)
{
const ISC_STATUS ret = ex.stuff_exception(user_status);
trace_failed_attach(NULL, filename, options, false, user_status);
ex.sleep();
return ret;
}
catch (const Exception& ex)
{
const ISC_STATUS ret = ex.stuff_exception(user_status);
trace_failed_attach(NULL, filename, options, false, user_status);
return ret;
}
// Check database against conf file.
const VdnResult vdn = verifyDatabaseName(expanded_name, user_status, is_alias);
if (!is_alias && vdn == VDN_FAIL)
{
trace_failed_attach(NULL, filename, options, false, user_status);
return user_status[1];
}
Database* dbb = NULL;
Attachment* attachment = NULL;
bool attachTraced = false;
// Initialize special error handling